','').strip().replace('\\xa0','').replace('\\n','').replace('','')\n \n yield item\n \n \n if self.offset<12:\n self.offset+=1\n yield(scrapy.Request('https://movie.douban.com/top250?start='+str(self.offset*25)+'&filter=',callback=self.parse))\n else:\n pass\n \n \n\n\n '''\n item['contury'] =text[-15:-10]\n item['kind'] =text[-13:]\n item['actor'] =re.findall(r'主演: [\\u4e00-\\u9fa5]+.[\\u4e00-\\u9fa5]+',text)\n item['dirctor'] =re.findall(r'导演: [\\u4e00-\\u9fa5]+.[\\u4e00-\\u9fa5]+',text)\n item['year'] =re.findall(r'\\d+',text)\n '''","sub_path":"py_scrapy_spider/ep7/ep7/spiders/db_top250.py","file_name":"db_top250.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"46419725","text":"# -*- coding: utf-8 -*-\nimport time\nimport scrapy\n\n\nclass MiddleSpider(scrapy.Spider):\n name = 'middle'\n allowed_domains = ['www.baidu.com']\n start_urls = ['https://www.baidu.com/']\n\n def parse(self, response):\n for i in range(20):\n time.sleep(0.1)\n\n print('>' * i)\n print('this is the output of parse()')\n","sub_path":"part_04.2_spider/scrapy_0/midwr_test/midwr_test/spiders/middle.py","file_name":"middle.py","file_ext":"py","file_size_in_byte":354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"306029296","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\npages=set()\ndef getlinks(url):\n html=urlopen(\"http://en.wikipedia.org\"+url)\n bsobj = BeautifulSoup(html, \"lxml\")\n try:\n print(bsobj.h1.get_text())\n print(bsobj.find(id=\"mw-content-text\").findAll(\"p\")[0])\n print(bsobj.find(id=\"ca-edit\").find(\"span\").find(\"a\").attrs[\"href\"])\n except AttributeError:\n print(\"lack few attribute\")\n for link in bsobj.find_all(\"a\",href=re.compile(\"^(/wiki/)\")): #((?!:).)*$\n if 'href' in link.attrs: # ^代表开始/wiki/ str:\n stk = []\n left = '('\n res = \"\"\n start = 0\n\n for i in range(len(S)):\n if S[i] == left:\n stk.append(left)\n else:\n stk.pop()\n\n if len(stk) == 0:\n res += S[start + 1: i]\n start = i + 1\n\n return res\n\n\nprint(removeOuterParentheses(\"(()())(())(()(()))\"))\n","sub_path":"栈/一般栈应用/1021. 删除最外层的括号.py","file_name":"1021. 删除最外层的括号.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"568169218","text":"import requests\n\n\ndef search_address(zipcode):\n response = requests.get(f'http://zipcloud.ibsnet.co.jp/api/search?zipcode={zipcode}')\n results = response.json()['results'][0]\n 都道府県名 = results['address1']\n 市区町村名 = results['address2']\n 町域名 = results['address3']\n address = f'{都道府県名}{市区町村名}{町域名}'\n return address\n\n\nif __name__ == '__main__':\n zipcode = '0287111'\n\n address = search_address(zipcode)\n\n assert '岩手県八幡平市大更' == address\n","sub_path":"surch_address.py","file_name":"surch_address.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"415024950","text":"\"\"\"OpenAPI core wrappers module\"\"\"\nfrom werkzeug.datastructures import ImmutableMultiDict\n\nfrom openapi_core.wrappers.base import BaseOpenAPIRequest, BaseOpenAPIResponse\n\n\nclass MockRequest(BaseOpenAPIRequest):\n\n def __init__(\n self, host_url, method, path, path_pattern=None, args=None,\n view_args=None, headers=None, cookies=None, data=None,\n mimetype='application/json'):\n self.host_url = host_url\n self.path = path\n self.path_pattern = path_pattern or path\n self.method = method.lower()\n\n self.parameters = {\n 'path': view_args or {},\n 'query': ImmutableMultiDict(args or []),\n 'header': headers or {},\n 'cookie': cookies or {},\n }\n\n self.body = data or ''\n\n self.mimetype = mimetype\n\n\nclass MockResponse(BaseOpenAPIResponse):\n\n def __init__(self, data, status_code=200, mimetype='application/json'):\n self.data = data\n\n self.status_code = status_code\n self.mimetype = mimetype\n","sub_path":"openapi_core/wrappers/mock.py","file_name":"mock.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"39248555","text":"import fullscreen\n\nfrom kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.uix.modalview import ModalView\nfrom kivy.uix.button import Button\nfrom kivy.uix.anchorlayout import AnchorLayout\nfrom kivy.core.window import Window\n\nfrom kivy.garden.iconfonts import *\n\nimport os\nfrom os.path import join, dirname\n\n\nclass ViewImage(ModalView):\n pass\n\n\nclass TestWindow(BoxLayout):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n self.images = self.get_imgs('img')\n self.imgs_show(self.images)\n\n def get_imgs(self, img_path):\n if not os.path.exists(img_path):\n print('invalid path')\n return -1\n else:\n all_file = os.listdir(img_path)\n imgs = []\n for f in all_file:\n if f.endswith('.png') or f.endswith('.jpg'):\n imgs.append('/'.join([img_path, f]))\n return imgs\n\n def imgs_show(self, imgs):\n base = self.ids.img_base\n base_data = []\n for img in imgs:\n im_name = img[img.rfind('/')+1:]\n if len(im_name) > 20:\n im_name = im_name[:18] + '...'\n base_data.append({'im_source': img, 'im_caption': im_name})\n base.data = base_data\n\n def get_image(self, im_path):\n self.ids.img_base.data = []\n self.images = [im_path]\n self.imgs_show(self.images)\n self.ids.scrn_mngr.current = 'scrn_media'\n self.ids.open_media.trigger = ''\n\n def get_folder(self, im_path):\n print(im_path)\n self.ids.img_base.data = []\n self.images = self.get_imgs(im_path)\n self.imgs_show(self.images)\n self.ids.scrn_mngr.current = 'scrn_media'\n\n def img_resize(self, img):\n im_size_x, im_size_y = img.texture_size\n ratio = im_size_x/im_size_y\n aspect = self.aspect_ratio(ratio, 50)\n\n while im_size_x >= Window.width or im_size_y >= Window.height:\n if im_size_x > im_size_y:\n im_size_x -= aspect[0]\n im_size_y -= aspect[1]\n else:\n im_size_y -= aspect[1]\n return [im_size_x, im_size_y]\n\n def aspect_ratio(self, val, lim):\n lower = [0, 1]\n upper = [1, 0]\n\n while True:\n mediant = [lower[0] + upper[0], lower[1] + upper[1]]\n\n if (val * mediant[1] > mediant[0]):\n if (lim < mediant[1]):\n return upper\n lower = mediant\n elif (val * mediant[1] == mediant[0]):\n if (lim >= mediant[1]):\n return mediant\n\n if (lower[1] < upper[1]):\n return lower\n\n return upper\n else:\n if (lim < mediant[1]):\n return lower\n upper = mediant\n\n def prev_im(self, inst):\n images = self.images\n cur_idx = None\n last_idx = len(images) - 1\n view_children = inst.parent.parent.parent.children\n cur_img = None\n image_container = None\n\n for child in view_children:\n if str(child).find('BoxLayout') > -1:\n image_container = child.children[0]\n cur_img = image_container.source\n for i, img in enumerate(images):\n if img == cur_img:\n cur_idx = i\n if cur_idx != 0:\n prev_img = images[cur_idx - 1]\n else:\n prev_img = images[last_idx]\n\n image_container.source = prev_img\n\n def next_im(self, inst):\n images = self.images\n cur_idx = None\n last_idx = len(images) - 1\n view_children = inst.parent.parent.parent.children\n cur_img = None\n image_container = None\n\n for child in view_children:\n if str(child).find('BoxLayout') > -1:\n image_container = child.children[0]\n cur_img = image_container.source\n\n for i, img in enumerate(images):\n if img == cur_img:\n cur_idx = i\n if cur_idx != last_idx:\n nxt_img = images[cur_idx + 1]\n else:\n nxt_img = images[0]\n\n image_container.source = nxt_img\n\n def viewimg(self, instance):\n im = Image(source=instance.im_source)\n view_size = self.img_resize(im)\n\n btn_prev = Button(text='%s'%(icon('zmdi-caret-left', 24)), markup=True)\n btn_prev.bind(on_release=self.prev_im)\n btn_rename = Button(text='%s'%(icon('zmdi-file', 24)), markup=True)\n btn_effects = Button(text='%s'%(icon('zmdi-blur-linear', 24)), markup=True)\n btn_next = Button(text='%s'%(icon('zmdi-caret-right', 24)), markup=True)\n btn_next.bind(on_release=self.next_im)\n\n image_ops = BoxLayout(size_hint=(None, None), size=(200, 30), spacing=4)\n\n image_ops.add_widget(btn_prev)\n image_ops.add_widget(btn_rename)\n image_ops.add_widget(btn_effects)\n image_ops.add_widget(btn_next)\n\n anchor = AnchorLayout(anchor_x='center', anchor_y='bottom')\n anchor.add_widget(image_ops)\n\n image_container = BoxLayout()\n\n view = ViewImage(size_hint=(None, None), size=view_size)\n image_container.add_widget(im)\n\n view.add_widget(image_container)\n view.add_widget(anchor)\n\n view.open()\n\n\nclass TestApp(App):\n def build(self):\n return TestWindow()\n\n\nif __name__ == \"__main__\":\n register('default_font', './assets/fonts/Material-Design-Iconic-Font.ttf', join(dirname(__file__), 'assets/fonts/zmd.fontd'))\n TestApp().run()\n","sub_path":"folder_test.py","file_name":"folder_test.py","file_ext":"py","file_size_in_byte":5622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"7174990","text":"#!/usr/bin/python3\nimport random\nimport urllib.request\nimport urllib.parse\nimport concurrent.futures\nfrom sys import exit\nfrom subprocess import check_call, CalledProcessError\n\nfit_home = 'http://binf1.memphis.edu/fitkids/'\nfit_tools = fit_home +'tools/'\ncache_dir = '/tmp/'\n\n# fitkids tools\nbmi_calcu = fit_tools + 'bmi_calculator/'\nassessment = fit_tools + 'fit_assessment/'\nmapit = fit_home + 'gis/'\ntagita = fit_tools + 'tagita/'\n\n# if a certain page is up\ndef ping_page(pageurl):\n try:\n response = urllib.request.urlopen(pageurl)\n return (True, None)\n except urllib.error.URLError as urlexception:\n return (False, urlexception.reason)\n\n# get a page cache\ndef curl_get(pageurl, cache_filename):\n curl_cmd = 'curl {} -s -o {}'.format(pageurl, cache_dir + cache_filename)\n try:\n check_call(curl_cmd.split())\n except CalledProcessError as curlerror:\n print (curlerror)\n exit(1)\n\ndef curl_post(pageurl, data, cache_filename):\n curl_cmd = 'curl --data {} {} -s -o {}'.format(data, pageurl, cache_filename)\n try:\n check_call(curl_cmd.split())\n except CalledProcessError as curlerror:\n print (curlerror)\n exit(1)\n\n# tool testing funcs\ndef test_bmi(tool_url):\n # entries in POST\n class bmi_POST:\n # append result generating script name\n entry_names = ['weight', 'height', 'age', 'gender', 'childname']\n def __init__(self):\n # 0+\n self.weight = 0\n # 0+\n self.height = 0\n # 3-20\n self.age = 0\n #'boy' 'girl'\n self.gender = None\n self.childname = 'binfbot'\n self.entries = {}\n\n def print_entries(self):\n print ('\\n')\n for entry in self.entries.items():\n print (entry)\n\n def fill_values(self):\n self.weight = random.randint(1, 300)\n self.height = random.randint(1, 100)\n self.age = random.randint(3, 20)\n self.gender = random.choice(['boy', 'girl'])\n self.entries = {'weight':self.weight, 'height':self.height, 'age':self.age, 'childname':self.childname}\n\n # generate post data\n post = bmi_POST()\n post.fill_values()\n post.print_entries()\n\n # post it and cache the result\n query_data = urllib.parse.urlencode(post.entries)\n result_page = tool_url + 'results.php'\n cache_name = cache_dir + 'fitkids_bmi_testcache.html'\n curl_post(result_page, query_data, cache_name)\n \n # TODO parse result and match with data posted\n\n\n\ndef test_assessment(tool_url):\n # entries in POST\n class fit_POST:\n entry_names = ['weight', 'height', 'age', 'gender', 'breakfast', 'fastfood', 'familyeat', 'childdrink', 'childdairy', 'milktype', 'fruit', 'sports', 'tv', 'active', 'bedroom', 'wakeup', 'mama_bear', 'childname']\n def __init__(self):\n self.weight = 0\n self.height = 0\n self.age = 0\n self.gender = None\n self.breakfast = 0\n self.fastfood = 0\n self.familyeat = 0\n self.childdrink = None\n self.childdairy = 0\n self.milktype = None\n self.fruit = None\n self.sports = 0\n self.tv = 0\n self.active = 0\n self.bedroom = None\n self.bedtime = 0\n self.wakeup = 0\n self.mama_bear = None\n self.childname = 'binfbot'\n self.entries = {}\n \n def fill_values(self):\n # 0+\n # 0+\n # 3-20\n #'boy' 'girl'\n # 0-7\n # 0:0-1, 1:2-4, else: 5+\n # 0+\n # 'yes' 'no'\n # 0+\n # 'skim' '1%' '2%' 'whole' 'none' else: non-dairy \n # 'yes' 'no'\n # 0:0-30, 1:30-60, else:60+\n # 0:0-2, else:3+\n # 0-7\n # 'yes' 'no'\n # -5-3\n # 5-10\n self.weight = random.randint(1, 300)\n self.height = random.randint(1, 100)\n self.age = random.randint(3, 20)\n self.gender = random.choice(['boy', 'girl'])\n self.breakfast = random.randint(0, 7)\n self.fastfood = random.randint(0, 2)\n self.familyeat = random.randint(0, 21)\n self.childdrink = random.choice(['yes','no'])\n self.childdairy = random.randint(0, 20)\n self.milktype = random.choice(['skim','1%','2%','whole','none'])\n self.fruit = random.choice(['yes', 'no'])\n self.sports = random.randint(0, 2)\n self.tv = random.randint(0, 1)\n self.active = random.randint(0, 7)\n self.bedroom = random.choice(['yes', 'no'])\n self.bedtime = random.randint(-5, 3)\n self.wakeup = random.randint(5, 10)\n self.entries = {'weight':self.weight, 'height':self.height, 'age':self.age, 'gender':self.gender, 'breakfast':self.breakfast, 'fastfood':self.fastfood, 'familyeat':self.familyeat, 'childdrink':self.childdrink, 'childdairy':self.childdairy, 'milktype':self.milktype, 'fruit':self.fruit, 'sports':self.sports, 'tv':self.tv, 'active':self.active, 'bedroom':self.bedroom, 'bedtime':self.bedtime,'wakeup':self.wakeup, 'mama_bear':self.mama_bear, 'childname':self.childname}\n\n def print_entries(self):\n print ('\\n')\n for entry in self.entries.items():\n print (entry)\n\n # generate post data\n post = fit_POST()\n post.fill_values()\n post.print_entries()\n\n # post it and cache the result\n query_data = urllib.parse.urlencode(post.entries)\n result_page = tool_url + 'results.php'\n cache_name = cache_dir + 'fitkids_assessment_testcache.html'\n curl_post(result_page, query_data, cache_name)\n \n # TODO parse result and match with data posted\n\ndef test_mapit(tool_url):\n pass\n\ndef test_tagita(tool_url):\n pass\n\n# organize tool testing funcs\nclass tool_tester:\n def __init__(self):\n self.tools = [bmi_calcu, assessment]\n self.tests = [test_bmi, test_assessment]\n # key: tool_url, value: test_func\n self.suites = { k:v for (k,v) in zip(self.tools, self.tests)}\n\n def run_test(self, tool_url):\n test_func = self.suites[tool_url]\n test_func(tool_url)\n\n def run_all_tests(self):\n with concurrent.futures.ThreadPoolExecutor(max_workers=len(self.tools)) as tester:\n # a dictionary where key: func exectution, value: func args\n futures = dict( (tester.submit(v, k), k) for k, v in self.suites.items() )\n\n for future in concurrent.futures.as_completed(futures):\n tool_url = futures[future]\n if future.exception() is not None:\n print ('Exception %s when testing %s' % (future.exception(), tool_url))\n else:\n print ('Test finish on %s' % tool_url)\n\n\n# test user register and login\nclass account_tester:\n def __init__(self):\n pass\n\nif __name__=='__main__':\n #result = ping_page(fit_home)\n #print (result)\n #curl_get(fit_home, 'fitkids_testcache.html')\n \n toolbot = tool_tester()\n toolbot.run_all_tests()\n\n #for tool in toolbot.tools:\n # toolbot.run_test(tool)\n\n #for suite in toolbot.suites.items():\n # print (suite)\n #test_bmi(bmi_calcu)\n #test_assessment(assessment)\n\n","sub_path":"test_fitkids/draft/testfitkids.py","file_name":"testfitkids.py","file_ext":"py","file_size_in_byte":7418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"123892406","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 5 14:10:04 2020\n\n@author: tonedogga\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport os\nfrom pathlib import Path\nfrom p_tqdm import p_map,p_umap\n\nimport pyglet\nfrom pyglet import clock\nfrom pyglet import gl\nfrom pyglet.gl import *\n\nfrom pyglet.window import key\nfrom pyglet.window import mouse\n\nfrom pyglet import shapes\n\n\n\n#from time import time\n\nMY_DEBUG=True #False\nBUTTON_LIST=[]\n#BUTTON_COLOR=(200,100,200)\n#global batch\n\n\n#########################################################################################################################\n\n\n\n\nclass QueryWindow(pyglet.window.Window):\n def __init__(self,*args,**kwargs):\n # super(MyWindow,self).__init__(*args,**kwargs)\n super(QueryWindow,self).__init__(*args,**kwargs)\n \n #set window size\n self.set_minimum_size(700,700)\n self.set_maximum_size(2048, 2048)\n \n # get window size\n self.x_max=self.get_size()[0]\n self.y_max=self.get_size()[1]\n\n # draw_buttons_to_batch()\n \n #print(self.get_size())\n \n # get window location\n #x, y = window.get_location()\n #window.set_location(x + 20, y + 20) \n \n # button_list is global \n \n # buttons=get_button_details()\n \n \n \n def on_key_press(self, symbol, modifiers):\n if symbol == key.A:\n if MY_DEBUG:\n # print('The \"A\" key was pressed.')\n text='The \"A\" key was pressed.'\n _display_text_in_active_window(text)\n # self.window.set_visible()\n elif symbol == key.LEFT:\n if MY_DEBUG:\n text='The left arrow key was pressed.'\n# print('The left arrow key was pressed.')\n _display_text_in_active_window(text)\n elif symbol == key.ENTER:\n if MY_DEBUG:\n text='The enter key was pressed.'\n # print('The enter key was pressed.')\n _display_text_in_active_window(text)\n\n \n \n \n def on_key_release(self, symbol, modifiers):\n pass\n \n \n def on_mouse_enter(self,x, y):\n pass\n\n def on_mouse_leave(self,x, y):\n pass\n \n def on_mouse_motion(self,x, y, dx, dy):\n # fps_display.draw()\n # batch=check_for_collisions(x,y)\n move_and_draw_pointer(x,y,dx,dy)\n \n def on_mouse_press(self,x,y,button, modifiers):\n if button == mouse.LEFT:\n # canvas={}\n # print('The left mouse button was pressed. x=',x,\"y=\",y)\n # batch=_check_for_collisions(x,y,batch)\n # if MY_DEBUG:\n # text=\"the left mouse button was pressed. x=\"+str(x)+\" y=\"+str(y)\n # _display_text_in_active_window(text)\n for b in BUTTON_LIST:\n if (b.active & b.visible & (x>=b.x_start) & (x<(b.x_start+b.x_len)) & (y>=b.y_start) & (y<(b.y_start+b.y_len))):\n b.pushed=not b.pushed\n #batch=display_buttons(batch) \n\n\n\n\n elif button == mouse.RIGHT:\n # print('The right mouse button was pressed.')\n if MY_DEBUG:\n text=\"the right mouse button was pressed. x=\"+str(x)+\" y=\"+str(y)\n\n _display_text_in_active_window(text)\n \n \n \n def on_mouse_release(self,x, y, button, modifiers):\n pass\n\n\n def on_mouse_drag(self,x, y, dx, dy, buttons, modifiers):\n if buttons & mouse.LEFT:\n if MY_DEBUG:\n text=\"mouse drag left x,y,dx,dy\"+str(x)+\" \"+str(y)+\" \"+str(dx)+\" \"+str(dy)\n _display_text_in_active_window(text)\n # print(text)\n elif buttons & mouse.RIGHT:\n if MY_DEBUG:\n text=\"mouse drag right x,y,dx,dy\"+str(x)+\" \"+str(y)+\" \"+str(dx)+\" \"+str(dy)\n _display_text_in_active_window(text)\n # print(text)\n \n \n\n \n def on_mouse_scroll(self,x, y, scroll_x, scroll_y):\n if MY_DEBUG:\n text=\"mouse scroll x,y,scroll_x,scroll_y\"+str(x)+\" \"+str(y)+\" \"+str(scroll_x)+\" \"+str(scroll_y)\n _display_text_in_active_window(text)\n\n \n \n\n def on_draw(self): \n #self.clear()\n \n draw_buttons()\n # check_for_collisions(x,y)\n pass\n \n \n \n # def on_resize(self,width, height):\n # print('The window was resized to %dx%d' % (width, height))\n # display = pyglet.canvas.Display()\n # screen = display.get_default_screen()\n # self.screen_width = screen.width\n # self.screen_height = screen.height\n\n # self.clear()\n # pass\n \n def update(self,dt):\n # display_buttons()\n #draw_batch(x,y,dx,dy)\n # window.clear()\n pass\n\n \n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nclass sales_trans(object):\n def __init__(self):\n self.sales_df_dict={\n \"cat\":True,\n \"code\":True,\n \"costval\":False,\n \"doctype\":False,\n \"docentryno\":False,\n \"linenumber\":False,\n \"location\":True,\n \"product\":True,\n \"productgroup\":True,\n \"qty\":False,\n \"refer\":False,\n \"salesrep\":True,\n \"saleval\":False,\n \"territory\":False,\n \"date\":False,\n \"glset\":True,\n \"specialpricecat\":True,\n \"period\":False}\n \n \n def load_pickle(self,save_dir,savefile):\n # os.makedirs(save_dir, exist_ok=True)\n my_file = Path(save_dir+savefile)\n if my_file.is_file():\n return pd.read_pickle(save_dir+savefile)\n else:\n print(\"load sales_df error.\")\n return\n \n \n\n def find_uniques(self,sales_df):\n unique_dict={}\n for k,v in self.sales_df_dict.items():\n if v:\n unique_dict[k]=sorted(pd.Series(sales_df[k]).astype(str).unique())\n \n return unique_dict\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nconfig = pyglet.gl.Config(double_buffer=True) \nwindow = QueryWindow(1200,1200,resizable=False,caption=\"Salestrans Queries\",config=config,visible=True)\n#canvas={}\n#batch = pyglet.graphics.Batch()\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# define and make live areas on window as pushable buttons\n\nclass query_window_object(object):\n def __init__():\n pass\n\n\n\nclass button_object(query_window_object):\n def __init__(self,*,name,x_start,x_len,y_start,y_len,colour,pushed_colour,title,active,visible,pushed,toggle,unique_list):\n # super().__init__()\n self.name=name\n self.x_start=x_start\n self.x_len=x_len\n self.y_start=y_start\n self.y_len=y_len\n self.colour=colour\n self.inactive_colour=(40,50,60)\n self.pushed_colour=pushed_colour\n self.title=title\n self.active=active\n self.visible=visible\n self.pushed=pushed\n self.toggle=toggle\n self.unique_list=unique_list\n # self.button_array=button_array\n # self.button_df=button_df.copy()\n \n \n \nclass buttons(object):\n def setup_buttons(self,filename,sales_df_dict,unique_dict):\n bdf=pd.read_csv(filename,index_col=False,header=0)\n \n for index, row in bdf.iterrows():\n colour=(int(row['colour1']),int(row['colour2']),int(row['colour3']))\n pushed_colour=(int(row['pcolour1']),int(row['pcolour2']),int(row['pcolour3']))\n button=button_object(name=str(row['name']),x_start=int(row['x_start']),x_len=int(row['x_len']),y_start=int(row['y_start']),y_len=int(row['y_len']),colour=colour,pushed_colour=pushed_colour,title=str(row['title']),active=bool(row['active']),visible=bool(row['visible']),pushed=bool(row['pushed']),toggle=bool(row['toggle']),unique_list=[]) \n BUTTON_LIST.append(button)\n \n x_start=0 \n y_start=990\n for fields,values in sales_df_dict.items():\n if values:\n colour=(200,200,200) #int(row['colour1']),int(row['colour2']),int(row['colour3']))\n pushed_colour=(100,100,100) #int(row['pcolour1']),int(row['pcolour2']),int(row['pcolour3']))\n button=button_object(name=str(fields),x_start=x_start,x_len=10,y_start=y_start,y_len=30,colour=colour,pushed_colour=pushed_colour,title=str(fields),active=True,visible=True,pushed=False,toggle=True,unique_list=unique_dict[fields]) \n x_start+=50\n y_start-=10\n BUTTON_LIST.append(button)\n \n self._resize_buttons(window.x_max,window.y_max)\n \n return BUTTON_LIST\n \n \n \n def _resize_buttons(self,x_max,y_max):\n # batch = pyglet.graphics.Batch()\n for button in BUTTON_LIST: \n if button.x_start<0:\n button.x_start=0\n if button.x_start>x_max:\n button.x_start=x_max\n if button.y_start<0:\n button.y_start=0\n if button.y_start>y_max:\n button.y_start=y_max\n \n \n if button.x_len<0:\n button.x_len=0\n if button.x_len>x_max:\n button.x_len=x_max\n if button.y_len<0:\n button.y_len=0\n if button.y_len>y_max:\n button.y_len=y_max\n \n \n if button.x_start+button.x_len>x_max:\n button.x_len=x_max-button.x_start\n \n if button.y_start+button.y_len>y_max:\n button.y_len=y_max-button.y_start\n\n \n \n \n \n#-------------------------------------------------------------------------------------------------------------------------\n\n\n\ndef check_for_collisions(x,y):\n # print(\"button object check for collissions\",x,y)\n # if x,y is over any button display on screen\n # button list is global\n# over_button=[]\n batch = pyglet.graphics.Batch()\n# batch=p_map(_check_button,BUTTON_LIST)\n for b in BUTTON_LIST:\n #b.active\n if (b.visible & b.active & (x>=b.x_start) & (x<(b.x_start+b.x_len)) & (y>=b.y_start) & (y<(b.y_start+b.y_len))):\n# position_text_in_active_window(b.name+\"\\nActive=\"+str(b.active)+\"\\nVisible=\"+str(b.visible)+\" Pushed=\"+str(b.pushed)+\" list=\"+str(b.unique_list),x=x,y=y)\n position_text_in_active_window(b.name+\"\\nActive=\"+str(b.active)+\"\\nVisible=\"+str(b.visible)+\" Pushed=\"+str(b.pushed),x=x,y=y)\n\n # over_button.append(True)\n # else:\n # over_button.append(False)\n # print(\"button cooll\",b.name,x,y)\n batch.draw() \n # return batch \n # return any(over_button),batch \n \n#def _check_button(b):\n# if (b.visible & b.active & (x>=b.x_start) & (x<(b.x_start+b.x_len)) & (y>=b.y_start) & (y<(b.y_start+b.y_len))):\n# position_text_in_active_window(b.name+\"\\nActive=\"+str(b.active)+\"\\nVisible=\"+str(b.visible)+\" Pushed=\"+str(b.pushed)+\" len=\"+str(b.unique_list_len),x=x,y=y)\n# return batch\n\n\n \ndef draw_buttons():\n batch = pyglet.graphics.Batch()\n for b in BUTTON_LIST:\n if b.visible:\n batch=_draw_button(b,batch)\n batch.draw() \n #return batch \n\n\n \n \n \n \ndef _draw_button(button,batch): \n if button.active:\n position_text_in_active_window(button.title,x=button.x_start+10,y=button.y_start+button.y_len-20)\n if not button.pushed:\n # batch=_draw_rect(button.x_start,button.x_len,button.y_start,button.y_len,colour=button.colour,batch=batch)\n _draw_solid_rect(button.x_start,button.y_start,button.x_len,button.y_len,colour=button.colour,batch=batch)\n\n else: \n # batch=_draw_rect(button.x_start,button.x_len,button.y_start,button.y_len,colour=button.pushed_colour,batch=batch)\n _draw_solid_rect(button.x_start,button.y_start,button.x_len,button.y_len,colour=button.pushed_colour,batch=batch)\n \n else:\n # batch=_draw_rect(button.x_start,button.x_len,button.y_start,button.y_len,colour=button.inactive_colour,batch=batch) \n _draw_solid_rect(button.x_start,button.y_start,button.x_len,button.y_len,colour=button.inactive_colour,batch=batch) \n return batch \n \n \n \n \ndef _draw_rect(x,x_len,y,y_len,colour,batch):\n final_colour=colour+colour\n # print(\"final colour=\",final_colour)\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x, y, x+x_len, y)), \n ('c3B', final_colour)\n )\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x+x_len, y, x+x_len, y+y_len)), \n ('c3B', final_colour)\n )\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x+x_len, y+y_len, x, y+y_len)), \n ('c3B', final_colour)\n )\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x, y+y_len, x, y)), \n ('c3B', final_colour)\n )\n \n # batch.add(4, GL_QUADS, None, 'v2f', 't2f')\n # batch.add(4, pyglet.gl.GL_RECTS, None,\n # ('v2i', (x, y, x+x_len, y)), \n # ('t2i', (x,y+y_len, x+x_len,y+y_len))\n \n # )\n # batch.add(2, pyglet.gl.GL_LINES, None,\n # ('v2i', (x+x_len, y, x+x_len, y+y_len)), \n # ('c3B', final_colour)\n # )\n # batch.add(2, pyglet.gl.GL_LINES, None,\n # ('v2i', (x+x_len, y+y_len, x, y+y_len)), \n # ('c3B', final_colour)\n # )\n # batch.add(2, pyglet.gl.GL_LINES, None,\n # ('v2i', (x, y+y_len, x, y)), \n # ('c3B', final_colour)\n # )\n \n return batch\n \n \n \n \n \n \ndef _draw_solid_rect(x,y,x_len,y_len,colour,batch):\n # final_colour=colour+colour\n \n \n rectangle = shapes.Rectangle(x, y, x_len, y_len, color=colour, batch=batch)\n rectangle.opacity = 128\n rectangle.rotation = 0\n \n batch.draw()\n# # print(\"final colour=\",final_colour)\n \n \n# # circle = shapes.Circle(700, 150, 100, color=(50, 225, 30), batch=batch)\n# square = shapes.Rectangle(200, 200, 200, 200, color=(55, 55, 255), batch=batch)\n# rectangle = shapes.Rectangle(250, 300, 400, 200, color=(255, 22, 20), batch=batch)\n# rectangle.opacity = 128\n# rectangle.rotation = 33\n# line = shapes.Line(100, 100, 100, 200, width=19, batch=batch)\n# line2 = shapes.Line(150, 150, 444, 111, width=4, color=(200, 20, 20), batch=batch)\n \n \n \n \n# def draw_pointers(x,y):\n# batch = pyglet.graphics.Batch()\n# batch.add(2, pyglet.gl.GL_LINES, None,\n# ('v2i', (0, 0, x, y)), \n# ('c3B', (255, 0, 0, 255, 255, 255))\n# )\n \n# batch.add(2, pyglet.gl.GL_LINES, None,\n# ('v2i', (0, window.get_size()[1], x, y)), \n# ('c3B', (0, 255, 0, 255, 255, 255))\n# )\n \n# batch.add(2, pyglet.gl.GL_LINES, None,\n# ('v2i', (window.get_size()[0],0, x, y)), \n# ('c3B', (0, 0, 255, 255, 255, 255))\n# )\n\n# batch.add(2, pyglet.gl.GL_LINES, None,\n# ('v2i', (window.get_size()[0], window.get_size()[1], x, y)), \n# ('c3B', (60, 70, 20, 255, 255, 255))\n# )\n# batch.draw() \n# # return batch \n \n \n \ndef draw_pointers(x,y,x_max,y_max):\n batch = pyglet.graphics.Batch()\n # batch.add(2, pyglet.gl.GL_LINES, None,\n # ('v2i', (0, 0, x, y,0,y_max)),\n # ('v2i', (x_max,0, x, y,x_max,y_max)), \n # ('c3B', (255, 0, 0, 255, 255, 255))\n # )\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (0, 0, x, y)), \n ('c3B', (255, 0, 0, 255, 255, 255))\n )\n\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (0, y_max, x, y)), \n ('c3B', (0, 255, 0, 255, 255, 255))\n )\n \n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x_max,0, x, y)), \n ('c3B', (0, 0, 255, 255, 255, 255))\n )\n\n batch.add(2, pyglet.gl.GL_LINES, None,\n ('v2i', (x_max, y_max, x, y)), \n ('c3B', (60, 70, 20, 255, 255, 255))\n )\n batch.draw() \n # return batch \n \n \n \n \n \n \n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ \n\n\n \n\ndef position_text_in_active_window(text,*,x,y):\n batch = pyglet.graphics.Batch()\n # canvas={}\n # canvas[1] = pyglet.text.Label(text, x=x, y=y, batch=batch)\n pyglet.text.Label(text, x=x, y=y, batch=batch)\n batch.draw()\n # return batch\n\n\n\ndef _display_text_in_active_window(text):\n batch = pyglet.graphics.Batch()\n # canvas={}\n # canvas[1] = pyglet.text.Label(text, x=x, y=y, batch=batch)\n pyglet.text.Label(text, x=5, y=window.get_size()[1]-12, batch=batch)\n # window.clear()\n batch.draw()\n \n\n\n\ndef move_and_draw_pointer(x,y,dx,dy):\n \n # batch = pyglet.graphics.Batch()\n window.clear()\n # draw_buttons()\n draw_pointers(x,y,window.x_max,window.y_max)\n check_for_collisions(x,y)\n clock.tick()\n if MY_DEBUG:\n position_text_in_active_window(\"fps=\"+str(int(clock.get_fps()))+\" size=\"+str(window.get_size())+\" loc=\"+str(window.get_location())+\" Pos=(\"+str(x)+\",\"+str(y)+\") dx=(\"+str(dx)+\",\"+str(dy)+\")\",x=0,y=5)\n # batch=draw_buttons_to_batch(x_max=window.x_max,y_max=window.y_max,batch=batch)\n # window.clear()\n # batch.draw() \n # for index in list(canvas):\n # canvas[index].delete()\n # del(canvas[index])\n\n\n#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n\ndef main():\n os.chdir(\"/home/tonedogga/Documents/python_dev\")\n st=sales_trans()\n sales_df=st.load_pickle(\"./dash2_saves/\",\"raw_savefile.pkl\")\n # print(sales_df.info(),sales_df.shape)\n unique_dict=st.find_uniques(sales_df)\n # print(\"unuqie dict\",unique_dict)\n \n \n b=buttons()\n BUTTON_LIST=b.setup_buttons('./dash2/buttons.csv',st.sales_df_dict,unique_dict)\n # print(\"button_list length=\",len(BUTTON_LIST))\n # batch = pyglet.graphics.Batch()\n # batch=display_buttons(batch)\n # window.clear()\n # batch.draw()\n\n pyglet.app.run()\n window.close()\n\n\nmain()\n\n\n #x, y = window.get_location()\n #window.set_location(x + 20, y + 20)\n \n \n #window = MyWindow(1200,1200,resizable=True,caption=\"Queries\",visible=True)\n \n #pyglet.clock.schedule_interval(draw_batch, 1.0/60.0)\n #window.switch_to()\n # signify that one frame has passed\n #pyglet.clock.tick()\n # poll the operating system event queue\n #window.dispatch_events()\n \n # getting window size \n #value = window.get_size() \n #window.activate() \n \n\n \n \n ","sub_path":"pyglet_queries2.py","file_name":"pyglet_queries2.py","file_ext":"py","file_size_in_byte":19705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"383378145","text":"import os\nimport tensorflow as tf\nimport numpy as np\nimport data_helpers\nimport gensim\nfrom gensim.models.word2vec import Word2Vec\n\nprint(\"Loading data...\")\nx_text, y = data_helpers.load_data_and_labels(\"./data/rt-polaritydata/rt-polarity.pos\", \"./data/rt-polaritydata/rt-polarity.neg\")\n#w2vec_model = Word2Vec.load('./data/GoogleNews-vectors-negative300.bin')\nw2vec_model = gensim.models.KeyedVectors.load_word2vec_format('./data/GoogleNews-vectors-negative300.bin', binary=True)\nembedding_size = w2vec_model.vector_size\nsequence_length = max([len(x.split(\" \")) for x in x_text])\nnum_classes = 2\n\nx = np.zeros((len(x_text), sequence_length, embedding_size), dtype=float)\nfor i,xi in enumerate(x_text):\n tokens = xi.split(' ')\n for j,token in enumerate(tokens):\n if token in w2vec_model.vocab:\n x[i,j] = w2vec_model[token]\n\n# Randomly shuffle data\nnp.random.seed(10)\nshuffle_indices = np.random.permutation(np.arange(len(y)))\nx_shuffled = x[shuffle_indices]\ny_shuffled = y[shuffle_indices]\n\n# Split train/test set\ndev_sample_index = -1 * int(.1 * float(len(y)))\nx_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\ny_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\n\ndel x, y, x_shuffled, y_shuffled, w2vec_model\n\nprint(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\n\n\n######################## TensorFlow Graph 구성\n\n# 값 초기화\n\nfilter_sizes = [3,4,5]\nnum_filters = 8\ndropout_keep_prob = 0.5\nnum_epoch = 30\nbatch_size = 100\n\n# X, Y 정의\ninput_x = tf.placeholder(tf.float32, [None, sequence_length, embedding_size], name='input_x')\ninput_y = tf.placeholder(tf.float32, [None, num_classes], name=\"input_y\")\n\n\nextended_input_x = tf.expand_dims(input_x, -1)\n\n# Convolution and Max-Pooling\npooled_outputs = []\nfor i, filter_size in enumerate(filter_sizes):\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n W_c = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name=\"W_c\")\n conv = tf.nn.conv2d(\n extended_input_x,\n W_c,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\")\n h = tf.nn.relu(conv, name=\"relu_c\")\n pooled = tf.nn.max_pool(\n h,\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding='VALID',\n name=\"pool\")\n pooled_outputs.append(pooled)\n\n# Flatten and Dropout\nnum_filters_total = num_filters * len(filter_sizes)\nh_pool = tf.concat(pooled_outputs, 3)\nh_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])\nh_drop = tf.nn.dropout(h_pool_flat, dropout_keep_prob)\n\n# Final Fully Connected Layer\nW_f = tf.get_variable(\n \"W_f\",\n shape=[num_filters_total, num_classes],\n initializer=tf.contrib.layers.xavier_initializer())\nb_f = tf.Variable(tf.constant(0.1, shape=[num_classes]), name=\"b_f\")\nscores = tf.nn.xw_plus_b(h_drop, W_f, b_f, name=\"scores\")\npredictions = tf.argmax(scores, 1, name=\"predictions\")\n\n#loss\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=scores, labels=input_y))\n\n#accuracy\ncorrect_predictions = tf.equal(predictions, tf.argmax(input_y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_predictions, \"float\"))\n\n#optimizer\noptimizer = tf.train.AdamOptimizer(1e-3).minimize(loss)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\ntotal_len = len(x_train)\nfor epoch in range(num_epoch):\n avg_loss = 0\n avg_acc = 0\n total_batch = int(total_len/batch_size)\n for i in range(total_batch):\n st = i*batch_size\n en = min((i+1)*batch_size,total_len)\n\n batch_xs = x_train[st:en]\n batch_ys = y_train[st:en]\n\n feed_dict = {input_x:batch_xs, input_y:batch_ys}\n\n acc, l, _ = sess.run([accuracy,loss, optimizer], feed_dict=feed_dict)\n\n avg_loss += l / total_batch\n avg_acc += acc / total_batch\n\n print('Epoch:', '%03d' % (epoch + 1), 'loss =', '{:.6f}'.format(avg_loss), 'accuracy =', '{:.6f}'.format(avg_acc))\n\nfeed_dict = {input_x:x_dev, input_y:y_dev}\n\nacc = sess.run(accuracy, feed_dict=feed_dict)\nprint ('Test Accuraacy : ', acc)","sub_path":"simple_cnn.py","file_name":"simple_cnn.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"86410921","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.linux-x86_64/egg/djutils/json_utils.py\n# Compiled at: 2015-06-22 10:37:13\nimport json\nfrom collections import OrderedDict\nfrom django.forms import model_to_dict\nfrom django.core.serializers.json import DjangoJSONEncoder\n\ndef object_to_json(obj, indent=2):\n \"\"\"\n transform object to json\n \"\"\"\n instance_json = json.dumps(obj, indent=indent, ensure_ascii=False, cls=DjangoJSONEncoder)\n return instance_json\n\n\ndef model_to_json(model_instance):\n \"\"\"\n transform instance to json\n \"\"\"\n instance_dict = model_to_dict(model_instance)\n return object_to_json(instance_dict)\n\n\ndef qs_to_json(qs, fields=None):\n \"\"\"\n transform QuerySet to json\n \"\"\"\n if not fields:\n fields = [ f.name for f in qs.model._meta.fields ]\n objects = []\n for value_dict in qs.values(*fields):\n o = OrderedDict()\n for f in fields:\n o[f] = value_dict[f]\n\n objects.append(o)\n\n json_qs = json.dumps(objects, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)\n return json_qs\n\n\ndef mongoqs_to_json(qs, fields=None):\n \"\"\"\n transform mongoengine.QuerySet to json\n \"\"\"\n l = list(qs.as_pymongo())\n for element in l:\n element.pop('_cls')\n\n json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)\n return json_qs","sub_path":"pycfiles/sw_django_utils-0.0.50-py2.7/json_utils.py","file_name":"json_utils.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"448480678","text":"from setuptools import setup\n\npackage = \"pycassos\"\nversion = \"0.0.1\"\n\nsetup(name = package,\n version = version,\n description=\"Python Caviar Solutions Software suite\",\n url='https://github.com/dicaso/pycassos',\n author = 'Christophe Van Neste',\n author_email = 'christophe.vanneste@ugent.be',\n license = 'MIT',\n packages = ['pycassos'],\n python_requires='>3.6',\n install_requires = [\n # dicaso packages\n 'leopard',\n 'genairics',\n 'bidali[retro]',\n 'pyni',\n # console packages\n 'ipython',\n # server packages\n 'flask',\n 'flask-login',\n 'flask-jsonpify',\n 'flask-mongoengine',\n #'flask-sqlalchemy',\n 'flask-restful',\n 'mpld3'\n ],\n extras_require = {\n 'development': ['twine','Sphinx']\n },\n package_data = {\n },\n include_package_data = True,\n zip_safe = False,\n entry_points = {\n 'console_scripts': ['pycassos=pycassos.__main__:main'],\n },\n test_suite = 'nose.collector',\n tests_require = ['nose']\n)\n\n#To install with symlink, so that changes are immediately available:\n#pip install -e .\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"334080751","text":"#!/usr/bin/env python\nfrom flask import Flask, flash, redirect, render_template, \\\n request, url_for\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template(\n 'select_menu.html',\n data=[{'name':'red'}, {'name':'green'}, {'name':'blue'}])\n\n@app.route(\"/test\" , methods=['GET', 'POST'])\ndef test():\n if request.method == 'POST':\n select = request.form.get('comp_select')\n return ' {0} '.format(str(select))\n return redirect(url_for('index'))\n \n\nif __name__=='__main__':\n app.run(debug=True, port=2745)","sub_path":"ElementsAutourDeFlask/selectmenu.py","file_name":"selectmenu.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"600205684","text":"def cfginfinite(grammar):\n for Q in [rule[0] for rule in grammar]:\n def helper(current, visited, sizexy):\n if current in visited:\n return sizexy > 0\n else:\n new_visited = visited + [current]\n for rhs in [rule[1] for rule in grammar if rule[0] == current]:\n for symbol in rhs:\n if helper(symbol, new_visited, sizexy + len(rhs) - 1):\n return True\n return False\n\n if helper(Q, [], 0):\n return True\n return False\n","sub_path":"exercise/L01-03/cfginfinite.py","file_name":"cfginfinite.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"71275285","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 14 15:22:02 2019\r\n\r\n@author: kna016\r\nScript to create 'iveg' and 'patchfrac' information for OzFLUX site-level runs in CABLE\r\nFeb. 2019: extended to read C4 fraction as well and append them to sitelist\r\n\"\"\"\r\n\r\nimport pandas as pd # dataframes\r\nimport numpy as np # multi-dimensional arrays\r\n\r\n\r\n## Options\r\nuse_site_years = False # use site years (True) or long-term climatologies (False)\r\nfrac_max = True # derive forest fraction from max. forest fraction (rest is grass)?\r\n\r\n\r\nbasepath='C:/Users/kna016/Documents/CABLE/'\r\n\r\n\r\n## 1) load dataframe containing vegfract timeseries and site list\r\nfcover = pd.read_csv(basepath + 'cover_fract/ozflux28.gimms3g_fcovfperfrec.csv',index_col='PointName')\r\nC4fraction = pd.read_csv(basepath + 'cover_fract/ozflux28.c4_grass_frac_cov.csv',index_col='PointName')\r\nsitelist = pd.read_csv(basepath + 'OzFLUX_sitelist_v2.txt',sep='\\t',index_col=0) \r\n\r\n\r\n## 2) extract fcover climatology information\r\n#clims_index = [k for k, i in enumerate(fcover.index) if '9999' in i]\r\n#fcover_climatology = fcover.iloc[clims_index,:]\r\nfcov_index = [k for k, i in enumerate(fcover.index) if '9999' in i and 'fcov' in i]\r\nfper_index = [k for k, i in enumerate(fcover.index) if '9999' in i and 'fper' in i]\r\nfrec_index = [k for k, i in enumerate(fcover.index) if '9999' in i and 'frec' in i]\r\n\r\n\r\n## 3) extract vegetation cover for each site\r\nfrac_forest = []\r\nfrac_grass = []\r\nfrac_C4 = []\r\n\r\n\r\nfor s,site in enumerate(sitelist.index):\r\n \r\n print('starting site ' + site)\r\n \r\n if use_site_years:\r\n \r\n print('not yet implemented!')\r\n\r\n# startyear = sitelist.loc[site,'startyear']\r\n# endyear = sitelist.loc[site,'endyear']\r\n# \r\n# #fcover[0,site]\r\n# dates=fcover.index.tolist()\r\n# index=[]\r\n# for year in range(startyear,endyear):\r\n# index.append([k for k, i in enumerate(dates) if 'fcov' in i and str(year) in i])\r\n \r\n else: \r\n \r\n# fcov.append(round(fcover.iloc[fcov_index,s].mean(),3))\r\n# fper.append(round(fcover.iloc[fper_index,s].mean(),3))\r\n# frec.append(round(fcover.iloc[frec_index,s].mean(),3))\r\n\r\n \r\n if frac_max:\r\n \r\n frac_forest.append(fcover.iloc[fper_index,s].max())\r\n frac_grass.append(1.0 - frac_forest[-1])\r\n \r\n \r\n else:\r\n \r\n fcov_site = fcover.iloc[fcov_index,s]\r\n fper_site = fcover.iloc[fper_index,s]\r\n frec_site = fcover.iloc[frec_index,s]\r\n \r\n \r\n frac_forest.append((np.array(fper_site) / np.array(fcov_site)).mean())\r\n frac_grass.append((np.array(frec_site) / np.array(fcov_site)).mean())\r\n \r\n\r\n frac_C4.append(C4fraction.iloc[3,s])\r\n \r\n \r\n \r\n \r\n \r\n## ensure that forest and grass fractions sum up to 1\r\nif frac_max==False:\r\n diff = (np.array(frac_forest) + np.array(frac_grass)) - 1.0\r\n \r\n frac_forest = frac_forest - diff*frac_forest\r\n frac_grass = frac_grass - diff*frac_grass\r\n \r\n diff = (np.array(frac_forest) + np.array(frac_grass)) - 1.0\r\n \r\n frac_forest = frac_forest - diff*frac_forest\r\n frac_grass = frac_grass - diff*frac_grass\r\n\r\n\r\nfrac_forest = np.array(frac_forest).round(3)\r\nfrac_grass = np.array(frac_grass).round(3)\r\nfrac_C4 = np.array(frac_C4).round(3)\r\n\r\n\r\n\r\n### append to sitelist\r\nsitelist['forest_fraction'] = frac_forest\r\nsitelist['grass_fraction'] = frac_grass\r\nsitelist['C4_fraction'] = frac_C4\r\n\r\n# sitelist.to_csv('C:/Users/kna016/Documents/CABLE/OzFLUX_sitelist_v3.txt',sep=\"\\t\") # frac_max=False\r\n#sitelist.to_csv('C:/Users/kna016/Documents/CABLE/OzFLUX_sitelist_v4.txt',sep=\"\\t\") # frac_max=True\r\nsitelist.to_csv('C:/Users/kna016/Documents/CABLE/OzFLUX_sitelist_v5.txt',sep=\"\\t\") # frac_C4 included\r\n\r\n\r\n\r\n### some tests:\r\n# x = filter(lambda funs: funs[0:3] == startyear, dates) \r\n# x = filter(lambda k: str(startyear) in k, dates)\r\n \r\n# lst = ['a', 'ab', 'abc', 'bac']\r\n# filter(lambda k: 'ab' in k,lst)\r\n# \r\n# x = [k for k in lst if 'ab' in k] # 'list comprehensions'\r\n# list(map(str,range(startyear,endyear)))","sub_path":"forcing/cover_fract/OzFlux_coverfract.py","file_name":"OzFlux_coverfract.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"639765788","text":"import hashlib, json, sys\nimport random\nrandom.seed(0)\n\ndef hashMe(msg=\"\"):\n # For convenience, this is a helper function that wraps our hashing algorithm\n if type(msg) != str:\n msg = json.dumps(msg,sort_keys=True) # if we don't sort keys, we can't guarantee repeatability!\n\n if sys.version_info.major == 2:\n return unicode(hashlib.sha256(msg).hexdigest(), 'utf-8')\n else:\n return hashlib.sha256(str(msg).encode('utf-8')).hexdigest()\n\n\ndef makeTransaction(maxValue=3):\n # This will create valid transactions in the range of (1,maxValue)\n sign = int(random.getrandbits(1))*2 - 1 # this will randomly choose -1 or 1\n amount = random.randint(1,maxValue)\n alicePays = sign * amount\n bobPays = -1 * alicePays\n # by construction, this will always return transactions that respect the conservation of tokens\n # however, note that we have not done anything to check whther these overdraft an account\n return {u'Alice':alicePays,u'Bob':bobPays}\n\ntxnBuffer = [makeTransaction() for i in range(30)]\n\ndef updateState(txn, state):\n # Inputs: txn, state: dictionaries keyed with account names, holding numeric values for the transfer amount (txn) or account balance (state)\n # Returns: Updated state, with additional users added to state if necessary\n # NOTE: This does not validate the transaction- just updates the state!\n\n # If the transaction is valid, then update the state\n state = state.copy() # As dictionaries are mutable, let's avoid any confusion by reating a vorking copy of the data.\n for key in txn:\n if key in state.keys():\n state[key] += txn[key]\n else:\n state[key] = txn[key]\n return state\n\ndef isValidTxn(txn, state):\n # assume that the transaction is a dictionary keyed by account names\n\n #check that the sum of the deposits and withdrawals is 0\n if sum(txn.values()) is not 0:\n return False\n\n # Check that the transaction does not cause an overdraft\n for key in txn.keys():\n if key in state.keys():\n acctBalance = state[key]\n else:\n acctBalance = 0\n if (acctBalance + txn[key]) < 0:\n return False\n\n return True\n\nstate = {u'Alice':5,u'Bob':5}\n\nprint(isValidTxn({u'Alice':-3,u'Bob':3},state))\nprint(isValidTxn({u'Alice':-4,u'Bob':3},state))\nprint(isValidTxn({u'Alice':-6,u'Bob':6},state))\nprint(isValidTxn({u'Alice':-4,u'Bob':2,u'Lisa':2},state))\nprint(isValidTxn({u'Alice':-4,u'Bob':3,u'Lisa':2},state))\n","sub_path":"Core.py","file_name":"Core.py","file_ext":"py","file_size_in_byte":2512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"132037630","text":"import datetime\nimport sys\nfrom collections import namedtuple\nfrom typing import Dict, List\n\nimport xlrd\n\nProductInfo = namedtuple(\n \"ProductInfo\",\n (\"name\", \"storage_type\", \"packaging\", \"weight\", \"date\"),\n defaults=(None, None, None, 0, datetime.datetime.now()),\n)\n\n\nclass BarcodeDatabase:\n def __init__(self, filepaths: List[str] = list()):\n self._codemap = {}\n self._filepaths = filepaths\n self._fill_database(filepaths)\n\n def __getitem__(self, key):\n return self._codemap[key]\n\n def __contains__(self, key):\n return key in self._codemap\n\n def clear(self):\n self._codemap.clear()\n\n def reload(self):\n self.clear()\n self._fill_database(self.filepaths)\n\n def read_db_file(self, filepath: str):\n if filepath.endswith(\".xls\"):\n self._codemap.update(BarcodeDatabase._from_xls(filepath))\n else:\n raise NotImplementedError\n\n def _from_xls(filepath: str) -> Dict[int, ProductInfo]:\n result = {}\n rb = xlrd.open_workbook(filepath)\n for sheetidx in range(rb.nsheets):\n sheet = rb.sheet_by_index(sheetidx)\n for rownum in range(1, sheet.nrows):\n values = sheet.row_values(rownum)\n result[int(values[0])] = ProductInfo(*values[1:])\n return result\n\n def _fill_database(self, filepaths: List[str]):\n for filepath in filepaths:\n self.read_db_file(filepath)\n\n\ndb = BarcodeDatabase(filepaths=sys.argv[1:])\nprint(db._codemap)\n","sub_path":"brreader/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"114466266","text":"class Solution(object):\n def hasCycle(self, head):\n i = head\n j = head.next\n while i is not None and i.next is not None:\n if i.next == head:\n return True\n i = i.next\n j.next = head\n j = i\n return False\n\n\nclass ListNode(object):\n def __init__(self, x, next=None):\n self.val = x\n self.next = next\n\nlst = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) # 1 -> 2 -> 3 -> 4\nlst.next.next.next.next = lst.next # создаём цикл 1 -> 2 -> 3 -> 4 ↘\nc = Solution() # ↖__________|\nprint(c.hasCycle(lst))\n","sub_path":"students/DariaSuslova/linked_list_cycle/linked_list_cycle_listok_2.py","file_name":"linked_list_cycle_listok_2.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"246386068","text":"#完全数を求めるプログラム\n\nvalue = int( input(\"約数を求めたい正の整数\"))\n\nsumNum = 0\nfor d in range(1, value + 1):\n if value % d == 0: sumNum += d\nprint(\"約数の総和は\",sumNum)\n\nif sumNum == 2 * value:\n print(value,\"は、完全数です\")\nelse:\n print(value,\"は、完全数ではありません。\")\n\n\nupper = 10000\nfor n in range(2, upper+1):\n sumNum = 0\n for d in range(1,n//2+1):\n if n % d == 0: sumNum += d\n if sumNum == n:\n print(n, end = ' ')\nprint()\n\n\n#2進数を使って、完全数の候補を求める\nbvalue = \"1\"\nfor n in range( 30 ):\n bvalue = \"1\" + bvalue + \"0\"\n value = int(bvalue, base = 2)\n print(value)\n\n #完全数かどうかを判定する\n sumNum = 0\n for d in range(1, value // 2 + 1):\n if value % d == 0: sumNum += d\n print(value , \":\", \"COMPLETE\" if sumNum == value else \"not\")\n","sub_path":"約数と素数/perfectNumbers.py","file_name":"perfectNumbers.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"411658272","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 ('cas', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Food',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(unique=True, max_length=200, verbose_name=b'\\xe4\\xb8\\xad\\xe6\\x96\\x87\\xe5\\x90\\x8d\\xe7\\xa7\\xb0')),\n ('info', models.CharField(max_length=500, null=True, verbose_name=b'\\xe6\\x8f\\x8f\\xe8\\xbf\\xb0', blank=True)),\n ('create_time', models.DateTimeField(auto_now_add=True)),\n ],\n options={\n 'ordering': ['-create_time'],\n 'verbose_name': '\\u98df\\u7269\\u5217\\u8868',\n 'verbose_name_plural': '\\u98df\\u7269\\u5217\\u8868',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Orders',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('create_time', models.DateField(auto_now_add=True)),\n ('food', models.ForeignKey(to='dinner.Food')),\n ('pro', models.ForeignKey(to='cas.Pro')),\n ],\n options={\n 'ordering': ['-create_time'],\n 'verbose_name': '\\u8ba2\\u5355\\u5217\\u8868',\n 'verbose_name_plural': '\\u8ba2\\u5355\\u5217\\u8868',\n },\n bases=(models.Model,),\n ),\n ]\n","sub_path":"dinner/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"295096306","text":"# #############################################\n#\n# Smart Wardrobe for the Raspberry Pi\n#\n# Developed by the Salmons for the 2013/2014 PA Consulting\n# Raspberry Pi Competition:\n# http://www.paconsulting.com/events/pas-new-raspberry-pi-competition-for-2013-14/\n#\n\n# This file takes a list of things that describe the weather e.g. gentle breeze,\n# fairly warm etc, and picks a slot from a wardrobe, because the clothes in that\n# slot appear to match the weather best.\n\n# turn debug on or off for this module\n#wardrobeDebugOn = 1\nwardrobeDebugOn = 0\n\ndef wardrobeDebug(debugText):\n if (wardrobeDebugOn):\n print (debugText)\n\nwardrobe = [# rain or sleet -> umbrella\n {'cloudCover': ['Any'],\n 'windSpeed': ['NextToNoWind', 'GentleBreeze'],\n 'minTemp': ['FairlyWarm'],\n 'maxTemp': ['FairlyWarm'],\n 'precipitationType': ['rain', 'drizzle'],\n 'clothes': 'Umbrella, jacket, shoes, jumper, T-shirt, trousers'},\n\n # hot and sunny but cloudy\n {'cloudCover': ['AverageAmountOfCloud', 'LotsOfCloud'],\n 'windSpeed': ['NextToNoWind'],\n 'minTemp': ['Hot'],\n 'maxTemp': ['Hot'],\n 'precipitationType': ['none'],\n 'clothes': 'Sun hat, T-shirt, shorts, flip-flops'},\n\n # hot and sunny with no cloud\n {'cloudCover': ['SmallAmountOfCloud'],\n 'windSpeed': ['NextToNoWind'],\n 'minTemp': ['Hot'],\n 'maxTemp': ['Hot'],\n 'precipitationType': ['none'],\n 'clothes': 'Sun hat, long-sleeved T-shirt, lightweight trousers, sandals'},\n\n # snow -> extra warm\n {'cloudCover': ['Any'],\n 'windSpeed': ['Any'],\n 'minTemp': ['RatherCold'],\n 'maxTemp': ['RatherCold'],\n 'precipitationType': ['snow'],\n 'clothes': 'Warm coat, hat, gloves, warm jumper, trousers, warm long-sleeved top'}\n ]\n\n\n# Compares two strings' position in the list of all possible values,\n# and returns a score based on how close they are to being at the same\n# position in the list (see getBestScore for details of the score)\ndef compareTwoStrings(stringA, stringB, allValues):\n for aPos in range(len(allValues)):\n if (stringA == allValues[aPos]):\n break\n\n for bPos in range(len(allValues)):\n if (stringB == allValues[bPos]):\n break\n\n if (aPos == len(allValues)):\n print (\"Error: can't find\", stringA, \"in\", allValues)\n\n if (bPos == len(allValues)):\n print (\"Error: can't find\", stringB, \"in\", allValues)\n\n gap = abs(aPos - bPos)\n\n score = 10 - (15 * gap)\n\n return score\n\n\n\n# General purpose function for comparing a string and a list of strings, that\n# all come from a list of possible values.\n#\n# The string is compared with each member of the list, and the score from\n# the best match is returned. If a given pair of strings are identical, the\n# score is 10. If the pair of strings come from different places in the list\n# of all possible values, their score is 10 - (15 * the number of places\n# difference between them in the list of all possible values). So, next to\n# each other is -5 (10 - 15). Next but one is -20 (10 - 30) etc.\n#\ndef getBestScore(testString, stringList, allValues):\n score = -99999\n\n for stringToCheck in stringList:\n tempScore = compareTwoStrings(testString, stringToCheck, allValues)\n\n if tempScore > score:\n score = tempScore\n\n return score\n\n\ndef getCloudScore(currentCloud, slotCloud):\n if (slotCloud[0] == 'Any'):\n score = 0\n else:\n score = getBestScore(currentCloud, slotCloud,\n ['SmallAmountOfCloud', 'AverageAmountOfCloud', 'LotsOfCloud'])\n\n wardrobeDebug (\"cloud score is \" + str(score))\n return score\n\n\n# ignore min temp for now\ndef getTemperatureScore(currentMinTemp, currentMaxTemp, slotMinTemp, slotMaxTemp):\n if (slotMaxTemp[0] == 'Any'):\n score = 0\n else:\n score = getBestScore(currentMaxTemp, slotMaxTemp, ['RatherCold', 'FairlyWarm', 'Hot'])\n\n wardrobeDebug (\"temperature score is \" + str(score))\n return score\n\n\ndef getWindScore(currentWind, slotWind):\n if (slotWind[0] == 'Any'):\n score = 0\n else:\n score = getBestScore(currentWind, slotWind, ['NextToNoWind', 'GentleBreeze', 'LotsOfWind'])\n\n wardrobeDebug (\"wind score is \" + str(score))\n return score\n\n\ndef getPrecScore(currentPrec, slotPrec):\n if (slotPrec[0] == 'Any'):\n score = 0\n else:\n score = getBestScore(currentPrec, slotPrec, ['none', 'drizzle', 'rain', 'snow'])\n\n wardrobeDebug (\"precipitation score is \" + str(score))\n return score\n\n\ndef getScoreForSlot(currentWeather, slot):\n \n s1 = getCloudScore(currentWeather['cloudCover'], slot['cloudCover'])\n \n s2 = getTemperatureScore(currentWeather['minTemp'],\n currentWeather['maxTemp'],\n slot['minTemp'],\n slot['maxTemp'])\n \n s3 = getWindScore(currentWeather['windSpeed'], slot['windSpeed'])\n \n s4 = getPrecScore(currentWeather['precipitationType'], slot['precipitationType'])\n\n score = s1 + s2 + s3 + s4\n\n wardrobeDebug (\"total score is \" + str(score))\n return score\n\n\ndef getSlotForWeather(currentWeather):\n bestSlotSoFar = -1\n bestScoreSoFar = -99999\n\n for slotNum in range(len(wardrobe)):\n wardrobeDebug(\">>> processing slot \" + str(slotNum))\n currentScore = getScoreForSlot(currentWeather, wardrobe[slotNum])\n\n if (currentScore > bestScoreSoFar):\n wardrobeDebug (\"Best score so far is \" + str(currentScore) + \" from slot \" + str(slotNum))\n bestScoreSoFar = currentScore\n bestSlotSoFar = slotNum\n\n print (\"Selecting these clothes \",\n wardrobe[bestSlotSoFar]['clothes'])\n \n return bestSlotSoFar\n\n\n# ######################################################################\n# test code\n# ######################################################################\n\n# snow - should get slot 3\n#currentWeather = {'cloudCover': 'None',\n# 'windSpeed': 'GentleBreeze',\n# 'minTemp': 'RatherCold',\n# 'maxTemp': 'RatherCold',\n# 'precipitationType': 'snow'}\n\n# hot and cloudy - slot 1\n#currentWeather = {'cloudCover': 'LotsOfCloud',\n# 'windSpeed': 'GentleBreeze',\n# 'minTemp': 'Hot',\n# 'maxTemp': 'Hot',\n# 'precipitationType': 'none'}\n\n# hot and no cloud - slot 2\n#currentWeather = {'cloudCover': 'SmallAmountOfCloud',\n# 'windSpeed': 'GentleBreeze',\n# 'minTemp': 'Hot',\n# 'maxTemp': 'Hot',\n# 'precipitationType': 'none'}\n\n# rainy and not too windy - slot 0\n#currentWeather = {'cloudCover': 'LotsOfCloud',\n# 'windSpeed': 'GentleBreeze',\n# 'minTemp': 'FairlyWarm',\n# 'maxTemp': 'FairlyWarm',\n# 'precipitationType': 'rain'}\n\n\n#slot = getSlotForWeather(currentWeather)\n\n#print (\"Slot for today's weather is\", slot)\n","sub_path":"Wardrobe.py","file_name":"Wardrobe.py","file_ext":"py","file_size_in_byte":7259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"297346754","text":"\n\nfrom xai.brain.wordbase.nouns._revival import _REVIVAL\n\n#calss header\nclass _REVIVALS(_REVIVAL, ):\n\tdef __init__(self,): \n\t\t_REVIVAL.__init__(self)\n\t\tself.name = \"REVIVALS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"revival\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_revivals.py","file_name":"_revivals.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"583290936","text":"import readFile\nimport dekoder\n\n# 0 - wolne\n# 1 - sciana\n# 2 - nie podlega monitorowaniu\n# 3 - zasloniete\n# 4 - policzone\n\n\ndef J(x, y, alpha, dep):\n table = readFile.getArray()\n no_0 = seen_counter_for_0(table)\n\n n = dekoder.n() # szerokosc x\n m = dekoder.m() # szerokosc y\n is_forbidden = False\n\n for k in range(len(x)):\n\n # print(alpha[k])\n # print(m)\n\n table = angel_change(alpha[k], table)\n temp_x = x[k]\n x[k] = change_x(alpha[k], x[k], y[k], n, m)\n y[k] = change_y(alpha[k], temp_x, y[k], n, m)\n\n # print(x[k])\n # print(y[k])\n\n temp = j_for_one(x[k], y[k], dep, table)\n table = temp[0]\n if temp[1]:\n is_forbidden = True\n table = angel_change_back(alpha[k], table)\n # print_matrix(table)\n\n if is_forbidden:\n return 0.6 * round((seen_counter(table) / no_0), 4), table\n else:\n return round((seen_counter(table) / no_0), 4), table\n\n\ndef J_return_forbidden(x, y, alpha, dep):\n table = readFile.getArray()\n no_0 = seen_counter_for_0(table)\n\n n = dekoder.n() # szerokosc x\n m = dekoder.m() # szerokosc y\n is_forbidden = False\n\n for k in range(len(x)):\n\n # print(alpha[k])\n # print(m)\n\n table = angel_change(alpha[k], table)\n temp_x = x[k]\n x[k] = change_x(alpha[k], x[k], y[k], n, m)\n y[k] = change_y(alpha[k], temp_x, y[k], n, m)\n\n # print(x[k])\n # print(y[k])\n\n temp = j_for_one(x[k], y[k], dep, table)\n table = temp[0]\n if temp[1]:\n is_forbidden = True\n table = angel_change_back(alpha[k], table)\n # print_matrix(table)\n\n if is_forbidden:\n return None\n else:\n return round((seen_counter(table) / no_0), 4)\n\n\ndef j_for_one(x, y, d, matrix=readFile.getArray()):\n d += 1\n n = len(matrix[0]) # szerokosc x\n m = len(matrix) # szerokosc y\n\n blocked_ranges = []\n if_forbidden = False\n\n if matrix[y][x] == 1 or matrix[y][x] == 2:\n if_forbidden = True\n\n for i in range(d):\n\n if y-i < 0 or y-i >= m:\n break\n for ii in range(2*i + 1):\n if 0 <= x-i+ii < n and matrix[y - i][x - i + ii] == 0:\n if not if_in_ranges(blocked_ranges, get_coords(2*i + 1, ii)):\n matrix[y-i][x-i+ii] = 4\n else:\n matrix[y - i][x - i + ii] = 0\n\n elif 0 <= x-i+ii < n and matrix[y - i][x - i + ii] == 1:\n blocked_ranges = add_range(blocked_ranges, get_coords((2*i + 1), ii))\n\n return matrix, if_forbidden\n\n\ndef add_range(ranges, new):\n ranges.append(new)\n merge_ranges(ranges)\n return ranges\n\n\ndef merge_ranges(ranges):\n for i in ranges:\n for ii in ranges:\n if i[1] >= ii[0] and ii[1] >= i[0]:\n i[0] = min(i[0], ii[0])\n i[1] = max(i[1], ii[1])\n ii[0] = i[0]\n ii[1] = i[1]\n\n\ndef get_coords(length, index):\n return [index/length, (index+1)/length]\n\n\ndef if_in_ranges(ranges, coords):\n for i in ranges:\n if i[0] <= coords[0] <= i[1] and i[0] <= coords[1] <= i[1]:\n return True\n return False\n\n\ndef print_matrix(matrix1):\n for i in matrix1:\n print(str(i))\n print('')\n\n\ndef seen_counter(matrix2):\n nb = 0\n for i in matrix2:\n for ii in i:\n if ii == 4:\n nb += 1\n return nb\n\n\ndef seen_counter_for_0(matrix2):\n nb = 0\n for i in matrix2:\n for ii in i:\n if ii == 0:\n nb += 1\n return nb\n\n\ndef matrix_transpose(m):\n rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]\n return rez\n\n\ndef matrix_vertical_symmetry(m):\n for i in m:\n i.reverse()\n return m\n\n\ndef matrix_horizontal_symmetry(m):\n rez = []\n for i in m:\n rez.insert(0, i)\n return rez\n\n\ndef angel_change(alpha, m):\n if alpha == 1:\n m = matrix_transpose(m)\n m = matrix_vertical_symmetry(m)\n elif alpha == 2:\n m = matrix_horizontal_symmetry(m)\n elif alpha == 3:\n m = matrix_vertical_symmetry(m)\n m = matrix_transpose(m)\n return m\n\n\ndef angel_change_back(alpha, m):\n if alpha == 1:\n m = angel_change(3, m)\n elif alpha == 2:\n m = angel_change(2, m)\n elif alpha == 3:\n m = angel_change(1, m)\n return m\n\n\ndef change_x(alpha, x, y, len_x, len_y):\n if alpha == 1:\n return len_y - y - 1\n elif alpha == 3:\n return y\n else:\n return x\n\n\ndef change_y(alpha, x, y, len_x, len_y):\n if alpha == 1: \n return x\n elif alpha == 2: \n return len_y - y - 1\n elif alpha == 3: \n return len_x - x - 1\n else: \n return y\n\n#\n# matrix22 = readFile.getArray()\n#\n# # print_matrix(matrix_vertical_symmetry(matrix22))\n# # print_matrix(matrix_horizontal_symmetry(matrix22))\n# # print_matrix(angel_change_back(0, matrix22))\n#\n#\n# print(J(matrix22, [2, 6], [7, 6], [0, 1], 3))\n","sub_path":"src2/afunction.py","file_name":"afunction.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"518550169","text":"import collections\nimport attr\n\nfrom flask import jsonify, render_template, abort, redirect\nimport courses\n\nclass Translations:\n def __init__(self):\n self.data = courses.load_yaml('coursedata/texts.yaml')\n\n def get_translations(self, language, section):\n # Merge with English when lacking translations\n # Start from a defaultdict\n d = collections.defaultdict(lambda: '???')\n d.update(**self.data.get('en', {}).get(section, {}))\n d.update(**self.data.get(language, {}).get(section, {}))\n return d\n\n\ndef render_assignment_editor(course, assignment_number, menu, translations, version):\n assignment = course.get_assignment(assignment_number)\n if not assignment:\n abort(404)\n\n arguments_dict = {}\n\n # Meta stuff\n arguments_dict['course'] = course\n arguments_dict['assignment_nr'] = str(assignment_number)\n arguments_dict['level'] = assignment.level\n arguments_dict['lang'] = course.language\n arguments_dict['next_assignment'] = int(assignment_number) + 1 if int(assignment_number) < course.max_level() else None\n arguments_dict['menu'] = menu\n arguments_dict['latest'] = version\n arguments_dict['selected_page'] = 'code'\n arguments_dict['page_title'] = f'Level {assignment_number} – Hedy'\n arguments_dict['docs'] = [attr.asdict(d) for d in assignment.docs]\n\n # Translations\n arguments_dict.update(**translations.get_translations(course.language, 'ui'))\n\n # Actual assignment\n arguments_dict.update(**attr.asdict(assignment))\n\n return render_template(\"code-page.html\", **arguments_dict)\n\n\ndef render_assignment_docs(doc_type, course, assignment_number, menu, translations):\n assignment = course.get_assignment(assignment_number)\n if not assignment:\n abort(404)\n\n arguments_dict = {}\n\n # Meta stuff\n arguments_dict['course'] = course\n arguments_dict['assignment_nr'] = str(assignment_number)\n arguments_dict['pagetitle'] = f'Level {assignment_number}'\n arguments_dict['lang'] = course.language\n arguments_dict['selected_page'] = doc_type\n arguments_dict['docs'] = [attr.asdict(d) for d in assignment.docs]\n\n # Translations\n arguments_dict.update(**translations.get_translations(course.language, 'ui'))\n\n # print(repr(assignment_number), course.docs)\n\n doc = course.docs.get(int(assignment_number), doc_type)\n if not doc:\n # Redirect to code page. Nasty 'import' here to work around\n # cyclic imports.\n import app\n return redirect(app.hedy_link(assignment_number))\n\n arguments_dict['mkd'] = doc.markdown\n arguments_dict['menu'] = menu\n arguments_dict['page_title'] = f'Level {assignment_number} – ' + doc.front_matter.get('title', '') + ' – Hedy'\n\n return render_template(\"per-level-text.html\", **arguments_dict)","sub_path":"hedyweb.py","file_name":"hedyweb.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"216771807","text":"import sys\nsys.path.append('../engel')\n\nfrom engel.widgets import Panel, Span\n\n\nclass FakeDispatchView(object):\n \"\"\"\n This fake view aims to help the testing of event dispatchers.\n \"\"\"\n\n def __init__(self, expected_command):\n self.expected_command = expected_command\n self.is_loaded = True\n\n self.was_dispatched = False\n\n def dispatch(self, cmd):\n self.was_dispatched = True\n assert self.expected_command == cmd\n\n def verify(self):\n assert self.was_dispatched\n\n\ndef test_event_append_child():\n\n expected = {\n 'name': 'append',\n 'html': 'oki ',\n 'selector': '#main-panel'\n }\n\n verifier = FakeDispatchView(expected)\n\n parent = Panel(id=\"main-panel\")\n parent.view = verifier\n\n child = Span(id=\"my-span\", text=\"oki\")\n parent.add_child(child)\n verifier.verify()\n\ndef test_event_remove_child():\n\n expected = {\n 'name': 'remove',\n 'selector': '#my-span'\n }\n\n verifier = FakeDispatchView(expected)\n\n parent = Panel(id='main-panel')\n\n child = Span(id=\"my-span\", text='oki')\n parent.add_child(child)\n parent.view = verifier\n\n parent.remove_child(child)\n verifier.verify()\n\n\ndef test_event_replace_child():\n\n expected = {\n 'name': 'replace',\n 'html': 'hello ',\n 'selector': '#my-span'\n }\n\n verifier = FakeDispatchView(expected)\n\n parent = Panel(id=\"main-panel\")\n\n child1 = Span(id=\"my-span\", text=\"oki\")\n parent.add_child(child1)\n\n parent.view = verifier\n\n child2 = Span(id=\"my-other-span\", text=\"hello\")\n\n parent.replace_child(child1, child2)\n verifier.verify()\n\n\ndef test_event_add_class():\n\n expected = {\n 'name': 'addclass',\n 'cl': 'hue',\n 'selector': '#my-span'\n }\n\n verifier = FakeDispatchView(expected)\n\n child = Span(id='my-span', text=\"oki\")\n child.view = verifier\n\n child.add_class('hue')\n verifier.verify()\n\ndef test_event_remove_class():\n\n expected = {\n 'name': 'removeclass',\n 'cl': 'hue',\n 'selector': '#my-span'\n }\n\n verifier = FakeDispatchView(expected)\n\n child = Span(id='my-span', text='oki', classname='hue')\n child.view = verifier\n\n child.remove_class('hue')\n verifier.verify()\n\n\ndef test_event_set_attr():\n\n expected = {\n 'name': 'attr',\n 'selector': '#my-span',\n 'attr': 'hello',\n 'value': 'world'\n }\n\n verifier = FakeDispatchView(expected)\n\n child = Span(id='my-span', text='oki')\n child.view = verifier\n\n child._set_attribute('hello', 'world')\n verifier.verify()\n","sub_path":"tests/test_widget_base.py","file_name":"test_widget_base.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"145852721","text":"import gym\nimport numpy as np\n\nBALL_RADIUS = 0.03\n\nBALL_OBJECT_NAME = \"object\"\nBALL_JOINT_NAME = \"object:joint\"\n\n\nclass ThrowEnvWrapper(gym.Wrapper):\n #\n #\n # Gym wrapper with features:\n # - new reward function\n # - detect ball collision with ground and reset\n #\n #\n def __init__(self, env):\n super(ThrowEnvWrapper, self).__init__(env)\n self.desired_ball_velocity = np.array([0, 0, 1])\n self.max_velocity = 0\n self.max_height = 0\n self.target_height = 0.4\n self.ball_velp = np.zeros((3,))\n self.ball_center_z = 0\n self.ball_center_vel_z = 0\n self.reached_target = False\n\n def reset(self, **kwargs):\n obs = self.env.reset(**kwargs)\n return obs[\"observation\"]\n\n def step(self, action):\n observation, reward, done, info = self.env.step(action)\n ball_center_pos = self.sim.data.get_joint_qpos(BALL_JOINT_NAME)\n self.ball_center_z = ball_center_pos[2]\n self.ball_velp = self.sim.data.get_joint_qvel(BALL_JOINT_NAME)[:3]\n self.ball_center_vel_z = self.ball_velp[2]\n\n self.ball_center_z = self.sim.data.get_joint_qpos(BALL_JOINT_NAME)[2]\n if self.ball_center_z <= BALL_RADIUS:\n print(\"Ball was dropped -> Reset Environment\")\n done = True\n\n return observation[\"observation\"], self.reward(reward), done, info\n\n def reward(self, reward):\n #return self.reward_functionA()\n return self.reward_functionB()\n #return reward\n\n def reward_functionA(self):\n reward = 1 - (self.target_height - self.ball_center_z) / self.target_height\n z_direction = np.sign(self.ball_center_vel_z)\n if z_direction > 0:\n reward += self.ball_center_vel_z * 10\n return reward\n\n def reward_functionB(self):\n reward = 1 - (self.target_height - self.ball_center_z) / self.target_height\n z_direction = np.sign(self.ball_center_vel_z)\n\n if not self.reached_target and self.ball_center_z > self.target_height:\n reward += 100\n self.reached_target = True\n\n if z_direction < 0:\n reward = 0\n\n return reward\n","sub_path":"reinforcement-learning-robohand/utils/gym_wrapper.py","file_name":"gym_wrapper.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"444641625","text":"from neural_compressor.experimental.strategy.utils.tuning_space import TuningSpace\nfrom neural_compressor.conf.dotdict import DotDict\nfrom neural_compressor.utils import logger\nfrom copy import deepcopy\nimport unittest\n\nop_cap = {\n # op1 have both weight and activation and support static/dynamic/fp32/b16\n ('op_name1', 'op_type1'): [\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': ['int4'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['uint4'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'dynamic',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': 'bf16'\n },\n 'weight':\n {\n 'dtype': 'bf16'\n }\n },\n {\n 'activation':\n {\n 'dtype': 'fp32'\n },\n 'weight':\n {\n 'dtype': 'fp32'\n }\n },\n ],\n # op2 have both weight and activation and support static/dynamic/fp32\n ('op_name2', 'op_type1'): [\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'dynamic',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': 'fp32'\n },\n 'weight':\n {\n 'dtype': 'fp32'\n }\n },\n ],\n # op3 have both weight and activation and support int4\n ('op_name3', 'op_type3'): [\n {\n 'activation':\n {\n 'dtype': ['int4'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int4'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': ['int8'],\n 'quant_mode': 'static',\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor'],\n 'algorithm': ['minmax', 'kl']\n },\n 'weight':\n {\n 'dtype': ['int8'],\n 'scheme': ['sym'],\n 'granularity': ['per_channel', 'per_tensor']\n }\n },\n {\n 'activation':\n {\n 'dtype': 'fp32'\n },\n 'weight':\n {\n 'dtype': 'fp32'\n }\n },\n ],\n}\n\nclass TestTuningSpaceV2(unittest.TestCase):\n def setUp(self) -> None:\n self.capability = {\n 'calib': {'calib_sampling_size': [1, 10, 50]},\n 'op': deepcopy(op_cap)\n }\n \n self.op_wise_user_cfg_for_fallback = {\n 'op_name1': {\n 'activation': {\n 'dtype': ['fp32']\n },\n 'weight': {\n 'dtype': ['fp32']\n }\n },\n }\n \n \n def test_tuning_sampler_int4(self):\n # op-wise\n conf = {'usr_cfg': { } }\n conf = DotDict(conf)\n # test space construction\n tuning_space = TuningSpace(deepcopy(self.capability), deepcopy(conf))\n logger.debug(tuning_space.root_item.get_details())\n found_int4_activation = False\n found_int4_weight = False\n op3_act_item = tuning_space.query_quant_mode_item_by_full_path(('op_name3', 'op_type3'),\\\n ('static', 'activation'))\n for dtype_item in op3_act_item.options:\n if dtype_item.name == 'int4':\n found_int4_activation = True\n self.assertTrue(found_int4_activation)\n op3_weight_item = tuning_space.query_quant_mode_item_by_full_path(('op_name3', 'op_type3'), \\\n ('static', 'weight'))\n for dtype_item in op3_weight_item.options:\n if dtype_item.name == 'int4':\n found_int4_weight = True\n self.assertTrue(found_int4_weight)\n \n def test_sampler_int4(self):\n # test sampler\n from collections import OrderedDict\n from neural_compressor.strategy.utils.tuning_structs import OpTuningConfig\n from neural_compressor.strategy.utils.tuning_sampler import OpWiseTuningSampler\n # op-wise\n conf = {'usr_cfg': { } }\n conf = DotDict(conf)\n # test space construction\n tuning_space = TuningSpace(deepcopy(self.capability), deepcopy(conf))\n logger.debug(tuning_space.root_item.get_details())\n initial_op_tuning_cfg = {}\n for item in tuning_space.root_item.options:\n if item.item_type == 'op':\n op_name, op_type = item.name\n initial_op_tuning_cfg[item.name] = OpTuningConfig(op_name, op_type, 'fp32', tuning_space)\n quant_mode_wise_items = OrderedDict()\n from neural_compressor.strategy.utils.constant import auto_query_order as query_order\n pre_items = set()\n for quant_mode in query_order:\n items = tuning_space.query_items_by_quant_mode(quant_mode)\n filtered_items = [item for item in items if item not in pre_items]\n pre_items = pre_items.union(set(items))\n quant_mode_wise_items[quant_mode] = filtered_items\n\n def initial_op_quant_mode(items_lst, target_quant_mode, op_item_dtype_dict):\n for item in items_lst:\n op_item_dtype_dict[item.name] = target_quant_mode\n\n op_item_dtype_dict = OrderedDict()\n for quant_mode, quant_mode_items in quant_mode_wise_items.items():\n initial_op_quant_mode(quant_mode_items, quant_mode, op_item_dtype_dict)\n \n op_wise_tuning_sampler = OpWiseTuningSampler(deepcopy(tuning_space), [], [],\n op_item_dtype_dict, initial_op_tuning_cfg)\n op3 = ('op_name3', 'op_type3')\n for tune_cfg in op_wise_tuning_sampler:\n op_cfg = tune_cfg[op3].get_state()\n act_dtype = op_cfg['activation']['dtype']\n weight_dtype = op_cfg['weight']['dtype']\n self.assertTrue(act_dtype == weight_dtype == 'int4')\n \n\n def test_tuning_space_merge_op_wise(self):\n # op-wise\n conf = {\n 'usr_cfg': {\n 'quantization': {\n 'op_wise': self.op_wise_user_cfg_for_fallback,\n }\n }\n\n }\n conf = DotDict(conf)\n # test fallback\n tuning_space2 = TuningSpace(deepcopy(self.capability), deepcopy(conf))\n logger.debug(tuning_space2.root_item.get_details())\n op_name1_only_fp32 = True\n for quant_mode in ['static', 'dynamic']:\n for item in tuning_space2.query_items_by_quant_mode(quant_mode):\n if item.name[0] == 'op_name1':\n op_name1_only_fp32 = False\n self.assertTrue(op_name1_only_fp32)\n\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/strategy/test_tuning_space_v2_1.x.py","file_name":"test_tuning_space_v2_1.x.py","file_ext":"py","file_size_in_byte":9544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"220787952","text":"__author__ = 'sophia'\nimport unittest\nimport sys\nfrom interfaceTest.Methods.BeopTools import BeopTools\nfrom interfaceTest import app\nimport datetime, time\n\nserverip = app.config['SERVERIP']\nt = 30\nsite_url = 'http://%s/v1/data/set_realtimedata_from_site' % serverip\nhistroy_url = \"http://%s/get_history_data_padded_reduce\" % serverip\nrealtime_url = \"http://%s/admin/dataPointManager/search/\" % serverip\n\n\nclass Service019(unittest.TestCase):\n testCaseID = 'Service019'\n projectName = \"不针对项目\"\n buzName = '接口v1/data/set_realtimedata_from_site测试'\n start = 0.0\n now = 0\n startTime = \"\"\n errors = []\n\n def setUp(self):\n self.start = datetime.datetime.now()\n self.startTime = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n self.logger = BeopTools.init_log(r'%s\\log\\%s.txt' % (sys.path[0], self.testCaseID))\n\n def Test(self):\n self.errors = []\n self.beopService()\n self.raiseError()\n\n def beopService(self):\n # 验证正确的参数,周期默认是m1,同时验证更新时间对不对\n data1 = {\"projId\": \"1\", \"point\": ['test_123_456'], \"value\": ['1'],\n 'time': str(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())), 'timePeriod': 'm1',\n 'waitForFinish': '0'}\n result_120 = self.postURL(data1, site_url)\n self.checkResult(result_120, data1)\n realtime_data = {\"projectId\": 1, \"current_page\": 1, \"page_size\": \"50\", \"text\": \"test_123_456\",\n \"isAdvance\": False, \"order\": None, \"isRemark\": None, \"flag\": None}\n result_realtime = self.postURL(realtime_data, realtime_url)\n self.checkRealTime(data1, result_realtime)\n ####验证传入中文参数,返回state为1\n data123 = {\"projId\": \"214\", \"point\": [\"ztest1\", \"ztest2\"], \"value\":[\"ceshi1\",\"测试2\"]}\n result_120 = self.postURL(data123, site_url)\n self.checkResult(result_120, data123)\n # 验证空的参数\n data2 = {}\n result_120 = self.postURL(data2, site_url)\n self.checkResult(result_120, data2)\n # 验证不完整的参数\n data3 = {\"projId\": \"1\", \"point\": ['test_123_456']}\n result_120 = self.postURL(data3, site_url)\n self.checkResult(result_120, data3)\n # 验证周期m1时候的值\n time_str = str(time.strftime(\"%Y-%m-%d %H:%M:00\", time.localtime()))\n print(time_str)\n data4 = {\"projId\": \"1\", \"point\": ['test_123_data4'], \"value\": ['1'], 'time': time_str, 'timePeriod': 'm1',\n 'waitForFinish': '0'}\n result_120 = self.postURL(data4, site_url)\n self.checkResult(result_120, data4)\n histroy_data = {\"projectId\": 1, \"pointList\": [\"test_123_data4\"], \"timeStart\": time_str,\n \"timeEnd\": time_str, \"timeFormat\": \"m1\"}\n result_history = self.postURL(histroy_data, histroy_url)\n self.checkHistory(data4, result_history)\n # 验证周期为m5时候的值\n time_str = self.comHM()\n print(time_str)\n data5 = {\"projId\": \"1\", \"point\": ['test_123_data5'], \"value\": ['1'], 'time': time_str,\n 'timePeriod': 'm5', 'waitForFinish': '0'}\n result_120 = self.postURL(data5, site_url)\n self.checkResult(result_120, data5)\n histroy_data = {\"projectId\": 1, \"pointList\": [\"test_123_data5\"], \"timeStart\": time_str,\n \"timeEnd\": time_str, \"timeFormat\": \"m5\"}\n result_history = self.postURL(histroy_data, histroy_url)\n self.checkHistory(data5, result_history)\n # 验证周期为h1时候的值\n time_str = str(time.strftime(\"%Y-%m-%d %H:00:00\", time.localtime()))\n print(time_str)\n data6 = {\"projId\": \"1\", \"point\": ['test_123_data6'], \"value\": ['1'], 'time': time_str,\n 'timePeriod': 'h1', 'waitForFinish': '0'}\n result_120 = self.postURL(data6, site_url)\n self.checkResult(result_120, data6)\n histroy_data = {\"projectId\": 1, \"pointList\": [\"test_123_data6\"], \"timeStart\": time_str,\n \"timeEnd\": time_str, \"timeFormat\": \"h1\"}\n result_history = self.postURL(histroy_data, histroy_url)\n self.checkHistory(data6, result_history)\n # 验证周期为d1的值\n time_str = str(time.strftime(\"%Y-%m-%d 00:00:00\", time.localtime()))\n print(time_str)\n data7 = {\"projId\": \"1\", \"point\": ['test_123_data7'], \"value\": ['1'], 'time': time_str,\n 'timePeriod': 'd1', 'waitForFinish': '0'}\n result_120 = self.postURL(data7, site_url)\n self.checkResult(result_120, data7)\n histroy_data = {\"projectId\": 1, \"pointList\": [\"test_123_data7\"], \"timeStart\": time_str,\n \"timeEnd\": time_str, \"timeFormat\": \"d1\"}\n result_history = self.postURL(histroy_data, histroy_url)\n self.checkHistory(data7, result_history)\n # # 验证周期不为m1,h1,m5,d1..例如为m6,看是否能够插进去数据\n # data8 = {\"projId\": \"1\", \"point\": ['test_123_data8'], \"value\": ['3'], 'time': '2016-07-22 00:20:00',\n # 'timePeriod': 'm6', 'waitForFinish': '0'}\n # result_120 = self.postURL(data8, site_url)\n # self.checkPeriod(result_120, data8)\n # # 验证时间格式不对,服务器不能保存数据,并有相关提示\n # data9 = {\"projId\": \"1\", \"point\": ['test_123_data9'], \"value\": ['4'], 'time': '2016-08-22',\n # 'timePeriod': 'm5', 'waitForFinish': '0'}\n # result_120 = self.postURL(data9, site_url)\n # self.checkTime(result_120, data9)\n # # 验证时间大于目前时间,服务器不能保存数据,并有相关提示\n # data10 = {\"projId\": \"1\", \"point\": ['test_123_data10'], \"value\": ['5'], 'time': '2016-08-22 00:20:00',\n # 'timePeriod': 'm5', 'waitForFinish': '0'}\n # result_120 = self.postURL(data10, site_url)\n # self.checkTime(result_120, data10)\n\n # 验证历史接口返回的点值和预期的是否相等\n def checkHistory(self, data, result):\n tool = BeopTools()\n name = data['point'][0]\n value = data['value'][0]\n if (result is not None and result.get('data') is not None):\n result_value = int(result['data'][name][0])\n if (int(data['value'][0]) == int(result['data'][data['point'][0]][0])):\n print('%s历史接口的值和预期的一致都是%s' % (data['point'][0], data['value'][0]))\n else:\n self.errors.append(\n '错误信息[%s]%s---没有保存数据,项目中芯国际(id=1)%s接口使用参数%s返回值和预期的点值不一致.预期点值:%s,%s接口返回的点值为:%d' % (\n tool.getTime(), self.testCaseID, histroy_url, str(data), value, histroy_url, result_value))\n else:\n print(result)\n self.errors.append('错误信息[%s]%s---项目:中芯国际(id=1)%s接口使用参数%s返回的值为空或者是没有历史数据' % (\n tool.getTime(), self.testCaseID, histroy_url, str(data)))\n\n def comHM(self):\n time_str = str(time.strftime(\"%Y-%m-%d %H:%M\", time.localtime()))\n h = time_str.split(' ')[1].split(':')[1][1]\n if (int(h) >= 0 and int(h) < 5):\n h0 = 0\n elif (int(h) >= 5 and int(h) <= 9):\n h0 = 5\n else:\n h0 = int(h)\n time_str0 = str(time_str.split(' ')[0]) + \" \" + str(time_str.split(' ')[1].split(':')[0]) + \":\" + str(\n time_str.split(' ')[1].split(':')[1][0]) + str(h0) + \":00\"\n return str(time_str0)\n\n def checkTime(self, result, data):\n tool = BeopTools()\n if result is not None:\n if type(result) == type({}) and 'state' in result.keys():\n self.errors.append(\n '错误信息[%s]%s---项目中芯国际(id=1)%s接口使用参数%s返回值与期待的不一致.实际为%s,应该是有时间格式或者时间不能大于目前时间的提示,并且没有保存数据' % (\n tool.getTime(), self.testCaseID, site_url, str(data), result))\n else:\n print('%s使用正确的参数返回值正确显示为%s' % (data['point'][0], result))\n\n def checkPeriod(self, result, data):\n tool = BeopTools()\n if result is not None:\n if type(result) == type({}) and 'state' in result.keys():\n self.errors.append(\n '错误信息[%s]%s---项目中芯国际(id=1)%s接口使用参数%s返回值与期待的不一致.实际为%s,应该是周期只能是m1,m5,h1,d1的提示,并且没有保存数据' % (\n tool.getTime(), self.testCaseID, site_url, str(data), result))\n else:\n print('%s使用正确的参数返回值正确显示为%s' % (data['point'][0], result))\n\n # 检查site_url接口返回过来的结果值\n def checkResult(self, result, data):\n tool = BeopTools()\n if result is not None:\n if type(result) == type({}) and 'state' in result.keys():\n print('%s使用正确的参数返回值正确显示为%s' % (data['point'][0], result))\n elif 'none' in result:\n if data == {}:\n print('使用空的参数返回值正确返回值为%s' % (result))\n else:\n print('%s点不完整的参数返回值正确返回值为%s' % (data['point'][0], result))\n else:\n self.errors.append('错误信息[%s]%s---项目中芯国际(id=1)%s接口使用参数%s返回值与期待的不一致.实际为%s,期待值:state:1' % (\n tool.getTime(), self.testCaseID, site_url, str(data), result))\n\n # 检查实时接口admin/dataPointManager/search/和site_url接口返回值是否相等\n def checkRealTime(self, value1, value2):\n tool = BeopTools()\n name = value1['point'][0]\n if value2 is not None and value2['list'] is not None:\n v1 = value1['value'][0]\n v2 = value2['list'][0]['pointvalue']\n update_time = value2['list'][0]['time']\n if (update_time):\n now = time.strftime(\"%Y-%m-%d %H:%M\", time.localtime())\n now = datetime.datetime.strptime(now, \"%Y-%m-%d %H:%M\")\n update = datetime.datetime.strptime(update_time, \"%Y-%m-%d %H:%M\")\n second = self.doTime(now, update)\n if second > 60*60+300:\n self.errors.append('错误信息[%s]%s---项目:中芯国际(id=1)%s接口点名%s更新时间超过5分钟' % (\n tool.getTime(), self.testCaseID, realtime_url, name))\n else:\n print(\"%s点更新正常。\" % (name))\n if (int(v1) == int(v2)):\n print('实时接口的值和post的值一样均为%s' % v1)\n else:\n self.errors.append(\n '错误信息没有保存数据,项目:中芯国际(id=1)%s接口使用参数%s,点值为%s,%s接口的点值为%s,两个值不一样' % (\n site_url, str(value1), v1, realtime_url, v2))\n else:\n self.errors.append(\n '错误信息[%s]%s---项目:中芯国际(id=1)%s接口点名%s返回值为空' % (tool.getTime(), self.testCaseID, realtime_url, name))\n\n def doTime(self, now, update):\n if (now > update):\n second = (now - update).seconds\n else:\n second = (update - now).seconds\n return second\n\n # post数据\n def postURL(self, data, url):\n tool = BeopTools()\n a = BeopTools()\n try:\n result = a.postData(url=url, data=data, t=t)\n return result\n except Exception as e:\n print(e.__str__())\n self.writeLog(e.__str__())\n self.errors.append(\"错误信息[%s]%s---访问%s接口失败.\" % (tool.getTime(), self.testCaseID, url))\n\n def writeLog(self, text):\n # logger = self.init_log()\n self.logger.info('[%s]---' % time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()) + '' + text)\n\n # 抛出异常值\n def raiseError(self):\n if self.errors != []:\n assert 0, \"\\n\".join(self.errors)\n else:\n pass\n\n def tearDown(self):\n use1 = str((datetime.datetime.now() - self.start).seconds)\n use = use1 + \"s\"\n self.now = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n # info.append([self.testCaseID, use, now])\n","sub_path":"service_case/Service019realtimedataFromSiteToV1.py","file_name":"Service019realtimedataFromSiteToV1.py","file_ext":"py","file_size_in_byte":12547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"425906183","text":"import argparse\nimport os\nfrom ldcEval import bleu_script,files2eval\n\nparser = argparse.ArgumentParser(\n description='Preprocess of LDC corpus')\nparser.add_argument('-test', type=str,\n default='nist03', metavar='S')\nparser.add_argument('-pair', type=str, default='cn-en', metavar='S')\nparser.add_argument('-len', type=int, default=80, metavar='N')\nparser.add_argument('-gpuid', type=int, default=0, metavar='N')\nparser.add_argument('-token', type=str, default='word', metavar='S')\n\nif __name__ == \"__main__\":\n nistSets = ['nist02']\n nistSets = ['nist02','nist03', 'nist04', 'nist05', 'nist06', 'nist08']\n pair = 'en-cn'\n src = pair.split('-')[0]\n tgt = pair.split('-')[1]\n state_name = 'obest'\n\n models=['rnn','bing','baidu','google']\n models=['rnn']\n for nist in nistSets:\n print(50*'-'+nist +'-'*50)\n for model in models:\n ref_path1 = 'corpus/ldc_data/'+nist+'/'+nist+'.clean.pkuseg.cn'\n # ref_path2 = 'corpus/ldc_data/'+nist+'/'+nist+'.clean.jieba.cn'\n # ref_path3 = 'corpus/ldc_data/'+nist+'/'+nist+'.clean.cn'\n hyp_path = 'generation/{}/'.format(model)+nist+'/'+nist+'.{}.pkuseg.cn'.format(model)\n if model =='rnn':\n hyp_path = 'generation/{}/'.format(model)+nist+'/'+nist+'.{}.pkuseg.{}.cn'.format(model,state_name)\n # hyp_path = 'generation/{}/'.format(model)+nist+'/'+nist+'.{}.raw.{}.cn'.format(model,state_name)\n # bleu0 = bleu_script(ref_path1+' '+ ref_path2 + ' ' + ref_path3,hyp_path)\n bleu0 = bleu_script(ref_path1,hyp_path)\n # print('BLEU score of baidu for the {} is {:.2f}'.format(nist,bleu0))\n bleu1, bleu2 = files2eval(ref_path1,hyp_path)\n print('BLEU score of {} for the {} is {:.2f}/{:.2f}'.format(model,nist,bleu0,bleu1))\n","sub_path":"oracleEva.py","file_name":"oracleEva.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"266913451","text":"# coding: utf-8\n\nfrom fabkit import * # noqa\n\n\n@task\ndef setup():\n python_version = '2.7.13'\n python = 'Python-{0}'.format(python_version)\n python_tgz = '{0}.tgz'.format(python)\n\n if not filer.exists(python_tgz):\n run('wget https://www.python.org/ftp/python/{0}/{1}'.format(python_version, python_tgz))\n\n if not filer.exists(python):\n run('[ -e {0} ] || tar xzf {1}'.format(python, python_tgz))\n\n sudo('yum groupinstall -y \"Development tools\"')\n sudo('yum install -y zlib-devel bzip2-devel python-devel openssl-devel'\n 'ncurses-devel sqlite-devel readline-devel tk-devel')\n\n if not filer.exists('/tmp/python27/bin/pip'):\n with api.cd(python):\n run('./configure --prefix=/tmp/python27')\n run('make')\n run('make altinstall')\n\n run('wget https://bootstrap.pypa.io/get-pip.py')\n run('/tmp/python27/bin/python2.7 get-pip.py')\n\n sudo('rm -rf /tmp/fabkit-repo')\n run('mkdir /tmp/fabkit-repo')\n with api.cd('/tmp/fabkit-repo'):\n run('git clone https://github.com/fabrickit/fabkit.git fabfile')\n run('/tmp/python27/bin/pip install -r fabfile/requirements.txt')\n run('cp -r /tmp/python27 /tmp/fabkit-repo/.python27')\n filer.template('/tmp/fabkit-repo/.gitignore')\n run('.python27/bin/fab -l')\n run('.python27/bin/fab -e genconfig')\n run('mv fabfile.ini.sample fabfile.ini')\n run('cp fabfile/etc/local_settings.py.sample conf/local_settings.py')\n run('cd .python27/bin/; ln -s python2.7 python')\n\n with api.cd('/tmp'):\n run('tar czf fabkit-repo.tar.gz fabkit-repo')\n\n scp('/tmp/fabkit-repo.tar.gz', '/tmp/fabkit-repo.tar.gz', is_local=False, is_receive=True)\n\n return {'status': 0}\n","sub_path":"fabscript/fabrickit/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"136735396","text":"'''\nextract c3d features files,\nproduce video_lists as format: video_name(full_path) frame_num feature_num\n'''\nimport os\nimport stat\nimport subprocess\nfrom get_frame_num import get_frame_num\n\n\n# video_dir = \"/home/wyd/C3D/examples/c3d_feature_extraction/input/HMDB51\"\n# if not os.path.exists(video_dir):\n# print \"cannot find video directory: %s\" % video_dir\n#\n# # create input list\n# # (0)\n# step_size = 8\ninput_list = \"./lists/c3d/input_lists.txt\"\n# input_f = open(input_list, 'w')\n# # create outputlist\n# # \noutput_list = \"./lists/c3d/output_lists.txt\"\n# output_f = open(output_list, 'w')\n#\n# video_list_f = open('./lists/video_lists.txt', 'w')\n#\n# # traversing the video_dir\n# for root, subdirs, files in os.walk(video_dir):\n# # for sub in subdirs:\n# # print os.path.join(root, sub)\n# for name in files:\n# file_name = os.path.join(root, name)\n# if '.avi' in file_name:\n# video_path = file_name\n# output_folder = video_path.replace('input', 'output').strip('.avi')\n# if not os.path.exists(output_folder):\n# os.makedirs(output_folder)\n# # get the frame num\n# print 'video: ', video_path\n# f_num = get_frame_num(video_path)\n# print 'frame: ', f_num\n# video_list_f.write(video_path + ' ' + str(f_num)) # write video name in lists\n# chunk_num = 0\n# for start in range(0, f_num-step_size+1, step_size):\n# input_f.write(video_path + ' ')\n# input_f.write(str(start))\n# input_f.write(' 0\\n')\n# # create an output folder for each video:\n# # output_folder/%06d % start\n# output_f.write(output_folder)\n# output_prefix = '/%06d' % start\n# output_f.write(output_prefix)\n# output_f.write('\\n')\n# chunk_num += 1\n# video_list_f.write(' ' + str(chunk_num) + '\\n')\n#\n# video_list_f.close()\n# input_f.close()\n# output_f.close()\n# run\ndata_dir = 'HMDB51'\ncpp_file = './cpp.sh'\nwith open(cpp_file, 'w') as cf:\n cf.write('./build/C3D ')\n cf.write(data_dir)\nos.chmod(cpp_file, stat.S_IRWXU)\nsubprocess.call(cpp_file, shell=True)\n# change the prototxt file\nmean_file = \"/home/wyd/C3D/examples/c3d_feature_extraction/sport1m_train16_128_mean.binaryproto\"\norg_proto_file = \"/home/wyd/C3D/examples/c3d_feature_extraction/prototxt/c3d_sport1m_feature_extractor_video.prototxt\"\nproto_file = \"./lists/c3d/c3d_sport1m_feature_extractor_video.prototxt\"\nproto_f = open(proto_file, 'w')\nfor line in open(org_proto_file):\n words = line.split()\n if 'source:' in words:\n proto_f.write(' source: ')\n proto_f.write('\\\"{}\\\"'.format(input_list))\n proto_f.write('\\n')\n elif 'mean_file:' in words:\n proto_f.write(' mean_file: ')\n proto_f.write('\\\"{}\\\"'.format(mean_file))\n proto_f.write('\\n')\n else:\n proto_f.write(line)\nproto_f.close()\n\npretrained_model = \"/home/wyd/C3D/examples/c3d_feature_extraction/conv3d_deepnetA_sport1m_iter_1900000\"\ngpu_id = '0'\nbatch_size = '50'\nbatch_num = '136'\nfeature_names = \"pool5\"\n\njob_file = \"./job.sh\"\n# create job file\nwith open(job_file, 'w') as f:\n f.write('GLOG_logtosterr=1 ')\n f.write('/home/wyd/C3D/build/tools/extract_image_features.bin ')\n f.write(proto_file + ' ')\n f.write(pretrained_model + ' ')\n f.write('{} {} {} '.format(gpu_id, batch_size, batch_num))\n f.write(output_list + ' ')\n f.write(feature_names)\n# run the job\n# os.chmod(job_file, stat.S_IRWXU)\n# subprocess.call(job_file, shell=True)\n\n# after this you will get the features in output_dir saved as\n# $output_dir/$action/$video_name/$start_frame.feature\n","sub_path":"util/run_c3d.py","file_name":"run_c3d.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"211642701","text":"\"\"\"\n Tests for the NYT Interface\n\n Run in directory with local config files\n > nosetests\n\n\"\"\"\nimport time\nimport unittest\nimport ConfigParser\nfrom datetime import datetime, timedelta\n\nfrom nyt_interface.nyt_interface import NytimesApi\n\nconfig = ConfigParser.ConfigParser()\nconfig.read(\"local_test_config.cfg\")\n\nNYT_API_KEY = config.get('NYTIMES', 'nyt_key')\n\n\nclass TestNYTInterface(unittest.TestCase):\n def tearDown(self):\n time.sleep(1)\n\n def testReturnArticleList(self):\n api = NytimesApi(NYT_API_KEY)\n articles = api.return_article_list('africa')\n self.assertIsInstance(articles, list)\n self.assertEqual(len(articles), 1)\n self.assertIsInstance(articles[0], dict)\n self.assertIn('web_url', articles[0].keys())\n\n def testReturnArticleListMultiple(self):\n api = NytimesApi(NYT_API_KEY)\n articles = api.return_article_list('sea', num=5)\n self.assertIsInstance(articles, list)\n self.assertTrue(len(articles) > 2)\n\n def testReturnAllClimateChangeQuery(self):\n api = NytimesApi(NYT_API_KEY)\n articles = api.return_all(\"climate change and the recession\")\n self.assertNotEqual(len(articles['response']['docs']), 0)\n\n def testReturnAllOtherQuery(self):\n api = NytimesApi(NYT_API_KEY)\n articles = api.return_all(\"dogs\")\n self.assertNotEqual(len(articles['response']['docs']), 0)\n\n def testTrendingArticleDates(self):\n api = NytimesApi(NYT_API_KEY)\n articles = api.return_trending_list(num=10)\n num_days_trending = 3\n first_date = datetime.today() - timedelta(num_days_trending)\n\n for art in articles:\n test_date = datetime.strptime(art['date'], '%Y-%m-%dT%H:%M:%S+%f')\n\n self.assertTrue(test_date.date() >= first_date.date())\n","sub_path":"climatechangebot/nyt_interface/tests/nyt_api_tests.py","file_name":"nyt_api_tests.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"30640772","text":"import scrapy\r\nfrom ..items import HorseAdsItem\r\n\r\n\r\nclass HorsezoneSpider(scrapy.Spider):\r\n name = 'HZ_ads'\r\n\r\n start_urls = [\r\n 'https://horsezone.com.au/category/196/Horses.html',\r\n 'https://horsezone.com.au/category/197/Stallions_at_Stud.html'\r\n ]\r\n\r\n # output format\r\n custom_settings = {'FEED_URI': \"HZ_ad_data.csv\",\r\n 'FEED_FORMAT': 'csv'}\r\n\r\n def parse(self, response):\r\n ad_links = response.css('div.title h3 a')\r\n yield from response.follow_all(ad_links, callback=self.parse_ad)\r\n\r\n # scrape all ad data\r\n try:\r\n next_page = response.css('ul.pagination li a')[-1].attrib['href']\r\n if next_page is not None:\r\n yield response.follow(next_page, callback=self.parse)\r\n except:\r\n pass\r\n\r\n def parse_ad(self, response):\r\n for item in response.css('div.main'):\r\n webpage = response.css('title').get()\r\n title = response.css('.listing_title::text').get()\r\n\r\n try:\r\n sold = item.xpath('.//div[@class=\"listing_title\"]/img/@src').get()\r\n except:\r\n sold = ''\r\n\r\n listing_id = item.xpath('.//div[contains(@style,\"display: inline; font-size: 0.6em\")]/text()').get()\r\n num_views = item.xpath('.//span[@class=\"times-viewed\"]/text()').get()\r\n seller_id = response.css('.seller_username a::text').get()\r\n extra_question = item.css('.question strong::text').get()\r\n extra_response = item.css('.answer::text').get()\r\n stallion_extras = item.xpath('.//div[@id=\"checkbox\"]/ul/li/text()').getall()\r\n text = item.css('.table.table-condensed.table-hover').get()\r\n info_label1 = item.css('.label::text')[0].get()\r\n info_value1 = item.css('.value::text')[1].get()\r\n info_label2 = item.css('.label::text')[1].get()\r\n info_value2 = item.css('.value::text')[2].get()\r\n info_label3 = item.css('.label::text')[2].get()\r\n info_value3 = item.css('.value::text')[3].get()\r\n info_label4 = item.css('.label::text')[3].get()\r\n info_value4 = item.css('.value::text')[4].get()\r\n\r\n try:\r\n info_label5 = item.css('.label::text')[4].get()\r\n except:\r\n info_label5 = ''\r\n\r\n try:\r\n info_value5 = item.css('.value::text')[5].get()\r\n except:\r\n info_value5 = ''\r\n\r\n try:\r\n info_label6 = item.css('.label::text')[5].get()\r\n except:\r\n info_label6 = ''\r\n\r\n try:\r\n info_value6 = item.css('.value::text')[6].get()\r\n except:\r\n info_value6 = ''\r\n\r\n try:\r\n info_label7 = item.css('.label::text')[6].get()\r\n except:\r\n info_label7 = ''\r\n\r\n try:\r\n info_value7 = item.css('.value::text')[7].get()\r\n except:\r\n info_value7 = ''\r\n\r\n try:\r\n info_label8 = item.css('.label::text')[7].get()\r\n except:\r\n info_label8 = ''\r\n\r\n try:\r\n info_value8 = item.css('.value::text')[8].get()\r\n except:\r\n info_value8 = ''\r\n\r\n try:\r\n info_label9 = item.css('.label::text')[8].get()\r\n except:\r\n info_label9 = ''\r\n\r\n items = HorseAdsItem()\r\n \r\n items['webpage'] = webpage\r\n items['title'] = title\r\n items['sold'] = sold\r\n items['listing_id'] = listing_id\r\n items['num_views'] = num_views\r\n items['seller_id'] = seller_id\r\n items['text'] = text\r\n items['extra_question'] = extra_question\r\n items['extra_response'] = extra_response\r\n items['stallion_extras'] = stallion_extras\r\n items['info_label1'] = info_label1\r\n items['info_value1'] = info_value1\r\n items['info_label2'] = info_label2\r\n items['info_value2'] = info_value2\r\n items['info_label3'] = info_label3\r\n items['info_value3'] = info_value3\r\n items['info_label4'] = info_label4\r\n items['info_value4'] = info_value4\r\n items['info_label5'] = info_label5\r\n items['info_value5'] = info_value5\r\n items['info_label6'] = info_label6\r\n items['info_value6'] = info_value6\r\n items['info_label7'] = info_label7\r\n items['info_value7'] = info_value7\r\n items['info_label8'] = info_label8\r\n items['info_value8'] = info_value8\r\n items['info_label9'] = info_label9\r\n\r\n yield items\r\n","sub_path":"horsezone_ads.py","file_name":"horsezone_ads.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"366592200","text":"# Download .wav file using youtube url example:\n# youtube-dl -a \"Batch file.txt\" -x --audio-format \"wav\" https://www.youtube.com/watch?v=q7DzC-y75-c\n\nimport os\n\nos.chdir('data')\nall_files = os.listdir()\ntext_files = [file for file in all_files if file[-4:] == '.txt']\nfor file in text_files:\n style = file[:-4]\n if not os.path.isdir(os.path.join('audio_data', style)):\n os.mkdir(os.path.join('audio_data', style))\n f = open(file)\n lines = f.readlines()\nfor line in lines:\n os.system(\"googler -x -w youtube.com --np '%s' | sed -n '2'p | sed 's/^[ ]*//' > tmp\" % line.strip())\n g = open('tmp')\n url = g.read()\n g.close()\n os.system(\"youtube-dl -x --audio-format 'wav' -o 'audio_data/{0}/%(title)s.%(ext)s' {1}\".format(style, url))\n\n# Manual for playlists\nstyle = 'tango'\nurl = 'https://www.youtube.com/playlist?list=PLa02XFyoGvTDkuBsWjCsay9ISx9Aam5w3'\nprint(\"youtube-dl -x --yes-playlist --playlist-start 1 --audio-format 'wav' -o 'audio_data/{0}/%(title)s.%(ext)s' {1}\".format(style, url))\n\n# Convert downloaded .wav files to mono and undersample to librosa default\nimport librosa as li\nimport soundfile as sf\n\naudio_dir = '/Users/eric/BMC/data/audio_data'\nstyles = os.listdir(audio_dir)[1:]\nfor style in styles:\n songs = os.listdir(os.path.join(audio_dir, style))[1:]\n for song in songs:\n if song[-7] == '5':\n song_file = os.path.join(audio_dir, style, song)\n y, sr = li.load(song_file)\n sf.write(song_file, y, sr)\n\nfor song in songs:\n song_file = os.path.join(audio_dir, style, song)\n y, sr = li.load(song_file)\n print(song + ': ' + str(li.beat.tempo(y)[0]))","sub_path":"code/old code/youtube_download.py","file_name":"youtube_download.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"329974813","text":"import numpy\nimport pandas\nimport matplotlib\nimport scipy\nimport sklearn\n\nfrom matplotlib import pyplot\nfrom sklearn.datasets import load_boston\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\ndef main():\n boston = load_boston()\n\n # create a pandas dataframe of the boston data\n frame = pandas.DataFrame(boston.data)\n\n # drop some columns that we suspect won't be as relevant\n ## CHAS, INDUS, NOX, AGE, B, PTRATIO\n predictors = frame.drop(labels = [2, 3, 4, 6, 10, 11], axis = 1)\n mhv = boston.target\n\n # create from our large dataset a randomly-generated training set and a randomly-generated test set\n pr_train, pr_test, mhv_train, mhv_test = sklearn.model_selection.train_test_split(predictors, mhv, test_size = 0.33, random_state = 50)\n\n # regression time!\n reg = LinearRegression()\n\n # fit our data and execute a prediction\n reg.fit(pr_train, mhv_train)\n mhv_pred = reg.predict(pr_test)\n\n # print out the r^2 value\n print(f\"r^2 value: {reg.score(pr_test, mhv_test)}\")\n\n # and plot it out!\n pyplot.scatter(mhv_test, mhv_pred)\n pyplot.xlabel(\"Actual listed value (in thousands)\")\n pyplot.ylabel(\"Predicted value based on data (in thousands)\")\n\n # and see how far off we were as mean squared error\n err = numpy.around(sklearn.metrics.mean_squared_error(mhv_test, mhv_pred), 3)\n pyplot.title(f\"Predicted versus actual listed value\\nfewer columns, 33% test set (MSE = {err})\")\n\n # determine the trendline\n tr = numpy.polyfit(mhv_test, mhv_pred, 1)\n trendline = numpy.poly1d(tr)\n\n # plot the line, coloring it magenta\n pyplot.plot(mhv_test, trendline(mhv_test), \"m-\")\n pyplot.show()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"boston-7.py","file_name":"boston-7.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"496708163","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BOARD)\n\n# Pin numbers\nPIN_MOTOR_DOOR = 40\n\n# Start configure pins for Door motor\nGPIO.setup(PIN_MOTOR_DOOR, GPIO.OUT) # output to send our PWM signal on\nmotorGateDoor = GPIO.PWM(PIN_MOTOR_DOOR, 50) # setup PWM on pin #3 at 50Hz\n# start it with 0 duty cycle so it doesn't set any angles on startup\nmotorGateDoor.start(0)\n# End Door motor\n\ntry:\n # open\n # turn towards 90 degree #Open\n motorGateDoor.ChangeDutyCycle(180 / 18 + 2)\n time.sleep(2)\n # close\n motorGateDoor.ChangeDutyCycle(2) # turn towards 0 degree\n time.sleep(1) # sleep 1 second\n motorGateDoor.stop()\n \nexcept KeyboardInterrupt:\n GPIO.cleanup()\n\nGPIO.cleanup()\n","sub_path":"raspberry-pi/tests/test-main-motor.py","file_name":"test-main-motor.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"621004759","text":"#! /usr/bin/env python3\n# imgurSearch.py - Launches new tabs for image searches.\nimport webbrowser\nimport sys\nimport pyperclip\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef imgurSearch():\n imgurBasis = 'http://imgur.com/search/score?q='\n if(len(sys.argv)>1):\n terms = ' '.join(sys.argv[1:])\n print('You searched for ' + terms + '.')\n terms = terms.replace(' ', '+')\n else:\n terms = pyperclip.paste()\n print('You searched for ' + terms + '.')\n terms = terms.replace(' ', '+')\n searches = imgurBasis+terms\n print('Getting imgur photo search page...')\n res = requests.get(searches)\n res.raise_for_status()\n #print(res)\n c = res.content\n soup = BeautifulSoup(c, 'html.parser')\n elements = soup.find_all('a', {'class': 'image-list-link'})\n #for i in range(len(elements)):\n # print(elements[i])\n # print('\\n\\n')\n #print(elements)\n #print(len(elements))\n c = 0\n for i in range(0,10):\n try:\n links = elements[i].find('img')['src']\n links = links[2:]\n webbrowser.open('https://' + links)\n c+=1\n except TypeError:\n continue\n print('There should have been ' + str(c) + ' different results.')\n\nimgurSearch()\n","sub_path":"Web_Scraping/imgurSearch.py","file_name":"imgurSearch.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"402706562","text":"import numpy as np\n\n# applies a function to the rows, columns, and the entire matrix and returns the results as a list\ndef compute(fn, arr):\n return [fn(arr, axis=0).tolist(), fn(arr, axis=1).tolist(), fn(arr)]\n\n\ndef calculate(list):\n # raise exception if the passed list doesn't contain 9 arguments\n if len(list) != 9:\n raise ValueError(\"List must contain nine numbers.\")\n\n # convert the passed list into a 3x3 numpy array\n arr = np.array(list).reshape((3, 3))\n\n # create a dictionary with empty lists as values\n calculations = dict.fromkeys(\n [\"mean\", \"variance\", \"standard deviation\", \"max\", \"min\", \"sum\"], []\n )\n\n # create a dictionary with the corresponding numpy functions as values\n funcs = {\n \"mean\": np.mean,\n \"variance\": np.var,\n \"standard deviation\": np.std,\n \"max\": np.max,\n \"min\": np.min,\n \"sum\": np.sum,\n }\n\n # applies each of the numpy functions to the numpy array, populating the dictionary\n for key in calculations.keys():\n calculations[key] = compute(funcs[key], arr)\n\n return calculations\n","sub_path":"mean_var_std.py","file_name":"mean_var_std.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"499239424","text":"import os\nimport sys\n\n#try:\n# dirname = sys.argv[1]\n#except IndexError:\n# exit('error: please provide argument')\n\ndirname = '../script_data/' # 4DEBUGGING\n\ntry:\n files = os.listdir(dirname)\nexcept IOError:\n exit('error: directory does not exist or is not readable'.format(dirname))\n\nfor filename in files:\n full_path = os.path.join(dirname, filename)\n file_size = os.path.getsize(full_path)\n if os.path.isfile(full_path):\n this_type = 'file'\n else:\n this_type = 'dir'\n\n print('{} ({}): {}'.format(filename, this_type, file_size))\n","sub_path":"scripts_CE9986/ex01-03review_problems/ex0806.py","file_name":"ex0806.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"169339869","text":"# coding: utf-8\n# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department\n# Distributed under the terms of \"New BSD License\", see the LICENSE file.\n\nfrom ctypes import c_double, c_int\nimport numpy as np\nimport os\nimport pandas as pd\nimport warnings\n\ntry:\n from lammps import lammps\nexcept ImportError:\n pass\nfrom pyiron.lammps.base import LammpsBase\nfrom pyiron.lammps.structure import UnfoldingPrism\nfrom pyiron.atomistics.job.interactive import GenericInteractive\nfrom pyiron.lammps.pipe import LammpsLibrary\n\n__author__ = \"Osamu Waseda, Jan Janssen\"\n__copyright__ = \"Copyright 2019, Max-Planck-Institut für Eisenforschung GmbH - \" \\\n \"Computational Materials Design (CM) Department\"\n__version__ = \"1.0\"\n__maintainer__ = \"Jan Janssen\"\n__email__ = \"janssen@mpie.de\"\n__status__ = \"production\"\n__date__ = \"Sep 1, 2018\"\n\n\nclass LammpsInteractive(LammpsBase, GenericInteractive):\n def __init__(self, project, job_name):\n super(LammpsInteractive, self).__init__(project, job_name)\n self._check_opened = False\n self._interactive_prism = None\n self._interactive_run_command = None\n self._interactive_grand_canonical = True\n self.interactive_cache = {'cells': [],\n 'energy_pot': [],\n 'energy_tot': [],\n 'forces': [],\n 'positions': [],\n 'pressures': [],\n 'steps': [],\n 'indices': [],\n 'temperature': [],\n 'computation_time': [],\n 'volume': []}\n\n @property\n def structure(self):\n return GenericInteractive.structure.fget(self)\n\n @structure.setter\n def structure(self, structure):\n GenericInteractive.structure.fset(self, structure)\n\n def get_structure(self, iteration_step=-1):\n return GenericInteractive.get_structure(self, iteration_step=iteration_step)\n\n def _interactive_lib_command(self, command):\n self._logger.debug('Lammps library: ' + command)\n self._interactive_library.command(command)\n\n def interactive_positions_getter(self):\n positions = np.reshape(np.array(self._interactive_library.gather_atoms(\"x\", 1, 3)),\n (len(self.structure), 3))\n if np.matrix.trace(self._interactive_prism.R) != 3:\n positions = np.dot(positions, self._interactive_prism.R.T)\n return positions.tolist()\n\n def interactive_positions_setter(self, positions):\n if np.matrix.trace(self._interactive_prism.R) != 3:\n positions = np.array(positions).reshape(-1, 3)\n positions = np.dot(positions, self._interactive_prism.R)\n positions = np.array(positions).flatten()\n if self.server.run_mode.interactive_non_modal:\n self._interactive_library.scatter_atoms(\"x\", 1, 3, positions)\n else:\n self._interactive_library.scatter_atoms(\"x\", 1, 3, (len(positions) * c_double)(*positions))\n self._interactive_lib_command('change_box all remap')\n\n def interactive_cells_getter(self):\n cc = np.array([[self._interactive_library.get_thermo('lx'),\n 0,\n 0],\n [self._interactive_library.get_thermo('xy'),\n self._interactive_library.get_thermo('ly'),\n 0],\n [self._interactive_library.get_thermo('xz'),\n self._interactive_library.get_thermo('yz'),\n self._interactive_library.get_thermo('lz')]])\n return self._interactive_prism.unfold_cell(cc)\n\n def interactive_cells_setter(self, cell):\n self._interactive_prism = UnfoldingPrism(cell)\n lx, ly, lz, xy, xz, yz = self._interactive_prism.get_lammps_prism()\n if np.matrix.trace(self._interactive_prism.R) != 3:\n warnings.warn('Warning: setting upper trangular matrix might slow down the calculation')\n if abs(xy) + abs(xz) + abs(yz) > 1.0e-6:\n if self.structure._is_scaled:\n self._interactive_lib_command(\n 'change_box all x final 0 %f y final 0 %f z final 0 %f \\\n xy final %f xz final %f yz final %f triclinic remap units box' % (lx, ly, lz, xy, xz, yz))\n else:\n self._interactive_lib_command(\n 'change_box all x final 0 %f y final 0 %f z final 0 %f \\\n xy final %f xz final %f yz final %f triclinic units box' % (lx, ly, lz, xy, xz, yz))\n else:\n if self.structure._is_scaled:\n self._interactive_lib_command(\n 'change_box all x final 0 %f y final 0 %f z final 0 %f remap units box' % (lx, ly, lz))\n else:\n self._interactive_lib_command(\n 'change_box all x final 0 %f y final 0 %f z final 0 %f units box' % (lx, ly, lz))\n\n def interactive_indices_setter(self, indices):\n el_struct_lst = self._structure_current.get_species_symbols()\n el_obj_lst = self._structure_current.get_species_objects()\n el_eam_lst = self.input.potential.get_element_lst()\n el_dict = {}\n for id_eam, el_eam in enumerate(el_eam_lst):\n if el_eam in el_struct_lst:\n id_el = list(el_struct_lst).index(el_eam)\n el = el_obj_lst[id_el]\n el_dict[el] = id_eam + 1\n elem_all = np.array([el_dict[self._structure_current.species[el]] for el in indices])\n if self.server.run_mode.interactive_non_modal:\n self._interactive_library.scatter_atoms('type', 0, 1, elem_all)\n else:\n self._interactive_library.scatter_atoms('type', 0, 1, (len(elem_all) * c_int)(*elem_all))\n\n def interactive_volume_getter(self):\n return self._interactive_library.get_thermo('vol')\n\n def interactive_forces_getter(self):\n ff = np.reshape(np.array(self._interactive_library.gather_atoms(\"f\", 1, 3)), (len(self.structure), 3))\n if np.matrix.trace(self._interactive_prism.R) != 3:\n ff = np.dot(ff, self._interactive_prism.R.T)\n return ff.tolist()\n\n def _interactive_lammps_input(self):\n del self.input.control['dump']\n del self.input.control['dump_modify']\n for key, value in zip(self.input.control.dataset['Parameter'], self.input.control.dataset['Value']):\n if key in ['read_data', 'units', 'dimension', 'boundary', 'atom_style', 'atom_modify', 'include', 'run',\n 'minimize']:\n continue\n else:\n self._interactive_lib_command(key + ' ' + str(value))\n\n def _interactive_set_potential(self):\n potential_lst = []\n if self.input.potential.files is not None:\n for potential in self.input.potential.files:\n if not os.path.exists(potential):\n raise ValueError('Potential not found: ', potential)\n potential_lst.append([potential.split('/')[-1], potential])\n for line in self.input.potential.get_string_lst():\n if len(line) > 2:\n for potential in potential_lst:\n if potential[0] in line:\n line = line.replace(potential[0], potential[1])\n self._interactive_lib_command(line.split('\\n')[0])\n\n def _reset_interactive_run_command(self):\n df = pd.DataFrame(self.input.control.dataset)\n self._interactive_run_command = \" \".join(df.T[df.index[-1]].values)\n\n def interactive_initialize_interface(self):\n if self.server.run_mode.interactive_non_modal:\n self._interactive_library = LammpsLibrary()\n else:\n self._interactive_library = lammps()\n if not all(self.structure.pbc):\n self.input.control['boundary'] = ' '.join(['p' if coord else 'f' for coord in self.structure.pbc])\n self._reset_interactive_run_command()\n self.interactive_structure_setter(self.structure)\n\n def calc_minimize(self, e_tol=1e-8, f_tol=1e-8, max_iter=1000, pressure=None, n_print=100):\n if self.server.run_mode.interactive_non_modal:\n warnings.warn('calc_minimize() is not implemented for the non modal interactive mode use calc_static()!')\n super(LammpsInteractive, self).calc_minimize(e_tol=e_tol, f_tol=f_tol, max_iter=max_iter, pressure=pressure,\n n_print=n_print)\n\n def run_if_interactive(self):\n if self._generic_input['calc_mode'] == 'md':\n self.input.control['run'] = self._generic_input['n_print']\n super(LammpsInteractive, self).run_if_interactive()\n self._reset_interactive_run_command()\n\n counter = 0\n iteration_max = int(self._generic_input['n_ionic_steps'] / self._generic_input['n_print'])\n while counter < iteration_max:\n self._interactive_lib_command(self._interactive_run_command)\n self.interactive_collect()\n counter += 1\n\n else:\n super(LammpsInteractive, self).run_if_interactive()\n self._interactive_lib_command(self._interactive_run_command)\n self.interactive_collect()\n\n def run_if_interactive_non_modal(self):\n if not self._interactive_fetch_completed:\n print('Warning: interactive_fetch being effectuated')\n self.interactive_fetch()\n super(LammpsInteractive, self).run_if_interactive()\n self._interactive_lib_command(self._interactive_run_command)\n self._interactive_fetch_completed = False\n\n def interactive_fetch(self):\n if self._interactive_fetch_completed and self.server.run_mode.interactive_non_modal:\n print('First run and then fetch')\n else:\n self.interactive_collect()\n self._logger.debug('interactive run - done')\n\n def interactive_structure_setter(self, structure):\n self._interactive_lib_command('clear')\n self._set_selective_dynamics()\n self._interactive_lib_command('units ' + self.input.control['units'])\n self._interactive_lib_command('dimension ' + str(self.input.control['dimension']))\n self._interactive_lib_command('boundary ' + self.input.control['boundary'])\n self._interactive_lib_command('atom_style ' + self.input.control['atom_style'])\n self._interactive_lib_command(\"atom_modify map array\")\n self._interactive_prism = UnfoldingPrism(structure.cell)\n if np.matrix.trace(self._interactive_prism.R) != 3:\n warnings.warn('Warning: setting upper trangular matrix might slow down the calculation')\n xhi, yhi, zhi, xy, xz, yz = self._interactive_prism.get_lammps_prism()\n if self._interactive_prism.is_skewed():\n self._interactive_lib_command('region 1 prism' +\n ' 0.0 ' + str(xhi) + ' 0.0 ' + str(yhi) + ' 0.0 ' + str(zhi) +\n ' ' + str(xy) + ' ' + str(xz) + ' ' + str(yz) + ' units box')\n else:\n self._interactive_lib_command('region 1 block' +\n ' 0.0 ' + str(xhi) + ' 0.0 ' + str(yhi) + ' 0.0 ' + str(zhi) + ' units box')\n el_struct_lst = self.structure.get_species_symbols()\n el_obj_lst = self.structure.get_species_objects()\n el_eam_lst = self.input.potential.get_element_lst()\n self._interactive_lib_command('create_box ' + str(len(el_eam_lst)) + ' 1')\n el_dict = {}\n for id_eam, el_eam in enumerate(el_eam_lst):\n if el_eam in el_struct_lst:\n id_el = list(el_struct_lst).index(el_eam)\n el = el_obj_lst[id_el]\n el_dict[el] = id_eam + 1\n self._interactive_lib_command('mass {0:3d} {1:f}'.format(id_eam + 1, el.AtomicMass))\n else:\n self._interactive_lib_command('mass {0:3d} {1:f}'.format(id_eam + 1, 1.00))\n self._interactive_lib_command('create_atoms 1 random ' + str(len(structure)) + ' 12345 1')\n positions = structure.positions.flatten()\n elem_all = np.array([el_dict[el] for el in structure.get_chemical_elements()])\n if self.server.run_mode.interactive_non_modal:\n self._interactive_library.scatter_atoms(\"x\", 1, 3, positions)\n self._interactive_library.scatter_atoms('type', 0, 1, elem_all)\n else:\n self._interactive_library.scatter_atoms(\"x\", 1, 3, (len(positions) * c_double)(*positions))\n self._interactive_library.scatter_atoms('type', 0, 1, (len(elem_all) * c_int)(*elem_all))\n self._interactive_lib_command('change_box all remap')\n self._interactive_lammps_input()\n self._interactive_set_potential()\n\n def from_hdf(self, hdf=None, group_name=None):\n \"\"\"\n Recreates instance from the hdf5 file\n\n Args:\n hdf (str): Path to the hdf5 file\n group_name (str): Name of the group which contains the object\n \"\"\"\n super(LammpsInteractive, self).from_hdf(hdf=hdf, group_name=group_name)\n self.species_from_hdf()\n\n def collect_output(self):\n if self.server.run_mode.interactive or self.server.run_mode.interactive_non_modal:\n pass\n else:\n super(LammpsInteractive, self).collect_output()\n\n def update_potential(self):\n self._interactive_lib_command(self.potential.Config[0][0])\n self._interactive_lib_command(self.potential.Config[0][1])\n\n def interactive_indices_getter(self):\n return super(LammpsInteractive, self).interactive_indices_getter().tolist()\n\n def interactive_energy_pot_getter(self):\n return self._interactive_library.get_thermo(\"pe\")\n\n def interactive_energy_tot_getter(self):\n return self._interactive_library.get_thermo(\"etotal\")\n\n def interactive_steps_getter(self):\n return self._interactive_library.get_thermo(\"step\")\n\n def interactive_temperatures_getter(self):\n return self._interactive_library.get_thermo(\"temp\")\n\n def interactive_stress_getter(self):\n \"\"\"\n This gives back an Nx3x3 array of stress/atom defined in http://lammps.sandia.gov/doc/compute_stress_atom.html\n Keep in mind that it is stress*volume in eV. Further discussion can be found on the website above.\n\n Returns:\n numpy.array: Nx3x3 np array of stress/atom\n \"\"\"\n if not 'stress' in self.interactive_cache.keys():\n self._interactive_lib_command('compute st all stress/atom NULL')\n self._interactive_lib_command('run 0')\n self.interactive_cache['stress'] = []\n ss = np.array([self._interactive_library.extract_compute('st', 1, 2)[i][j + (j != k) * (k + 2)]\n for i in range(len(self.structure))\n for j in range(3)\n for k in range(3)]).reshape(len(self.structure), 3, 3)/1.602e6\n if np.matrix.trace(self._interactive_prism.R) != 3:\n ss = np.dot(np.dot(self._interactive_prism.R, ss), self._interactive_prism.R.T)\n return ss\n\n def interactive_pressures_getter(self):\n pp = np.array([[self._interactive_library.get_thermo('pxx'),\n self._interactive_library.get_thermo('pxy'),\n self._interactive_library.get_thermo('pxz')],\n [self._interactive_library.get_thermo('pxy'),\n self._interactive_library.get_thermo('pyy'),\n self._interactive_library.get_thermo('pyz')],\n [self._interactive_library.get_thermo('pxz'),\n self._interactive_library.get_thermo('pyz'),\n self._interactive_library.get_thermo('pzz')]])\n if np.matrix.trace(self._interactive_prism.R) != 3:\n pp = np.dot(np.dot(self._interactive_prism.R, pp), self._interactive_prism.R.T)\n return pp / 10000 # bar -> GPa\n\n def interactive_close(self):\n if self.interactive_is_activated():\n self._interactive_library.close()\n with self.project_hdf5.open(\"output\") as h5:\n if 'interactive' in h5.list_groups():\n for key in h5['interactive'].list_nodes():\n h5['generic/' + key] = h5['interactive/' + key]\n super(LammpsInteractive, self).interactive_close()\n","sub_path":"pyiron/lammps/interactive.py","file_name":"interactive.py","file_ext":"py","file_size_in_byte":16674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"146214390","text":"from flask import Flask, request, redirect\nfrom algoliasearch import algoliasearch\nimport json\nimport re\nimport os\nimport geocoder\n\napp = Flask(__name__)\nclient = algoliasearch.Client(\"user\", 'passs')\nindex = client.init_index('temp')\n\ndef hasNumbers(inputString):\n return bool(re.search(r'\\d', inputString))\n\n\n@app.route(\"/sms\", methods=['GET', 'POST'])\ndef incoming_sms():\n if request.method == 'POST':\n text = request.data.decode('utf-8').replace(u'\\ufeff', '')\n print(str(text))\n g = geocoder.arcgis(str(text))\n geoco = g.geojson\n lat = geoco['features'][0]['geometry']['coordinates'][1]\n lon = geoco['features'][0]['geometry']['coordinates'][0]\n aroundLatLng = str(lat)+','+str(lon)\n print(aroundLatLng)\n result = index.search('', {\"aroundLatLng\": aroundLatLng})\n msg_result = \"Nearest clinic for your location is : \\n\"\n #msg_result += \"Serial Number : \"+str(result['hits'][0]['Serial Number'])+\"\\n\"\n msg_result += \"Name : \"+str(result['hits'][0]['Name'])+\"\\n\"\n msg_result += \"Address-1 : \"+str(result['hits'][0]['Address-1'])+\"\\n\"\n msg_result += \"Address-2 : \"+str(result['hits'][0]['Address-2'])+\"\\n\"\n msg_result += \"City : \"+str(result['hits'][0]['City'])+\"\\n\"\n msg_result += \"State : \"+str(result['hits'][0]['State'])+\"\\n\"\n msg_result += \"Zip Code : \"+str(result['hits'][0]['Zip'])+\"\\n\"\n msg_result += \"Phone Number : \"+str(result['hits'][0]['Phone Number'])+\"\\n\"\n msg_result += \"Website : \"+str(result['hits'][0]['Website'])+\"\\n\"\n print(msg_result)\n return str(msg_result)\n else:\n return \"Hello Welcome to Clinic-finder\"\n \nif __name__ == \"__main__\":\n app.debug = True\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"using-studio.py","file_name":"using-studio.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"185337494","text":"import numpy as np\nimport operator #for sorting\nimport matplotlib.pyplot as plt\nimport os\nfrom lib import kNN\n\ndef CreateDataset():\n _group = np.array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])\n _labels = ['a','a','b','b']\n return _group, _labels\n\ndef file2mat(fileName, delimeter = '\\t') :\n '''\n output feature_array, label_Vector\n '''\n #get number of lines in file\n \n with open(fileName,'r') as fr:\n raw_data = fr.readlines()\n nb_row = len(raw_data)\n nb_col = len(raw_data[0].split(delimeter))\n #initiate Numpy matrix to return\n return_array = np.empty((nb_row,nb_col - 1))\n label_Vector = []\n\n #parse line to a list\n love_dict = {'largeDoses':3,'smallDoses':2, 'didntLike':1}\n index = 0\n\n for line in raw_data:\n line = line.strip() #strip(), take all the char btw the given char in the str, if '', then take the whole line\n list_By_line = line.split(delimeter) #element delimited by the tab char\n return_array[index,:] = list_By_line[0:3]\n if(list_By_line[-1].isdigit()): #test if the last columne is digital value. create a dict to transfer str to digit\n label_Vector.append(int(list_By_line[-1]))\n else:\n label_Vector.append(love_dict.get(list_By_line[-1]))\n index += 1\n\n return return_array, np.array(label_Vector)\n\ndef load_image(filepath):\n '''\n load data from a image-like file\n\n Parameters:\n -----------\n fname: str or path-like object( absolute or current working dir)\n\n Results:\n --------\n feature vector: array.\n the feature vector with the shape (n_features,) \n '''\n with open(filepath,'r') as dossier:\n raw_image = [row.strip() for row in dossier.readlines()]\n img_feature = np.array(list(''.join(raw_image)),dtype = 'i4') # i4 means int32\n return img_feature\n\ndef images_data(folder):\n '''\n get all digit images into a numpy array which serves as the feature array of kNN and it's labels.\n\n Parameters:\n -----------\n folder path : str or working path dir\n the name of folder where the images are stored.\n\n Return:\n -------\n feature array : array\n feature array with the shape (n_sample , n_features). each sample is from a digit and each feature is a pixel.\n label vector : array (n_simple,)\n class labels with the shape(n_sample,).\n '''\n fld = os.listdir(folder) #this method returns a list contaning the names of the entities in the given directory \n #initialize feature array (n_sample,n_feature)\n n_s = len(fld)\n n_f = len(load_image(os.path.join(folder,fld[0])))\n f_array = np.empty([n_s, n_f], dtype = 'i4')\n label = np.empty(n_s, dtype = 'i4')\n\n #put the image vector into each line of feature array\n for i ,f_name in enumerate(fld):\n digitPath = os.path.join(folder,f_name) \n f_array[i,:] = load_image(digitPath)\n label[i] = f_name.split('_')[0]\n \n return f_array, label\n\ndef data_Norm(dataSet):\n '''\n output normalized vector, min_vector and d_interval\n '''\n d_min = dataSet.min(0) # 0 means the values in each colume\n d_max = dataSet.max(0)\n d_interval = d_max - d_min\n d_Norm = np.empty(np.shape(dataSet))\n d_Norm = (dataSet - np.tile(d_min,(dataSet.shape[0],1))) / np.tile(d_interval,(dataSet.shape[0],1)) \n return d_Norm, d_min, d_interval\n\ndef Split_train_set(X, y, ratio):\n '''\n creating a training set and test set with given ratio\n randomly choose ratio * len(X) sample as training set. \n\n Parameters:\n -----------\n X : array.\n Feature array with the shape(n_sample, n_feature)\n y : array.\n Label array with the shape(n_samples,)\n ratio : float\n The ratio of n_training_set and n_test_set\n\n Result:\n -------\n x_train : array.\n Training feature array. \n y_train : array.\n Training label\n x_test : array.\n Testing feature array\n y_test : array.\n Testing label\n '''\n permuted_indices = np.random.permutation(len(X)) #take the indice and get values later\n nb_test= int(ratio * len(X))\n test_indice = permuted_indices[:nb_test] #take the first nb_test element, per[nb_test] isn't included \n train_indice = permuted_indices[nb_test:]\n #take the relavent row\n x_test = X[test_indice,:]\n y_test = y[test_indice]\n x_train = X[train_indice,:]\n y_train = y[test_indice]\n\n return x_test,y_test,x_train,y_train\n \ndef ErrorTest(ratio,filename,k, method = 'kNN'):\n '''\n using the given algorithm to test the error rate of prediction\n\n Parameter:\n ----------\n ratio: float.\n division of testing set and training set\n filename: array.\n the row data\n k : int\n number of nearest neighborhood\n \n Results:\n --------\n errorRate:float.\n the error rate of prediction using given method.\n '''\n _X_raw, _y = file2mat(filename)\n _X, d_min, d_interval = data_Norm(_X_raw)\n x_test,y_test,x_train,y_train = Split_train_set(_X,_y,ratio)\n err_Count = 0.0\n for i in range(len(x_test)):\n Predict_rs = kNN.kNN_Classify0(x_test[i], _X, _y, k)\n # print( \"the classifer came back with : %s, the real answer is :%s\" %(Predict_rs,y_test[i]))\n if (Predict_rs != y_test[i]): err_Count += 1.0\n errorRate = err_Count/float(len(x_test)) \n #print(\"the total error rate is : %f \" % errorRate)\n return errorRate\n\n","sub_path":"1_kNN/lib/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"388411851","text":"import sys\nimport configparser\nimport torch\nimport os\nimport math\nimport numpy as np\nimport scipy.ndimage.filters as fil\n\n# import config file\nconf_path = os.path.dirname(os.path.dirname(os.path.dirname(\n os.path.dirname(os.path.abspath(__file__)))))\nconf_path += '/conf.ini'\nconf = configparser.ConfigParser()\nconf.read(conf_path)\n\n# add parent path, if not already added\nparent_path = conf['PATHS']['PARENT_DIR']\nins = sys.path.insert(1, parent_path)\nins if parent_path not in sys.path else 0\n\ntorch.manual_seed(5)\n\ndef gaussian_filter(imL, new_dimension, device):\n channels = imL.shape[1]\n dim = 2 # nof dimensions (=2, spatial data)\n downscale = imL.shape[2]/new_dimension[0]*0.5 + imL.shape[3]/new_dimension[1]*0.5\n sigma = downscale / 3.0\n radius = int(4.0*sigma + 0.5)\n kernel_size = 2*radius + 1\n\n # method\n kernel_size = [kernel_size] * dim\n sigma = [sigma] * dim\n kernel = 1\n meshgrids = torch.meshgrid(\n [torch.arange(size, dtype=torch.float32)\n for size in kernel_size\n ]\n )\n \n for size, std, mgrid in zip(kernel_size, sigma, meshgrids):\n mean = (size - 1) / 2\n kernel *= 1 / (std * math.sqrt(2 * math.pi)) * \\\n torch.exp((-((mgrid - mean) / (std)) ** 2)/2)\n \n kernel = kernel / torch.sum(kernel)\n\n # repeat along input's channels\n kernel = kernel.view(1, 1, *kernel.size())\n kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))\n \n if device == 'cuda':\n kernel = kernel.cuda()\n imL = torch.nn.functional.pad(imL, (radius, radius, radius, radius), 'reflect')\n imL = torch.nn.functional.conv2d(imL, weight = kernel, groups = channels)\n return imL\n\n# f1: 2d downsampling\ndef downsampling_2d(x, new_dimension, device):\n x = gaussian_filter(x, new_dimension, device)\n x = torch.nn.functional.interpolate(\n x, [new_dimension[0], new_dimension[1]], mode='bilinear',\n align_corners=False)\n return x\n\n\n# helper module\nclass residual_2d_module(torch.nn.Module):\n # bn + relu + conv2d strategy\n def __init__(self, ch):\n super().__init__()\n self.seq1 = torch.nn.Sequential(\n torch.nn.BatchNorm2d(ch),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv2d(ch, ch, 3, 1, 1, 1, bias=False)\n )\n\n self.seq2 = torch.nn.Sequential(\n torch.nn.BatchNorm2d(ch),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv2d(ch, ch, 3, 1, 1, 1, bias=False))\n\n def forward(self, x):\n out = self.seq1(x)\n out = self.seq2(out)\n out += x\n return out\n\n\n# f2: 2d cnn between scales\n# class cnn_2d_between_scales(torch.nn.Module):\n# def __init__(self, ch, num_of_residuals):\n# super().__init__()\n\n# layers = []\n# for i in range(num_of_residuals):\n# layers.append(residual_2d_module(ch))\n# self.seq = torch.nn.Sequential(*layers)\n\n# def forward(self, x):\n# return self.seq(x)\n\n\n# f3: 2d cnn to compute comparable features\nclass cnn_2d_for_comparable_features(torch.nn.Module):\n def __init__(self, ch, num_of_residuals):\n super().__init__()\n\n # first layer\n self.first_2d_layer = torch.nn.Sequential(\n torch.nn.Conv2d(3, ch, 3, 1, 1, 1, bias=True)\n )\n\n layers = []\n for i in range(num_of_residuals):\n layers.append(residual_2d_module(ch))\n self.seq = torch.nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.first_2d_layer(x)\n return self.seq(x)\n\n\n# 2d module: downsampling + f3\nclass module_2d(torch.nn.Module):\n def __init__(self, ch, num_of_residuals_on_f2,\n num_of_residuals_on_f3):\n super().__init__()\n\n # self.f2 = cnn_2d_between_scales(ch, num_of_residuals_on_f2)\n self.f3 = cnn_2d_for_comparable_features(ch, num_of_residuals_on_f3)\n\n def forward(self, x, new_dimension, extract, device):\n out = downsampling_2d(x, new_dimension, device)\n # out = self.f2(out)\n if extract:\n out1 = self.f3(out)\n else:\n out1 = None\n return out, out1\n\n\nclass descriptors_extraction(torch.nn.Module):\n def __init__(self, ch, num_of_residuals_on_f2,\n num_of_residuals_on_f3):\n super().__init__()\n\n # # first layer\n # self.first_2d_layer = torch.nn.Sequential(\n # torch.nn.Conv2d(3, ch, 3, 1, 1, 1, bias=True)\n # )\n\n # basic_module\n self.module_2d_1 = module_2d(ch, num_of_residuals_on_f2,\n num_of_residuals_on_f3)\n self.module_2d_2 = module_2d(ch, num_of_residuals_on_f2,\n num_of_residuals_on_f3)\n self.module_2d_3 = module_2d(ch, num_of_residuals_on_f2,\n num_of_residuals_on_f3)\n self.module_2d_4 = module_2d(ch, num_of_residuals_on_f2,\n num_of_residuals_on_f3)\n \n def forward(self, im, scales, prediction_from_scales, device):\n min_prediction_scale = min(prediction_from_scales)\n\n # 3 -> ch1 channels\n tmp = im\n\n # 2d processing\n out_tensors = []\n for i in range(len(scales)):\n sc = scales[i]\n extract = True if i >= min_prediction_scale else False\n if i == 0:\n tmp1, tmp2 = self.module_2d_1(tmp, sc[1:], extract, device)\n elif i == 1:\n tmp1, tmp2 = self.module_2d_2(tmp, sc[1:], extract, device)\n elif i == 2:\n tmp1, tmp2 = self.module_2d_3(tmp, sc[1:], extract, device)\n elif i == 3:\n tmp1, tmp2 = self.module_2d_4(tmp, sc[1:], extract, device)\n else:\n tmp1, tmp2 = self.module_2d_1(tmp, sc[1:], extract, device)\n \n out_tensors.append(tmp2)\n\n return out_tensors\n\n# f4: patch comparison module\ndef patch_comparison_volume(imL, imR, imL_d, imR_d, max_disp, is_training, device, ref = 'left'):\n if ref == 'left':\n b = imL_d.size()[0]\n ch = imL_d.size()[1]\n h = imL_d.size()[2]\n w = imL_d.size()[3]\n\n imL_d_abs = torch.abs(imL_d)\n imR_d_abs = torch.abs(imR_d)\n\n imL = torch.nn.functional.interpolate(\n imL, (h,w), mode='bilinear', align_corners=True)\n imR = torch.nn.functional.interpolate(\n imR, (h,w), mode='bilinear', align_corners=True)\n\n vol = torch.zeros([b, ch+3, max_disp+1, h, w], dtype=torch.float32,\n device=device, requires_grad=False)\n\n tmp = (imL_d_abs + imR_d_abs)/2 * torch.exp(-torch.abs(imL_d - imR_d))\n vol[:, :3, 0, :, :] = imL\n vol[:, 3:, 0, :, :] = tmp\n\n for i in range(1, max_disp + 1):\n vol[:, :3, i, :, i:] = imL[:,:,:,i:]\n\n tmp1 = imL_d[:,:,:,i:]\n tmp2 = imR_d[:,:,:,:-i]\n tmp1_abs = imL_d_abs[:,:,:,i:]\n tmp2_abs = imR_d_abs[:,:,:,:-i]\n tmp = (tmp1_abs + tmp2_abs)/2 * torch.exp(-torch.abs(tmp1 - tmp2))\n vol[:, 3:, i, :, i:] = tmp\n\n # assure tensor is contiguous\n if not vol.is_contiguous():\n vol = vol.contiguous()\n \n elif ref == 'right':\n b = imL_d.size()[0]\n ch = imL_d.size()[1]\n h = imL_d.size()[2]\n w = imL_d.size()[3]\n\n imL_d_abs = torch.abs(imL_d)\n imR_d_abs = torch.abs(imR_d)\n\n imL = torch.nn.functional.interpolate(\n imL, (h,w), mode='bilinear', align_corners=True)\n imR = torch.nn.functional.interpolate(\n imR, (h,w), mode='bilinear', align_corners=True)\n\n vol = torch.zeros([b, ch+3, max_disp+1, h, w], dtype=torch.float32,\n device=device, requires_grad=False)\n\n tmp = (imL_d_abs + imR_d_abs)/2 * torch.exp(-torch.abs(imL_d - imR_d))\n vol[:, :3, 0, :, :] = imR\n vol[:, 3:, 0, :, :] = tmp\n\n for i in range(1, max_disp + 1):\n vol[:, :3, i, :, :-i] = imR[:,:,:,:-i]\n\n tmp1 = imL_d[:,:,:,i:]\n tmp2 = imR_d[:,:,:,:-i]\n tmp1_abs = imL_d_abs[:,:,:,i:]\n tmp2_abs = imR_d_abs[:,:,:,:-i]\n tmp = (tmp1_abs + tmp2_abs)/2 * torch.exp(-torch.abs(tmp1 - tmp2))\n vol[:, 3:, i, :, :-i] = tmp\n\n # assure tensor is contiguous\n if not vol.is_contiguous():\n vol = vol.contiguous()\n \n\n return vol\n\n# helper module\nclass residual_3d_module(torch.nn.Module):\n # bn + relu + conv3d strategy\n def __init__(self, ch):\n super().__init__()\n self.seq1 = torch.nn.Sequential(\n torch.nn.BatchNorm3d(ch),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv3d(ch, ch, 3, 1, 1, 1, bias=False)\n )\n\n self.seq2 = torch.nn.Sequential(\n torch.nn.BatchNorm3d(ch),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv3d(ch, ch, 3, 1, 1, 1, bias=False))\n\n def forward(self, x):\n out = self.seq1(x)\n out = self.seq2(out)\n out += x\n return out\n\n\n# f5: for out\nclass for_out_3d(torch.nn.Module):\n def __init__(self, ch, num_of_residuals):\n super().__init__()\n\n self.first_layer = torch.nn.Sequential(\n torch.nn.BatchNorm3d(ch),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv3d(ch, ch, 3, 1, 1, 1, bias=False)\n )\n\n layers = []\n for i in range(num_of_residuals):\n layers.append(residual_3d_module(ch))\n self.seq = torch.nn.Sequential(*layers)\n\n self.last_layer = torch.nn.Sequential(\n torch.nn.BatchNorm3d(ch),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv3d(ch, 1, 3, 1, 1, 1, bias=False)\n )\n\n def forward(self, x):\n out = self.first_layer(x)\n out = self.seq(out)\n out = self.last_layer(out)\n return out\n\n\n# f6: 3d upsample\ndef upsampling_3d(x, new_dimension):\n return torch.nn.functional.interpolate(\n x, new_dimension, mode='trilinear',\n align_corners=True)\n\n\n# f7: process before merging\nclass before_merging(torch.nn.Module):\n def __init__(self, ch, num_of_residuals):\n super().__init__()\n\n self.first_layer = torch.nn.Sequential(\n torch.nn.BatchNorm3d(ch + 3),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv3d(ch+3, ch, 3, 1, 1, 1, bias=False)\n )\n\n layers = []\n for i in range(num_of_residuals):\n layers.append(residual_3d_module(ch))\n self.seq = torch.nn.Sequential(*layers)\n\n def forward(self, x):\n out = self.first_layer(x)\n out = self.seq(out)\n return out\n\n\n# f8: merging\nclass merging_3d(torch.nn.Module):\n def __init__(self, ch, num_of_residuals):\n super().__init__()\n\n self.first_layer = torch.nn.Sequential(\n torch.nn.BatchNorm3d(2*ch),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv3d(2*ch, 2*ch, 3, 1, 1, 1, bias=False),\n torch.nn.BatchNorm3d(2*ch),\n torch.nn.ReLU(inplace=True),\n torch.nn.Conv3d(2*ch, ch, 3, 1, 1, 1, bias=False)\n \n )\n\n layers = []\n for i in range(num_of_residuals):\n layers.append(residual_3d_module(ch))\n self.seq = torch.nn.Sequential(*layers)\n\n def forward(self, x1, x2):\n if isinstance(x1, torch.Tensor):\n out = torch.cat((x1, x2), 1)\n out = self.first_layer(out)\n out = self.seq(out)\n else:\n out = x2\n return out\n\n\n# wrapper module\nclass module_3d(torch.nn.Module):\n def __init__(self, ch, num_of_residuals_f7, num_of_residuals_f8):\n super().__init__()\n\n self.before_merging = before_merging(ch, num_of_residuals_f7)\n self.merging_3d = merging_3d(ch, num_of_residuals_f8)\n\n def forward(self, x1, x2):\n # processing of x1\n if isinstance(x1, torch.Tensor):\n tmp1 = upsampling_3d(x1, x2.shape[2:])\n else:\n tmp1 = x1\n # tmp1 = self.before_merging(tmp1)\n\n # processing of x2\n tmp2 = self.before_merging(x2)\n\n # merging\n tmp = self.merging_3d(tmp1, tmp2)\n\n return tmp\n\n\ndef softargmax(vol, new_dimension, device):\n vol = torch.nn.functional.interpolate(vol, new_dimension, mode='trilinear', align_corners=True)\n \n # prepare vol\n vol = vol.squeeze(1)\n vol = torch.nn.functional.softmax(vol, 1)\n\n # prepare coeffs\n tmp = torch.linspace(0, vol.shape[1]-1, steps=vol.shape[1], requires_grad=False)\n tmp = tmp.reshape((1, vol.shape[1], 1, 1)).expand(\n (vol.shape[0], vol.shape[1], vol.shape[2], vol.shape[3]))\n\n tmp = tmp.contiguous().to(device)\n\n return torch.sum(tmp*vol, 1)\n","sub_path":"vol2/models/merging_info_net_custom_features_free_2d_weights/submodules1.py","file_name":"submodules1.py","file_ext":"py","file_size_in_byte":12839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"381000596","text":"# -*- coding: UTF-8 -*-\r\n# -------------------------------------------------------------\r\n# @Author : Etpoem\r\n# @Time : 2020/12/18 16:22\r\n# @Desc : \r\n# -------------------------------------------------------------\r\nimport toml\r\nimport json\r\nimport time\r\nimport pymysql\r\nimport logging\r\nfrom DBUtils.PersistentDB import PersistentDB\r\nfrom pathlib import Path\r\n\r\nlogger = logging.getLogger('main.mysql')\r\ncfg = toml.load(Path(__file__).parents[1] / 'config.toml')\r\n\r\n_HOST = cfg['mysql']['host']\r\n_PORT = cfg['mysql']['port']\r\n_DATABASE = cfg['mysql']['database']\r\n\r\n\r\nclass MysqlManager(object):\r\n def __init__(self):\r\n self.pool = PersistentDB(creator=pymysql,\r\n ping=0,\r\n host=_HOST,\r\n port=_PORT,\r\n user=cfg['mysql']['user'],\r\n password=cfg['mysql']['password'])\r\n self._connect_check()\r\n del self.pool\r\n self.pool = PersistentDB(creator=pymysql,\r\n ping=0,\r\n host=_HOST,\r\n port=_PORT,\r\n user=cfg['mysql']['user'],\r\n password=cfg['mysql']['password'],\r\n database=_DATABASE)\r\n self.main_table = cfg['mysql']['main_pedestrian_table']\r\n logger.info(f'MySQL internal 初始化完成 ')\r\n\r\n def _connect_check(self):\r\n \"\"\"\r\n 检查 MySQL 服务端是否可用,连接失败后进行多次重连接,睡眠时间递增\r\n :return:\r\n \"\"\"\r\n retry_count = 5\r\n sleep_time = 10\r\n for i in range(retry_count):\r\n if i < retry_count - 1:\r\n try:\r\n conn = self.pool.connection()\r\n cursor = conn.cursor()\r\n cursor.execute(\"CREATE DATABASE IF NOT EXISTS {}\".format(_DATABASE))\r\n cursor.execute(\"USE {}\".format(_DATABASE))\r\n conn.commit()\r\n conn.close()\r\n logger.info(f'MySQL {_HOST}:{_PORT}/{_DATABASE} 连接成功!')\r\n break\r\n except Exception as e:\r\n logger.exception(f'MySQL {_HOST}:{_PORT}/{_DATABASE} 连接失败')\r\n logger.error(f'{sleep_time} 秒之后进行重新连接')\r\n time.sleep(sleep_time)\r\n sleep_time += 10\r\n else:\r\n conn = self.pool.connection()\r\n conn.close()\r\n\r\n # def create_table(self, db_name):\r\n # \"\"\"\r\n # :param db_name: string --\r\n # :return:\r\n # if success:\r\n # string -- 'success'\r\n # else:\r\n # string -- error info\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # cursor.execute(\"CREATE TABLE {} (\"\r\n # \"face_id BIGINT PRIMARY KEY,\"\r\n # \"face_vector BLOB NOT NULL,\"\r\n # \"face_coord BLOB NOT NULL,\"\r\n # \"face_info BLOB ,\"\r\n # \"create_datetime DATETIME NOT NULL)\"\r\n # \"ENGINE=MyISAM DEFAULT CHARSET=utf8\".format(table_name))\r\n # conn.commit()\r\n # cursor.close()\r\n # conn.close()\r\n # logger.info(f'人脸信息表 {table_name} 创建成功!')\r\n # return 'success'\r\n # except Exception as e:\r\n # logger.exception(f'人脸信息表 {table_name} 创建失败!')\r\n # return str(e)\r\n #\r\n # def drop_table(self, db_name):\r\n # \"\"\"\r\n # :param db_name: string --\r\n # :return:\r\n # if success:\r\n # string -- 'success'\r\n # else:\r\n # string -- error info\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # cursor.execute(\"DROP TABLE {}\".format(table_name))\r\n # conn.commit()\r\n # cursor.close()\r\n # conn.close()\r\n # logger.info(f'人脸信息表 {table_name} 删除完成')\r\n # return 'success'\r\n # except Exception as e:\r\n # logger.exception(f'人脸信息表 {table_name} 删除失败')\r\n # return str(e)\r\n #\r\n # def insert_data(self, db_name, face_id, face_vector, face_coord, face_info, create_datetime):\r\n # \"\"\"\r\n # :param db_name: string --\r\n # :param face_id: int --\r\n # :param face_vector: list -- [512]\r\n # :param face_coord: list -- [x1, y1, x2, y2]\r\n # :param face_info: string --\r\n # :param create_datetime: datetime.datetime -- format '%Y-%m-%d %H:%M:%S'\r\n # :return:\r\n # if success:\r\n # string -- 'success'\r\n # else:\r\n # string -- error info\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # face_vector = json.dumps(face_vector)\r\n # face_coord = json.dumps(face_coord)\r\n # cursor.execute(\"INSERT INTO {} \"\r\n # \"(face_id, face_vector, face_coord, face_info, create_datetime) \"\r\n # \"VALUES (%s, %s, %s, %s, %s)\".format(table_name),\r\n # (face_id, face_vector, face_coord, face_info, create_datetime))\r\n # conn.commit()\r\n # cursor.close()\r\n # conn.close()\r\n # return 'success'\r\n # except Exception as e:\r\n # conn.rollback()\r\n # logger.exception(f'face_id:{face_id} 人脸信息插入失败')\r\n # return str(e)\r\n #\r\n # def insert_data_batch(self, db_name, face_data):\r\n # \"\"\"\r\n # :param db_name: string\r\n # :param face_data: list -- [(face_id, face_vector, face_coord, face_info, create_datetime), ...]\r\n # :return:\r\n # string -- 'success' or error info\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # sql = \"INSERT INTO {} \" \\\r\n # \"(face_id, face_vector, face_coord, face_info, create_datetime) \" \\\r\n # \"VALUES (%s, %s, %s, %s, %s)\".format(table_name)\r\n # cursor.executemany(sql, face_data)\r\n # conn.commit()\r\n # cursor.close()\r\n # conn.close()\r\n # return 'success'\r\n # except Exception as e:\r\n # conn.rollback()\r\n # logger.exception(f'{db_name} 表 插入数据发生异常')\r\n # return str(e)\r\n #\r\n # def delete_data(self, db_name, face_id):\r\n # \"\"\"\r\n # :param db_name: string --\r\n # :param face_id: int --\r\n # :return:\r\n # if success:\r\n # string -- 'success'\r\n # else:\r\n # string -- error info\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # ret = cursor.execute(\"DELETE FROM {} \"\r\n # \"WHERE face_id=%s\".format(table_name), (face_id,))\r\n # conn.commit()\r\n # cursor.close()\r\n # conn.close()\r\n # if ret == 0:\r\n # return f'feature_id: {face_id} 不存在'\r\n # else:\r\n # return 'success'\r\n # except Exception as e:\r\n # conn.rollback()\r\n # logger.exception(f'feature_id: {face_id} 删除失败')\r\n # return str(e)\r\n #\r\n # def delete_data_batch(self, db_name, face_ids):\r\n # \"\"\"\r\n # :param db_name: string --\r\n # :param face_ids: list --\r\n # :return:\r\n # string -- 'success' or error info\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # face_ids_str = ','.join([str(i) for i in face_ids])\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # cursor.execute(\"DELETE FROM {0} \"\r\n # \"WHERE face_id in ({1})\".format(table_name, face_ids_str))\r\n # conn.commit()\r\n # cursor.close()\r\n # conn.close()\r\n # return 'success'\r\n # except Exception as e:\r\n # conn.rollback()\r\n # logger.exception(f'{table_name}表 删除 ({face_ids_str}) 发生异常')\r\n # return str(e)\r\n #\r\n # def select_coord_info(self, db_name, face_ids):\r\n # \"\"\"\r\n # :param db_name: string --\r\n # :param face_ids: list --\r\n # :return:\r\n # dict -- {\r\n # str(feature_id) : {\r\n # 'feature_id' : int,\r\n # 'faceCoord': list,\r\n # 'info' string }\r\n # ......\r\n # }\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # face_ids_str = ','.join([str(i) for i in face_ids])\r\n # face_ids.insert(0, 'face_id')\r\n # fiels_str = ','.join([str(i) for i in face_ids])\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # cursor.execute(\"SELECT face_id, face_coord, face_info \"\r\n # \"FROM {0} \"\r\n # \"WHERE face_id in ({1}) \"\r\n # \"ORDER BY FIELD({2})\".format(table_name, face_ids_str, fiels_str))\r\n # result_dict = {}\r\n # for data in cursor.fetchall():\r\n # result_dict[str(data[0])] = {\r\n # 'feature_id': int(data[0]),\r\n # 'faceCoord': json.loads(data[1]),\r\n # 'info': str(data[2], encoding='utf-8')\r\n # }\r\n # cursor.close()\r\n # conn.close()\r\n # return result_dict\r\n # except Exception as e:\r\n # logger.error(f'获取 {face_ids} 信息失败')\r\n # logger.error(str(e))\r\n\r\n def select_vector_coord_info(self, db_name, face_id):\r\n \"\"\"\r\n :param db_name: string --\r\n :param face_id: int --\r\n :return:\r\n list -- face_vector\r\n list -- face_coord\r\n string -- face_info\r\n \"\"\"\r\n table_name = f'{self.table_prefix}{db_name}'\r\n try:\r\n conn = self.pool.connection()\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT face_vector, face_coord, face_info \"\r\n \"FROM {} \"\r\n \"WHERE face_id=%s\".format(table_name), (face_id,))\r\n data = cursor.fetchone()\r\n cursor.close()\r\n conn.close()\r\n if data is not None:\r\n face_vector = json.loads(data[0])\r\n face_coord = json.loads(data[1])\r\n face_info = str(data[2], encoding='utf-8')\r\n return 'success', face_vector, face_coord, face_info\r\n else:\r\n error_info = f'{db_name}: {face_id} 不存在'\r\n return error_info, '', '', ''\r\n except Exception as e:\r\n logger.exception(f'获取{db_name}:{face_id}人脸信息失败')\r\n return str(e), '', '', ''\r\n\r\n # def get_id_by_date(self, db_name, begin_date, end_date):\r\n # \"\"\"\r\n # 获取指定时间段内的人脸特征id\r\n # :param db_name: string --\r\n # :param begin_date: datetime object -- format '%Y-%m-%d %H:%M:%S'\r\n # :param end_date: datetime object -- format '%Y-%m-%d %H:%M:%S'\r\n # :return:\r\n # list -- face_ids\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # cursor.execute(\"SELECT face_id \"\r\n # \"FROM {} \"\r\n # \"WHERE create_datetime BETWEEN %s AND %s\".format(table_name), (begin_date, end_date))\r\n # face_ids = [int(face_id[0]) for face_id in cursor.fetchall()]\r\n # cursor.close()\r\n # conn.close()\r\n # return face_ids\r\n # except Exception as e:\r\n # logger.exception(f'从人脸信息表{db_name}获取{begin_date}到{end_date}的feature_id 失败')\r\n #\r\n # def delete_by_date(self, db_name, begin_date, end_date):\r\n # \"\"\"\r\n # 删除指定人脸库特定时间段的数据\r\n # :param db_name: string --\r\n # :param begin_date: datetime object -- format '%Y-%m-%d %H:%M:%S'\r\n # :param end_date: datetime object -- format '%Y-%m-%d %H:%M:%S'\r\n # :return:\r\n # if success:\r\n # string -- 'success'\r\n # else:\r\n # string -- error info\r\n # \"\"\"\r\n # table_name = f'{self.table_prefix}{db_name}'\r\n # try:\r\n # conn = self.pool.connection()\r\n # cursor = conn.cursor()\r\n # ret = cursor.execute(\"DELETE FROM {} \"\r\n # \"WHERE create_datetime BETWEEN %s AND %s\".format(table_name), (begin_date, end_date))\r\n # conn.commit()\r\n # cursor.close()\r\n # conn.close()\r\n # logger.info(f'人脸库{db_name},删除了{begin_date}到{end_date}内共{ret}条记录')\r\n # return 'success'\r\n # except Exception as e:\r\n # conn.rollback()\r\n # logger.exception(f'{db_name} 删除{begin_date}到{end_date}数据发生错误')\r\n # return str(e)\r\n\r\n def main_table_delete_by_date(self, begin_date, end_date):\r\n \"\"\"\r\n 删除行人库主表特定时间段的数据\r\n :param begin_date: datetime object -- format '%Y-%m-%d %H:%M:%S'\r\n :param end_date: datetime object -- format '%Y-%m-%d %H:%M:%S'\r\n :return:\r\n if success:\r\n string -- 'success'\r\n else:\r\n string -- error info\r\n \"\"\"\r\n try:\r\n conn = self.pool.connection()\r\n cursor = conn.cursor()\r\n ret = cursor.execute(\"DELETE FROM {} \"\r\n \"WHERE create_datetime BETWEEN %s AND %s\".format(self.main_table), (begin_date, end_date))\r\n conn.commit()\r\n cursor.close()\r\n conn.close()\r\n logger.info(f'删除行人库主表{self.main_table},从{begin_date} 到 {end_date} 内共{ret}条记录')\r\n return 'success'\r\n except Exception as e:\r\n conn.rollback()\r\n logger.exeception(f'删除行人库主表{self.main_table}, {begin_date}-{end_date} 数据发生异常')\r\n return str(e)\r\n\r\n def select_person_ids(self, face_ids):\r\n \"\"\"\r\n 获取 face_ids 对应的person_id\r\n :param face_ids: list --\r\n :return:\r\n dict -- {\r\n str(feature_id): int(person_id),\r\n ...\r\n }\r\n \"\"\"\r\n face_ids_str = ','.join([str(i) for i in face_ids])\r\n try:\r\n conn = self.pool.connection()\r\n cursor = conn.cursor()\r\n cursor.execute(\"SELECT face_id, person_id \"\r\n \"FROM {} \"\r\n \"WHERE face_id in ({})\".format(self.main_table, face_ids_str))\r\n result_dict = {}\r\n for data in cursor.fetchall():\r\n result_dict[str(data[0])] = int(data[1])\r\n cursor.close()\r\n conn.close()\r\n return result_dict\r\n except Exception as e:\r\n logger.exception(f'获取 {face_ids} 的person_id 信息失败')\r\n","sub_path":"utils/mysql_util.py","file_name":"mysql_util.py","file_ext":"py","file_size_in_byte":16667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"436656596","text":"from data.utils import load_data_torch\nfrom src.utils import *\nfrom src.layers import *\nimport pickle\nimport sys\nimport time\n\n\n\nwith open('./TIP/data/decagon_et.pkl', 'rb') as f: # the whole dataset\n et_list = pickle.load(f)\n\nout_dir = './TIP/qu_out/ggm/'\n\nEPOCH_NUM = 100\n\n#########################################################################\n# et_list = et_list[-200:]\n#########################################################################\n\nfeed_dict = load_data_torch(\"./TIP/data/\", et_list, mono=True)\n\n[n_drug, n_feat_d] = feed_dict['d_feat'].shape\nn_et_dd = len(et_list)\n\ndata = Data.from_dict(feed_dict)\n\n\ndata.train_idx, data.train_et, data.train_range,data.test_idx, data.test_et, data.test_range = process_edges(data.dd_edge_index)\n\n# TODO: add drug feature\ndata.d_feat = sparse_id(n_drug)\nn_feat_d = n_drug\ndata.x_norm = torch.ones(n_drug)\n# data.x_norm = torch.sqrt(data.d_feat.sum(dim=1))\n\nn_base = 16\n\nn_embed = 16\nn_hid1 = 64\nn_hid2 = 32\n\n\nclass Encoder(torch.nn.Module):\n\n def __init__(self, in_dim, num_et, num_base):\n super(Encoder, self).__init__()\n self.num_et = num_et\n\n self.embed = Param(torch.Tensor(in_dim, n_embed))\n\n self.reset_paramters()\n\n def forward(self, x, edge_index, edge_type, range_list, x_norm):\n x = torch.matmul(x, self.embed)\n x = x / x_norm.view(-1, 1)\n\n x = F.relu(x, inplace=True)\n return x\n\n def reset_paramters(self):\n self.embed.data.normal_()\n\n\nclass MultiInnerProductDecoder(torch.nn.Module):\n def __init__(self, in_dim, num_et):\n super(MultiInnerProductDecoder, self).__init__()\n self.num_et = num_et\n self.in_dim = in_dim\n self.weight = Param(torch.Tensor(num_et, in_dim))\n\n self.reset_parameters()\n\n def forward(self, z, edge_index, edge_type, sigmoid=True):\n value = (z[edge_index[0]] * z[edge_index[1]] * self.weight[edge_type]).sum(dim=1)\n return torch.sigmoid(value) if sigmoid else value\n\n def reset_parameters(self):\n self.weight.data.normal_(std=1/np.sqrt(self.in_dim))\n\n\nencoder = Encoder(n_feat_d, n_et_dd, n_base)\ndecoder = MultiInnerProductDecoder(n_embed, n_et_dd)\nmodel = MyGAE(encoder, decoder)\n\ndevice_name = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(device_name)\ndevice = torch.device(device_name)\n\nmodel = model.to(device)\noptimizer = torch.optim.Adam(model.parameters(), lr=0.01)\ndata = data.to(device)\n\ntrain_record = {}\ntest_record = {}\ntrain_out = {}\ntest_out = {}\n\n\n@profile\ndef train():\n model.train()\n\n optimizer.zero_grad()\n z = model.encoder(data.d_feat, data.train_idx, data.train_et, data.train_range, data.x_norm)\n\n pos_index = data.train_idx\n neg_index = typed_negative_sampling(data.train_idx, n_drug, data.train_range).to(device)\n\n pos_score = model.decoder(z, pos_index, data.train_et)\n neg_score = model.decoder(z, neg_index, data.train_et)\n\n # pos_loss = F.binary_cross_entropy(pos_score, torch.ones(pos_score.shape[0]).cuda())\n # neg_loss = F.binary_cross_entropy(neg_score, torch.ones(neg_score.shape[0]).cuda())\n pos_loss = -torch.log(pos_score + EPS).mean()\n neg_loss = -torch.log(1 - neg_score + EPS).mean()\n loss = pos_loss + neg_loss\n # loss = pos_loss\n\n loss.backward()\n optimizer.step()\n\n record = np.zeros((3, n_et_dd)) # auprc, auroc, ap\n for i in range(data.train_range.shape[0]):\n [start, end] = data.train_range[i]\n p_s = pos_score[start: end]\n n_s = neg_score[start: end]\n\n pos_target = torch.ones(p_s.shape[0])\n neg_target = torch.zeros(n_s.shape[0])\n\n score = torch.cat([p_s, n_s])\n target = torch.cat([pos_target, neg_target])\n\n record[0, i], record[1, i], record[2, i] = auprc_auroc_ap(target, score)\n\n train_record[epoch] = record\n [auprc, auroc, ap] = record.sum(axis=1) / n_et_dd\n train_out[epoch] = [auprc, auroc, ap]\n\n print('{:3d} loss:{:0.4f} auprc:{:0.4f} auroc:{:0.4f} ap@50:{:0.4f}'\n .format(epoch, loss.tolist(), auprc, auroc, ap))\n\n return z, loss\n\n\ntest_neg_index = typed_negative_sampling(data.test_idx, n_drug, data.test_range).to(device)\n\n\ndef test(z):\n model.eval()\n\n record = np.zeros((3, n_et_dd)) # auprc, auroc, ap\n\n pos_score = model.decoder(z, data.test_idx, data.test_et)\n neg_score = model.decoder(z, test_neg_index, data.test_et)\n\n for i in range(data.test_range.shape[0]):\n [start, end] = data.test_range[i]\n p_s = pos_score[start: end]\n n_s = neg_score[start: end]\n\n pos_target = torch.ones(p_s.shape[0])\n neg_target = torch.zeros(n_s.shape[0])\n\n score = torch.cat([p_s, n_s])\n target = torch.cat([pos_target, neg_target])\n\n record[0, i], record[1, i], record[2, i] = auprc_auroc_ap(target, score)\n\n return record\n\n\nprint('model training ...')\nfor epoch in range(EPOCH_NUM):\n time_begin = time.time()\n\n z, loss = train()\n\n if epoch % 10 == 9:\n record_te = test(z)\n [auprc, auroc, ap] = record_te.sum(axis=1) / data.n_dd_et\n\n print('{:3d} loss:{:0.4f} auprc:{:0.4f} auroc:{:0.4f} ap@50:{:0.4f} time:{:0.1f}'.format(epoch+1, loss.tolist(), auprc, auroc, ap, (time.time() - time_begin)))\n else:\n print('{:3d} time:{:0.2f}'.format(epoch+1, (time.time() - time_begin)))\n\n# # save model state\nfilepath_state = out_dir + '100ep.pth'\ntorch.save(model.state_dict(), filepath_state)\n# # to restore\n# # model.load_state_dict(torch.load(filepath_state))\n# # model.eval()\n#\n# # save whole model\nfilepath_model = out_dir + '100ep_model.pb'\ntorch.save(model, filepath_model)\n","sub_path":"eva_dist.py","file_name":"eva_dist.py","file_ext":"py","file_size_in_byte":5625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"417883201","text":"#!/usr/bin/env python\n# ----------------------------------------------------------------------------\n# Copyright 2016 Nervana Systems Inc.\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\"\"\"\nTest a trained Faster-RCNN model to do object detection using PASCAL VOC dataset.\nThis test currently runs 1 image at a time.\n\nReference:\n \"Faster R-CNN\"\n http://arxiv.org/abs/1506.01497\n https://github.com/rbgirshick/py-faster-rcnn\n\nUsage:\n python examples/faster-rcnn/inference.py --model_file faster_rcnn.pkl\n\nAt the end of the a training process, the model is serialized with the bounding box\nregression layer normalized. If you like to test on a model file before the training\nis finished, use --normalize flag to do the normalization here.\n\nThe mAP evaluation script is adapted from:\nhttps://github.com/rbgirshick/py-faster-rcnn/\n\"\"\"\n\nimport sys\nimport os\nfrom builtins import range\n\nimport util\nfrom objectlocalization import PASCAL\n\nfrom neon.backends import gen_backend\nfrom neon.util.argparser import NeonArgparser, extract_valid_args\nfrom neon import logger as neon_logger\n\n\n# parse the command line arguments\nparser = NeonArgparser(__doc__, default_overrides={'batch_size': 1})\nparser.add_argument('--normalize', action='store_true',\n help='Normalize the final bounding box regression layers.')\nparser.add_argument('--output_dir', default=None,\n help='Directory to save AP metric results. Default is [data_dir]/frcn_output/')\n\nargs = parser.parse_args()\nif args.output_dir is None:\n args.output_dir = os.path.join(args.data_dir, 'frcn_output')\n\nassert args.model_file is not None, \"Model file required for Faster-RCNN testing\"\n\n# hyperparameters\nassert args.batch_size is 1, \"Faster-RCNN only supports batch size 1\"\nn_mb = None\nrpn_rois_per_img = 256\nfrcn_rois_per_img = 128\n\n# setup backend\nbe = gen_backend(**extract_valid_args(args, gen_backend))\n\nimage_set = 'test'\nyear = '2007'\nvalid_set = PASCAL(image_set, year, path=args.data_dir, n_mb=n_mb,\n rpn_rois_per_img=rpn_rois_per_img, frcn_rois_per_img=frcn_rois_per_img,\n add_flipped=False, shuffle=False, rebuild_cache=True)\n\nnum_classes = valid_set.num_classes\n\n# build the Faster-RCNN network\n(model, proposalLayer) = util.build_model(valid_set, frcn_rois_per_img, inference=True)\n\n# load parameters and initialize model\nmodel.load_params(args.model_file)\nmodel.initialize(dataset=valid_set)\n\n# normalize the model by the bbtarget mean and std if needed\n# if a full training run was completed using train.py, then normalization\n# was already performed prior to saving the model.\nif args.normalize:\n model = util.scale_bbreg_weights(model, [0.0, 0.0, 0.0, 0.0],\n [0.1, 0.1, 0.2, 0.2], num_classes)\n\n# run inference\n# model.benchmark(valid_set, inference=True)\n\n# detection parameters\nnum_images = valid_set.num_image_entries if n_mb is None else n_mb\nmax_per_image = 100 # maximum detections per image\nthresh = 0.001 # minimum threshold on score\nnms_thresh = 0.3 # threshold used for non-maximum supression\n\n# all detections are collected into:\n# all_boxes[cls][image] = N x 5 array of detections in\n# (x1, y1, x2, y2, score)\nall_boxes = [[[] for _ in range(num_classes)]\n for _ in range(num_images)]\n\nlast_strlen = 0\nfor mb_idx, (x, y) in enumerate(valid_set):\n\n prt_str = \"Finished: {} / {}\".format(mb_idx, valid_set.nbatches)\n sys.stdout.write('\\r' + ' '*last_strlen + '\\r')\n sys.stdout.write(prt_str.encode('utf-8'))\n last_strlen = len(prt_str)\n sys.stdout.flush()\n\n # perform forward pass\n outputs = model.fprop(x, inference=True)\n\n # retrieve image metadata\n im_shape = valid_set.im_shape.get()\n im_scale = valid_set.im_scale.get()\n\n # retrieve region proposals generated by the model\n (proposals, num_proposals) = proposalLayer.get_proposals()\n\n # convert outputs to bounding boxes\n boxes = util.get_bboxes(outputs, proposals, num_proposals, valid_set.num_classes,\n im_shape, im_scale, max_per_image, thresh, nms_thresh)\n\n all_boxes[mb_idx] = boxes\n\nneon_logger.display('Evaluating detections')\nannopath, imagesetfile = valid_set.evaluation(all_boxes, args.output_dir)\nutil.run_voc_eval(annopath, imagesetfile, year, image_set, valid_set.CLASSES, args.output_dir)\n","sub_path":"examples/faster-rcnn/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"403864415","text":"import matplotlib.pyplot as plt\nimport results_manager as resm\nimport numpy as np\n\n\ndef plot_with_intervals(ax: plt.Axes, x_vals, y_vals, band_fn='std', const=False, pos=1, lfactor=50, alpha=1, decay=5, label=None, **kwargs):\n ax.plot(x_vals, np.mean(y_vals, 0), label=label, alpha=alpha, **kwargs)\n if decay > 0:\n alpha /= decay\n else:\n alpha = 0\n label = None\n\n def minmax():\n return np.min(y_vals, 0), np.max(y_vals, 0)\n\n def std():\n mean = np.mean(y_vals, 0)\n _std = np.std(y_vals, 0)\n return mean - _std, mean + _std\n\n if band_fn is not None:\n y1, y2 = locals()[band_fn]()\n if not const:\n ax.fill_between(x_vals, y1, y2, alpha=alpha, label=label, **kwargs)\n else:\n ax.plot((x_vals[pos], x_vals[pos]), (y1, y2), alpha=alpha, linestyle='-', linewidth=1, color='k')\n l = (x_vals[-1] - x_vals[0]) / lfactor\n ax.plot((x_vals[pos] - l, x_vals[pos] + l), (y1, y1), alpha=alpha, linestyle='-', linewidth=1, color='k')\n ax.plot((x_vals[pos] - l, x_vals[pos] + l), (y2, y2), alpha=alpha, linestyle='-', linewidth=1, color='k')\n\n\ndef merge_runs(inputs, output):\n data = []\n out = {}\n for file in inputs:\n data.append(resm.load_json(file))\n for d in data:\n for key in d.keys():\n if key not in out.keys():\n out[key] = []\n out[key] += d[key]\n resm.store_json(output, out)\n\n\ndef visualize(filenames, labels, colors, snap_list, pr_list, name='eb_results'):\n fig: plt.Figure = plt.figure(name)\n ax = []\n for j in range(len(pr_list)):\n ax.append(fig.add_subplot(len(pr_list), 1, j+1))\n ax[-1].set_title('Pruning rate '+str(pr_list[j]))\n for i in range(len(filenames)):\n data = resm.load_json(filenames[i])\n pruned_test_acc = np.array(data['pruned_test_accuracy'])\n for j in range(len(pruned_test_acc[0])):\n plot_with_intervals(ax[j], snap_list, pruned_test_acc[:, j, :], color=colors[i], label=labels[i])\n ax[j].grid(True)\n ax[j].set_axisbelow(True)\n ax[j].legend()\n ax[j].set_ylabel('Test Accuracy')\n ax[j].set_xlim(10, 160)\n ax[-1].set_xlabel('Epochs')\n fig.tight_layout()\n plt.show()\n\n\n# base_names = './results/vgg16-cifar100_gbr_vgg16-cifar100_%d.json'\n# out = './results/vgg16-cifar100_gbr_vgg16-cifar100.json'\n# files = [base_names % (i) for i in range(5)]\n# merge_runs(files, out)\n\nfilenames = ['./results/vgg16-cifar100_lf.json', './results/vgg16-cifar100_lfg.json', './results/vgg16-cifar100_gbr_vgg16-cifar100.json']\nlabels = ['lf', 'lfg', 'gbr']\ncolors = plt.cm.tab10.colors\nsnap_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]\npr_list = [30, 50, 70]\nvisualize(filenames, labels, colors, snap_list, pr_list)\n","sub_path":"visualize_results.py","file_name":"visualize_results.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"228107694","text":"from crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Button, Submit\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django_lazifier.utils.django.form import Frm\nfrom django_ltgt.ltgt.apps.data_table.forms import DataTableUpdateForm\nimport re\nfrom ticket_distro.apps.event.forms import EventBasedForm\nfrom ticket_distro.apps.seat.models import Seat\nfrom django.utils.translation import ugettext as _\nfrom ticket_distro.apps.transaction.models import Transaction\nfrom ticket_distro.apps.zone.models import Zone\n\n\nclass SeatCreateForm(EventBasedForm):\n class Meta:\n model = Seat\n exclude = []\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\nclass SeatUpdateForm(SeatCreateForm, DataTableUpdateForm):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\nclass SeatsCreationForm(forms.Form):\n zone = forms.ModelChoiceField(queryset=Zone.objects.all(), label=_('Zone'), required=True)\n seats = forms.CharField(label=_('Seats'), widget=forms.Textarea,\n help_text=_('eg. E1-3,E7 will create E1, E2, E3 and E7.'), required=True)\n\n def clean_seats(self):\n seats_str = self.cleaned_data['seats']\n result = Seat.get_seats(seats_str)\n\n return result\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request', None)\n super().__init__(*args, **kwargs)\n\n helper = FormHelper()\n helper.form_method = 'POST'\n helper.form_action = 'manage/?mode=create'\n helper.form_id = 'frm-dt-create'\n helper.add_input(Button('ajax-reset', _('Reset'), css_class='btn btn-warning ajax-reset'))\n helper.add_input(Submit('submit', _('Create')))\n\n self.helper = helper\n\n def save(self, commit=True):\n new_seats = self.cleaned_data['seats']\n zone = self.cleaned_data['zone']\n\n seat_list = []\n seat_in_current_zone = Seat.objects.filter(zone=zone).values_list('seat_number', flat=True)\n\n for s in new_seats:\n if s not in seat_in_current_zone:\n seat_list.append(Seat(zone=zone, seat_number=s))\n\n if seat_list:\n Seat.objects.bulk_create(seat_list)\n\n return True\n\n\nclass AssignSeatsForm(forms.Form):\n command = forms.CharField(widget=forms.HiddenInput, initial='assign-seats')\n seller = forms.ModelChoiceField(get_user_model().objects.all(), label=_('Assign To'))\n seats = forms.ModelMultipleChoiceField(Seat.objects.none(), label=_('Seats'), required=False,\n help_text=_('Select seats or use the seat range below.'))\n seat_ranges = forms.CharField(widget=forms.Textarea, label=_('Seat Ranges'), required=False)\n\n def clean_seat_ranges(self):\n seats_str = self.cleaned_data['seat_ranges']\n result = Seat.get_seats(seats_str)\n return result\n\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop('request', None)\n super().__init__(*args, **kwargs)\n\n helper = FormHelper()\n helper.form_method = 'POST'\n helper.form_action = 'manage/?mode=custom'\n helper.form_id = 'frm-dt-create'\n helper.add_input(Button('ajax-reset', _('Reset'), css_class='btn btn-warning ajax-reset'))\n helper.add_input(Submit('submit', _('Assign')))\n\n self.helper = helper\n\n self.fields['seats'].queryset = Seat.objects.filter(zone__event__is_active=True, seller__isnull=True)\n\n def save(self, commit=True):\n seats = self.cleaned_data['seats']\n seat_ranges = self.cleaned_data['seat_ranges']\n\n seller_seats = seat_ranges\n if seats:\n seats = [s.seat_number for s in seats]\n seller_seats += seats\n\n if seller_seats:\n Seat.assign_seats(self.cleaned_data['seller'], seller_seats)\n return True\n\n\nclass SaleSingleSeatForm(EventBasedForm):\n id = forms.IntegerField(widget=forms.HiddenInput())\n command = forms.CharField(widget=forms.HiddenInput, initial='sale')\n seat = forms.CharField(label=_('Seat'))\n\n class Meta:\n model = Transaction\n exclude = ['seller']\n\n def __init__(self, *args, seat, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.helper.form_action = 'manage/?mode=custom'\n self.seat_for_sale = seat\n\n self.fields['seat'].initial = seat\n Frm.set_as_readonly(self, ['seat'])\n Frm.order_fields(self, ['seat'])\n\n def save(self, commit=True):\n transaction = super().save(commit)\n\n self.seat_for_sale.transaction = transaction\n self.seat_for_sale.save()\n\n\n","sub_path":"ticket_distro/apps/seat/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"375174565","text":"#-------------------------------------------------------------------------\n# Copyright (c) Microsoft. 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# 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 sys\nimport types\n\nfrom datetime import datetime\nfrom xml.dom import minidom\nfrom azure import (WindowsAzureData,\n WindowsAzureError,\n METADATA_NS,\n xml_escape,\n _create_entry,\n _decode_base64_to_text,\n _decode_base64_to_bytes,\n _encode_base64,\n _fill_data_minidom,\n _fill_instance_element,\n _get_child_nodes,\n _get_child_nodesNS,\n _get_children_from_path,\n _get_entry_properties,\n _general_error_handler,\n _list_of,\n _parse_response_for_dict,\n _sign_string,\n _unicode_type,\n _ERROR_CANNOT_SERIALIZE_VALUE_TO_ENTITY,\n )\n\n# x-ms-version for storage service.\nX_MS_VERSION = '2012-02-12'\n\n\nclass EnumResultsBase(object):\n\n ''' base class for EnumResults. '''\n\n def __init__(self):\n self.prefix = u''\n self.marker = u''\n self.max_results = 0\n self.next_marker = u''\n\n\nclass ContainerEnumResults(EnumResultsBase):\n\n ''' Blob Container list. '''\n\n def __init__(self):\n EnumResultsBase.__init__(self)\n self.containers = _list_of(Container)\n\n def __iter__(self):\n return iter(self.containers)\n\n def __len__(self):\n return len(self.containers)\n\n def __getitem__(self, index):\n return self.containers[index]\n\n\nclass Container(WindowsAzureData):\n\n ''' Blob container class. '''\n\n def __init__(self):\n self.name = u''\n self.url = u''\n self.properties = Properties()\n self.metadata = {}\n\n\nclass Properties(WindowsAzureData):\n\n ''' Blob container's properties class. '''\n\n def __init__(self):\n self.last_modified = u''\n self.etag = u''\n\n\nclass RetentionPolicy(WindowsAzureData):\n\n ''' RetentionPolicy in service properties. '''\n\n def __init__(self):\n self.enabled = False\n self.__dict__['days'] = None\n\n def get_days(self):\n # convert days to int value\n return int(self.__dict__['days'])\n\n def set_days(self, value):\n ''' set default days if days is set to empty. '''\n self.__dict__['days'] = value\n\n days = property(fget=get_days, fset=set_days)\n\n\nclass Logging(WindowsAzureData):\n\n ''' Logging class in service properties. '''\n\n def __init__(self):\n self.version = u'1.0'\n self.delete = False\n self.read = False\n self.write = False\n self.retention_policy = RetentionPolicy()\n\n\nclass Metrics(WindowsAzureData):\n\n ''' Metrics class in service properties. '''\n\n def __init__(self):\n self.version = u'1.0'\n self.enabled = False\n self.include_apis = None\n self.retention_policy = RetentionPolicy()\n\n\nclass StorageServiceProperties(WindowsAzureData):\n\n ''' Storage Service Propeties class. '''\n\n def __init__(self):\n self.logging = Logging()\n self.metrics = Metrics()\n\n\nclass AccessPolicy(WindowsAzureData):\n\n ''' Access Policy class in service properties. '''\n\n def __init__(self, start=u'', expiry=u'', permission='u'):\n self.start = start\n self.expiry = expiry\n self.permission = permission\n\n\nclass SignedIdentifier(WindowsAzureData):\n\n ''' Signed Identifier class for service properties. '''\n\n def __init__(self):\n self.id = u''\n self.access_policy = AccessPolicy()\n\n\nclass SignedIdentifiers(WindowsAzureData):\n\n ''' SignedIdentifier list. '''\n\n def __init__(self):\n self.signed_identifiers = _list_of(SignedIdentifier)\n\n def __iter__(self):\n return iter(self.signed_identifiers)\n\n def __len__(self):\n return len(self.signed_identifiers)\n\n def __getitem__(self, index):\n return self.signed_identifiers[index]\n\n\nclass BlobEnumResults(EnumResultsBase):\n\n ''' Blob list.'''\n\n def __init__(self):\n EnumResultsBase.__init__(self)\n self.blobs = _list_of(Blob)\n self.prefixes = _list_of(BlobPrefix)\n self.delimiter = ''\n\n def __iter__(self):\n return iter(self.blobs)\n\n def __len__(self):\n return len(self.blobs)\n\n def __getitem__(self, index):\n return self.blobs[index]\n\n\nclass BlobResult(bytes):\n\n def __new__(cls, blob, properties):\n return bytes.__new__(cls, blob if blob else b'')\n\n def __init__(self, blob, properties):\n self.properties = properties\n\n\nclass Blob(WindowsAzureData):\n\n ''' Blob class. '''\n\n def __init__(self):\n self.name = u''\n self.snapshot = u''\n self.url = u''\n self.properties = BlobProperties()\n self.metadata = {}\n\n\nclass BlobProperties(WindowsAzureData):\n\n ''' Blob Properties '''\n\n def __init__(self):\n self.last_modified = u''\n self.etag = u''\n self.content_length = 0\n self.content_type = u''\n self.content_encoding = u''\n self.content_language = u''\n self.content_md5 = u''\n self.xms_blob_sequence_number = 0\n self.blob_type = u''\n self.lease_status = u''\n self.lease_state = u''\n self.lease_duration = u''\n self.copy_id = u''\n self.copy_source = u''\n self.copy_status = u''\n self.copy_progress = u''\n self.copy_completion_time = u''\n self.copy_status_description = u''\n\n\nclass BlobPrefix(WindowsAzureData):\n\n ''' BlobPrefix in Blob. '''\n\n def __init__(self):\n self.name = ''\n\n\nclass BlobBlock(WindowsAzureData):\n\n ''' BlobBlock class '''\n\n def __init__(self, id=None, size=None):\n self.id = id\n self.size = size\n\n\nclass BlobBlockList(WindowsAzureData):\n\n ''' BlobBlockList class '''\n\n def __init__(self):\n self.committed_blocks = []\n self.uncommitted_blocks = []\n\n\nclass PageRange(WindowsAzureData):\n\n ''' Page Range for page blob. '''\n\n def __init__(self):\n self.start = 0\n self.end = 0\n\n\nclass PageList(object):\n\n ''' Page list for page blob. '''\n\n def __init__(self):\n self.page_ranges = _list_of(PageRange)\n\n def __iter__(self):\n return iter(self.page_ranges)\n\n def __len__(self):\n return len(self.page_ranges)\n\n def __getitem__(self, index):\n return self.page_ranges[index]\n\n\nclass QueueEnumResults(EnumResultsBase):\n\n ''' Queue list'''\n\n def __init__(self):\n EnumResultsBase.__init__(self)\n self.queues = _list_of(Queue)\n\n def __iter__(self):\n return iter(self.queues)\n\n def __len__(self):\n return len(self.queues)\n\n def __getitem__(self, index):\n return self.queues[index]\n\n\nclass Queue(WindowsAzureData):\n\n ''' Queue class '''\n\n def __init__(self):\n self.name = u''\n self.url = u''\n self.metadata = {}\n\n\nclass QueueMessagesList(WindowsAzureData):\n\n ''' Queue message list. '''\n\n def __init__(self):\n self.queue_messages = _list_of(QueueMessage)\n\n def __iter__(self):\n return iter(self.queue_messages)\n\n def __len__(self):\n return len(self.queue_messages)\n\n def __getitem__(self, index):\n return self.queue_messages[index]\n\n\nclass QueueMessage(WindowsAzureData):\n\n ''' Queue message class. '''\n\n def __init__(self):\n self.message_id = u''\n self.insertion_time = u''\n self.expiration_time = u''\n self.pop_receipt = u''\n self.time_next_visible = u''\n self.dequeue_count = u''\n self.message_text = u''\n\n\nclass Entity(WindowsAzureData):\n\n ''' Entity class. The attributes of entity will be created dynamically. '''\n pass\n\n\nclass EntityProperty(WindowsAzureData):\n\n ''' Entity property. contains type and value. '''\n\n def __init__(self, type=None, value=None):\n self.type = type\n self.value = value\n\n\nclass Table(WindowsAzureData):\n\n ''' Only for intellicens and telling user the return type. '''\n pass\n\n\ndef _parse_blob_enum_results_list(response):\n respbody = response.body\n return_obj = BlobEnumResults()\n doc = minidom.parseString(respbody)\n\n for enum_results in _get_child_nodes(doc, 'EnumerationResults'):\n for child in _get_children_from_path(enum_results, 'Blobs', 'Blob'):\n return_obj.blobs.append(_fill_instance_element(child, Blob))\n\n for child in _get_children_from_path(enum_results,\n 'Blobs',\n 'BlobPrefix'):\n return_obj.prefixes.append(\n _fill_instance_element(child, BlobPrefix))\n\n for name, value in vars(return_obj).items():\n if name == 'blobs' or name == 'prefixes':\n continue\n value = _fill_data_minidom(enum_results, name, value)\n if value is not None:\n setattr(return_obj, name, value)\n\n return return_obj\n\n\ndef _update_storage_header(request):\n ''' add additional headers for storage request. '''\n if request.body:\n assert isinstance(request.body, bytes)\n\n # if it is PUT, POST, MERGE, DELETE, need to add content-lengt to header.\n if request.method in ['PUT', 'POST', 'MERGE', 'DELETE']:\n request.headers.append(('Content-Length', str(len(request.body))))\n\n # append addtional headers base on the service\n request.headers.append(('x-ms-version', X_MS_VERSION))\n\n # append x-ms-meta name, values to header\n for name, value in request.headers:\n if 'x-ms-meta-name-values' in name and value:\n for meta_name, meta_value in value.items():\n request.headers.append(('x-ms-meta-' + meta_name, meta_value))\n request.headers.remove((name, value))\n break\n return request\n\n\ndef _update_storage_blob_header(request, account_name, account_key):\n ''' add additional headers for storage blob request. '''\n\n request = _update_storage_header(request)\n current_time = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')\n request.headers.append(('x-ms-date', current_time))\n request.headers.append(\n ('Content-Type', 'application/octet-stream Charset=UTF-8'))\n request.headers.append(('Authorization',\n _sign_storage_blob_request(request,\n account_name,\n account_key)))\n\n return request.headers\n\n\ndef _update_storage_queue_header(request, account_name, account_key):\n ''' add additional headers for storage queue request. '''\n return _update_storage_blob_header(request, account_name, account_key)\n\n\ndef _update_storage_table_header(request):\n ''' add additional headers for storage table request. '''\n\n request = _update_storage_header(request)\n for name, _ in request.headers:\n if name.lower() == 'content-type':\n break\n else:\n request.headers.append(('Content-Type', 'application/atom+xml'))\n request.headers.append(('DataServiceVersion', '2.0;NetFx'))\n request.headers.append(('MaxDataServiceVersion', '2.0;NetFx'))\n current_time = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')\n request.headers.append(('x-ms-date', current_time))\n request.headers.append(('Date', current_time))\n return request.headers\n\n\ndef _sign_storage_blob_request(request, account_name, account_key):\n '''\n Returns the signed string for blob request which is used to set\n Authorization header. This is also used to sign queue request.\n '''\n\n uri_path = request.path.split('?')[0]\n\n # method to sign\n string_to_sign = request.method + '\\n'\n\n # get headers to sign\n headers_to_sign = [\n 'content-encoding', 'content-language', 'content-length',\n 'content-md5', 'content-type', 'date', 'if-modified-since',\n 'if-match', 'if-none-match', 'if-unmodified-since', 'range']\n\n request_header_dict = dict((name.lower(), value)\n for name, value in request.headers if value)\n string_to_sign += '\\n'.join(request_header_dict.get(x, '')\n for x in headers_to_sign) + '\\n'\n\n # get x-ms header to sign\n x_ms_headers = []\n for name, value in request.headers:\n if 'x-ms' in name:\n x_ms_headers.append((name.lower(), value))\n x_ms_headers.sort()\n for name, value in x_ms_headers:\n if value:\n string_to_sign += ''.join([name, ':', value, '\\n'])\n\n # get account_name and uri path to sign\n string_to_sign += '/' + account_name + uri_path\n\n # get query string to sign if it is not table service\n query_to_sign = request.query\n query_to_sign.sort()\n\n current_name = ''\n for name, value in query_to_sign:\n if value:\n if current_name != name:\n string_to_sign += '\\n' + name + ':' + value\n else:\n string_to_sign += '\\n' + ',' + value\n\n # sign the request\n auth_string = 'SharedKey ' + account_name + ':' + \\\n _sign_string(account_key, string_to_sign)\n return auth_string\n\n\ndef _sign_storage_table_request(request, account_name, account_key):\n uri_path = request.path.split('?')[0]\n\n string_to_sign = request.method + '\\n'\n headers_to_sign = ['content-md5', 'content-type', 'date']\n request_header_dict = dict((name.lower(), value)\n for name, value in request.headers if value)\n string_to_sign += '\\n'.join(request_header_dict.get(x, '')\n for x in headers_to_sign) + '\\n'\n\n # get account_name and uri path to sign\n string_to_sign += ''.join(['/', account_name, uri_path])\n\n for name, value in request.query:\n if name == 'comp' and uri_path == '/':\n string_to_sign += '?comp=' + value\n break\n\n # sign the request\n auth_string = 'SharedKey ' + account_name + ':' + \\\n _sign_string(account_key, string_to_sign)\n return auth_string\n\n\ndef _to_python_bool(value):\n if value.lower() == 'true':\n return True\n return False\n\n\ndef _to_entity_int(data):\n int_max = (2 << 30) - 1\n if data > (int_max) or data < (int_max + 1) * (-1):\n return 'Edm.Int64', str(data)\n else:\n return 'Edm.Int32', str(data)\n\n\ndef _to_entity_bool(value):\n if value:\n return 'Edm.Boolean', 'true'\n return 'Edm.Boolean', 'false'\n\n\ndef _to_entity_datetime(value):\n return 'Edm.DateTime', value.strftime('%Y-%m-%dT%H:%M:%S')\n\n\ndef _to_entity_float(value):\n return 'Edm.Double', str(value)\n\n\ndef _to_entity_property(value):\n if value.type == 'Edm.Binary':\n return value.type, _encode_base64(value.value)\n\n return value.type, str(value.value)\n\n\ndef _to_entity_none(value):\n return None, None\n\n\ndef _to_entity_str(value):\n return 'Edm.String', value\n\n\n# Tables of conversions to and from entity types. We support specific\n# datatypes, and beyond that the user can use an EntityProperty to get\n# custom data type support.\n\ndef _from_entity_binary(value):\n return EntityProperty('Edm.Binary', _decode_base64_to_bytes(value))\n\n\ndef _from_entity_int(value):\n return int(value)\n\n\ndef _from_entity_datetime(value):\n format = '%Y-%m-%dT%H:%M:%S'\n if '.' in value:\n format = format + '.%f'\n if value.endswith('Z'):\n format = format + 'Z'\n return datetime.strptime(value, format)\n\n_ENTITY_TO_PYTHON_CONVERSIONS = {\n 'Edm.Binary': _from_entity_binary,\n 'Edm.Int32': _from_entity_int,\n 'Edm.Int64': _from_entity_int,\n 'Edm.Double': float,\n 'Edm.Boolean': _to_python_bool,\n 'Edm.DateTime': _from_entity_datetime,\n}\n\n# Conversion from Python type to a function which returns a tuple of the\n# type string and content string.\n_PYTHON_TO_ENTITY_CONVERSIONS = {\n int: _to_entity_int,\n bool: _to_entity_bool,\n datetime: _to_entity_datetime,\n float: _to_entity_float,\n EntityProperty: _to_entity_property,\n str: _to_entity_str,\n}\n\nif sys.version_info < (3,):\n _PYTHON_TO_ENTITY_CONVERSIONS.update({\n long: _to_entity_int,\n types.NoneType: _to_entity_none,\n unicode: _to_entity_str,\n })\n\n\ndef _convert_entity_to_xml(source):\n ''' Converts an entity object to xml to send.\n\n The entity format is:\n \n \n 2008-09-18T23:46:19.3857256Z \n \n \n \n \n \n \n Mountain View \n 23 \n 200.23 \n \n c9da6455-213d-42c9-9a79-3e9149a57833 \n 2008-07-10T00:00:00 \n true \n 255 \n mypartitionkey \n myrowkey1 \n 0001-01-01T00:00:00 \n \n \n \n '''\n\n # construct the entity body included in and \n entity_body = '{properties} '\n\n if isinstance(source, WindowsAzureData):\n source = vars(source)\n\n properties_str = ''\n\n # set properties type for types we know if value has no type info.\n # if value has type info, then set the type to value.type\n for name, value in source.items():\n mtype = ''\n conv = _PYTHON_TO_ENTITY_CONVERSIONS.get(type(value))\n if conv is None and sys.version_info >= (3,) and value is None:\n conv = _to_entity_none\n if conv is None:\n raise WindowsAzureError(\n _ERROR_CANNOT_SERIALIZE_VALUE_TO_ENTITY.format(\n type(value).__name__))\n\n mtype, value = conv(value)\n\n # form the property node\n properties_str += ''.join([' '\n else:\n if mtype:\n properties_str += ''.join([' m:type=\"', mtype, '\"'])\n properties_str += ''.join(['>',\n xml_escape(value), ''])\n\n if sys.version_info < (3,):\n if isinstance(properties_str, unicode):\n properties_str = properties_str.encode('utf-8')\n\n # generate the entity_body\n entity_body = entity_body.format(properties=properties_str)\n xmlstr = _create_entry(entity_body)\n return xmlstr\n\n\ndef _convert_table_to_xml(table_name):\n '''\n Create xml to send for a given table name. Since xml format for table is\n the same as entity and the only difference is that table has only one\n property 'TableName', so we just call _convert_entity_to_xml.\n\n table_name: the name of the table\n '''\n return _convert_entity_to_xml({'TableName': table_name})\n\n\ndef _convert_block_list_to_xml(block_id_list):\n '''\n Convert a block list to xml to send.\n\n block_id_list:\n a str list containing the block ids that are used in put_block_list.\n Only get block from latest blocks.\n '''\n if block_id_list is None:\n return ''\n xml = ''\n for value in block_id_list:\n xml += '{0} '.format(_encode_base64(value))\n\n return xml + ' '\n\n\ndef _create_blob_result(response):\n blob_properties = _parse_response_for_dict(response)\n return BlobResult(response.body, blob_properties)\n\n\ndef _convert_response_to_block_list(response):\n '''\n Converts xml response to block list class.\n '''\n blob_block_list = BlobBlockList()\n\n xmldoc = minidom.parseString(response.body)\n for xml_block in _get_children_from_path(xmldoc,\n 'BlockList',\n 'CommittedBlocks',\n 'Block'):\n xml_block_id = _decode_base64_to_text(\n _get_child_nodes(xml_block, 'Name')[0].firstChild.nodeValue)\n xml_block_size = int(\n _get_child_nodes(xml_block, 'Size')[0].firstChild.nodeValue)\n blob_block_list.committed_blocks.append(\n BlobBlock(xml_block_id, xml_block_size))\n\n for xml_block in _get_children_from_path(xmldoc,\n 'BlockList',\n 'UncommittedBlocks',\n 'Block'):\n xml_block_id = _decode_base64_to_text(\n _get_child_nodes(xml_block, 'Name')[0].firstChild.nodeValue)\n xml_block_size = int(\n _get_child_nodes(xml_block, 'Size')[0].firstChild.nodeValue)\n blob_block_list.uncommitted_blocks.append(\n BlobBlock(xml_block_id, xml_block_size))\n\n return blob_block_list\n\n\ndef _remove_prefix(name):\n colon = name.find(':')\n if colon != -1:\n return name[colon + 1:]\n return name\n\n\ndef _convert_response_to_entity(response):\n if response is None:\n return response\n return _convert_xml_to_entity(response.body)\n\n\ndef _convert_xml_to_entity(xmlstr):\n ''' Convert xml response to entity.\n\n The format of entity:\n \n \n 2008-09-18T23:46:19.3857256Z \n \n \n \n \n \n \n Mountain View \n 23 \n 200.23 \n \n c9da6455-213d-42c9-9a79-3e9149a57833 \n 2008-07-10T00:00:00 \n true \n 255 \n mypartitionkey \n myrowkey1 \n 0001-01-01T00:00:00 \n \n \n \n '''\n xmldoc = minidom.parseString(xmlstr)\n\n xml_properties = None\n for entry in _get_child_nodes(xmldoc, 'entry'):\n for content in _get_child_nodes(entry, 'content'):\n # TODO: Namespace\n xml_properties = _get_child_nodesNS(\n content, METADATA_NS, 'properties')\n\n if not xml_properties:\n return None\n\n entity = Entity()\n # extract each property node and get the type from attribute and node value\n for xml_property in xml_properties[0].childNodes:\n name = _remove_prefix(xml_property.nodeName)\n # exclude the Timestamp since it is auto added by azure when\n # inserting entity. We don't want this to mix with real properties\n if name in ['Timestamp']:\n continue\n\n if xml_property.firstChild:\n value = xml_property.firstChild.nodeValue\n else:\n value = ''\n\n isnull = xml_property.getAttributeNS(METADATA_NS, 'null')\n mtype = xml_property.getAttributeNS(METADATA_NS, 'type')\n\n # if not isnull and no type info, then it is a string and we just\n # need the str type to hold the property.\n if not isnull and not mtype:\n _set_entity_attr(entity, name, value)\n elif isnull == 'true':\n if mtype:\n property = EntityProperty(mtype, None)\n else:\n property = EntityProperty('Edm.String', None)\n else: # need an object to hold the property\n conv = _ENTITY_TO_PYTHON_CONVERSIONS.get(mtype)\n if conv is not None:\n property = conv(value)\n else:\n property = EntityProperty(mtype, value)\n _set_entity_attr(entity, name, property)\n\n # extract id, updated and name value from feed entry and set them of\n # rule.\n for name, value in _get_entry_properties(xmlstr, True).items():\n if name in ['etag']:\n _set_entity_attr(entity, name, value)\n\n return entity\n\n\ndef _set_entity_attr(entity, name, value):\n try:\n setattr(entity, name, value)\n except UnicodeEncodeError:\n # Python 2 doesn't support unicode attribute names, so we'll\n # add them and access them directly through the dictionary\n entity.__dict__[name] = value\n\n\ndef _convert_xml_to_table(xmlstr):\n ''' Converts the xml response to table class.\n Simply call convert_xml_to_entity and extract the table name, and add\n updated and author info\n '''\n table = Table()\n entity = _convert_xml_to_entity(xmlstr)\n setattr(table, 'name', entity.TableName)\n for name, value in _get_entry_properties(xmlstr, False).items():\n setattr(table, name, value)\n return table\n\n\ndef _storage_error_handler(http_error):\n ''' Simple error handler for storage service. '''\n return _general_error_handler(http_error)\n\n# make these available just from storage.\nfrom azure.storage.blobservice import BlobService\nfrom azure.storage.queueservice import QueueService\nfrom azure.storage.tableservice import TableService\nfrom azure.storage.cloudstorageaccount import CloudStorageAccount\nfrom azure.storage.sharedaccesssignature import (\n SharedAccessSignature,\n SharedAccessPolicy,\n Permission,\n WebResource,\n )\n","sub_path":"OSPatching/azure/storage/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":26885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"475048005","text":"# Universidad del Valle de Guatemala\n# Cifrado de informacion\n# Lab 3\n# Julio Herrera\n# Bryann Alfaro\n# Diego Arredondo\n\n#Referencia\n#Algoritmos de clase\n#https://en.wikipedia.org/wiki/Linear_congruential_generator\n#https://en.wikipedia.org/wiki/Wichmann%E2%80%93Hill\n#https://en.wikipedia.org/wiki/Linear-feedback_shift_register\n\nimport numpy as np\n\n# Linear congruential generator\n# seed, a, b, N and size must be positive int values\ndef lgc(a, b, N, seed, size):\n k = 1 # ultimos bits a tomar\n t = int(size / k) # cantidad de iteraciones\n h = seed\n cadena = ''\n for _ in range(t):\n bits = format(((a * h) + b) % N, '08b')\n h = ((a * h) + b) % N\n cadena += bits[-k:]\n return cadena\n\n# Wichman-Hill generator\ndef wichman(s1, s2, s3, size):\n k = 1\n t = int(size/k)\n s = ''\n for _ in range(t):\n s1 = (171*s1) % 30269\n s2 = (172*s2) % 30307\n s3 = (170*s3) % 30323\n\n v = (s1/30269.0 + s2/30307.0 + s3/30323.0) % 1\n s += format(int(v*1e15), '08b')[-k:]\n return s\n\n# LSFR generator\ndef lfsr(seed, taps, nbits):\n rbits = ''\n state = seed\n while len(rbits) < nbits:\n xor = int(state[taps[0]-1])\n for t in taps:\n if t != taps[0]:\n xor = xor ^ int(state[t-1])\n rbits += state[-1:]\n state = str(xor) + state[:-1]\n return rbits\n\n# converts image to bits\n# receives an opened PIL image on \"L\" mode (8 bits)\n# returns a full string of bits\ndef read_image(image):\n image = np.array(image)\n width, height = image.shape\n bits = \"\"\n for i in range(0, width):\n for j in range(0, height):\n bits += '{0:08b}'.format(image[i, j])\n return bits\n\n# converts bits to image\n# receives a full string of bits\n# returns a numpy array with 8 bits values per pixel\ndef write_image(bits, image):\n imgArray = np.empty(int(len(bits)/8), dtype=np.uint8)\n for i in range(int(len(bits)/8)):\n imgArray[i] = int(bits[(i*8):(i*8)+8], 2)\n img = imgArray.reshape(np.array(image).shape)\n return img\n\n# xor two strings of bits\n# returns a string of bits\ndef xor(bits1, bits2):\n return ''.join(str(int(bits1[i]) ^ int(bits2[i])) for i in range(len(bits1)))\n","sub_path":"cifrados.py","file_name":"cifrados.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"231209851","text":"import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport argparse\nimport os\nimport time\n\nimport torch\nimport torch.optim as optim\n\nimport lib.utils as utils\nfrom lib.visualize_flow import visualize_transform\nimport lib.layers.odefunc as odefunc\n\nfrom train_misc import standard_normal_logprob\nfrom train_misc import set_cnf_options, count_nfe, count_parameters, count_total_time\nfrom train_misc import add_spectral_norm, spectral_norm_power_iteration\nfrom train_misc import create_regularization_fns, get_regularization, append_regularization_to_log\nfrom train_misc import build_model_tabular\n\nfrom diagnostics.viz_scrna import save_trajectory, trajectory_to_video\nfrom diagnostics.viz_toy import save_vectors\n\nSOLVERS = [\"dopri5\", \"bdf\", \"rk4\", \"midpoint\", 'adams', 'explicit_adams', 'fixed_adams']\nparser = argparse.ArgumentParser('Continuous Normalizing Flow')\nparser.add_argument('--test', type=eval, default=False, choices=[True, False])\nparser.add_argument('--data', type=str, default='dummy')\nparser.add_argument(\n \"--layer_type\", type=str, default=\"concatsquash\",\n choices=[\"ignore\", \"concat\", \"concat_v2\", \"squash\", \"concatsquash\", \"concatcoord\", \"hyper\", \"blend\"]\n)\nparser.add_argument('--dims', type=str, default='64-64-64')\nparser.add_argument(\"--num_blocks\", type=int, default=1, help='Number of stacked CNFs.')\nparser.add_argument('--time_length', type=float, default=0.5)\nparser.add_argument('--train_T', type=eval, default=True)\nparser.add_argument(\"--divergence_fn\", type=str, default=\"brute_force\", choices=[\"brute_force\", \"approximate\"])\nparser.add_argument(\"--nonlinearity\", type=str, default=\"tanh\", choices=odefunc.NONLINEARITIES)\n\nparser.add_argument('--solver', type=str, default='dopri5', choices=SOLVERS)\nparser.add_argument('--atol', type=float, default=1e-5)\nparser.add_argument('--rtol', type=float, default=1e-5)\nparser.add_argument(\"--step_size\", type=float, default=None, help=\"Optional fixed step size.\")\n\nparser.add_argument('--test_solver', type=str, default=None, choices=SOLVERS + [None])\nparser.add_argument('--test_atol', type=float, default=None)\nparser.add_argument('--test_rtol', type=float, default=None)\n\nparser.add_argument('--residual', type=eval, default=False, choices=[True, False])\nparser.add_argument('--rademacher', type=eval, default=False, choices=[True, False])\nparser.add_argument('--spectral_norm', type=eval, default=False, choices=[True, False])\nparser.add_argument('--batch_norm', type=eval, default=False, choices=[True, False])\nparser.add_argument('--bn_lag', type=float, default=0)\n\nparser.add_argument('--niters', type=int, default=10000)\nparser.add_argument('--num_workers', type=int, default=8)\nparser.add_argument('--batch_size', type=int, default=1000)\nparser.add_argument('--test_batch_size', type=int, default=1000)\nparser.add_argument('--viz_batch_size', type=int, default=2000)\nparser.add_argument('--lr', type=float, default=1e-3)\nparser.add_argument('--weight_decay', type=float, default=1e-5)\n\n# Track quantities\nparser.add_argument('--l1int', type=float, default=None, help=\"int_t ||f||_1\")\nparser.add_argument('--l2int', type=float, default=None, help=\"int_t ||f||_2\")\nparser.add_argument('--dl2int', type=float, default=None, help=\"int_t ||f^T df/dt||_2\")\nparser.add_argument('--JFrobint', type=float, default=None, help=\"int_t ||df/dx||_F\")\nparser.add_argument('--JdiagFrobint', type=float, default=None, help=\"int_t ||df_i/dx_i||_F\")\nparser.add_argument('--JoffdiagFrobint', type=float, default=None, help=\"int_t ||df/dx - df_i/dx_i||_F\")\n\nparser.add_argument('--save', type=str, default='experiments/cnf')\nparser.add_argument('--viz_freq', type=int, default=100)\nparser.add_argument('--val_freq', type=int, default=100)\nparser.add_argument('--log_freq', type=int, default=10)\nparser.add_argument('--gpu', type=int, default=0)\nargs = parser.parse_args()\n\n# logger\nutils.makedirs(args.save)\nlogger = utils.get_logger(logpath=os.path.join(args.save, 'logs'), filepath=os.path.abspath(__file__))\n\nif args.layer_type == \"blend\":\n logger.info(\"!! Setting time_length from None to 1.0 due to use of Blend layers.\")\n args.time_length = 1.0\n\nlogger.info(args)\n\ndevice = torch.device('cuda:' + str(args.gpu) if torch.cuda.is_available() else 'cpu')\n\ntimes = [args.time_length, 2*args.time_length]\nimport numpy as np\nimport atongtf.dataset as atd\nfrom sklearn.preprocessing import StandardScaler\n\ndef load_data():\n data = atd.Branch_Dataset(noise=0.2)\n labels = data.labels\n labels = labels\n scaler = StandardScaler()\n scaler.fit(data.data)\n transformed = scaler.transform(data.data)\n return transformed, labels, scaler\n\ndata, labels, scaler = load_data()\ntimepoints = np.unique(labels)\n\n#########\n# SELECT TIMEPOINTS\n#timepoints = timepoints[:2]\n\n# Integration timepoints, where to evaluate the ODE\nint_tps = (timepoints+1) * args.time_length\nprint(int_tps)\n\n#########\n\ndef inf_sampler(arr, batch_size=None, noise=0.0):\n if batch_size is None: batch_size = args.batch_size\n ind = np.random.randint(len(arr), size=batch_size)\n samples = arr[ind]\n if noise > 0:\n samples += np.random.randn(*samples.shape) * noise\n return samples\n\ndef train_sampler(i):\n return inf_sampler(data[labels==i], noise=0.1)\n\ndef val_sampler(i):\n return inf_sampler(data[labels==i], batch_size=args.test_batch_size)\n\ndef viz_sampler(i):\n return inf_sampler(data[labels==i], batch_size=args.viz_batch_size)\n\nfull_sampler = lambda: inf_sampler(data, 2000)\n#train_samplers = [lambda: inf_sampler(data[labels==i], noise = 0.1) for i in timepoints]\n#val_samplers = [lambda: inf_sampler(data[labels==i], args.test_batch_size) for i in timepoints]\n#viz_samplers = [lambda: inf_sampler(data[labels==i], args.viz_batch_size) for i in timepoints]\n\ndef scatter_timepoints():\n import matplotlib.pyplot as plt\n\n LOW = -4\n HIGH = 4\n fig, axes = plt.subplots(2,3, figsize=(20,10))\n axes = axes.flatten()\n titles = ['D00-03', 'D06-09', 'D12-15', 'D18-21', 'D24-27', 'Full']\n for i in range(len(timepoints)):\n ax = axes[i]\n dd = np.concatenate([train_sampler(i) for _ in range(10)])\n ax.hist2d(dd[:,0], dd[:,1], range=[[LOW,HIGH], [LOW,HIGH]], bins=100)\n ax.invert_yaxis()\n ax.set_aspect('equal')\n ax.set_title(titles[i])\n ax = axes[5]\n ax.hist2d(data[:,0], data[:,1], range=[[LOW,HIGH], [LOW,HIGH]], bins=100)\n ax.invert_yaxis()\n ax.set_aspect('equal')\n ax.set_title(titles[5])\n plt.savefig('scatter.png')\n plt.close()\n\nscatter_timepoints()\n\"\"\"\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler, BatchSampler\ndatasets = [TensorDataset(data[labels==i]) for i in classes]\nprint(classes)\ndata_sampler = [BatchSampler(RandomSampler(d, replacement=True), args.batch_size, False) for d in datasets]\ndata_loader = [DataLoader(d, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=True, sampler=s) for d,s in zip(datasets, data_sampler)]\n\"\"\"\n\ndef get_transforms(model, integration_times):\n \"\"\"\n Given a list of integration points,\n returns a function giving integration times\n \"\"\"\n def sample_fn(z, logpz=None):\n int_list = [torch.tensor([it - args.time_length, it]).type(torch.float32).to(device) \n for it in integration_times]\n if logpz is not None:\n # TODO this works right?\n for it in int_list:\n z, logpz = model(z, logpz, integration_times=it, reverse=True)\n return z, logpz\n else:\n for it in int_list:\n z = model(z, integration_times=it, reverse=True)\n return z\n\n def density_fn(x, logpx=None):\n int_list = [torch.tensor([it - args.time_length, it]).type(torch.float32).to(device)\n for it in integration_times[::-1]]\n if logpx is not None:\n for it in int_list:\n x, logpx = model(x, logpx, integration_times=it, reverse=False)\n return x, logpx\n else:\n for it in int_list:\n x = model(x, integration_times=it, reverse=False)\n return x\n return sample_fn, density_fn\n\n\ndef compute_loss(args, model):\n \"\"\"\n Compute loss by integrating backwards from the last time step\n At each time step integrate back one time step, and concatenate that\n to samples of the empirical distribution at that previous timestep\n repeating over and over to calculate the likelihood of samples in\n later timepoints iteratively, making sure that the ODE is evaluated\n at every time step to calculate those later points.\n \"\"\"\n deltas = []\n for i, (itp, tp) in enumerate(zip(int_tps[::-1], timepoints[::-1])): # tp counts down from last\n integration_times = torch.tensor([itp-args.time_length, itp]).type(torch.float32).to(device)\n print(integration_times)\n\n # load data\n x = train_sampler(tp)\n x = torch.from_numpy(x).type(torch.float32).to(device)\n if i > 0:\n x = torch.cat((z, x))\n zero = torch.zeros(x.shape[0], 1).to(x)\n\n # transform to previous timepoint\n z, delta_logp = model(x, zero, integration_times=integration_times)\n deltas.append(delta_logp)\n\n # compute log q(z)\n logpz = standard_normal_logprob(z).sum(1, keepdim=True)\n\n logps = [logpz]\n losses = []\n for delta_logp in deltas[::-1]:\n logpx = logps[-1] - delta_logp\n logps.append(logpx[:-args.batch_size])\n losses.append(-torch.mean(logpx[-args.batch_size:]))\n #weights = torch.tensor([0,0,0,0,1]).to(logpx)\n #weights = torch.tensor([1,0,0,0,0]).to(logpx)\n #weights = torch.tensor([1,1,1,1,1]).to(logpx)\n weights = torch.tensor([3,2,1]).to(logpx)\n loss = torch.sum(torch.stack(losses) * weights)\n return loss\n\n\nif __name__ == '__main__':\n regularization_fns, regularization_coeffs = create_regularization_fns(args)\n model = build_model_tabular(args, 2, regularization_fns).to(device)\n if args.spectral_norm: add_spectral_norm(model)\n set_cnf_options(args, model)\n\n if args.test:\n model.load_state_dict(torch.load(args.save + '/checkpt.pth')['state_dict'])\n else:\n logger.info(model)\n logger.info(\"Number of trainable parameters: {}\".format(count_parameters(model)))\n\n optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)\n\n time_meter = utils.RunningAverageMeter(0.93)\n loss_meter = utils.RunningAverageMeter(0.93)\n nfef_meter = utils.RunningAverageMeter(0.93)\n nfeb_meter = utils.RunningAverageMeter(0.93)\n tt_meter = utils.RunningAverageMeter(0.93)\n\n end = time.time()\n best_loss = float('inf')\n model.train()\n for itr in range(1, args.niters + 1):\n optimizer.zero_grad()\n\n ### Train\n if args.spectral_norm: spectral_norm_power_iteration(model, 1)\n\n loss = compute_loss(args, model)\n loss_meter.update(loss.item())\n\n if len(regularization_coeffs) > 0 and tp == timepoints[-1]:\n # Only regularize on the last timepoint\n reg_states = get_regularization(model, regularization_coeffs)\n reg_loss = sum(\n reg_state * coeff for reg_state, coeff in zip(reg_states, regularization_coeffs) if coeff != 0\n )\n loss = loss + reg_loss\n\n total_time = count_total_time(model)\n nfe_forward = count_nfe(model)\n\n loss.backward()\n optimizer.step()\n\n ### Eval\n nfe_total = count_nfe(model)\n nfe_backward = nfe_total - nfe_forward\n nfef_meter.update(nfe_forward)\n nfeb_meter.update(nfe_backward)\n\n time_meter.update(time.time() - end)\n tt_meter.update(total_time)\n\n log_message = (\n 'Iter {:04d} | Time {:.4f}({:.4f}) | Loss {:.6f}({:.6f}) | NFE Forward {:.0f}({:.1f})'\n ' | NFE Backward {:.0f}({:.1f}) | CNF Time {:.4f}({:.4f})'.format(\n itr, time_meter.val, time_meter.avg, loss_meter.val, loss_meter.avg, nfef_meter.val, nfef_meter.avg,\n nfeb_meter.val, nfeb_meter.avg, tt_meter.val, tt_meter.avg\n )\n )\n if len(regularization_coeffs) > 0:\n log_message = append_regularization_to_log(log_message, regularization_fns, reg_states)\n\n logger.info(log_message)\n\n if itr % args.val_freq == 0 or itr == args.niters:\n with torch.no_grad():\n model.eval()\n test_loss = compute_loss(args, model)\n test_nfe = count_nfe(model)\n log_message = '[TEST] Iter {:04d} | Test Loss {:.6f} | NFE {:.0f}'.format(itr, test_loss, test_nfe)\n logger.info(log_message)\n\n if test_loss.item() < best_loss:\n best_loss = test_loss.item()\n utils.makedirs(args.save)\n torch.save({\n 'args': args,\n 'state_dict': model.state_dict(),\n }, os.path.join(args.save, 'checkpt.pth'))\n model.train()\n\n if itr % args.viz_freq == 0:\n with torch.no_grad():\n model.eval()\n for i, _ in enumerate(timepoints):\n p_samples = viz_sampler(i)\n sample_fn, density_fn = get_transforms(model, int_tps[:i+1])\n plt.figure(figsize=(9, 3))\n visualize_transform(\n p_samples, torch.randn, standard_normal_logprob, transform=sample_fn, inverse_transform=density_fn,\n samples=True, npts=800, device=device\n )\n fig_filename = os.path.join(args.save, 'figs', '{:04d}_{:01d}.jpg'.format(itr, i))\n utils.makedirs(os.path.dirname(fig_filename))\n plt.savefig(fig_filename)\n plt.close()\n model.train()\n\n end = time.time()\n\n logger.info('Training has finished.')\n\n save_traj_dir = os.path.join(args.save, 'trajectory')\n logger.info('Plotting trajectory to {}'.format(save_traj_dir))\n data_samples = inf_sampler(data[labels==0], batch_size=100)\n data_samples = torch.tensor(data_samples).type(torch.float32)\n\n save_vectors(model, data_samples, args.save, device=device, end_times=int_tps, ntimes=100)\n print('end save vectors')\n exit()\n save_trajectory(model, data_samples, save_traj_dir, device=device, end_times=int_tps, ntimes=5)\n trajectory_to_video(save_traj_dir)\n","sub_path":"train_toy2.py","file_name":"train_toy2.py","file_ext":"py","file_size_in_byte":14822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"208025785","text":"import math\nimport numpy as np\nimport torch\nimport gpytorch\nimport tqdm\nimport random\nimport time\nfrom matplotlib import pyplot as plt\nfrom torch.utils.data import TensorDataset, DataLoader\nimport sys\nsys.path.append(\"../\")\nsys.path.append(\"../directionalvi/utils\")\nsys.path.append(\"../directionalvi\")\nfrom RBFKernelDirectionalGrad import RBFKernelDirectionalGrad\n#from DirectionalGradVariationalStrategy import DirectionalGradVariationalStrategy\nfrom dfree_directional_vi import train_gp, eval_gp\nfrom metrics import MSE\nimport testfun\n\n# data parameters\nn = 600\ndim = 2\nn_test = 1000\n\n# training params\nnum_inducing = 20\nnum_directions = 2\nminibatch_size = 200\nnum_epochs = 400\n\n# seed\ntorch.random.manual_seed(0)\n# use tqdm or just have print statements\ntqdm = False\n# use data to initialize inducing stuff\ninducing_data_initialization = False\n# use natural gradients and/or CIQ\nuse_ngd = False\nuse_ciq = False\nnum_contour_quadrature=15\n# learning rate\nlearning_rate_hypers = 0.01\nlearning_rate_ngd = 0.1\ngamma = 10.0\n#levels = np.array([20,150,300])\n#def lr_sched(epoch):\n# a = np.sum(levels > epoch)\n# return (1./gamma)**a\nlr_sched = None\n\n# training and testing data\ntrain_x = torch.rand(n,dim)\ntest_x = torch.rand(n_test,dim)\ntrain_y = testfun.f(train_x, deriv=False)\ntest_y = testfun.f(test_x, deriv=False)\nif torch.cuda.is_available():\n train_x, train_y, test_x, test_y = train_x.cuda(), train_y.cuda(), test_x.cuda(), test_y.cuda()\n\ntrain_dataset = TensorDataset(train_x, train_y)\ntest_dataset = TensorDataset(test_x, test_y)\ntrain_loader = DataLoader(train_dataset, batch_size=minibatch_size, shuffle=True)\ntest_loader = DataLoader(test_dataset, batch_size=n_test, shuffle=False)\n\n# train\nprint(\"\\n\\n---DirectionalGradVGP---\")\nprint(f\"Start training with {n} trainig data of dim {dim}\")\nprint(f\"VI setups: {num_inducing} inducing points, {num_directions} inducing directions\")\nargs={\"verbose\":True}\nt1 = time.time()\t\nmodel,likelihood = train_gp(train_dataset,\n num_inducing=num_inducing,\n num_directions=num_directions,\n minibatch_size = minibatch_size,\n minibatch_dim = num_directions,\n num_epochs =num_epochs, \n learning_rate_hypers=learning_rate_hypers,\n learning_rate_ngd=learning_rate_ngd,\n inducing_data_initialization=inducing_data_initialization,\n use_ngd = use_ngd,\n use_ciq = use_ciq,\n lr_sched=lr_sched,\n num_contour_quadrature=num_contour_quadrature,\n tqdm=tqdm,**args\n )\nt2 = time.time()\t\n\n# save the model\n# torch.save(model.state_dict(), \"../data/test_dvi_basic.model\")\n\n# test\nmeans, variances = eval_gp( test_dataset,model,likelihood,\n num_directions=num_directions,\n minibatch_size=n_test,\n minibatch_dim=num_directions)\nt3 = time.time()\t\n\n# compute MSE\ntest_y = test_y.cpu()\ntest_mse = MSE(test_y,means)\n# compute mean negative predictive density\ntest_nll = -torch.distributions.Normal(means, variances.sqrt()).log_prob(test_y).mean()\nprint(f\"At {n_test} testing points, MSE: {test_mse:.4e}, nll: {test_nll:.4e}.\")\nprint(f\"Training time: {(t2-t1):.2f} sec, testing time: {(t3-t2):.2f} sec\")\n\nplot=1\nif plot == 1:\n from mpl_toolkits.mplot3d import axes3d\n import matplotlib.pyplot as plt\n fig = plt.figure(figsize=(12,6))\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(test_x[:,0],test_x[:,1],test_y, color='k')\n ax.scatter(test_x[:,0],test_x[:,1],means, color='b')\n plt.title(\"f(x,y) variational fit; actual curve is black, variational is blue\")\n plt.show()\n\n","sub_path":"tests/test_dfree_dsvgp.py","file_name":"test_dfree_dsvgp.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"593503817","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 8 18:37:56 2019\n\n@author: eesryan & mj5rw\n\"\"\"\n\nimport pytest\nimport pandas as pd\nimport my_package.cobb_tables as cbt\n\nfile_path = 'data/data.csv'\n\n#use the appropirate pandas read function for your source data file.\ndf = pd.read_csv(file_path)\n\nsubjectid = 'SubjectID'\nsex = 'Sex'\nethn = 'Ethn'\nvisc_man = ('Scoliosis', 'Lung Disease', 'Autism', 'ADD_ADHD', 'Splenectomy')\n\ndef test_function():\n assert cbt.table_2(df, subjectid, sex, ethn, *visc_man) >= 0\n\n\n","sub_path":"tests/test_cobb_tables.py","file_name":"test_cobb_tables.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"340865406","text":"from ibis import Node,Problem_Resolving_Structure\nimport MeCab\nimport CaboCha\nimport re\nimport xml.etree.ElementTree as ET\n\nclass Morph():\n\tdef __init__(self,morph_id,word,pos,pos_detail,original_word):\n\t\tself.id = morph_id\n\t\tself.word = word\n\t\tself.pos = pos\n\t\tself.pos_detail = pos_detail\n\t\tself.original_word = original_word\n\nclass Clause():\n\t#def __init__(self,clause_id,link,head,func):\n\tdef __init__(self,clause_id,head,func,to=None):\n\t\tself.clause_id = clause_id\n\t\t#self.link = link\n\t\tself.receiving_from = []\n\t\tself.receiving_to = to\n\t\tself.morphs = []\n\t\tself.words = []\n\t\tself.head = head\n\t\tself.func = func\n\n\tdef add_morph(self,morph):\n\t\tself.morphs.append(morph)\n\t\tself.words.append(morph.word)\n\n\tdef delete_morph(self,morph):\n\t\tprint(self.words)\n\t\tprint(morph.word)\n\t\tself.words.remove(morph.word)\n\t\tself.morphs.remove(morph)\n\n\tdef get_string(self):\n\t\treturn ''.join(self.words)\n\n\tdef get_end_original(self):\n\t\tif len(self.morphs) == 1 :\n\t\t\treturn self.morphs[0].original_word\n\t\telse :\n\t\t\treturn ''.join(self.words[:-1]) + self.morphs[-1].original_word\n\n\t#用途不明\n\tdef get_morphs(self,start_range=0,end_range=-1):\n\t\treturn self.morphs[start_range:end_range] \n\n\tdef get_after_head_morphs(self):\n\t\tflag = False\n\t\tarray = []\n\t\tfor morph in self.morphs :\n\t\t\tif flag :\n\t\t\t\tarray.append(morph)\n\t\t\t\n\t\t\tif morph.id == self.head :\n\t\t\t\tflag = True\n\t\treturn array\n\nclass Clause_Structure() :\n\tdef __init__(self):\n\t\tself.predicate = None\n\t\tself.argument = []\n\n\tdef set_predicate(self,clause):\n\t\tself.predicate = clause\n\n\tdef add_argument(self,clause):\n\t\tself.argument.insert(0,clause)\n\n\tdef add_arg_receiving_from(self,to_clause,from_clause):\n\t\tto_clause.receiving_from.append(from_clause)\n\n\tdef search_clause_from_id(self,c_id):\n\t\tif self.predicate.clause_id == c_id :\n\t\t\treturn self.predicate\n\t\telse :\n\t\t\tfor arg in self.argument:\n\t\t\t\tif arg.clause_id == c_id :\n\t\t\t\t\treturn arg\n\n\t\treturn None\n\n#質問に使用するフレーズの抽出モジュール(new)\n#def extract_phrase(node,id_relation):\ndef extract_phrase(node):\n\tphrase = \"\"\n\tsentence = node.detail\n\n\t#除外辞書でフィルタリング(言い回し)\n\tsentence = filtering_phrase(sentence)\n\n\tclause_structure = make_clauses(sentence)\n\n\t#いらない形態素のフィルタリング\n\tfiltering_morph(clause_structure)\n\n\t#述語項構造で単文取得\n\tphrase = get_simple_sentence(clause_structure)\n\n\treturn phrase\n\ndef make_clauses(sentence):\n\tclauses = []\n\n\tc = CaboCha.Parser()\n\tkabotya = c.parse(sentence)\n\txml = kabotya.toString(CaboCha.FORMAT_XML)\n\t#print(xml)\n\t#print(kabotya.toString(CaboCha.FORMAT_LATTICE))\n\n\troot = ET.fromstring(xml)\n\t#print(root.tag,root.attrib)\n\trelation = Clause_Structure()\n\tfor child in reversed(root):\n\t\t#print(child.tag, child.attrib)\n\t\tif child.attrib['link'] == '-1' :\n\t\t\tclause = Clause(child.attrib['id'],child.attrib['head'],child.attrib['func'])\n\t\t\trelation.set_predicate(clause)\n\t\telse :\n\t\t\tto_clause = relation.search_clause_from_id(child.attrib['link'])\n\t\t\tclause = Clause(child.attrib['id'],child.attrib['head'],child.attrib['func'],to_clause)\n\t\t\trelation.add_arg_receiving_from(to_clause,clause)\n\t\t\trelation.add_argument(clause)\n\n\t\tfor grand in child:\n\t\t\t#print(grand.tag, grand.attrib)\n\t\t\tfeature = grand.attrib['feature'].split(\",\")\n\t\t\tclause.add_morph(Morph(grand.attrib['id'],grand.text,feature[0],feature[1],feature[6]))\n\t#return clauses\n\treturn relation\n\n'''\ndef make_clauses(sentence):\n\tclauses = []\n\n\tc = CaboCha.Parser()\t\n\tkabotya = c.parse(sentence)\n\txml = kabotya.toString(CaboCha.FORMAT_XML)\n\t#print(xml)\n\n\troot = ET.fromstring(xml)\n\t#print(root.tag,root.attrib)\n\tfor child in root:\n\t\t#print(child.tag, child.attrib)\n\t\tclause = Clause(child.attrib['id'],child.attrib['link'],child.attrib['head'],child.attrib['func'])\n\t\tfor grand in child:\n\t\t\t#print(grand.tag, grand.attrib)\n\t\t\tfeature = grand.attrib['feature'].split(\",\")\n\t\t\tclause.add_morph(Morph(grand.attrib['id'],grand.text,feature[0],feature[1],feature[6]))\n\t\tclauses.append(clause)\n\treturn clauses\n'''\ndef filtering_phrase(sentence):\n\tstart_errors = []\n\tend_errors = ['のでは','できるから','なのでしょう','かもしれ']\n\n\tsent = sentence\n\tfor error in start_errors :\n\t\tif error in sent :\n\t\t\tsep_sent = sent.split(error)\n\t\t\tsent = sep_sent[1]\n\n\tfor error in end_errors :\n\t\tif error in sent:\n\t\t\tsep_sent = sent.split(error)\n\t\t\tsent = sep_sent[0]\n\n\treturn sent\n\ndef filtering_morph(clause_structure):\n\tfilter_pos = [\"助詞\",\"助動詞\",\"感動詞\",\"記号\",\"フィラー\",\"名詞\",\"動詞\"]\n\t#末尾の助詞,助動詞,感動し,記号,句読点,フィラーなどをカット\n\tend_clause = clause_structure.predicate\n\t#Nonetype error\n\tnot_head = end_clause.get_after_head_morphs()\n\n\tdel_morphs = []\n\tif not_head :\n\t\tfor morph in not_head :\n\t\t\tif morph.pos in filter_pos :\n\t\t\t\tif (morph.pos == \"名詞\" or morph.pos == \"動詞\") and morph.pos_detail != \"非自立\":\n\t\t\t\t\tcontinue\n\t\t\t\t#静的に削除 不完全\n\t\t\t\t#print(\"delete:\",morph.word)\n\t\t\t\tdel_morphs.append(morph)\n\n\tfor morph in del_morphs :\n\t\tend_clause.delete_morph(morph)\n\n\t#文頭の接続詞 <- ibisにはない希ガス\n\t\ndef get_simple_sentence(clause_structure):\n\t#単文取得\n\tpredicate = clause_structure.predicate\n\tfrom_receive = predicate.receiving_from #list\n\tprint(\"predicate:\",predicate.get_string())\n\t#print(\"from_r:\",from_receive)\n\n\t#from_receiveの中から一番的適したものを選択(文が一文節しかないと成立しない)\n\t#とりあえず一番最後の項とする\n\t#ここエラーでる out of list\n\tif from_receive :\n\t\targument = follow_clause(from_receive[0])\n\telse :\n\t\t#print(\"nothing argument!!!\")\n\t\targument = \"\" \n\n\treturn argument+predicate.get_string()\n\n#項が複数に分岐するときは係り受けの計測値がつかえるかも\ndef follow_clause(clause,sentence=\"\"):\n\tif clause.receiving_from :\n\t\tprint(\"follow:\",clause.get_string())\n\t\tsentence = clause.get_string() + sentence\n\t\tfor rf_cla in clause.receiving_from :\n\t\t\t#sentence = clause.get_string() + sentence\n\t\t\t#print(\"fllow:\",clause.get_string())\n\t\t\tsentence = follow_clause(rf_cla,sentence)\n\telse :\n\t\tsentence = clause.get_string() + sentence\n\treturn sentence\n'''\nCabochaの述語項解析で単文を取得しmecabにかけて余分な情報(接頭,接尾語など)\nをカットしてフレーズ作成(末尾の形態素でテンプレを選択)\n\nq_based_ibisから呼び出される予定\n'''\n\nif __name__ == '__main__':\n\t#sentence =\"トップダウンでの指針を示すのも重要ですが、地域の人たちも巻き込んで作れるといいですね\"\n\tprint(\"input string:\")\n\tsentence = input()\n\tif sentence == \"\":\n\t\tsentence =\"各文書における用語の出現を表した文書-単語マトリクスが使われる。\"\n\n\t#clauses = make_clauses(sentence)\n\tsentence = filtering_phrase(sentence)\n\tstructure = make_clauses(sentence)\n\tfiltering_morph(structure)\n\n\tfor clause in structure.argument:\n\t\tprint(clause.clause_id,clause.get_string(),clause.receiving_from)\n\t\tmorphs = clause.morphs\n\t\tprint(morphs[0].word,morphs[0].pos,morphs[0].pos_detail)\n\tpre = structure.predicate\n\tprint(pre.clause_id,pre.get_string())\n\tmorphs = pre.morphs\n\t#print(morphs[0].word,morphs[0].pos)\n\tfor cla in pre.receiving_from :\n\t\tprint(\"from: \",cla.clause_id)\n\n\tprint(get_simple_sentence(structure),pre.get_end_original())\n\n","sub_path":"extract_phrase.py","file_name":"extract_phrase.py","file_ext":"py","file_size_in_byte":7293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"355668510","text":"#!/usr/bin/python\ndef outlierCleaner(predictions, ages_train, net_worths_train):\n\n\n\t\"\"\"\n\tClean away the 10% of points that have the largest\n\tresidual errors (difference between the prediction\n\tand the actual net worth).\n\n\tReturn a list of tuples named cleaned_data where \n\teach tuple is of the form (age, net_worth, error).\n\t\"\"\"\n\n\t#Going through each entry in the array and calculating the error value (value - mean)\n\tcleaned_data=[]\n\teval_data = []\n\tfor i in range(0,predictions.shape[0]):\n\t\t#Loading each value up\n\t\tage_val = ages_train[i][0]\n\t\tnet_worths_val = net_worths_train[i][0]\n\t\tpred_val = predictions[i][0]\n\t\t#Comparing the actual value to the predicted value. \n\t\terror = pred_val - net_worths_val\n\t\tee = error * error #squaring it to remove any value ambiquity of which is largest\n\t\t#Storing the values in a tuple and array\n\t\ttup = (age_val, net_worths_val, ee)\n\t\teval_data.append(tup)\n\t\n\t#this is sorting (in min->max) the array by the error value located within the tuple\n\teval_data.sort(key=lambda tup:tup[2]) \n\n\t#Discarding the worst 10% of the data \n\tdiscards = int(0.1 * predictions.shape[0]) # figuring out what th 10% size is\n\tcleaned_data = eval_data[0:(len(eval_data)-discards)]\n\n\treturn cleaned_data\n\n","sub_path":"outliers/outlier_cleaner.py","file_name":"outlier_cleaner.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"2166931","text":"# coding: utf8\nimport re, config, os\nfrom codecs import open\n\nsource_directory = os.path.join(os.path.dirname(__file__),'data\\\\')\n\ndict = open(source_directory+config.Config().wordFreqList, \"rb\")\ncontents = dict.read().decode(\"UTF-8\")\ndict.close()\n\ndict = open(source_directory+config.Config().kanjiList, \"rb\")\nkanjiList = dict.read().decode(\"UTF-8\")\ndict.close()\n\ndef stringContainsKanji(searchTerm):\n for c in searchTerm:\n #Checks if codepoint of character is anything but hiragana/katakana\n if ord(c) < 12353 or ord(c) > 12543:\n return True\n return False\n\ndef getWordFreq(hira, kanji):\n matchObj = None\n freq = 999999\n if isinstance(kanji, list):\n for k in kanji:\n regex = u\"\"+k+\"\t\"+hira+\"\t(.*?)\t\"\n matchObj = re.search(regex, contents)\n if matchObj != None and matchObj.group(1) < freq:\n freq = matchObj.group(1)\n\n else:\n regex = u\"\"+kanji+\"\t\"+hira+\"\t(.*?)\t\"\n matchObj = re.search(regex, contents)\n if matchObj != None:\n freq = re.search(regex, contents).group(1)\n\n #if matchObj == None:\n # return 999999 #Just something high so the sort gets this word to the back of the list\n\n return freq\n\ndef getRTKKeyword(kanji):\n kanjiFound = False\n kanjiField = \"\"\n keywordList = []\n #print(\"recieved kanji len: \"+ str(len(kanji)))\n for x in range(0, len(kanji)):\n #print(str(x))\n if stringContainsKanji(kanji[x]):\n #print(\"Contained kanji\")\n regex = kanji[x]+u\"\\t(.*)\"\n keyword = re.search(regex, kanjiList)\n #print(\"Keywords: \"+str(keyword))\n if keyword != None:\n if kanjiFound:\n kanjiField += \"
\"\n kanjiField += u\"\"+kanji[x]\n kanjiField += \" \"+str(keyword.group(1)).replace(\"\\r\",\"\")\n kanjiFound = True\n #print(\"Found kanji: \"+kanji[x]+\" = \"+keyword.group(1))\n #print(kanjiField)\n return kanjiField\n","sub_path":"Anki 2.0/shinmeikai_definitions/jpParser.py","file_name":"jpParser.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"239303595","text":"#!/usr/bin/env python3\nfrom time import gmtime, strftime\nimport paho.mqtt.client as mqtt\nimport sqlite3\n\n\nall_topics = \"JsonDataFromBatteries/#\"\ndbFile = \"mqttbatterydata.db\"\n\n############################## mqtt ################################################ \n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n client.subscribe(all_topics)\n \n# The callback for when a PUBLISH message is received from the server.\ndef on_message(client, userdata, msg):\n # theTime = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n # result = (theTime + \"\\t\" + str(msg.payload))\n # print(msg.topic + \":\\t\" + result)\n # if (str(msg.topic) == all_topics):\n print(\"Message received from topic: \" + str(msg.topic) + \" payload: \" + str(msg.payload))\n tablename = str(msg.topic).split(\"/\")\n print(\"creating table:\" +tablename[1])\n createTableDb(tablename[1])\n writeToDb(tablename[1],str(msg.payload))\n #return\n return\n\n####################### database ##################################################\n#Creating table in database\ndef createTableDb(TABLE):\n \n print (\"creating table: \"+TABLE)\n connection = sqlite3.connect(dbFile)\n cursor = connection.cursor()\n sql_create =\"CREATE TABLE IF NOT EXISTS \"+TABLE+\" ( timestamp TEXT, DATA TEXT )\"\n print (sql_create)\n cursor.execute(sql_create)\n connection.commit()\n cursor.close()\n connection.close()\n\n \ndef writeToDb(TABLE,datatoDb):\n print (\"writting table: \"+TABLE)\n datatoDb=datatoDb[1:len(datatoDb)]#eliminate that molest b at the begining\n timestamptoDb = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n connection = sqlite3.connect(dbFile)\n cursor = connection.cursor()\n sql_insert =\"INSERT INTO \"+TABLE+\"(timestamp,DATA) VALUES ('\"+timestamptoDb+\"',\"+ datatoDb +\")\"\n print (sql_insert)\n cursor.execute(sql_insert)\n connection.commit()\n cursor.close()\n print(\"Success Writting table\");\n connection.close()\n\n \nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(\"raspberrypi\", 1883, 60)\n\n# Blocking call that processes network traffic, dispatches callbacks and\n# handles reconnecting.\n# Other loop*() functions are available that give a threaded interface and a\n# manual interface.\nclient.loop_forever()\n","sub_path":"sqlwriter.py","file_name":"sqlwriter.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"516700532","text":"#!/usr/bin/env python3\nimport sys\ntry:\n from typing import List\nexcept ImportError:\n pass\n\n\nsys.setrecursionlimit(1000000)\n\n\ndef solve(N: int, M: int, X: \"List[int]\", Y: \"List[int]\", Z: \"List[int]\"):\n par = list(range(N))\n\n def getpar(n: int):\n if par[n] == n:\n return n\n par[n] = getpar(par[n])\n return par[n]\n\n def union(a: int, b: int):\n par[getpar(b)] = getpar(a)\n\n for Xi, Yi in zip(X, Y):\n Xi -= 1\n Yi -= 1\n union(Xi, Yi)\n\n print(len({getpar(i) for i in range(N)}))\n\n\ndef main():\n def iterate_tokens():\n for line in sys.stdin:\n for word in line.split():\n yield word\n tokens = iterate_tokens()\n N = int(next(tokens)) # type: int\n M = int(next(tokens)) # type: int\n X = [int()] * (M) # type: \"List[int]\"\n Y = [int()] * (M) # type: \"List[int]\"\n Z = [int()] * (M) # type: \"List[int]\"\n for i in range(M):\n X[i] = int(next(tokens))\n Y[i] = int(next(tokens))\n Z[i] = int(next(tokens))\n solve(N, M, X, Y, Z)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python_codes/p03045/s948190897.py","file_name":"s948190897.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"605594127","text":"#!/usr/bin/python3\r\nclass Solution:\r\n def searchInsert(self, nums, target: int) -> int:\r\n if target in nums:\r\n return nums.index(target)\r\n else:\r\n if target > nums[-1]: return len(nums)\r\n for i,value in enumerate(nums):\r\n if target < value:\r\n return (i)\r\n #i = len(nums)-1\r\n #while target <= nums[i]:\r\n # i -= 1\r\n #return i+1\r\n \r\n\r\n\r\ndef main():\r\n print(obj.searchInsert([1,3,5,6],5))\r\n\r\n# Start program\r\nif __name__ == \"__main__\":\r\n obj = Solution()\r\n main()\r\n ","sub_path":"problem_35_search_insert_position/search_insert_position.py","file_name":"search_insert_position.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"11632191","text":"\"\"\"\nRun Script for Creating a Preprocessed Training Dataset\nOn Casper\n\"\"\"\n\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport sys\n\n# set path to Fourier Optics library\ndirP_str = '/glade/u/home/mhayman/Python/Python-Optics/Libraries/'\nif dirP_str not in sys.path:\n sys.path.append(dirP_str)\n\nsoftware_path = \"/glade/u/home/mhayman/Python/holodec-ml/scripts/mhayman/\"\n\nds_path = \"/glade/work/mhayman/holodec-ml-data/UNET/\"\nds_file = \"UNET_image_256x256_5000count_5particles_v02.nc\"\n\nsave_path = \"/glade/scratch/mhayman/holodec/holodec-ml-data/UNET/\"\nrescale = 255\n\n# specify number of layers to reconstruct\n# params = {'zplanes':2,\n# 'preprocess_type':'multi-plane reconstruction',\n# 'raw_file':ds_file,\n# 'complevel':9}\nparams = {'zplanes':0,\n 'preprocess_type':'Fourier Transform',\n 'raw_file':ds_file,\n 'complevel':9}\n\n# exec_file = software_path+\"PreProcess/PreProcess_MultiPlane_UNET.py\"\nexec_file = software_path+\"PreProcess/PreProcess_FT_UNET.py\"\nexec(compile(open(exec_file,'rb').read(),exec_file,'exec'))","sub_path":"scripts/mhayman/run_scripts/casper_unet_preprocess.py","file_name":"casper_unet_preprocess.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"317473048","text":"\"\"\"\nConfiguration specific to a generic development environment\n\nThis controls settings that enable a developer-friendly experience. It is *not* where machine-specific\nconfiguration is stored. For that, use a .env file in your local directory\n\nRecommended reading:\nhttps://12factor.net/\n\"\"\"\nfrom .base import * # noqa\n\nDEBUG = True\n\n# Provide a default secret key if one is not present in the user's .env file\nSECRET_KEY: str = (\n SECRET_KEY # noqa type: ignore\n or \"for development environments we provide some generic secret key placeholder\"\n)\n","sub_path":"pheget/settings/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"92496630","text":"import pytest\nfrom backends.feed.backend import (\n Feed,\n Item,\n Description\n)\n\n\n@pytest.fixture\ndef invalid_xml_format():\n return (''\n 'M ')\n\n\n@pytest.fixture\ndef valid_feed_object():\n description = Description(\n type='text',\n content='test content'\n )\n\n item = Item(\n title=\"Test Auto Esporte\",\n link=\"http://teste.com.br\",\n description=[description]\n )\n\n feed = Feed(\n item=[item]\n )\n return feed\n","sub_path":"feed_test_api/extensions/service/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"104882560","text":"import platform\nimport xbmc\nimport struct\nimport os\nimport stat\n\nfrom defs import BINARY_URL\n\nelf_machines = {2: \"sparc\", 3: \"x86\", 8: \"mips\", 20: \"ppc\", 21: \"ppc64\", 22: \"s390\",\n 40: \"arm\", 42: \"superh\", 50: \"ia64\", 62: \"amd64\", 183: \"aarch64\", 243: \"riscv\"}\n\n\ndef detect_os():\n system = platform.system().lower()\n if \"windows\" in system or xbmc.getCondVisibility('system.platform.windows'):\n return \"windows\"\n if \"linux\" in system or xbmc.getCondVisibility('system.platform.linux'):\n if xbmc.getCondVisibility('system.platform.android'):\n return \"android\"\n return \"linux\"\n\n\ndef getelfabi():\n def readbyte(offset, decoder=\"B\", size=1):\n f.seek(offset)\n return struct.unpack(decoder, f.read(size))[0]\n mflags_d = {}\n with open(\"/proc/self/exe\") as f:\n is64 = readbyte(0x4) == 2\n oseabi = readbyte(0x7)\n eabiver = readbyte(0x8)\n machine = elf_machines.get(readbyte(0x12, \"H\", 2))\n if is64:\n f.seek(0x30)\n else:\n f.seek(0x24)\n mflags = f.read(4)\n if machine in [\"arm\", \"arm64\"]:\n first, mid, abi = struct.unpack(\"HBB\", mflags)\n mflags_d[\"ABI\"] = abi\n mflags_d[\"HRD\"] = first >> 10 & 1\n mflags_d[\"SFT\"] = first >> 9 & 1\n toolchains = []\n if machine == \"x86\":\n toolchains.append(\"i386\")\n elif machine == \"amd64\":\n if is64:\n toolchains.append(\"amd64\")\n toolchains.append(\"i386\")\n else:\n toolchains.append(\"i386\")\n elif machine in [\"arm\", \"aarch64\"]:\n if is64:\n toolchains.append(\"aarch64\")\n elif mflags_d[\"HARD\"]:\n toolchains.append(\"armhf\")\n toolchains.append(\"armel\")\n else:\n toolchains.append(\"armel\")\n return toolchains, machine, is64, mflags\n\n\ndef getbinary():\n error = None\n os = detect_os()\n if os == \"linux\":\n toolchains, machine, is64, mflags = getelfabi()\n if toolchains:\n return [(\"%s-%s\" % (os, x), \"%s/triblerd-%s-%s/triblerd\" % (BINARY_URL,\n os,\n x)) for x in toolchains], error\n else:\n return [], \"Can't detect abi for os linux, machine: %s, 64bit: %s, flags: %s\" % (machine,\n is64,\n mflags)\n else:\n return [], \"%s os is not supported\" % os\n\n\ndef chmod_plus_x(path):\n os.chmod(path, os.stat(path).st_mode | ((stat.S_IXUSR |\n stat.S_IXGRP |\n stat.S_IXOTH\n ) & ~ os.umask(os.umask(0))\n ))\n","sub_path":"plugin.program.tribler/tribler/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"6090978","text":"import os\nimport threading\n\nimport arrow\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler, ConversationHandler\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardRemove\n\nfrom config import TOKEN, TZ, proxy_url, proxy_user, proxy_pass\nfrom data_catcher import get_nearest_lesson, print_nearest_lesson, get_names\nfrom collections import defaultdict\n\nupdater = Updater(token=TOKEN, use_context=True)\ndispatcher = updater.dispatcher\n\nchat_ids = defaultdict(lambda: {'GroupId': [], 'StudentId': []})\ntmp = {}\n\ndef subscribe(id_type, ruz_id, chat_id):\n global tmp\n if not (ruz_id, tmp[ruz_id]) in chat_ids[int(chat_id)][id_type]:\n chat_ids[int(chat_id)][id_type].append((ruz_id, tmp[ruz_id]))\n tmp = {}\n\n\ndef unsubscribe(id_type, chat_id, ruz_id, query):\n for i in range(len(chat_ids[int(chat_id)][id_type])):\n if chat_ids[int(chat_id)][id_type][i][0] == ruz_id:\n del chat_ids[int(chat_id)][id_type][i]\n break\n query.edit_message_text(text='Вы отписались')\n\n\ndef get_next(update, context):\n markup = InlineKeyboardMarkup(\n [[InlineKeyboardButton(text='Расписание группы',\n callback_data=f'GetGroup {update.effective_user.id}')],\n [InlineKeyboardButton(text='Индивидуальное расписание',\n callback_data=f'GetStudent {update.effective_user.id}')]]\n )\n context.bot.send_message(\n chat_id=update.message.chat_id,\n text='Какое расписание Вы хотите получить?',\n reply_markup=markup)\n return SUBQUESTION\n\n\ndef start_help(update, context):\n context.bot.send_message(\n chat_id=update.message.chat_id,\n text='Здравствуйте! Я - рузбот, напомню о парах и скину расписание.\\n'\n 'Доступные команды:\\n'\n '/help - помощь\\n'\n '/subscribe - подписать чат на уведомления о приближающихся парах для группы или студента\\n'\n '/unsubscribe - отписать чат от уведомлений\\n'\n '/getnext - получить информацию о ближайшей паре для группы или студента, на которых подписан чат\\n'\n 'По всем вопросам обращаться к @sphericalpotatoinvacuum, @allisyonok или @grenlayk'\n )\n\n\ndef unsubscribe_chat(update, context):\n markup = InlineKeyboardMarkup(\n [[InlineKeyboardButton(text='Расписание группы',\n callback_data=f'UnSubGroup {update.effective_user.id}')],\n [InlineKeyboardButton(text='Индивидуальное расписание',\n callback_data=f'UnSubStudent {update.effective_user.id}')]]\n )\n context.bot.send_message(\n chat_id=update.message.chat_id,\n text=\"От чего вы хотите отписаться?\",\n reply_markup=markup)\n return UNSUB\n\n\ndef subscribe_chat(update, context):\n markup = InlineKeyboardMarkup(\n [[InlineKeyboardButton(text='Расписание группы',\n callback_data=f'SubGroup {update.effective_user.id}')],\n [InlineKeyboardButton(text='Индивидуальное расписание',\n callback_data=f'SubStudent {update.effective_user.id}')]]\n )\n context.bot.send_message(\n chat_id=update.message.chat_id,\n text=\"Получать индивидуальное расписание или расписание группы?\",\n reply_markup=markup)\n return SUBQUESTION\n\n\ndef button(update, context):\n query = update.callback_query\n data = query.data.split()\n\n if data[0] == 'SubGroup':\n if int(data[1]) == update.effective_user.id:\n query.edit_message_text(\n text='Введите номер группы в формате БПМИ195')\n return SUBGROUP\n elif data[0] == 'SubStudent':\n if int(data[1]) == update.effective_user.id:\n query.edit_message_text(text='Введите ФИО')\n return SUBSTUDENT\n elif data[0] == 'StudentId' or data[0] == 'GroupId':\n if data[1] != '0':\n if int(data[3]) == update.effective_user.id:\n subscribe(data[0], data[1], data[2])\n query.edit_message_text(text='Вы успешно подписались!')\n else:\n if int(data[3]) == update.effective_user.id:\n query.edit_message_text(\n text='Попробуйте уточнить правильность написания. '\n 'Если не поможет, то Вас нет в базе данных РУЗа'\n )\n return ConversationHandler.END\n elif data[0] == 'UnSubGroup' or data[0] == 'UnSubStudent':\n print(data[1], update.effective_user.id)\n if int(data[1]) == update.effective_user.id:\n if data[0] == 'UnSubGroup':\n id_type = 'GroupId'\n text = 'От какой группы Вы хотите отписаться?'\n chosen_type = 'GroupChosen'\n else:\n id_type = 'StudentId'\n text = 'От какого студента Вы хотите отписаться?'\n chosen_type = 'StudentChosen'\n markup = []\n for (ruz_id, ruz_name) in chat_ids[update.effective_chat.id][id_type]:\n markup.append([InlineKeyboardButton(\n text=f'{ruz_name}',\n callback_data=f'{chosen_type} {ruz_id} '\n f'{update.effective_chat.id} {update.effective_user.id}'\n )])\n if not markup:\n query.edit_message_text(\n text='Вы ещё ни на кого не подписались. '\n 'Подписаться вы можете командой /subscribe'\n )\n return ConversationHandler.END\n query.edit_message_text(\n text=text,\n reply_markup=InlineKeyboardMarkup(markup))\n return UNSUB\n elif data[0] == 'StudentChosen' or data[0] == 'GroupChosen':\n if int(data[3]) == update.effective_user.id:\n if data[0] == 'StudentChosen':\n id_type = 'StudentId'\n else:\n id_type = 'GroupId'\n unsubscribe(id_type, data[2], data[1], query)\n return ConversationHandler.END\n elif data[0] == 'GetGroup' or data[0] == 'GetStudent':\n if int(data[1]) == update.effective_user.id:\n if data[0] == 'GetStudent':\n id_type = 'StudentId'\n send_type = 'PrintStudent'\n message_text = 'Для кого вы хотите получить расписание?'\n else:\n id_type = 'GroupId'\n send_type = 'PrintGroup'\n message_text = 'Для какой группы вы хотите получить расписание?'\n chat_id = update.effective_chat.id\n\n if not chat_ids[chat_id][id_type]:\n query.edit_message_text(\n text='Вы ещё ни на кого не подписались. '\n 'Подписатьсяs вы можете командой /subscribe'\n )\n return ConversationHandler.END\n\n if len(chat_ids[chat_id][id_type]) == 1:\n for (user_id, user_name) in chat_ids[chat_id][id_type]:\n query.edit_message_text(\n text=f'Расписание для: {user_name}\\n{print_nearest_lesson(id_type, user_id)}'\n )\n return ConversationHandler.END\n\n markup = []\n for (user_id, user_name) in chat_ids[chat_id][id_type]:\n markup.append([InlineKeyboardButton(\n text=f'{user_name}',\n callback_data=f'{send_type} {user_id}')])\n query.edit_message_text(\n text=message_text,\n reply_markup=InlineKeyboardMarkup(markup))\n return PRINTNEXT\n elif data[0] == 'PrintGroup' or data[0] == 'PrintStudent':\n chat_id = update.effective_chat.id\n if data[0] == 'PrintStudent':\n id_type = 'StudentId'\n else:\n id_type = 'GroupId'\n for (user_id, user_name) in chat_ids[chat_id][id_type]:\n if int(user_id) == int(data[1]):\n query.edit_message_text(\n text=f'Расписание для: {user_name}\\n{print_nearest_lesson(id_type, user_id)}')\n return ConversationHandler.END\n\n\ndef to_ruz(name_type):\n def search(update, context):\n name = update.message.text\n\n if name_type == 'student':\n id_type = 'StudentId'\n else:\n id_type = 'GroupId'\n\n names = get_names(name, name_type)\n markup = []\n for name in names:\n tmp[name[\"id\"]] = name[\"label\"]\n markup.append([InlineKeyboardButton(\n text=f'{name[\"label\"]}, {name[\"description\"]}',\n callback_data=f'{id_type} {name[\"id\"]} {update.message.chat_id} {update.effective_user.id}'\n )])\n markup.append([InlineKeyboardButton(\n text='Меня тут нет!',\n callback_data=f'{id_type} 0 0 {update.effective_user.id}'\n )])\n markup = InlineKeyboardMarkup(markup)\n\n if name_type == 'student':\n text = 'Следующие студенты удовлетворяют условиям поиска, выберите себя:'\n else:\n text = 'Следующие группы удовлетворяют условиям поиска, выберите свою:'\n update.message.reply_text(\n text=text,\n reply_markup=markup\n )\n\n return SUBCHOOSE\n return search\n\n\ndef check_timetable():\n timeout = 5\n\n now = arrow.now(TZ)\n\n for chat_id in chat_ids:\n for id_type in chat_ids[chat_id]:\n for (user_id, user_name) in chat_ids[chat_id][id_type]:\n nearest_lesson = get_nearest_lesson(id_type, user_id)\n if nearest_lesson == {}:\n continue\n if now <= arrow.get(\n f'{nearest_lesson[\"date\"]} {nearest_lesson[\"beginLesson\"]}'\n ).replace(tzinfo=TZ) <= now.shift(minutes=+10):\n updater.bot.send_message(\n chat_id=chat_id,\n text=f'Расписание для: {user_name}\\n'\n f'{print_nearest_lesson(id_type, user_id)}',\n disable_web_page_preview=True\n )\n timeout = 700\n\n threading.Timer(timeout, check_timetable).start()\n\n\ndef cancel(update, context):\n update.message.reply_text('Жаль, что не смог Вам помочь.',\n reply_markup=ReplyKeyboardRemove())\n\n return ConversationHandler.END\n\n\nstart_handler = CommandHandler('start', start_help)\nhelp_handler = CommandHandler('help', start_help)\nsubscribe_handler = CommandHandler('subscribe', subscribe_chat)\nunsubscribe_handler = CommandHandler('unsubscribe', unsubscribe_chat)\ngetnext_handler = CommandHandler('getnext', get_next)\ncallback_handler = CallbackQueryHandler(button)\n\nSUBQUESTION, SUBGROUP, SUBSTUDENT, SUBCHOOSE, UNSUB, PRINTNEXT = range(6)\n\nsub_conv_handler = ConversationHandler(\n entry_points=[subscribe_handler],\n states={\n SUBQUESTION: [callback_handler],\n SUBGROUP: [MessageHandler(filters=Filters.text, callback=to_ruz('group'))],\n SUBSTUDENT: [MessageHandler(filters=Filters.text, callback=to_ruz('student'))],\n SUBCHOOSE: [callback_handler]\n },\n fallbacks=[CommandHandler('cancel', cancel)],\n allow_reentry=True\n)\n\nunsub_conv_handler = ConversationHandler(\n entry_points=[unsubscribe_handler],\n states={\n UNSUB: [callback_handler],\n },\n fallbacks=[CommandHandler('cancel', cancel)],\n allow_reentry=True\n)\n\nnext_conv_handler = ConversationHandler(\n entry_points=[getnext_handler],\n states={\n SUBQUESTION: [callback_handler],\n PRINTNEXT: [callback_handler],\n },\n fallbacks=[CommandHandler('cancel', cancel)],\n allow_reentry=True\n)\n\ndispatcher.add_handler(start_handler)\ndispatcher.add_handler(help_handler)\ndispatcher.add_handler(sub_conv_handler)\ndispatcher.add_handler(unsub_conv_handler)\ndispatcher.add_handler(next_conv_handler)\ndispatcher.add_handler(callback_handler)\n\ncheck_timetable()\n\nPORT = int(os.environ.get('PORT', '8443'))\nDEV = bool(os.environ.get('DEV', False))\n\nif DEV:\n updater.start_polling()\nelse:\n updater.start_webhook(listen=\"0.0.0.0\", port=PORT, url_path=TOKEN)\n updater.bot.set_webhook('https://ruzbot.herokuapp.com/' + TOKEN)\n updater.idle()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"503199725","text":"import pygame as pg\nimport numpy as np\nfrom menu.Menu import Menu\nimport minigame1.Minigame1 as m1\nimport minigame2.Minigame2 as m2\nimport minigame3.Minigame3 as m3\nimport minigame4.Minigame4 as m4\nimport minigame5.Minigame5 as m5\nimport minigame6.Minigame6 as m6\nfrom minigame1.HighScore import HighScore\nfrom os import path\n\n\n\ndef main():\n pg.init()\n screen = pg.display.set_mode((800, 640))\n pg.display.set_caption(\"Het Strand Leven\")\n timer = pg.time.Clock()\n\n menu = Menu(screen)\n sk = \"\"\n \n\n # button = Menu.menu(screen)\n\n \n while True:\n timer.tick(30)\n\n menu = Menu(screen)\n print(menu.allHigs)\n whileMenu(menu,screen)\n sk = menu.sk\n \n startMiniGame(sk)\n\n\n\n\ndef whileMenu (menu,screen):\n screen = pg.display.set_mode((800, 640))\n while not menu.start:\n # print('Menu')\n # hs = menu.test\n button = Menu.menu(screen,menu.m1Higs,menu.m2Higs,menu.m3Higs,menu.m4Higs,menu.m5Higs,menu.m6Higs)\n menu.checkInput(button)\n\ndef startMiniGame(sk):\n if(sk == \"Minigame1\"):\n m1.Tim_2dPlatform()\n elif (sk == \"Minigame2\"):\n m2.Game().game_intro()\n # m2.Game().run()\n elif (sk == \"Minigame3\"):\n m3.game()\n elif (sk == \"Minigame4\"):\n m4.wilco()\n elif (sk == \"Minigame5\"):\n m5.gameLoop()\n elif (sk == \"Minigame6\"):\n m6.main()\n \n \n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"643372714","text":"# _*_ coding:utf-8 _*_\n# @time : 20:52\n# @Author : lemon_Liming\n# @Email : 1104197970@qq.com\n# @File : my_logging.py\n\nimport logging\nfrom common import project_path\nclass ReadLogging:\n\n def my_log(self,level,msg):\n my_logger=logging.getLogger('api_log')\n my_logger.setLevel('DEBUG')\n\n\n formatter= logging.Formatter('[%(asctime)s]-[%(levelname)s]-[日志信息]:%(message)s')\n ch=logging.StreamHandler()\n ch.setLevel('INFO')#设置级别\n ch.setFormatter(formatter)#设置格式\n\n fh=logging.FileHandler(project_path.my_log_path,encoding='utf-8')#写入到指定文件\n fh.setLevel('INFO')#设置级别\n fh.setFormatter(formatter)#设置格式\n\n my_logger.addHandler(ch)\n my_logger.addHandler(fh)\n\n if level=='DEBUG':\n my_logger.debug(msg)\n elif level=='INFO':\n my_logger.info(msg)\n elif level=='WARNING':\n my_logger.warning(msg)\n elif level=='ERROR':\n my_logger.error(msg)\n else:\n my_logger.critical(msg)\n\n my_logger.removeHandler(fh)#fh ch\n my_logger.removeHandler(ch)#一定要记得移除掉\n\n def debug(self,msg):#可以优化的地方\n self.my_log('DEBUG',msg)\n\n def info(self,msg):\n self.my_log('INFO',msg)\n\n def error(self,msg):\n self.my_log('ERROR',msg)\n\nif __name__ == '__main__':\n ReadLogging().info('me')\n ReadLogging().info('you')\n","sub_path":"common/my_log.py","file_name":"my_log.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"116356869","text":"import socket\r\nimport time\r\nimport machine\r\nimport onewire, ds18x20\r\n\r\ndef do_connect():\r\n import network\r\n sta_if = network.WLAN(network.STA_IF)\r\n sta_if.active(True)\r\n if not sta_if.isconnected():\r\n sta_if.ifconfig(('192.168.178.21','255.255.255.0','192.168.178.1','192.168.178.1'))\r\n print('connecting to network...')\r\n sta_if.connect(ESSID, PWD)\r\n while not sta_if.isconnected():\r\n pass\r\n print('network config:', sta_if.ifconfig())\r\n\r\ndef http_get(url):\r\n _, _, host, path = url.split('/', 3)\r\n print(host, path)\r\n s = socket.socket()\r\n try:\r\n addr = socket.getaddrinfo(host, 80)[0][-1]\r\n s.connect(addr)\r\n except:\r\n s.connect((host.split(':')[0], int(host.split(':')[1])))\r\n\r\n try:\r\n s.send(bytes('GET /%s HTTP/1.0\\r\\nHost: %s\\r\\n\\r\\n' % (path, host), 'utf8'))\r\n except:\r\n s.close()\r\n return -1\r\n# while True:\r\n# data = s.recv(100)\r\n# if data:\r\n# print(str(data, 'utf8'), end='')\r\n# else:\r\n# break\r\n# print('\\r\\n')\r\n s.close()\r\n\r\ndef get_temps():\r\n\r\n # the device is on GPIO12 for esp8266\r\n dat = machine.Pin(12)\r\n\r\n # the device is on GPIO27 for esp32\r\n #dat = machine.Pin(27)\r\n\r\n\r\n # create the onewire object\r\n ds = ds18x20.DS18X20(onewire.OneWire(dat))\r\n\r\n # scan for devices on the bus\r\n roms = ds.scan()\r\n #print('found devices:', roms)\r\n\r\n # loop 10 times and print all temperatures\r\n #for i in range(10):\r\n # print('temperatures:', end=' ')\r\n ds.convert_temp()\r\n time.sleep_ms(750)\r\n # for rom in roms:\r\n # print(ds.read_temp(rom), end=' ')\r\n # print()\r\n\r\n try:\r\n return ds.read_temp(roms[0])\r\n except:\r\n print(\"no DS18X20 found\")\r\n return 0\r\n\r\ndef get_adc():\r\n\r\n adc = machine.ADC(0)\r\n\r\n value=0\r\n for i in range(1000):\r\n value += adc.read()\r\n\r\n #print(value/1000)\r\n return value/1000\r\n\r\ndef do_deepsleep(s):\r\n# configure RTC.ALARM0 to be able to wake the device\r\n global rtc\r\n rtc = machine.RTC()\r\n rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)\r\n\r\n # set RTC.ALARM0 to fire after miliseconds (waking the device)\r\n rtc.alarm(rtc.ALARM0, s*1000)\r\n machine.deepsleep()\r\n\r\n# check if the device woke from a deep sleep\r\nif machine.reset_cause() == machine.DEEPSLEEP_RESET:\r\n print('woke from a deep sleep')\r\n\r\nstrTemp = str(round(get_temps(),1))\r\nstrBat = str(round(2*(((get_adc()*2)/337)+v_corr),1)/2)\r\n\r\ndo_connect()\r\n#print(str(round(get_temps(),1))+'\\n')\r\ntry:\r\n http_get('http://192.168.178.201:8080/json.htm?type=command¶m=udevice&idx='+str(idx_temp)+'&nvalue=0&svalue='+strTemp)\r\n# nodemcu v3: has a voltage divider and a max range of 3.3V - though above 2.5 very non-linear - 337/Volt empirical found\r\n# print(str(round(2*(((get_adc()*2)/337)+v_corr),1)/2)+'\\n')\r\n http_get('http://192.168.178.201:8080/json.htm?type=command¶m=udevice&idx='+str(idx_bat)+'&nvalue=0&svalue='+strBat)\r\nexcept:\r\n print('Could not connect to Server1')\r\ntry:\r\n http_get('http://192.168.178.202:8080/json.htm?type=command¶m=udevice&idx='+str(idx_temp)+'&nvalue=0&svalue='+strTemp)\r\n http_get('http://192.168.178.202:8080/json.htm?type=command¶m=udevice&idx='+str(idx_bat)+'&nvalue=0&svalue='+strBat)\r\nexcept:\r\n print('Could not connect to Server2')\r\n\r\n# put the device to sleep in seconds\r\ndo_deepsleep(m_sleep_time*60)\r\n","sub_path":"MicroPython/esp8266/esp8266-01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"317608575","text":"\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities \nimport sys\nimport time\nimport os\n\n\ndef get_bb_slot(url):\n \n driver = webdriver.Chrome(executable_path = \"/usr/local/lib/python3.7/site-packages/chromedriver_binary/chromedriver\")#bring the chromedriver exec to the script path\n driver.get(url)\n print(\"Please login using OTP and then wait for a while.\")\n time.sleep(180)\n\n\n while 1:\n driver.get(url) \n time.sleep(2)\n print(\"Trying to find a slot!\")\n try:\n driver.find_element_by_xpath(\"//button[@id = 'checkout']\").click()\n time.sleep(3) #driver take a few sec to update the new url\n if \"checkout\" in driver.current_url:\n print(\"Found the slots!\")\n for i in range(60):\n notify(\"Slots Available!\", \"Please go and choose the slots!\")\n os.system('say \"Slots for delivery available!\"')\n time.sleep(20)\n except:\n print(\"If this message pops up multiple times, please find the error and create a PR!\")\n pass\n print(\"No Slots found. Will retry again.\")\n time.sleep(120)\n\ndef notify(title, text):\n os.system(\"\"\"\n osascript -e 'display notification \"{}\" with title \"{}\"'\n \"\"\".format(text, title))\nget_bb_slot('https://www.bigbasket.com/basket/?ver=1')\n\n\n","sub_path":"BB_slot.py","file_name":"BB_slot.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"192555422","text":"#import random \n#import operator\nfrom config import *\nfrom CardGame import *\nfrom flask import Flask, request, render_template, redirect, url_for, session, current_app\nfrom flask_socketio import SocketIO, emit\n\napp = Flask(__name__)\napp.secret_key = 'blackjack' # has to be set to use session, which is a client side session\n\n# initialize application wide variables, which are shared among all users/requests\ndef init():\n with app.app_context():\n current_app.deck = Deck(); current_app.deck.shuffle()\n current_app.players = {}\n # add dealer first\n current_app.players['Dealer'] = Player('Dealer')\n for _ in range(2): current_app.players['Dealer'].draw(current_app.deck)\n current_app.players_order = ['Dealer']\n # dealer stop hit if points >= 17 or busted, pass to next player\n while current_app.players['Dealer'].points() != float('-inf') and current_app.players['Dealer'].points() < 17:\n current_app.players['Dealer'].draw(current_app.deck)\n current_app.cur_order = 1 # dealer is done, start with other players\n current_app.start_game = False\n current_app.reply = ''\n current_app.reset = True # used for reset event only\n\ninit()\nsocketio = SocketIO(app, logger=True)\n\n@app.route('/')\ndef index():\n if current_app.reset:\n session['me'] = None\n init()\n current_app.reset = False\n return render_template('join.html')\n if 'me' in session and session['me'] and session['me'] in current_app.players:\n return render_template('lobby.html', \n me=session['me'], \n players=current_app.players, \n players_order=current_app.players_order,\n cur_order=current_app.cur_order,\n start_game=current_app.start_game,\n reply=current_app.reply)\n session['me'] = None\n return render_template('join.html')\n\n@app.route('/join', methods=['POST', 'GET'])\ndef join():\n if session['me']: # current user already logged in\n return render_template('lobby.html', \n me=session['me'], \n players=current_app.players, \n players_order=current_app.players_order,\n cur_order=current_app.cur_order,\n start_game=current_app.start_game,\n reply=current_app.reply)\n username = request.form['username']\n ip = request.remote_addr\n if username in current_app.players:\n if ip != current_app.players[username].ip: # new user with duplicate name\n return render_template('join.html', err_msg='Player %s already exists, use another name.' % username)\n else: # same user logged in\n session['me'] = username\n return render_template('lobby.html', \n me=username, \n players=current_app.players, \n players_order=current_app.players_order,\n cur_order=current_app.cur_order,\n start_game=current_app.start_game,\n reply=current_app.reply)\n session['me'] = username # set current user session\n # create a new player\n if len(current_app.players) >= MAX_PLAYERS:\n return render_template('join.html', err_msg='Already reached maximum %s players.' % MAX_PLAYERS)\n player = Player(username); player.ip = ip\n for _ in range(2): player.draw(current_app.deck)\n current_app.players[username] = player\n current_app.players_order.append(username)\n return render_template('lobby.html', \n me=session['me'], \n players=current_app.players, \n players_order=current_app.players_order,\n cur_order=current_app.cur_order,\n start_game=current_app.start_game,\n reply=current_app.reply)\n\n@socketio.on('start')\ndef start(data):\n current_app.start_game = True\n # random.shuffle(current_app.players_order) # no need shuffle, take turn by joining order, dealer always first\n socketio.emit('continue', {'msg': 'done'})\n\n@socketio.on('hit')\ndef hit(data):\n player = current_app.players[session['me']]\n if player.points() == float(\"-inf\") or player.points() == float(\"inf\") \\\n or player.points() == 21: # busted or blackjack or 21 points, pass to next player\n if current_app.cur_order == len(current_app.players_order) - 1:\n socketio.emit('result', {'msg': 'done'})\n return\n current_app.cur_order += 1\n current_app.reply = session['me'] + ' passed'\n else: # get new card\n player.draw(current_app.deck)\n if player.points() == float(\"-inf\") or player.points() == float(\"inf\") \\\n or player.points() == 21: # busted or blackjack or 21 points, pass to next player\n if current_app.cur_order == len(current_app.players_order) - 1:\n socketio.emit('result', {'msg': 'done'})\n return\n current_app.cur_order += 1\n current_app.reply = session['me'] + ' got new card'\n socketio.emit('continue', {'msg': 'done'})\n\n@socketio.on('stand') \ndef stand(data):\n current_app.reply = session['me'] + ' passed'\n if current_app.cur_order == len(current_app.players_order) - 1:\n socketio.emit('result', {'msg': 'done'})\n return\n current_app.cur_order += 1\n socketio.emit('continue', {'msg': 'done'})\n\n@socketio.on('restart') \ndef restart(data):\n current_app.deck.shuffle()\n current_app.players['Dealer'].resetHand()\n for _ in range(2): current_app.players['Dealer'].draw(current_app.deck)\n # dealer stop hit if points >= 17 or busted, pass to next player\n while current_app.players['Dealer'].points() != float('-inf') and current_app.players['Dealer'].points() < 17:\n current_app.players['Dealer'].draw(current_app.deck)\n current_app.cur_order = 1 # dealer is done, start with other players\n current_app.reply = ''\n for p in current_app.players.values():\n if p.name == 'Dealer': continue # dealer is done\n p.resetHand()\n for _ in range(2): p.draw(current_app.deck)\n socketio.emit('restart', {'msg': 'done'})\n\n@socketio.on('next')\ndef next(data):\n if current_app.cur_order == len(current_app.players_order) - 1:\n socketio.emit('result', {'msg': 'done'})\n return\n current_app.cur_order += 1\n socketio.emit('continue', {'msg': 'done'})\n\n@socketio.on('reset')\ndef reset(data):\n init()\n socketio.emit('reset', {'msg': 'done'})\n\ndef win():\n scores = [p.points() for p in current_app.players.values()]\n w = max(scores)\n winners = []\n for p in current_app.players.values():\n if p.points() == w:\n winners.append(p.name)\n return ', '.join(winners)\n \n@app.route('/result')\ndef result():\n winners = win()\n return render_template('result.html',\n me=session['me'],\n players=current_app.players, \n players_order=current_app.players_order,\n winners=winners)\n\nif __name__ == '__main__':\n #app.run(SERVER, PORT, DEBUG)\n socketio.run(app, host=SERVER, port=PORT, debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"512059909","text":"import random\n\ndef noReplacementSimulation(numTrials):\n '''\n Runs numTrials trials of a Monte Carlo simulation\n of drawing 3 balls out of a bucket containing\n 4 red and 4 green balls. Balls are not replaced once\n drawn. Returns the a decimal - the fraction of times 3 \n balls of the same color were drawn.\n '''\n num_allones = 0 \n for i in range(numTrials):\n num_red = 4\n num_green = 4\n num_total = 8\n for i in range (3):\n if random.random () < (num_red/float(num_total)):\n num_red -= 1\n else:\n num_green -= 1\n num_total -= 1\n if num_red == 1 or num_green == 1:\n num_allones += 1\n \n \n return num_allones/float(numTrials)\n ","sub_path":"lect5_prob1.py","file_name":"lect5_prob1.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"319515608","text":"import tkinter\nfrom tkinter import *\nfrom google_trans_new import google_translator\ntranslator = google_translator()\nroot =Tk()\nroot.geometry(\"2000x2000\")\nroot.title(\"Personal Translator\")\nroot.configure(bg=\"#b8b894\")\nbutton101=Button(root, text='TRANSLATE', bg='#5F9EA0',font='Papyrus 14', fg='#003366', padx='50', pady='10')\nbutton101.place(x=550, y=200)\ndef convert():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='ja')\n text2.insert(\"end\", out)\ndef convert1():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='bg')\n text2.insert(\"end\", out)\ndef convert2():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='it')\n text2.insert(\"end\", out)\ndef convert3():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='fr')\n text2.insert(\"end\", out)\ndef convert4():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='bn')\n text2.insert(\"end\", out)\ndef convert5():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='es')\n text2.insert(\"end\", out)\ndef convert6():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='da')\n text2.insert(\"end\", out)\ndef convert7():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='no')\n text2.insert(\"end\", out)\ndef convert8():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='ur')\n text2.insert(\"end\", out)\ndef convert9():\n inputText=text1.get(\"1.0\", \"end\")\n print(inputText)\n out = translator.translate(inputText, lang_tgt='vi')\n text2.insert(\"end\", out)\ntext1=Text(root, height=5, width=30,bg='#6A5ACD')\ntext1.grid(row=1,column=1)\ntext2=Text(root, height=5, width=30, bg='#F0E68C')\ntext2.grid(row=2, column=1)\nbutton1=Button(root, text='JAPANESE', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command = convert)\nbutton1.grid(row=1, column=11)\nbutton2=Button(root, text='BULGARIAN', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command= convert1 )\nbutton2.grid(row=1, column=9)\nbutton3=Button(root, text='ITALIAN', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command= convert2)\nbutton3.grid(row=1, column=7)\nbutton4=Button(root, text='FRENCH', bg='#4d1a00',font='Garamond', fg='#ffffcc', padx='50', pady='10', command=convert3)\nbutton4.grid(row=1, column=5)\nbutton5=Button(root, text='BANGLA', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command=convert4)\nbutton5.grid(row=1, column=3)\nbutton6=Button(root, text='SPANISH', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command=convert5)\nbutton6.grid(row=2, column=3)\nbutton6=Button(root, text='DANISH', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command=convert6)\nbutton6.grid(row=2, column=5)\nbutton7=Button(root, text='Norwegian', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command=convert7)\nbutton7.grid(row=2, column=7)\nbutton8=Button(root, text='URDU', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command=convert8)\nbutton8.grid(row=2, column=9)\nbutton9=Button(root, text='VIETNAMESE', bg='#4d1a00',font='Garamond 12', fg='#ffffcc', padx='50', pady='10', command=convert9)\nbutton9.grid(row=2, column=11)\ndef clear():\n text1.delete(1.0, END)\n text2.delete(1.0,END)\nbutton10 = Button(root, text='clear', bg='#00ffbf',fg='black',command=clear)\nbutton10.grid(row=4,column=1, padx=10, pady=10)\nbuttonExit = Button(root, text='close', bg='#00ffbf',fg='black', command=root.destroy)\nbuttonExit.grid(row=5, column=1, padx=10, pady=10)\nroot.mainloop()","sub_path":"student_assignments/zabeerP1.py","file_name":"zabeerP1.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"338461224","text":"from knot_check import *\nfrom numpy import *\nfrom scipy import *\nfileroot='data/r'\nsavefolder='data/'\nNmin=1;\nNmax=10;\ndelta=zeros([Nmax-Nmin+1,1])\n\nfor fileindex in range(Nmin,Nmax+1):\n delta[fileindex-Nmin,0]=alexander(fileroot+str(fileindex),savefolder[0:-1])\n\ndelta=rint(delta)\ndelta=delta.astype(int)\nsavetxt(savefolder + 'delta',delta.astype(str),fmt=\"%s\")\n\n","sub_path":"structure_analysis_scripts/knot_script.py","file_name":"knot_script.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"385571028","text":"from kivy.lang import Builder\r\nfrom kivy.uix.screenmanager import Screen, ScreenManager\r\n\r\nBuilder.load_string(\"\"\"\r\n#:import randint random\r\n\r\n:\r\n text_size: self.size\r\n halign: 'left'\r\n valign: 'top'\r\n\r\n:\r\n\r\n BoxLayout:\r\n orientation: 'vertical'\r\n spacing: 10\r\n padding: 10\r\n pos_hint: {'center_x': 0.5, 'center_y': 0.5}\r\n size_hint: 0.8, 0.8\r\n \r\n Button:\r\n text: 'New Game'\r\n size_hint: 1, 0.25\r\n on_press: root.start_game('new game')\r\n \r\n Button:\r\n text: 'Load Game'\r\n size_hint: 1, 0.25\r\n on_press: root.start_game('load game')\r\n \r\n Button:\r\n text: 'Options'\r\n size_hint: 1, 0.25\r\n on_press: root.switch_to_settings('options')\r\n \r\n:\r\n Button:\r\n text: 'Back'\r\n size_hint: None, 0.1\r\n pos_hint: {'x': 0.01, 'top':0.99}\r\n size: 75, 50\r\n on_press: root.switch_back()\r\n\r\n BoxLayout:\r\n orientation: 'vertical'\r\n pos_hint: {'top': 0.9}\r\n size_hint_y: 0.9 \r\n Slider:\r\n min: 1\r\n max: 50\r\n # value: random.randint(1, 50)\r\n value: 2\r\n on_value: root.slider_1(self.value)\r\n Slider:\r\n min: 1\r\n max: 50\r\n # value: random.randint(1, 50)\r\n value: 25\r\n on_value: root.slider_2(self.value)\r\n \r\n BoxLayout:\r\n orientation: 'vertical'\r\n pos_hint: {'top': 0.9}\r\n size_hint_y: 0.9 \r\n \r\n CustomLabel:\r\n text: 'Option 1'\r\n \r\n CustomLabel:\r\n text: 'Option 2'\r\n\"\"\")\r\n\r\n\r\nclass SettingScreen(Screen):\r\n\r\n def slider_1(self, val, *args):\r\n # print('SettingScreen.slider_1:', val)\r\n pass\r\n\r\n def slider_2(self, val, *args):\r\n # print('SettingScreen.slider_1:', val)\r\n pass\r\n\r\n def switch_back(self, *args):\r\n self.manager.current = 'main'\r\n\r\n def on_touch_down(self, touch):\r\n return super(SettingScreen, self).on_touch_down(touch)\r\n\r\n\r\nclass MainMenuScreen(Screen):\r\n def start_game(self, text):\r\n # print('MainMenuScreen.start_game:', text)\r\n self.manager.parent.start_game(text)\r\n\r\n def switch_to_settings(self, text):\r\n # print('MainMenuScreen.switch_to_settings', text)\r\n self.manager.parent.switch_to_settings(text)\r\n\r\n\r\nclass MenuScreen(Screen):\r\n\r\n def __init__(self, **kwargs):\r\n super(MenuScreen, self).__init__(**kwargs)\r\n self.menu_sm = ScreenManager()\r\n self.menu_sm.add_widget(MainMenuScreen(name='main'))\r\n self.menu_sm.add_widget(SettingScreen(name='setting'))\r\n self.menu_sm.current = 'main'\r\n self.add_widget(self.menu_sm)\r\n\r\n def start_game(self, text, *args):\r\n # print('MenuScreen.start_game:', text)\r\n self.manager.current = 'game'\r\n\r\n def switch_to_settings(self, text, *args):\r\n # print('MenuScreen.switch_to_settings:', text)\r\n self.menu_sm.current = 'setting'\r\n\r\n def on_pre_enter(self, *args):\r\n # print('MenuScreen.on_pre_enter')\r\n pass\r\n\r\n def on_enter(self, *args):\r\n # print('MenuScreen.on_enter')\r\n pass\r\n","sub_path":"shmup/MenuScreen.py","file_name":"MenuScreen.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"534904722","text":"import sqlite3\ndef insert():\n conn = sqlite3.connect('states.db')\n\n cur = conn.cursor()\n\n cur.execute('''INSERT INTO CONTROLTABLE(\n NAME,STATE) VALUES('FRONT_GATE','TRUE')\n ''')\n conn.commit()\n conn.close()\ndef update(state,name):\n conn = sqlite3.connect('states.db')\n cur = conn.cursor()\n sql = 'UPDATE CONTROLTABLE SET STATE = ' + \"'\" + str(state) + \"'\" + \"WHERE NAME = \" + \"'\" + str(name) + \"'\"\n print(sql)\n cur.execute(str(sql))\n\n conn.commit()\n conn.close()\ndef fetch():\n conn = sqlite3.connect('states.db')\n\n cur = conn.cursor()\n\n cur.execute('''SELECT * FROM CONTROLTABLE''')\n result = cur.fetchall()\n print(result)\n conn.commit()\n conn.close()\ndef main():\n conn = sqlite3.connect('states.db')\n\n cur = conn.cursor()\n\n cur.execute('DROP TABLE IF EXISTS CONTROLTABLE')\n\n sql = '''CREATE TABLE CONTROLTABLE(\n ID INTEGER PRIMARY KEY,\n NAME VARCHAR,\n STATE BOOLEAN\n )'''\n cur.execute(sql)\n print(\"Table created\")\n conn.commit()\n conn.close()\nif __name__ == '__main__':\n #main()\n #fetch()\n BACKYARD = 'AQUARIUM'\n FALSE = 'FALSE'\n update(FALSE,BACKYARD)\n #insert()\n\n","sub_path":"db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"169784998","text":"# Copyright (C) 2015 Hewlett Packard Enterprise Development LP\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\n# NOTE: run using Python3\nimport urllib\nimport httplib2\nimport json\nfrom pprint import pprint\n\n'''\nTest script to save a new startup configuration data into OVSDB.\n\njson.data is a file containing the tables that are to be saved to DB.\n'''\n\n\nwith open('json.data') as data_file:\n _data = json.loads(data_file.read())\nhttp = httplib2.Http()\n\n_headers = {\"Content-type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"text/plain\"}\nurl = 'https://172.17.0.39/rest/v1/system/full-configuration?type=startup'\n\n_headers = {\"Content-type\": \"multipart/form-data\", \"Accept\": \"text/plain\"}\nresponse, content = http.request(url, 'PUT', headers=_headers,\n body=json.dumps(_data))\nprint(response)\nprint(content)\n","sub_path":"tests/startupconfig-put.py","file_name":"startupconfig-put.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"291867149","text":"# DESCRIPTION: Testing suite for the visualiser\n\nimport unittest\nimport matplotlib.pyplot as plt\nfrom lib import visualiser\n\nclass TestIndividualMethods(unittest.TestCase):\n \"\"\"Performs individual, disconnected unit tests on the methods and functions\n in visualiser.py\"\"\"\n\n def setUp(self):\n self.proportions = [30, 10, 60]\n self.labels = ['Data A', 'Data B', 'Data C']\n self.pieCallable = visualiser.PieChart\n return None\n\n def test_init(self):\n try:\n self.pieCallable(self.proportions, labels=self.labels)\n except Exception as e: # Any error raised is an instant fail.\n print(e)\n self.fail(e)\n return None\n\n def test_show(self):\n pie = self.pieCallable(self.proportions)\n pie.show()\n raw_input(\"Press ENTER to continue...\")\n return None\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"tests/test_visualiser.py","file_name":"test_visualiser.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"396899862","text":"#! /usr/bin/env python\nimport sys\nfrom collections import Counter\n\nc = Counter()\n\ncount = 0\n\nfor line in sys.stdin:\n gram1 = line.split()\n gram2=[]\n for i in range(len(gram1)):\n if i!=len(gram1)-1:\n gram2.append(gram1[i]+' '+gram1[i+1])\n for word in gram2:\n count += 1\n c[word] += 1\n\nnum = 0\nwords = 0\n\nfor key,f in sorted(c.items(), key=lambda x: x[1], reverse=True):\n words += f\n num += 1\n print(key,f)\n\n","sub_path":"tools/Vocab/get_vocab_2.py","file_name":"get_vocab_2.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"153040450","text":"#!/usr/bin/python3.8\n\nimport socket\nimport threading\n\nbind_ip = \"127.0.0.1\"\nbind_port = 5555\n\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver_socket.bind((bind_ip, bind_port))\nserver_socket.listen(5)\n\nprint(\"[*] Listening on %s:%d\" % (bind_ip, bind_port))\n\n# This is our client-handling thread\ndef handle_client(client_socket):\n\n\t# Print out what the client sends\n\trequest = client_socket.recv(1024).decode(encoding = \"UTF-8\")\n\n\tprint(\"[*] Received: %s\" % request)\n\n\t# Send back a packet\n\tclient_socket.send(b\"ACK!\")\n\n\tclient_socket.close()\n\nwhile True:\n\n\t(client_socket, addr) = server_socket.accept()\n\n\tprint(\"[*] Accepted connection from: %s:%d\" % (addr[0], addr[1]))\n\n\t# Spin up our client thread to handle incoming data\n\tclient_handler = threading.Thread(target = handle_client, args = (client_socket,))\n\tclient_handler.start()\n","sub_path":"Chap2/TCP_server.py","file_name":"TCP_server.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"17036950","text":"import requests\r\nimport streamer\r\nfrom threading import Thread\r\nimport time\r\nimport os\r\nimport utility\r\n\r\n\r\ndef download_media():\r\n \"\"\"\r\n Method to retrieve the hidden message from the tweet media.\r\n :return:\r\n \"\"\"\r\n while True:\r\n if os.path.exists('tweets.txt'):\r\n file = open('tweets.txt', 'r')\r\n if file.mode == 'r':\r\n # Reading from txt file with the media url\r\n img_url = file.read()\r\n print('Downloading from: ' + img_url)\r\n\r\n file = requests.get(img_url)\r\n\r\n try:\r\n file.raise_for_status()\r\n except Exception as exc:\r\n print('There was a problem: %s' % exc)\r\n\r\n # Create temporary image file\r\n play_file = open('img.png', 'wb')\r\n for chunk in file.iter_content(100000):\r\n play_file.write(chunk)\r\n play_file.close()\r\n\r\n print('Created img.png')\r\n print('Inspecting image')\r\n # Extract message from image\r\n print('Intercepted: ' + utility.retrieve('img.png'))\r\n\r\n # Cleaning up\r\n os.remove('tweets.txt')\r\n os.remove('img.png')\r\n\r\n time.sleep(5)\r\n\r\n\r\ndef main():\r\n stream_thread = Thread(target=streamer.TwitterStreamer.stream)\r\n stream_thread.start()\r\n\r\n download_thread = Thread(target=download_media)\r\n download_thread.start()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"586152844","text":"# Test BLE GAP advertising and scanning\n\nfrom micropython import const\nimport time, machine, bluetooth\n\n_IRQ_SCAN_RESULT = const(1 << 4)\n_IRQ_SCAN_COMPLETE = const(1 << 5)\n\nADV_TIME_S = 3\n\n\ndef instance0():\n multitest.globals(BDADDR=ble.config(\"mac\"))\n print(\"gap_advertise(20_000)\")\n ble.gap_advertise(20_000, b\"\\x02\\x01\\x06\\x04\\xffMPY\")\n multitest.next()\n time.sleep(ADV_TIME_S)\n print(\"gap_advertise(None)\")\n ble.gap_advertise(None)\n ble.active(0)\n\n\ndef instance1():\n multitest.next()\n finished = False\n adv_data = None\n\n def irq(ev, data):\n nonlocal finished, adv_data\n if ev == _IRQ_SCAN_RESULT:\n if data[1] == BDADDR:\n adv_data = bytes(data[4])\n elif ev == _IRQ_SCAN_COMPLETE:\n finished = True\n\n ble.config(rxbuf=2000)\n ble.irq(irq)\n ble.gap_scan(ADV_TIME_S * 1000, 10000, 10000)\n while not finished:\n machine.idle()\n ble.active(0)\n print(\"adv_data:\", adv_data)\n\n\nble = bluetooth.BLE()\nble.active(1)\n","sub_path":"tests/multi_bluetooth/ble_gap_advertise.py","file_name":"ble_gap_advertise.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"508130663","text":"#!/usr/bin/env python\nimport rospy\nimport std_msgs.msg\nimport PySpin\nimport numpy as np\nimport cv2\nimport serial#sudo pip3 install pyserial\nimport time\nimport io \nimport os\nimport SharedArray as sa\nimport thread\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom sensor_msgs.msg import Image\n\nsetting_list = [\n ['TriggerMode' , 'Off' , 'General'],\n ['StreamBufferHandlingMode' , 'NewestOnly' , 'Stream' ],\n ['AcquisitionMode' , 'Continuous' , 'General'],\n# ['PixelFormat' , 'BayerRG8' , 'stream'],\n ]\n\nclass Camera():\n def config_camera(self):\n cam = self.cam\n setting_list = self.setting_list\n for i in range(len(setting_list)):\n if setting_list[i][2] == 'General':\n nodemap = cam.GetNodeMap()\n if setting_list[i][2] == 'Stream':\n nodemap = cam.GetTLStreamNodeMap()\n attribute = setting_list[i][0]\n value = setting_list[i][1]\n node = PySpin.CEnumerationPtr(nodemap.GetNode(attribute))\n if not PySpin.IsAvailable(node) or not PySpin.IsWritable(node):\n print('Unable to set attribute : %s'%attribute)\n continue\n node_new_value = node.GetEntryByName(value)\n if not PySpin.IsAvailable(node_new_value) or not PySpin.IsReadable(node_new_value):\n print('Cant set %s --> %s'%(value,attribute))\n continue\n node.SetIntValue(node_new_value.GetValue())\n\n node_pixel_format = PySpin.CEnumerationPtr(nodemap.GetNode('PixelFormat'))\n\n def __init__(self):\n self.setting_list = setting_list\n self.system = PySpin.System.GetInstance()\n self.cam_list = self.system.GetCameras()\n num_cameras = self.cam_list.GetSize()\n if num_cameras == 0:\n self.cam_list.Clear()\n self.system.ReleaseInstance()\n print('Not enough cameras!')\n os._exit(0)\n self.cam = self.cam_list[0]\n self.cam.Init()\n self.config_camera()\n \n self.cam.BeginAcquisition()\n\n def __del__(self):\n self.cam.EndAcquisition()\n self.cam.DeInit()\n del self.cam\n self.cam_list.Clear()\n self.system.ReleaseInstance()\n\n def read(self):\n image_pt = self.cam.GetNextImage()\n if image_pt.IsIncomplete():\n print('Image incomplete with image status %d ...' % image_pt.GetImageStatus())\n os._exit(0) \n #image_converted = image_pt.Convert(PySpin.PixelFormat_BGR8, PySpin.NEAREST_NEIGHBOR_AVG)\n image= image_pt.GetNDArray()\n image_pt.Release()\n return image\n\nif __name__ == '__main__':\n rospy.init_node('camera_node', anonymous=False)\n image_path_pub = rospy.Publisher('image_path', std_msgs.msg.String, queue_size=1)\n raw_image_pub = rospy.Publisher('image_raw', Image, queue_size=1)\n bridge = CvBridge()\n cam = Camera()\n image_id = 0\n os.system('rm /dev/shm/*.opy')\n storing_path = 'shm://'\n x = []\n image = cam.read()\n image = cv2.cvtColor(image, cv2.COLOR_BAYER_BG2BGR)\n for i in range(20):\n x.append(sa.create(\"shm://%d.opy\"%i,image.shape,dtype = 'uint8'))\n while not rospy.is_shutdown():\n t0 = time.time() * 1000\n raw = cam.read()\n t1 = time.time() * 1000\n image = cv2.cvtColor(raw, cv2.COLOR_BAYER_BG2BGR)\n image_id = (image_id + 1) % 20 \n image_path = storing_path + '%d.opy'%(image_id)\n x[image_id][:] = image\n image_path_pub.publish(image_path)\n t2 = time.time() * 1000\n raw_ros_image = bridge.cv2_to_imgmsg(raw, \"bayer_rggb8\")\n raw_image_pub.publish(raw_ros_image)\n t3 = time.time() * 1000\n\n# image_to_show = cv2.resize(image,(240,160))\n# cv2.circle(image_to_show, (120,60), 5,(0,0,255), 1)\n# cv2.imshow('a',image_to_show)\n# key = cv2.waitKey(1)\n# t2 = time.time() * 1000\n# print(\"%6.2f %6.2f\"%(t1-t0,t2-t0))\n# if key == ord('q'):\n# break\n# print(\"cap %5.2f memory %5.2f ros_pub %5.2f sum %5.2f\"%(t1-t0,t2-t1,t3-t2,t3-t0))\n if rospy.is_shutdown():\n del cam\n break\n \n","sub_path":"camera/camera_node.py","file_name":"camera_node.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"31582011","text":"from tkinter import Tk, Frame, Label\nimport threading\nimport time\nfrom model.board import BOARD_DIMENSION\nfrom model.pieces.constants import Pieces\nfrom model.color import Color\nimport queue\n\nWIDTH = 600\nHEIGHT = 600\n\nclass View:\n def __init__(self, game, master=Tk()):\n self.master = master\n self.game = game\n self.board = self.game.get_board_safely()\n self.labels = []\n self.draw_grid()\n\n def draw_grid(self):\n for label in self.labels:\n label.destroy()\n for rank_index in range(BOARD_DIMENSION):\n for file_index in range(BOARD_DIMENSION):\n piece = self.board.get((file_index, rank_index))\n color = 'snow'\n if piece is not None and piece.get_color() is Color.WHITE:\n color = 'linen'\n elif piece is not None:\n color = 'grey55'\n row = rank_index\n rect = Label(self.master, text=str(piece), bg=color, borderwidth=1)\n self.labels.append(rect)\n rect.grid(column=file_index, row=row, sticky='')\n self.master.grid_columnconfigure(file_index, weight=1)\n self.master.grid_rowconfigure(row, weight=1)\n \n def set_board(self, board):\n self.board = board\n self.draw_grid()\n self.master.update()\n\n def run(self):\n self.master.mainloop()\n","sub_path":"game/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"212941333","text":"#!/usr/bin/env python3\nimport math\nimport sys\n\nwidth = 25\nheight = 6\nimage = []\n\nwith open('input.txt', 'r') as f:\n line = f.readline().strip()\n layer = -1 \n for (i, digit) in enumerate(line):\n if i % (width * height) == 0:\n layer += 1\n image.append(list())\n image[layer].append(digit)\n\ndef f(pos, layer):\n global image\n if layer > len(image):\n print('whoops something is very wrong')\n sys.exit(1)\n if image[layer][pos] != '2':\n return image[layer][pos]\n \n return f(pos, layer+1)\n\nres = []\nfor (i,top) in enumerate(image[0]):\n r = f(i, 0)\n res.append(r)\n\nfor (i, letter) in enumerate(res):\n if i % width == 0:\n print()\n if letter == '0':\n print(' ', end='')\n else:\n print(letter, end='')\n","sub_path":"2019/python/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"509944759","text":"import cv2\n\n\nVIDEO_CAPTURE_PROPS_LIST = [\n \"CAP_PROP_POS_MSEC\",\n \"CAP_PROP_POS_FRAMES\",\n \"CAP_PROP_POS_AVI_RATIO\",\n \"CAP_PROP_FRAME_WIDTH\",\n \"CAP_PROP_FRAME_HEIGHT\",\n \"CAP_PROP_FPS\",\n \"CAP_PROP_FOURCC\",\n \"CAP_PROP_FRAME_COUNT\",\n \"CAP_PROP_FORMAT\",\n]\n\nVIDEO_CAPTURE_PROPS = {\n prop.split(\"CAP_PROP_\").pop().lower(): prop for prop in VIDEO_CAPTURE_PROPS_LIST\n}\n\n\ndef add_props(props):\n def deco(cls):\n for prop in props:\n setattr(cls, prop, VideoCaptureProperty(prop))\n return cls\n\n return deco\n\n\nclass VideoCaptureProperty:\n\n _set_err = (\n \"The property {p} is not supported by\\n\"\n \"the backend used by the cv2.VideoCapture() instance.\"\n )\n _docstring = (\n \"Alias for cap.get(cv2.{p}) and cap.set(cv2.{p}, value).\\n\"\n \"Raises AttributeError when setting if that property is not supported.\\n\"\n )\n\n def __init__(self, name):\n self.name = name\n self.prop = getattr(cv2, VIDEO_CAPTURE_PROPS[name])\n self.__doc__ = self._docstring.format(p=VIDEO_CAPTURE_PROPS[name])\n\n def __get__(self, obj, objtype=None):\n return obj.get(self.prop)\n\n def __set__(self, obj, value):\n if not obj.set(self.prop, value):\n raise AttributeError(self._set_err.format(p=VIDEO_CAPTURE_PROPS[self.name]))\n\n\n@add_props(VIDEO_CAPTURE_PROPS.keys())\nclass VideoCapture(cv2.VideoCapture):\n \"\"\"An adapter for `cv2.VideoCapture`, giving a more Pythonic interface.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if not self.isOpened():\n raise ValueError(\"Unable to open video source:\", *args, **kwargs)\n\n def __iter__(self):\n \"\"\"Resets the frame position to 0 at the start for repeatable iteration.\"\"\"\n try:\n self.pos_frames = 0\n except AttributeError:\n pass\n while self.isOpened():\n success, frame = self.read()\n if success:\n yield frame\n else:\n return\n\n def __enter__(self):\n \"\"\"Enter the context manager.\"\"\"\n return self\n\n def __exit__(self, exctype, exc, exctrace):\n \"\"\"Releases the video capture object on exiting the context manager.\"\"\"\n self.release()\n\n\nclass VideoPlayer:\n\n _actions = {\"quit\": set(map(ord, \"\\x1bq\"))}\n\n def __init__(self, cap):\n self.cap = cap\n self.rate = int(1000 / self.cap.fps)\n\n def play(self, window_name=\"VideoPlayer\", framefunc=None, loop=False):\n \"\"\"Plays through the video file with OpenCV's imshow().\"\"\"\n\n framefunc = framefunc or (lambda frame: frame)\n\n for frame in self.cap:\n cv2.imshow(window_name, framefunc(frame))\n key = cv2.waitKey(self.rate) & 0xFF\n if key in self._actions[\"quit\"]:\n return\n\n if loop:\n return self.play(window_name, framefunc, loop)\n","sub_path":"cvtools/videoio.py","file_name":"videoio.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"418410669","text":"from . import abstract_dao\nfrom ...db import db\n\n\nclass Book(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(200), unique=True, nullable=False)\n author = db.Column(db.String(120), unique=False, nullable=False)\n description = db.Column(db.String(300), unique=False, nullable=False)\n price = db.Column(db.Float, unique=False, nullable=False)\n cover = db.Column(db.String(400), unique=False, nullable=False)\n publisher = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n\n def __repr__(self):\n return '' % self.title\n\n def as_dict(self):\n return {c.name: getattr(self, c.name) for c in self.__table__.columns}\n\n\nclass BooksSQLDAO(abstract_dao.AbstractBooksDAO):\n \"\"\"\n Implements the in sql data access object for the Books\n \"\"\"\n def create_book(self, book_data):\n book = Book(title=book_data['title'],\n author=book_data['author'],\n description=book_data['description'],\n price=book_data['price'],\n cover=book_data['cover'],\n publisher=book_data['publisher'])\n db.session.add(book)\n db.session.commit()\n return book.as_dict()\n\n def get_all_books(self):\n books = Book.query.all()\n books_dict = list(map(lambda book: book.as_dict(), books))\n return books_dict\n\n def find_book_by_id(self, book_id):\n book = Book.query.get(book_id)\n if book is None:\n return None\n return book.as_dict()\n\n def find_book_by_title(self, book_title):\n book = Book.query.filter_by(title=book_title).first()\n if book is None:\n return None\n return book.as_dict()\n\n def find_books_by_publisher(self, publisher_id):\n books = Book.query.filter_by(publisher=publisher_id)\n books_dict = list(map(lambda book: book.as_dict(), books))\n return books_dict\n\n def delete_book_by_id(self, book_id):\n book = Book.query.get(book_id)\n if book is None:\n return None\n db.session.delete(book)\n db.session.commit()\n","sub_path":"src/wookie/books/dao/sql_dao.py","file_name":"sql_dao.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"48953793","text":"import os\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D\nfrom keras import optimizers\nfrom keras.preprocessing import image\nfrom keras.applications.resnet50 import preprocess_input, decode_predictions\nfrom keras.models import load_model\nfrom PIL import Image\n\nimg_width, img_height = 80,80\nnum_epoch = 5\nactivation_type = 'linear'\nsave_loc = \"../models/basic_cnn_\"+activation_type+\"_\"+str(num_epoch)+\"_epochs.h5\"\n\n\ndef create_model():\n\tmodel = Sequential()\n\tmodel.add(Conv2D(32, (3, 3), input_shape=(img_width, img_height, 3)))\n\tmodel.add(Activation('relu'))\n\tmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n\tmodel.add(Conv2D(32, (3, 3)))\n\tmodel.add(Activation('relu'))\n\tmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n\t\n\tmodel.add(Activation('relu'))\n\tmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\n\tmodel.add(Flatten())\n\tmodel.add(Dense(64))\n\tmodel.add(Activation('relu'))\n\tmodel.add(Dropout(0.5))\n\tmodel.add(Dense(1))\n\tmodel.add(Activation(activation_type))\n\n\treturn model\n\ndef train(model, train_generator, validation_generator):\n\tmodel.compile(loss='binary_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\n\tmodel.fit_generator(\n\t train_generator,\n\t steps_per_epoch=70,\n\t epochs=num_epoch,\n\t validation_data=validation_generator,\n \tvalidation_steps=70)\n\ndef load_pretrained_model(path):\n\tmodel = create_model()\n\t\n\tmodel.compile(loss='binary_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\n\tmodel.load_weights(path)\n\treturn model\n\ndef start():\n\ttraining_data = \"../train_2\"\n\tvalidation_data = \"../train_2\"\n\n\tdatagen = ImageDataGenerator(\n rescale=1./255) # normalize pixel values to [0,1]\n # shear_range=0.2, # randomly applies shearing transformation\n # zoom_range=0.2, # randomly applies shearing transformation\n # horizontal_flip=True) # randomly flip the images\n\n\ttrain_generator = datagen.flow_from_directory(\n\t training_data,\n\t target_size=(img_width, img_height),\n\t batch_size=16,\n\t class_mode='binary')\n\n\tvalidation_generator = datagen.flow_from_directory(\n\t validation_data,\n\t target_size=(img_width, img_height),\n\t batch_size=32,\n\t class_mode='binary')\n\n\n\tmodel = create_model()\n\ttrain(model, train_generator, validation_generator)\n\n\tmodel.save_weights(save_loc)\n\tprint(model.evaluate_generator(validation_generator, 70))\n\n\ndef test_model():\n\tmodel = load_pretrained_model(save_loc)\n\n\tclass1 = 0 \n\tclass2 = 0\n\tcounter = 0\n\n\tfiles = os.listdir(\"../train_2/uninfected/\")\n\tfor data in files:\n\t\tif(\".jpg\" in data):\n\t\t\timg = image.load_img(\"../train_2/uninfected/\"+data, target_size= (img_width,img_height))\n\t\t\tx = image.img_to_array(img)\n\t\t\tx = np.expand_dims(x, axis = 0)\n\t\t\tx = preprocess_input(x)\n\n\n\n\t\t\tprediction = model.predict(x, verbose=0)\n\t\t\tprint(str(counter) + \":\" + str(prediction))\n\t\t\tif(prediction[0][0] < 0.5):\n\t\t\t\tclass1+= 1\n\t\t\telse:\n\t\t\t\tclass2+=1\n\t\t\tcounter+=1\n\n\tprint(\"Class 1: \"+str(class1) + \"/\" + str(counter))\n\tprint(\"Class 2: \"+str(class2) + \"/\" + str(counter))\n\ndef predict_me(model, img):\n\tx = image.img_to_array(img)\n\tx = np.expand_dims(x, axis = 0)\n\tx = preprocess_input(x)\n\n\tprediction = model.predict_classes(x, verbose=0)\n\n\treturn prediction\n\n\n\n# start()\n# test_model()\n\n\n\n","sub_path":"classifiers/cell_classifier.py","file_name":"cell_classifier.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"284611496","text":"'''\nUses HPI [[https://github.com/karlicoss/HPI/blob/master/doc/MODULES.org#myhypothesis][hypothesis]] module\n'''\nfrom ..common import Visit, Results, logger, Loc\n\n\ndef index() -> Results:\n from . import hpi\n import my.hypothesis as hyp\n for h in hyp.get_highlights():\n if isinstance(h, Exception):\n yield h\n continue\n hl = h.highlight\n ann = h.annotation\n tags = h.tags\n cparts = []\n if hl is not None:\n cparts.append(hl)\n if ann is not None:\n cparts.extend(['comment: ' + ann])\n if tags:\n cparts.append(\" \".join(f\"#{t}\" for t in tags))\n yield Visit(\n url=h.url,\n dt=h.created,\n context='\\n\\n'.join(cparts),\n locator=Loc.make(\n title='hypothesis',\n href=h.hyp_link,\n )\n )\n","sub_path":"src/promnesia/sources/hypothesis.py","file_name":"hypothesis.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"605163667","text":"from aimacode.logic import PropKB\nfrom aimacode.planning import Action\nfrom aimacode.search import (\n Node, Problem,\n)\nfrom aimacode.utils import expr\nfrom lp_utils import (\n FluentState, encode_state, decode_state,\n)\nfrom my_planning_graph import PlanningGraph\n\nfrom functools import lru_cache\n\nfrom itertools import product\n\n# to prevent typos, some handy functions for generating expressions:\ndef expr_at(plane_or_cargo, airport) -> expr:\n return expr(\"At({}, {})\".format(plane_or_cargo, airport))\n\n\ndef expr_in(cargo, plane) -> expr:\n return expr(\"In({}, {})\".format(cargo, plane))\n\n\ndef expr_load(cargo, plane, airport) -> expr:\n return expr('Load({}, {}, {})'.format(cargo, plane, airport))\n\n\ndef expr_unload(cargo, plane, airport) -> expr:\n return expr('Unload({}, {}, {})'.format(cargo, plane, airport))\n\n\ndef expr_fly(plane, fr, to) -> expr:\n return expr(\"Fly({}, {}, {})\".format(plane, fr, to))\n\n\nclass AirCargoProblem(Problem):\n def __init__(self, cargos, planes, airports, initial: FluentState, goal: list):\n \"\"\"\n\n :param cargos: list of str\n cargos in the problem\n :param planes: list of str\n planes in the problem\n :param airports: list of str\n airports in the problem\n :param initial: FluentState object\n positive and negative literal fluents (as expr) describing initial state\n :param goal: list of expr\n literal fluents required for goal test\n \"\"\"\n self.state_map = initial.pos + initial.neg\n self.initial_state_TF = encode_state(initial, self.state_map)\n Problem.__init__(self, self.initial_state_TF, goal=goal)\n self.cargos = cargos\n self.planes = planes\n self.airports = airports\n self.actions_list = self.get_actions()\n\n def get_actions(self):\n \"\"\"\n This method creates concrete actions (no variables) for all actions in the problem\n domain action schema and turns them into complete Action objects as defined in the\n aimacode.planning module. It is computationally expensive to call this method directly;\n however, it is called in the constructor and the results cached in the `actions_list` property.\n\n Returns:\n ----------\n list\n list of Action objects\n \"\"\"\n\n def load_actions():\n \"\"\"Create all concrete Load actions and return a list\n\n :return: list of Action objects\n \"\"\"\n loads = []\n for (airport, plane, cargo) in product(self.airports, self.planes, self.cargos):\n precond_pos = [expr_at(plane, airport),\n expr_at(cargo, airport)]\n effect_add = [expr_in(cargo, plane)]\n effect_rem = [expr_at(cargo, airport)]\n loads.append(Action(expr_load(cargo, plane, airport),\n [precond_pos, []],\n [effect_add, effect_rem]))\n return loads\n\n def unload_actions():\n \"\"\"Create all concrete Unload actions and return a list\n\n :return: list of Action objects\n \"\"\"\n unloads = []\n for (airport, plane, cargo) in product(self.airports, self.planes, self.cargos):\n precond_pos = [expr_at(plane, airport),\n expr_in(cargo, plane)]\n effect_add = [expr_at(cargo, airport)]\n effect_rem = [expr_in(cargo, plane)]\n unloads.append(Action(expr_unload(cargo, plane, airport),\n [precond_pos, []],\n [effect_add, effect_rem]))\n return unloads\n\n def fly_actions():\n \"\"\"Create all concrete Fly actions and return a list\n\n :return: list of Action objects\n \"\"\"\n flys = []\n for fr in self.airports:\n for to in self.airports:\n if fr != to:\n for p in self.planes:\n precond_pos = [expr_at(p, fr)]\n precond_neg = []\n effect_add = [expr_at(p, to)]\n effect_rem = [expr_at(p, fr)]\n fly = Action(expr_fly(p, fr, to),\n [precond_pos, precond_neg],\n [effect_add, effect_rem])\n flys.append(fly)\n return flys\n\n return load_actions() + unload_actions() + fly_actions()\n\n def actions(self, state: str) -> list:\n \"\"\" Return the actions that can be executed in the given state.\n\n :param state: str\n state represented as T/F string of mapped fluents (state variables)\n e.g. 'FTTTFF'\n :return: list of Action objects\n \"\"\"\n possible_actions = []\n kb = PropKB()\n kb.tell(decode_state(state, self.state_map).pos_sentence())\n for action in self.actions_list:\n is_possible = True\n for clause in action.precond_pos:\n if clause not in kb.clauses:\n is_possible = False\n for clause in action.precond_neg:\n if clause in kb.clauses:\n is_possible = False\n if is_possible:\n possible_actions.append(action)\n\n return possible_actions\n\n def result(self, state: str, action: Action):\n \"\"\" Return the state that results from executing the given\n action in the given state. The action must be one of\n self.actions(state).\n\n :param state: state entering node\n :param action: Action applied\n :return: resulting state after action\n \"\"\"\n old_state = decode_state(state, self.state_map)\n already_added = set(action.effect_add + action.effect_rem)\n new_state = FluentState(\n action.effect_add + [f for f in old_state.pos if f not in already_added],\n action.effect_rem + [f for f in old_state.neg if f not in already_added])\n return encode_state(new_state, self.state_map)\n\n def goal_test(self, state: str) -> bool:\n \"\"\" Test the state to see if goal is reached\n\n :param state: str representing state\n :return: bool\n \"\"\"\n kb = PropKB()\n kb.tell(decode_state(state, self.state_map).pos_sentence())\n\n for clause in self.goal:\n if clause not in kb.clauses:\n return False\n return True\n\n def h_1(self, node: Node):\n # note that this is not a true heuristic\n h_const = 1\n return h_const\n\n @lru_cache(maxsize=8192)\n def h_pg_levelsum(self, node: Node):\n \"\"\"This heuristic uses a planning graph representation of the problem\n state space to estimate the sum of all actions that must be carried\n out from the current state in order to satisfy each individual goal\n condition.\n \"\"\"\n # requires implemented PlanningGraph class\n pg = PlanningGraph(self, node.state)\n pg_levelsum = pg.h_levelsum()\n return pg_levelsum\n\n @lru_cache(maxsize=8192)\n def h_ignore_preconditions(self, node: Node):\n \"\"\"This heuristic estimates the minimum number of actions that must be\n carried out from the current state in order to satisfy all of the goal\n conditions by ignoring the preconditions required for an action to be\n executed.\n \"\"\"\n # based on https://discussions.udacity.com/t/understanding-ignore-precondition-heuristic/225906/2\n kb = PropKB()\n kb.tell(decode_state(node.state, self.state_map).pos_sentence())\n\n count = sum([1 for clause in self.goal if clause not in kb.clauses])\n return count\n\n\ndef air_cargo_p1() -> AirCargoProblem:\n cargos = ['C1', 'C2']\n planes = ['P1', 'P2']\n airports = ['JFK', 'SFO']\n pos = [expr('At(C1, SFO)'),\n expr('At(C2, JFK)'),\n expr('At(P1, SFO)'),\n expr('At(P2, JFK)'),\n ]\n neg = [expr('At(C2, SFO)'),\n expr('In(C2, P1)'),\n expr('In(C2, P2)'),\n expr('At(C1, JFK)'),\n expr('In(C1, P1)'),\n expr('In(C1, P2)'),\n expr('At(P1, JFK)'),\n expr('At(P2, SFO)'),\n ]\n init = FluentState(pos, neg)\n goal = [expr('At(C1, JFK)'),\n expr('At(C2, SFO)'),\n ]\n return AirCargoProblem(cargos, planes, airports, init, goal)\n\n\ndef air_cargo_p2() -> AirCargoProblem:\n cargos = ['C1', 'C2', 'C3']\n planes = ['P1', 'P2', 'P3']\n airports = ['JFK', 'SFO', 'ATL']\n\n # generate list of all fluents\n all = set(expr_in(c, p) for (c, p) in product(cargos, planes)) \\\n | set(expr_at(p, a) for (p, a) in product(planes, airports)) \\\n | set(expr_at(c, a) for (c, a) in product(cargos, airports))\n\n pos = [expr_at('C1', 'SFO'), expr_at('C2', 'JFK'), expr_at('C3', 'ATL'),\n expr_at('P1', 'SFO'), expr_at('P2', 'JFK'), expr_at('P3', 'ATL')]\n init = FluentState(pos, list(all - set(pos)))\n goal = [expr_at('C1', 'JFK'), expr_at('C2', 'SFO'), expr_at('C3', 'SFO')]\n return AirCargoProblem(cargos, planes, airports, init, goal)\n\n\ndef air_cargo_p3() -> AirCargoProblem:\n cargos = ['C1', 'C2', 'C3', 'C4']\n planes = ['P1', 'P2']\n airports = ['JFK', 'SFO', 'ATL', 'ORD']\n\n # generate list of all fluents\n all = set(expr_in(c, p) for (c, p) in product(cargos, planes)) \\\n | set(expr_at(p, a) for (p, a) in product(planes, airports)) \\\n | set(expr_at(c, a) for (c, a) in product(cargos, airports))\n\n pos = [expr_at('C1', 'SFO'), expr_at('C2', 'JFK'), expr_at('C3', 'ATL'), expr_at('C4', 'ORD'),\n expr_at('P1', 'SFO'), expr_at('P2', 'JFK')]\n init = FluentState(pos, list(all - set(pos)))\n goal = [expr_at('C1', 'JFK'), expr_at('C2', 'SFO'), expr_at('C3', 'JFK'), expr_at('C4', 'SFO')]\n return AirCargoProblem(cargos, planes, airports, init, goal)\n","sub_path":"my_air_cargo_problems.py","file_name":"my_air_cargo_problems.py","file_ext":"py","file_size_in_byte":10062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"337234263","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'gk'\n\n\n''' Lesson05 '''\n\n# Easy\n# 1\n# Напишите скрипт, создающий директории dir_1 - dir_9 в папке,\n# из которой запущен данный скрипт.\n\nimport os\nimport sys\n\ndef mk_dir(path):\n try:\n os.mkdir(path)\n print('Директория успешно создана')\n except FileExistsError:\n print('Директория уже существует')\n except PermissionError:\n print('Недостаточно прав для создания директории')\n\n\ndef rm_dir(path):\n try:\n os.removedirs(path)\n print('Директория успешно удалена')\n except FileNotFoundError:\n print('Директория для удаления не найдена.')\n except PermissionError:\n print('Недостаточно прав для удаления директории')\n\n\n# Задача-2:\n# Напишите скрипт, отображающий папки текущей директории.\n\ndef list_dir():\n print([i for i in os.listdir() if os.path.isdir(i)])\n\n\n# Задача-3:\n# Напишите скрипт, создающий копию файла, из которого запущен данный скрипт.\n\ndef create_file_copy():\n filename = sys.argv[0]\n\n with open(filename, 'rb') as f:\n name, extension = filename.split('.')\n with open(name + '_copy.' + extension, 'wb') as destination_f:\n destination_f.write(f.read())\n\n\nif __name__ == \"__main__\":\n dir_path = 'dir_{}'\n [mk_dir(dir_path.format(i)) for i in range(1, 10)]\n [rm_dir(dir_path.format(i)) for i in range(1, 10)]\n\n list_dir()\n create_file_copy()\n\n\n# 2 \n# скрипт, отображающий папки текущей директории.\n# import os\n# from os.path import isfile \n# print('Папки текущей директории:', [dir for dir in os.listdir(os.getcwd()) if os.path.isdir(dir)])\n \n# 3\n# скрипт, создающий копию файла, из которого запущен данный скрипт.\n# import shutil\n# shutil.copy(__file__, __file__ + '.dupl')\n\n# import в normal\n# def create_dir(dir_name):\n# dir_path = os.path.join(os.getcwd(), dir_name)\n# try:\n# os.mkdir(dir_path)\n# print('Успешно создано')\n# except FileExistsError:\n# print('Невозможно создать', dir_name)\n \n# def delete_dir(dir_name):\n# dir_path = os.path.join(os.getcwd(), dir_name)\n# try:\n# os.removedirs(dir_path)\n# print('Успешно удалено')\n# except FileNotFoundError:\n# print('Невозможно удалить', dir_name)","sub_path":"4/hw_lesson05_Easy.py","file_name":"hw_lesson05_Easy.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"72846854","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.\n\nimport collections\nimport random\nfrom functools import partial\nfrom typing import Deque, Dict, List, NamedTuple, Optional, Union\n\n\nFEATURES = Dict[int, float]\nACTION = Union[str, FEATURES]\n\n\nclass Samples(NamedTuple):\n mdp_ids: List[str]\n sequence_numbers: List[int]\n sequence_number_ordinals: List[int]\n states: List[FEATURES]\n actions: List[ACTION]\n action_probabilities: List[float]\n rewards: List[float]\n possible_actions: List[List[ACTION]]\n next_states: List[FEATURES]\n next_actions: List[ACTION]\n terminals: List[bool]\n possible_next_actions: List[List[ACTION]]\n\n\nclass MultiStepSamples(NamedTuple):\n mdp_ids: List[str]\n sequence_numbers: List[int]\n sequence_number_ordinals: List[int]\n states: List[FEATURES]\n actions: List[ACTION]\n action_probabilities: List[float]\n rewards: List[List[float]]\n possible_actions: List[List[ACTION]]\n next_states: List[List[FEATURES]]\n next_actions: List[List[ACTION]]\n terminals: List[List[bool]]\n possible_next_actions: List[List[List[ACTION]]]\n\n def to_single_step(self) -> Samples:\n return Samples(\n mdp_ids=self.mdp_ids,\n sequence_numbers=self.sequence_numbers,\n sequence_number_ordinals=self.sequence_number_ordinals,\n states=self.states,\n actions=self.actions,\n action_probabilities=self.action_probabilities,\n rewards=[r[0] for r in self.rewards],\n possible_actions=self.possible_actions,\n next_states=[ns[0] for ns in self.next_states],\n next_actions=[na[0] for na in self.next_actions],\n terminals=[t[0] for t in self.terminals],\n possible_next_actions=[pna[0] for pna in self.possible_next_actions],\n )\n\n\ndef shuffle_samples(samples):\n merged = list(zip(*[getattr(samples, f) for f in samples._fields]))\n random.shuffle(merged)\n return type(samples)(**dict(zip(samples._fields, zip(*merged))))\n\n\nclass Environment:\n def reset(self):\n \"\"\" Reset the environment and return the initial state \"\"\"\n pass\n\n def step(self, action):\n \"\"\"\n Proceed one step ahead using the action.\n Return next state, reward, terminal, and info\n \"\"\"\n return None, None, None, None\n\n def _process_state(self, state):\n \"\"\"\n Transform the state to the format that can be uploaded to Hive\n \"\"\"\n pass\n\n def sample_policy(self, state, use_continuous_action, epsilon):\n \"\"\"\n Sample an action following epsilon-greedy\n Return the raw action which can be fed into env.step(), the processed\n action which can be uploaded to Hive, and action probability\n \"\"\"\n return None, None, None\n\n def action_to_features(self, action) -> FEATURES:\n \"\"\"\n Transform an action into a feature vector (as a dictionary)\n Call this function when discrete actions need to be transformed into\n continuous formats\n \"\"\"\n raise NotImplementedError\n\n def possible_actions(\n self,\n state,\n terminal=False,\n ignore_terminal=False,\n use_continuous_action: bool = False,\n **kwargs,\n ) -> List[ACTION]:\n \"\"\"\n Get possible actions at the current state. If ignore_terminal is False,\n then this function always returns an empty list at a terminal state.\n \"\"\"\n pass\n\n @staticmethod\n def set_if_in_range(index, limit, container, value):\n if index >= limit:\n return\n container[index] = value\n\n def generate_random_samples(\n self,\n num_transitions: int,\n use_continuous_action: bool,\n epsilon: float = 1.0,\n multi_steps: Optional[int] = None,\n max_step: Optional[int] = None,\n include_shorter_samples_at_start: bool = False,\n include_shorter_samples_at_end: bool = True,\n ) -> Union[Samples, MultiStepSamples]:\n \"\"\" Generate samples:\n [\n s_t,\n (a_t, a_{t+1}, ..., a_{t+steps}),\n (r_t, r_{t+1}, ..., r_{t+steps}),\n (s_{t+1}, s_{t+2}, ..., s_{t+steps+1})\n ]\n\n :param num_transitions: How many transitions to collect\n :param use_continuous_action: True if a discrete action needs to be\n represented as a vector using a dictionary; otherwise the action is\n represented as string.\n :param epsilon: (1-epsilon) determines the chance of taking optimal actions.\n Only valid when the environment (e.g., gridworld) records optimal actions.\n :param multi_steps: An integer decides how many steps of transitions\n contained in each sample. Only used if you want to train multi-step RL.\n :param max_step: An episode terminates after max_step number of steps\n :param include_shorter_samples_at_start: Whether to return samples of shorter\n steps at the beginning of an episode.\n :param include_shorter_samples_at_end: Whether to return samples of shorter\n steps at the end of an episode.\n \"\"\"\n return_single_step_samples = False\n if multi_steps is None:\n return_single_step_samples = True\n multi_steps = 1\n\n states: List[FEATURES] = [{} for _ in range(num_transitions)]\n action_probabilities: List[float] = [0.0] * num_transitions\n rewards: List[List[float]] = [[] for _ in range(num_transitions)]\n next_states: List[List[FEATURES]] = [[{}] for _ in range(num_transitions)]\n terminals: List[List[bool]] = [[] for _ in range(num_transitions)]\n mdp_ids = [\"\"] * num_transitions\n sequence_numbers = [0] * num_transitions\n possible_actions: List[List[ACTION]] = [[] for _ in range(num_transitions)]\n possible_next_actions: List[List[List[ACTION]]] = [\n [[]] for _ in range(num_transitions)\n ]\n next_actions: List[List[ACTION]] = [[] for _ in range(num_transitions)]\n actions: List[ACTION] = []\n if use_continuous_action:\n actions = [{} for _ in range(num_transitions)]\n else:\n actions = [\"\"] * num_transitions\n\n state = None\n terminal = True\n raw_action = None\n processed_action = None\n next_raw_action = None\n next_processed_action = None\n next_action_probability = 1.0\n transition = 0\n mdp_id = -1\n sequence_number = 0\n\n state_deque: Deque[FEATURES] = collections.deque(maxlen=multi_steps)\n action_deque: Deque[ACTION] = collections.deque(maxlen=multi_steps)\n action_probability_deque: Deque[float] = collections.deque(maxlen=multi_steps)\n reward_deque: Deque[float] = collections.deque(maxlen=multi_steps)\n next_state_deque: Deque[FEATURES] = collections.deque(maxlen=multi_steps)\n next_action_deque: Deque[ACTION] = collections.deque(maxlen=multi_steps)\n terminal_deque: Deque[bool] = collections.deque(maxlen=multi_steps)\n sequence_number_deque: Deque[int] = collections.deque(maxlen=multi_steps)\n possible_action_deque: Deque[List[ACTION]] = collections.deque(\n maxlen=multi_steps\n )\n possible_next_action_deque: Deque[List[ACTION]] = collections.deque(\n maxlen=multi_steps\n )\n\n # We run until we finish the episode that completes N transitions, but\n # we may have to go beyond N to reach the end of that episode\n while not terminal or transition < num_transitions:\n if terminal:\n state = self.reset()\n terminal = False\n mdp_id += 1\n sequence_number = 0\n state_deque.clear()\n action_deque.clear()\n action_probability_deque.clear()\n reward_deque.clear()\n next_state_deque.clear()\n next_action_deque.clear()\n terminal_deque.clear()\n sequence_number_deque.clear()\n possible_action_deque.clear()\n possible_next_action_deque.clear()\n raw_action, processed_action, action_probability = self.sample_policy(\n state, use_continuous_action, epsilon\n )\n else:\n raw_action = next_raw_action\n processed_action = next_processed_action\n action_probability = next_action_probability\n sequence_number += 1\n\n possible_action = self.possible_actions(\n state,\n terminal=terminal,\n ignore_terminal=False,\n use_continuous_action=use_continuous_action,\n )\n next_state, reward, terminal, _ = self.step(raw_action)\n if max_step is not None and sequence_number >= max_step:\n terminal = True\n next_raw_action, next_processed_action, next_action_probability = self.sample_policy(\n next_state, use_continuous_action, epsilon\n )\n possible_next_action = self.possible_actions(\n next_state,\n terminal=terminal,\n ignore_terminal=False,\n use_continuous_action=use_continuous_action,\n )\n\n state_deque.append(self._process_state(state))\n action_deque.append(processed_action)\n action_probability_deque.append(action_probability)\n reward_deque.append(reward)\n terminal_deque.append(terminal)\n sequence_number_deque.append(sequence_number)\n possible_action_deque.append(possible_action)\n possible_next_action_deque.append(possible_next_action)\n\n next_processed_state: FEATURES = self._process_state(next_state)\n next_state_deque.append(next_processed_state)\n\n # Format terminals in same way we ask clients to log terminals (in RL dex)\n # i.e., setting next action empty if the episode terminates\n if terminal:\n # We need to keep next state even at the terminal state\n # first, fblearner/flow/projects/rl/core/data_fetcher.py decides\n # terminal signals by looking at next action, not next state\n # second, next state will be used for world model building\n if type(next_processed_action) is str:\n next_processed_action = \"\"\n else:\n next_processed_action = {}\n next_action_deque.append(next_processed_action)\n\n # We want exactly N data points, but we need to wait until the\n # episode is over so we can get the episode values. `set_if_in_range`\n # will set episode values if they are in the range [0,N) and ignore\n # otherwise.\n if not terminal and (\n include_shorter_samples_at_start or len(terminal_deque) == multi_steps\n ):\n set_if_in_range = partial(\n self.set_if_in_range, transition, num_transitions\n )\n set_if_in_range(states, state_deque[0])\n set_if_in_range(actions, action_deque[0])\n set_if_in_range(action_probabilities, action_probability_deque[0])\n set_if_in_range(rewards, list(reward_deque))\n set_if_in_range(next_states, list(next_state_deque))\n set_if_in_range(next_actions, list(next_action_deque))\n set_if_in_range(terminals, list(terminal_deque))\n set_if_in_range(mdp_ids, str(mdp_id))\n set_if_in_range(sequence_numbers, sequence_number_deque[0])\n set_if_in_range(possible_actions, possible_action_deque[0])\n set_if_in_range(possible_next_actions, list(possible_next_action_deque))\n transition += 1\n # collect samples at the end of the episode.\n if terminal:\n num_samples_at_end = 0\n if include_shorter_samples_at_end:\n num_samples_at_end = len(state_deque)\n elif len(terminal_deque) == multi_steps:\n num_samples_at_end = 1\n for _ in range(num_samples_at_end):\n set_if_in_range = partial(\n self.set_if_in_range, transition, num_transitions\n )\n set_if_in_range(states, state_deque.popleft())\n set_if_in_range(actions, action_deque.popleft())\n set_if_in_range(\n action_probabilities, action_probability_deque.popleft()\n )\n set_if_in_range(rewards, list(reward_deque))\n set_if_in_range(next_states, list(next_state_deque))\n set_if_in_range(next_actions, list(next_action_deque))\n set_if_in_range(terminals, list(terminal_deque))\n set_if_in_range(mdp_ids, str(mdp_id))\n set_if_in_range(sequence_numbers, sequence_number_deque.popleft())\n set_if_in_range(possible_actions, possible_action_deque.popleft())\n set_if_in_range(\n possible_next_actions, list(possible_next_action_deque)\n )\n reward_deque.popleft()\n next_state_deque.popleft()\n next_action_deque.popleft()\n terminal_deque.popleft()\n possible_next_action_deque.popleft()\n transition += 1\n\n state = next_state\n\n samples = MultiStepSamples(\n mdp_ids=mdp_ids,\n sequence_numbers=sequence_numbers,\n sequence_number_ordinals=sequence_numbers,\n states=states,\n actions=actions,\n action_probabilities=action_probabilities,\n rewards=rewards,\n possible_actions=possible_actions,\n next_states=next_states,\n next_actions=next_actions,\n terminals=terminals,\n possible_next_actions=possible_next_actions,\n )\n if return_single_step_samples:\n return samples.to_single_step()\n return samples\n","sub_path":"ml/rl/test/environment/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":14458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"331602953","text":"#!/usr/bin/python3\n\n# while loops\nx = 0\nwhile x < 10:\n print('{} hello'.format(x + 1))\n x += 1\nprint('All done!')\n\n\n# break, continue and pass (pass does nothing)\nx = 0\nwhile x < 10:\n print('x is currently: ',x)\n print('x is still less than 10, adding 1 to x')\n x += 1\n\n if x == 3:\n print('Hey, x equals 3!')\n break\n else:\n print('continuing...')\n # original course placed a continue here, \n # but it works the same without a continue statement...\n\n","sub_path":"python/zero-to-hero/31-38-statements/34_while_loops.py","file_name":"34_while_loops.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"275679954","text":"# -*- coding: utf-8 -*-\n\"\"\"Queries for summaries and summary samples.\"\"\"\n\nfrom __future__ import print_function\n\nfrom verta import data_types\nfrom verta._internal_utils import arg_handler, pagination_utils, time_utils\nfrom verta._internal_utils._utils import as_list_of_str\nfrom verta._protos.public.monitoring.Summary_pb2 import (\n AggregationQuerySummary,\n FilterQuerySummarySample,\n FindSummaryRequest,\n FindSummarySampleRequest,\n LabelFilterQuerySummarySample,\n)\n\nfrom .aggregation import Aggregation\n\n\ndef _labels_proto(labels):\n return {\n key: LabelFilterQuerySummarySample(label_value=as_list_of_str(values))\n for key, values in labels.items()\n }\n\n\nclass SummaryQuery(object):\n \"\"\"\n A query for summaries.\n\n Parameters\n ----------\n ids : list of int, optional\n Only fetch these summaries.\n names : list of str, optional\n Only fetch these summaries with one of these names.\n data_type_classes : list of :mod:`VertaDataType `, optional\n Only fetch summaries with one of these data types.\n monitored_entities : list of :class:`~verta.monitoring.monitored_entity.MonitoredEntity`, optional\n Only fetch summaries belonging to one of these monitored entities.\n page_number : int, default 1\n Pagination page number for the backend query request. Used in\n conjunction with `page_limit`.\n page_limit : int, optional\n Number of samples to fetch from the backend in a single query. If not\n provided, all accessible samples will be fetched.\n\n Examples\n --------\n .. code-block:: python\n\n from datetime import datetime, timezone\n from verta.monitoring.summary import SummaryQuery, SummarySampleQuery\n from verta.data_types import FloatHistogram, DiscreteHistogram\n\n summary_query = SummaryQuery(\n names=[\"Income Distributions\"]),\n data_types=[FloatHistogram, DiscreteHistogram],\n )\n\n client = Client()\n for summary in client.monitoring.summaries.find(sample_query):\n print(summary)\n \"\"\"\n\n def __init__(\n self,\n ids=None,\n names=None,\n data_type_classes=None,\n monitored_entities=None,\n page_number=1,\n page_limit=None,\n ):\n self._ids = arg_handler.extract_ids(ids) if ids else None\n self._names = names\n\n self._initialize_data_types(data_type_classes)\n self._monitored_entity_ids = (\n arg_handler.extract_ids(monitored_entities) if monitored_entities else None\n )\n self._page_number = page_number\n self._page_limit = page_limit\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n\n return self._to_proto_request() == other._to_proto_request()\n\n @property\n def monitored_entity_ids(self):\n return self._monitored_entity_ids\n\n @property\n def data_type_classes(self):\n return self._data_type_classes\n\n @property\n def type_names(self):\n return self._type_names\n\n def _initialize_data_types(self, classes_or_strings):\n self._type_names = None\n self._data_type_classes = None\n if classes_or_strings:\n try:\n self._type_names = [cls._type_string() for cls in classes_or_strings]\n self._data_type_classes = classes_or_strings\n except AttributeError:\n self._type_names = [type_string for type_string in classes_or_strings]\n self._data_type_classes = data_types._VertaDataType._from_type_strings(\n classes_or_strings\n )\n\n @classmethod\n def _from_proto_request(cls, msg):\n types = map(data_types._VertaDataType._from_type_string, msg.type_names)\n types = [dt for dt in types if dt is not None]\n return cls(\n ids=msg.ids,\n names=msg.names,\n data_type_classes=types,\n monitored_entities=msg.monitored_entity_ids,\n page_number=msg.page_number,\n page_limit=pagination_utils.page_limit_from_proto(msg.page_limit),\n )\n\n def _to_proto_request(self):\n return FindSummaryRequest(\n ids=self._ids,\n names=self._names,\n type_names=self._type_names,\n monitored_entity_ids=self._monitored_entity_ids,\n page_number=self._page_number,\n page_limit=pagination_utils.page_limit_to_proto(self._page_limit),\n )\n\n def __repr__(self):\n return \"SummaryQuery({}, {}, {}, {})\".format(\n self._ids, self._names, self._type_names, self._monitored_entity_ids\n )\n\n\nclass SummarySampleQuery(object):\n \"\"\"\n A query for summary samples.\n\n Parameters\n ----------\n summary_query : :class:`SummaryQuery`, optional\n Only fetch samples whose summaries match this query.\n ids : list of int, optional\n Only fetch these samples.\n labels : dict of str to list of str, optional\n Only fetch samples that have at least one of these labels. A mapping\n between label keys and lists of corresponding label values.\n time_window_start : datetime.datetime or int, optional\n Only fetch samples whose time windows start at or after this time.\n Either a timezone aware datetime object or unix epoch milliseconds.\n time_window_end : datetime.datetime or int, optional\n Only fetch samples whose time windows end at or before this time.\n Either a timezone aware datetime object or unix epoch milliseconds.\n created_after : datetime.datetime or int, optional\n Only fetch samples created at or after this time. Either a timezone\n aware datetime object or unix epoch milliseconds.\n aggregation : :class:`~verta.monitoring.summaries.aggregation.Aggregation`, optional\n Parameters for aggregation of summary samples.\n page_number : int, default 1\n Pagination page number for the backend query request. Used in\n conjunction with `page_limit`.\n page_limit : int, optional\n Number of samples to fetch from the backend in a single query. If not\n provided, all accessible samples will be fetched.\n\n Examples\n --------\n .. code-block:: python\n\n from datetime import datetime, timedelta, timezone\n from verta.monitoring.summaries.aggregation import Aggregation\n from verta.monitoring.summaries.queries import SummaryQuery, SummarySampleQuery\n\n samples = Client().monitoring.summary_samples\n\n sample_query = SummarySampleQuery(\n summary_query=SummaryQuery(names=[\"Income Distributions\"]),\n labels={\"datasource\": [\"census2010\", \"census2020\"]},\n created_after=datetime(year=2021, month=2, day=22, tzinfo=timezone.utc),\n aggregation=Aggregation(timedelta(days=7), \"sum\")\n )\n\n for sample in samples.find(sample_query):\n print(sample.content)\n\n \"\"\"\n\n def __init__(\n self,\n summary_query=None,\n ids=None,\n labels=None,\n time_window_start=None,\n time_window_end=None,\n aggregation=None,\n created_after=None,\n page_number=1,\n page_limit=None,\n ):\n if summary_query is None:\n summary_query = SummaryQuery()\n\n self._msg = FindSummarySampleRequest(\n filter=FilterQuerySummarySample(\n sample_ids=arg_handler.extract_ids(ids) if ids else None,\n labels=arg_handler.maybe(_labels_proto, labels),\n time_window_start_at_millis=time_utils.epoch_millis(time_window_start),\n time_window_end_at_millis=time_utils.epoch_millis(time_window_end),\n created_at_after_millis=time_utils.epoch_millis(created_after),\n ),\n page_number=page_number,\n page_limit=pagination_utils.page_limit_to_proto(page_limit),\n )\n\n self.summary_query = summary_query\n self.aggregation = aggregation\n\n def __eq__(self, other):\n if not isinstance(other, type(self)):\n return NotImplemented\n\n return self._to_proto_request() == other._to_proto_request()\n\n @property\n def summary_query(self):\n return SummaryQuery._from_proto_request(self._msg.filter.find_summaries)\n\n @summary_query.setter\n def summary_query(self, query):\n self._msg.filter.find_summaries.CopyFrom(query._to_proto_request())\n\n @property\n def aggregation(self):\n return Aggregation._from_proto(self._msg.aggregation)\n\n @aggregation.setter\n def aggregation(self, value):\n if value is None:\n self._msg.ClearField(\"aggregation\")\n elif isinstance(value, AggregationQuerySummary):\n self._msg.aggregation.CopyFrom(value)\n elif isinstance(value, Aggregation):\n self._msg.aggregation.CopyFrom(value._to_proto())\n else:\n raise ValueError(\n \"value must be Aggregation object or proto, not {}\".format(type(value))\n )\n\n @classmethod\n def _from_proto_request(cls, msg):\n obj = cls()\n obj._msg.CopyFrom(msg)\n\n return obj\n\n def _to_proto_request(self):\n return self._msg\n\n def __repr__(self):\n return \"SummarySampleQuery({})\".format(self._to_proto_request())\n","sub_path":"client/verta/verta/monitoring/summaries/queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":9393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"166406630","text":"from pymysql import connect\nimport re\n\n\nURL_FUNC_DICT = dict()\n\n# 这个装饰器的功能只是用来在字典中添加类似\"/index.html\": index的键值对\n# 其中index是方法的引用\n# 到时候直接根据key调用方法,不会调用到call_func\ndef route(url):\n\n def set_func(func):\n URL_FUNC_DICT[url] = func\n\n def call_func():\n pass\n return call_func()\n return set_func\n\n\n@route(\"/index.html\")\ndef index():\n with open(\"./templates/index.html\", \"r\") as f:\n content = f.read()\n\n # 使用MySQL展示数据\n # 1.创建连接数据库\n conn = connect(host=\"localhost\", port=3306, user=\"root\", password=\"damonmok\", database=\"stock_db\")\n\n # 2.获取游标\n cursor = conn.cursor()\n\n # 3.操作sql语句\n cursor.execute(\"\"\"select * from info;\"\"\")\n\n # 4.获取数据\n stock_info = cursor.fetchall() # 因为数据少,所以一次性获取。多的话要分页获取。\n\n # 5.关闭游标和连接\n cursor.close()\n conn.close()\n\n # 替换数据\n html = \"\"\n tr_template = \"\"\"\n %s \n %s \n %s \n %s \n %s \n %s \n %s \n %s \n \n \n \n \n \"\"\"\n\n for line_info in stock_info:\n html += tr_template % (line_info[0], line_info[1], line_info[2], line_info[3],\n line_info[4], line_info[5], line_info[6], line_info[7], line_info[0])\n\n content = re.sub(\"\\{%content%\\}\", html, content)\n\n return content\n\n\n@route(\"/center.html\")\ndef center():\n with open(\"./templates/center.html\", \"r\") as f:\n content = f.read()\n\n # 使用MySQL展示数据\n # 1.创建连接数据库\n conn = connect(host=\"localhost\", port=3306, user=\"root\", password=\"damonmok\", database=\"stock_db\")\n\n # 2.获取游标\n cursor = conn.cursor()\n\n # 3.操作sql语句\n cursor.execute(\"\"\"select i.code,i.short,i.chg,i.turnover,i.price,i.highs,f.note_info from info as i inner join \n focus as f on i.id=f.info_id;\"\"\")\n\n # 4.获取数据\n stock_info = cursor.fetchall() # 因为数据少,所以一次性获取。多的话要分页获取。\n\n # 5.关闭游标和连接\n cursor.close()\n conn.close()\n\n # 替换数据\n html = \"\"\n tr_template = \"\"\"\n \n %s \n %s \n %s \n %s \n %s \n %s \n %s \n \n 修改 \n \n \n \n \n \n \"\"\"\n\n for line_info in stock_info:\n html += tr_template % (line_info[0], line_info[1], line_info[2], line_info[3],\n line_info[4], line_info[5], line_info[6])\n\n content = re.sub(\"\\{%content%\\}\", html, content)\n\n return content\n\n\ndef application(environ, start_response):\n\n # 1.调用web服务器传过来的函数,给服务器返回header信息\n start_response('200 OK', [('Content-Type', 'text/html;charset=\"utf-8\"')])\n\n # 2.给服务器返回body信息\n file_name = environ['PATH_INFO']\n\n try:\n func = URL_FUNC_DICT[file_name]\n return func()\n except Exception as ret:\n return \"产生了异常:%s\" % str(ret)\n","sub_path":"dynamic/mini_frame8.py","file_name":"mini_frame8.py","file_ext":"py","file_size_in_byte":4033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"91487176","text":"from sys import argv, exit\r\nfrom PyQt5.QtWidgets import QApplication\r\n\r\nfrom main import ElmoCut\r\nfrom assets import app_icon\r\nfrom utils import goto\r\nfrom utils_gui import npcap_exists, duplicate_elmocut, repair_settings\r\nfrom qtools import msg_box, Buttons, MsgIcon\r\n\r\nfrom constants import *\r\n\r\nif __name__ == \"__main__\":\r\n app = QApplication(argv)\r\n icon = ElmoCut.processIcon(app_icon)\r\n\r\n # Check if Npcap is installed\r\n if not npcap_exists():\r\n if msg_box('elmoCut', 'Npcap is not installed\\n\\nClick OK to download',\r\n MsgIcon.CRITICAL, icon, Buttons.OK | Buttons.CANCEL) == Buttons.OK:\r\n goto(NPCAP_URL)\r\n \r\n # Check if another elmoCut process is running\r\n elif duplicate_elmocut():\r\n msg_box('elmoCut', 'elmoCut is already running!', MsgIcon.WARN, icon)\r\n \r\n # Run the GUI\r\n else:\r\n repair_settings()\r\n GUI = ElmoCut()\r\n GUI.show()\r\n GUI.resizeEvent()\r\n GUI.scanner.init()\r\n GUI.scanner.flush_arp()\r\n GUI.scanEasy()\r\n GUI.UpdateThread_Starter()\r\n exit(app.exec_())","sub_path":"src/elmocut.py","file_name":"elmocut.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"532098812","text":"# coding: utf-8\n\n\"\"\" Simple unit tests of SuperFreq \"\"\"\n\nfrom __future__ import division, print_function\n\n__author__ = \"adrn \"\n\n# Standard library\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n# Third-party\nimport numpy as np\n\n# Project\nfrom ..naff import SuperFreq\n\ndef test_cy_naff():\n \"\"\" This checks the Cython frequency determination function \"\"\"\n\n from .._naff import naff_frequency\n\n t = np.linspace(0., 300., 12000)\n naff = SuperFreq(t)\n\n true_ws = 2*np.pi*np.array([0.581, 0.73])\n true_as = np.array([5*(np.cos(np.radians(15.)) + 1j*np.sin(np.radians(15.))),\n 1.8*(np.cos(np.radians(85.)) + 1j*np.sin(np.radians(85.)))])\n f = np.sum(true_as[None] * np.exp(1j * true_ws[None] * t[:,None]), axis=1)\n\n ww = naff_frequency(true_ws[0], naff.tz, naff.chi,\n np.ascontiguousarray(f.real),\n np.ascontiguousarray(f.imag),\n naff.T)\n np.testing.assert_allclose(ww, true_ws[0], atol=1E-8)\n\nclass SimpleBase(object):\n\n \"\"\" Need to define:\n\n self.amp\n self.omega\n self.p\n\n in subclass setup().\n \"\"\"\n def setup(self):\n self.A = np.sqrt(self.amp.imag**2 + self.amp.real**2)\n self.phi = np.arctan2(self.amp.imag, self.amp.real)\n\n def make_f(self, t):\n a = self.amp\n w = self.omega\n return np.sum(a[None] * np.exp(1j * w[None] * t[:,None]), axis=1)\n\n def test_freq_recovery(self):\n # define a bunch of arrays of times to make sure SuperFreq isn't\n # sensitive to the times\n ts = [np.linspace(0., 150., 12000),\n np.linspace(0., 150., 24414),\n np.linspace(0., 150., 42104),\n np.linspace(150., 300., 12000),\n np.linspace(150., 300., 24414),\n np.linspace(150., 300., 42104),\n np.linspace(0., 150., 12000) + 50*(2*np.pi/self.omega[0])]\n\n for i,t in enumerate(ts):\n logger.debug(i, t.min(), t.max(), len(t))\n f = self.make_f(t)\n nfreq = len(self.omega)\n\n # create SuperFreq object for this time array\n sf = SuperFreq(t, p=self.p)\n\n # solve for the frequencies\n w,amp,phi = sf.frecoder(f[:sf.n], break_condition=1E-5)\n np.testing.assert_allclose(self.omega, w[:nfreq], atol=1E-8)\n np.testing.assert_allclose(self.A, amp[:nfreq], atol=1E-6)\n np.testing.assert_allclose(self.phi, phi[:nfreq], atol=1E-6)\n\n def test_rolling_window(self):\n ts = [np.linspace(0.+dd, 150.+dd, 42104) for dd in np.linspace(0,10,50)]\n dws = []\n for i,t in enumerate(ts):\n logger.debug(i, t.min(), t.max(), len(t))\n f = self.make_f(t)\n nfreq = len(self.omega)\n\n # create SuperFreq object for this time array\n sf = SuperFreq(t, p=self.p)\n\n # try recovering the strongest frequency\n w,amp,phi = sf.frecoder(f[:sf.n], break_condition=1E-5)\n dws.append(np.abs(self.omega - w[:nfreq]))\n\n dws = np.array(dws)\n assert np.all(np.abs(dws) < 1E-8)\n\nclass TestSimple1(SimpleBase):\n\n def setup(self):\n self.omega = 2*np.pi*np.array([0.581, 0.73])\n self.amp = np.array([5*(np.cos(np.radians(15.)) + 1j*np.sin(np.radians(15.))),\n 1.8*(np.cos(np.radians(85.)) + 1j*np.sin(np.radians(85.)))])\n self.p = 2\n super(TestSimple1, self).setup()\n\nclass TestSimple2(SimpleBase):\n\n def setup(self):\n self.omega = 2*np.pi*np.array([0.581, -0.73, 0.91])\n self.amp = np.array([5*(np.cos(np.radians(35.)) + 1j*np.sin(np.radians(35.))),\n 1.8*(np.cos(np.radians(75.)) + 1j*np.sin(np.radians(75.))),\n 0.7*(np.cos(np.radians(45.)) + 1j*np.sin(np.radians(45.)))])\n self.p = 2\n super(TestSimple2, self).setup()\n","sub_path":"superfreq/tests/test_simple.py","file_name":"test_simple.py","file_ext":"py","file_size_in_byte":4005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"512444597","text":"num = int(input())\nfor i in range(num):\n n = int(input())\n count = 0\n arr = sorted(list(map(int, input().split(\" \"))))\n for j in range(n // 2 + 1):\n sum = arr[-1 - j]\n for k in range(n - 1 - j):\n if sum - arr[k] in arr[k+1:]:\n count += 1\n if count == 0:\n print(-1)\n else:\n print(count)\n\n","sub_path":"Code/CodeRecords/2359/60769/242060.py","file_name":"242060.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"241524251","text":"\"\"\"loja_automoveis URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom carros import views\n\nurlpatterns = [\n path('admin/', admin.site.urls, name=\"admin\"),\n #path('cores/', views.listar_cores, name=\"cores\"),\n path('', views.index, name=\"index\"),\n path('home/', views.index, name=\"home\"),\n path('sobre/', views.sobre_carros, name=\"sobre\"),\n path('montadora/', views.montadoras, name=\"montadora\"),\n path('montadora/cadastrar', views.montadora_cadastrar, name=\"cadastrar_montadora\"),\n path('montadora/', views.montadoras, name=\"montadoralista\"),\n path('montadora/editar/', views.montadora_editar, name=\"editar_montadora\"),\n path('cores/', views.mostrar_cores, name=\"cores\"),\n path('cores/', views.mostrar_cores, name=\"cores_opcao\"),\n path('cores/cadastrar/', views.cores_cadastrar, name=\"cores_cadastrar\"),\n path('cores/editar/', views.cores_editar, name=\"cores_editar\"),\n]\n","sub_path":"loja_automoveis/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"642393782","text":"def bubble_sort(seq):\n j=0\n while j seq[i+1]:\n seq[i], seq[i+1] = seq[i+1], seq[i]\n j+=1\n print (seq)\nimport random,time\nalist=[random.randint(0,100) for i in range(10)]\nstart=time.time()\nbubble_sort(alist)\nend=time.time()\nprint(end-start,\"Seconds\")\nprint(alist)","sub_path":"bubble sort.py","file_name":"bubble sort.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"548715434","text":"#!/usr/bin/env python\nimport numpy as np\n\ndef addSaltAndPepper(img, prob, s_vs_p_ratio=0.5):\n '''\n function\n\n :param img: numpy array reprresenting image, of shape (H,W,C)\n :param prob: float in range [0,1] representing probability of pixel to\n be affected by this\n :param s_vs_p_ratio: salt vs pepper ratio, 0 => everything is salt\n 1 => everything is pepper\n :returns: Nothing, img is object, modifications is saved within it\n '''\n\n pixels = img.shape[0] * img.shape[1]\n salt_cnt = np.ceil(pixels * prob * s_vs_p_ratio)\n\n # Construct 2 list with randomly selected coordinations for height, width\n coords = [ np.random.randint(0, i - 1, int(salt_cnt)) for i in img.shape[:-1]]\n img[tuple(coords)] = np.array([255,255,255])\n\n pepper_cnt = np.ceil(pixels * prob * (1 - s_vs_p_ratio))\n coords = [ np.random.randint(0, i - 1, int(pepper_cnt)) for i in img.shape[:-1]]\n img[tuple(coords)] = np.array([0,0,0])\n","sub_path":"helpers/effects/salt_and_pepper.py","file_name":"salt_and_pepper.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"530846588","text":"\"\"\"\ncreated on: 14-03-2018\n\"\"\"\nfrom migration import fastexport, file_togds\nfrom datetime import datetime, date\n\nif __name__ == '__main__':\n \"\"\" main script template para subir una tabla determinada\n \"\"\"\n for fold in range(10):\n print(str(fold) + ' start')\n dns_name = 'TDP1'\n database_name = 'DL_CI_ACCESO'\n table_name = 'GEOGRAPHY_VT_address'\n condition= 'WHERE right(cast(address_id as VARCHAR(15)),1) = ' + str(fold)\n file_dir ='files/'\n file_name = '_'.join([table_name,\n str(fold),\n datetime.now().strftime(\"%Y-%m-%d\"),\n ])+ '.gz'\n\n sub_folder_date = date(2018,3,15) # date en la cual se guarda el archivo\n # export desde teradata\n\n fastexport(dns_name = dns_name,\n database_name = database_name,\n table_name = table_name,\n file_dir = file_dir,\n file_name = file_name,\n condition = condition )\n # función de carga a google storage\n file_togds(database_name = database_name,\n table_name = table_name,\n sub_folder_date = sub_folder_date,\n file_dir = file_dir,\n file_name = file_name)\n print (str(fold) + ' end')\n","sub_path":"python/download_table_GEOGRAPHY_VT_ADDRESS.py","file_name":"download_table_GEOGRAPHY_VT_ADDRESS.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"21174426","text":"# Day_03_02_mnist_cell.py\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n\ndef mnist_basic():\n mnist = input_data.read_data_sets('mnist', one_hot=True)\n\n print(mnist.train.images.shape) # (55000, 784)\n print(mnist.train.labels.shape) # (55000, 10)\n\n print(mnist.validation.images.shape) # (5000, 784)\n print(mnist.test.images.shape) # (10000, 784)\n\n w = tf.Variable(tf.random_uniform([784, 10]))\n b = tf.Variable(tf.random_uniform([10]))\n\n ph_x = tf.placeholder(tf.float32)\n ph_y = tf.placeholder(tf.float32)\n\n # (55000, 10) = (55000, 784) @ (784, 10)\n z = tf.matmul(ph_x, w) + b\n hx = tf.nn.softmax(z)\n loss_i = tf.nn.softmax_cross_entropy_with_logits_v2(logits=z, labels=ph_y)\n loss = tf.reduce_mean(loss_i)\n\n optimizer = tf.train.GradientDescentOptimizer(0.1)\n train = optimizer.minimize(loss)\n\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n\n for i in range(1000):\n xx, yy = mnist.train.next_batch(100)\n sess.run(train, {ph_x: xx, ph_y: yy})\n\n if i % 100 == 0:\n print(i, sess.run(loss, {ph_x: xx, ph_y: yy}))\n print('-' * 50)\n\n pred = sess.run(z, {ph_x: mnist.test.images})\n pred_arg = np.argmax(pred, axis=1)\n y_arg = np.argmax(mnist.test.labels, axis=1)\n\n equals = (pred_arg == y_arg)\n print('acc :', np.mean(equals))\n sess.close()\n\n\ndef mnist_rnn_cell():\n mnist = input_data.read_data_sets('mnist', one_hot=True)\n\n elem_size = 28\n time_step = 28 # sequence_length\n n_classes = 10\n batch_size = 100 # 128\n hidden_size = 150\n\n ph_x = tf.placeholder(tf.float32, [None, time_step, elem_size])\n ph_y = tf.placeholder(tf.float32, [None, n_classes])\n\n cell = tf.nn.rnn_cell.BasicRNNCell(num_units=hidden_size)\n outputs, _states = tf.nn.dynamic_rnn(cell, ph_x, dtype=tf.float32)\n print(outputs.shape) # (100, 28, 150) = (batch_size, time_step, hidden_size)\n\n # outputs = tf.transpose(outputs, [1, 0, 2]) # (28, 100, 150)\n # final = outputs[-1]\n\n final = outputs[:, -1, :] # (100, 150)\n print(final.shape)\n\n z = tf.layers.dense(final, n_classes)\n\n loss_i = tf.nn.softmax_cross_entropy_with_logits_v2(logits=z, labels=ph_y)\n loss = tf.reduce_mean(loss_i)\n\n optimizer = tf.train.RMSPropOptimizer(0.001)\n train = optimizer.minimize(loss)\n\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n\n for i in range(1000):\n xx, yy = mnist.train.next_batch(batch_size)\n xx = xx.reshape(batch_size, time_step, elem_size) # (100, 28, 28)\n\n sess.run(train, {ph_x: xx, ph_y: yy})\n\n if i % 100 == 0:\n print(i, sess.run(loss, {ph_x: xx, ph_y: yy}))\n print('-' * 50)\n\n pred = sess.run(z, {ph_x: mnist.test.images.reshape(-1, time_step, elem_size)})\n pred_arg = np.argmax(pred, axis=1)\n y_arg = np.argmax(mnist.test.labels, axis=1)\n\n equals = (pred_arg == y_arg)\n print('acc :', np.mean(equals))\n sess.close()\n\n\n\n\n\n# mnist_basic()\nmnist_rnn_cell()\n\n\n\n\n\n\n\n\n\nprint('\\n\\n\\n\\n\\n\\n\\n')","sub_path":"Day_03_02_mnist_cell.py","file_name":"Day_03_02_mnist_cell.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"449122238","text":"import time\nimport os\nimport numpy as np\nimport sys\nimport click\nfrom src.tools import *\n\n\n@click.group()\ndef commands_plotting():\n pass\n\n@commands_plotting.command()\n@click.argument(\"input\", type=click.STRING)\n@click.option(\"-cmap\", default=\"Plotly\", help=\"set colormap from plotly qualitative colors\", type=click.STRING)\n@click.option(\"-long\", is_flag=True, help=\"Full page version\")\ndef specplot(input,cmap,long):\n \"\"\"\n Plots the file output by the Crosspec function.\n \"\"\"\n import matplotlib.pyplot as plt\n import seaborn as sns\n import plotly.colors as pcol\n from cycler import cycler\n\n sns.set_context(\"notebook\", font_scale=2, rc={\"lines.linewidth\": 2})\n sns.set_style(\"whitegrid\")\n\n # Swap colors around\n colors=getattr(pcol.qualitative,cmap) \n if cmap==\"Plotly\":\n colors.insert(3,colors.pop(-1))\n plt.rcParams[\"mathtext.fontset\"] = \"stix\"\n custom_style = {\n 'grid.color': '0.8',\n 'grid.linestyle': '--',\n 'grid.linewidth': 0.5,\n 'savefig.dpi':300,\n 'font.size': 20, \n 'axes.linewidth': 1.5,\n 'axes.prop_cycle': cycler(color=colors),\n 'mathtext.fontset': 'stix',\n 'font.family': 'serif',\n 'font.serif': 'Times',\n }\n sns.set_style(custom_style)\n lmax = 200\n ell, ee, bb, eb = np.loadtxt(input, usecols=(0,2,3,6), skiprows=3, max_rows=lmax, unpack=True)\n \n ee = ee*(ell*(ell+1)/(2*np.pi))\n bb = bb*(ell*(ell+1)/(2*np.pi))\n eb = eb*(ell*(ell+1)/(2*np.pi))\n \n if long:\n f, (ax1, ax2) = plt.subplots(2, 1, figsize=(24,6), gridspec_kw={'height_ratios': [3, 1]}, sharex=True)\n else:\n f, (ax1, ax2) = plt.subplots(2, 1, figsize=(12,8), gridspec_kw={'height_ratios': [3, 1]}, sharex=True)\n\n l1 = ax1.loglog(ell, ee, linewidth=2, label=\"EE\", color='C0')\n l2 = ax1.loglog(ell, bb, linewidth=2, label=\"BB\", color='C1')\n ax1.set_ylabel(r\"$D_l$ [$\\mu K^2$]\",)\n\n l3 = ax2.semilogx(ell, bb/ee, linewidth=2, label=\"BB/EE\", color='C2')\n ax2.set_ylabel(r\"BB/EE\",)\n ax2.set_xlabel(r'Multipole moment, $l$',)\n #plt.semilogx(ell, eb, label=\"EB\")\n\t\n sns.despine(top=True, right=True, left=True, bottom=False, ax=ax1)\n sns.despine(top=True, right=True, left=True, bottom=True, ax=ax2)\n #plt.xlim(0,200)\n ax1.set_ylim(0.11,150)\n ax2.set_ylim(-0.,2.)\n #ax.axes.xaxis.grid()\n ls = l1+l2+l3\n labs = [l.get_label() for l in ls]\n ax1.legend(ls, labs, frameon=False,)\n #ax1.legend(frameon=False)\n if long:\n outname = input.replace(\".dat\",\"_long.pdf\")\n else:\n outname = input.replace(\".dat\",\".pdf\")\n\n plt.tight_layout(h_pad=0.3)\n plt.subplots_adjust(wspace=0, hspace=0.01)\n plt.savefig(outname, dpi=300, bbox_inches=\"tight\", pad_inches=0.02,)\n plt.show()\n\n@commands_plotting.command()\n@click.argument(\"input\", nargs=-1,)\n@click.option(\"-dataset\", type=click.STRING, help=\"for .h5 plotting (ex. 000007/cmb/amp_alm)\")\n@click.option(\"-nside\", type=click.INT, help=\"nside for optional ud_grade.\",)\n@click.option(\"-auto\", is_flag=True, help=\"Automatically sets all plotting parameters.\",)\n@click.option(\"-min\", default=False, help=\"Min value of colorbar, overrides autodetector.\",)\n@click.option(\"-max\", default=False, help=\"Max value of colorbar, overrides autodetector.\",)\n@click.option(\"-mid\", multiple=True, help='Adds tick values \"-mid 2 -mid 4\"',)\n@click.option(\"-range\", default=\"auto\", type=click.STRING, help='Color range. \"-range auto\" sets to 97.5 percentile of data., or \"minmax\" which sets to data min and max values.',) # str until changed to float\n@click.option(\"-colorbar\", \"-bar\", is_flag=True, help='Adds colorbar (\"cb\" in filename)',)\n@click.option(\"-graticule\", is_flag=True, help='Adds graticule',)\n@click.option(\"-lmax\", default=None, type=click.FLOAT, help=\"This is automatically set from the h5 file. Only available for alm inputs.\",)\n@click.option(\"-fwhm\", default=0.0, type=click.FLOAT, help=\"FWHM of smoothing, in arcmin.\",)\n@click.option(\"-mask\", default=None, type=click.STRING, help=\"Masks input with specified maskfile.\",)\n@click.option(\"-mfill\", default=None, type=click.STRING, help='Color to fill masked area. for example \"gray\". Transparent by default.',)\n@click.option(\"-sig\", default=[0,], type=click.INT, multiple=True, help=\"Signal to be plotted 0 by default (0, 1, 2 is interprated as IQU)\",)\n@click.option(\"-remove_dipole\", default=None, type=click.STRING, help=\"Fits a dipole to the map and removes it.\",)\n@click.option(\"-remove_monopole\", default=None, type=click.STRING, help=\"Fits a monopole to the map and removes it.\",)\n@click.option(\"-log/-no-log\", \"logscale\", default=None, help=\"Plots using planck semi-logscale (Linear between -1,1). Autodetector sometimes uses this.\",)\n@click.option(\"-size\", default=\"m\", type=click.STRING, help=\"Size: 1/3, 1/2 and full page width (8.8/12/18cm) [ex. x, s, m or l, or ex. slm for all], m by default\",)\n@click.option(\"-white_background\", is_flag=True, help=\"Sets the background to be white. (Transparent by default [recommended])\",)\n@click.option(\"-darkmode\", is_flag=True, help='Plots all outlines in white for dark bakgrounds (\"dark\" in filename)',)\n@click.option(\"-png\", is_flag=True, help=\"Saves output as .png ().pdf by default)\",)\n@click.option(\"-cmap\", default=None, help=\"Chose colormap (ex. sunburst, planck, etc). Available are matplotlib and cmasher. Also qualitative plotly [ex. q-Plotly-4 (q for qualitative 4 for max color)]\",)\n@click.option(\"-title\", default=None, type=click.STRING, help=\"Set title (Upper right), has LaTeX functionality. Ex. $A_{s}$.\",)\n@click.option(\"-ltitle\", default=None, type=click.STRING, help=\"Set title (Upper left), has LaTeX functionality. Ex. $A_{s}$.\",)\n@click.option(\"-unit\", default=None, type=click.STRING, help=\"Set unit (Under color bar), has LaTeX functionality. Ex. $\\mu$\",)\n@click.option(\"-scale\", default=None, type=click.FLOAT, help=\"Scale input map [ex. 1e-6 for muK to K]\",)\n@click.option(\"-outdir\", type=click.Path(exists=True), help=\"Output directory for plot\",)\n@click.option(\"-labelsize\", default=10, type=click.INT, help=\"Title size.\",)\n@click.option(\"-gif\", is_flag=True, help=\"Make gifs from input\",)\n@click.option(\"-oldfont\", is_flag=True, help=\"Use the old DejaVu font and not Times\",)\n@click.option(\"-fontsize\", default=11, type=click.INT, help=\"Fontsize\",)\n@click.option(\"-verbose\", is_flag=True, help=\"Verbose mode\")\ndef plot(input, dataset, nside, auto, min, max, mid, range, colorbar, graticule, lmax, fwhm, mask, mfill, sig, remove_dipole, remove_monopole, logscale, size, white_background, darkmode, png, cmap, title, ltitle, unit, scale, outdir, labelsize,gif, oldfont, fontsize, verbose,):\n \"\"\"\n Plots map from .fits or h5 file.\n ex. c3pp plot coolmap.fits -bar -auto -lmax 60 -darkmode -pdf -title $\\beta_s$\n ex. c3pp plot coolhdf.h5 -dataset 000007/cmb/amp_alm -nside 512 -remove_dipole maskfile.fits -cmap cmasher.arctic \n\n Uses 97.5 percentile values for min and max by default!\\n\n RECOMMENDED: Use -auto to autodetect map type and set parameters.\\n\n Some autodetected maps use logscale, you will be warned.\n \"\"\"\n from src.plotter import Plotter\n data=None\n Plotter(input, dataset, nside, auto, min, max, mid, range, colorbar, graticule, lmax, fwhm, mask, mfill, sig, remove_dipole, remove_monopole, logscale, size, white_background, darkmode, png, cmap, title, ltitle, unit, scale, outdir, verbose, data,labelsize,gif,oldfont, fontsize)\n\n\n@commands_plotting.command()\n@click.argument(\"filename\", type=click.STRING)\n@click.option(\"-lon\", default=0,type=click.INT)\n@click.option(\"-lat\", default=0,type=click.INT)\n@click.option(\"-size\", default=20, type=click.INT)\n@click.option(\"-sig\", default=0, help=\"Which sky signal to plot\",)\n@click.option(\"-min\", \"min_\", type=click.FLOAT, help=\"Min value of colorbar, overrides autodetector.\",)\n@click.option(\"-max\", \"max_\", type=click.FLOAT, help=\"Max value of colorbar, overrides autodetector.\",)\n@click.option(\"-range\", \"rng\", type=click.FLOAT, help=\"Color bar range\")\n@click.option(\"-unit\", default=None, type=click.STRING, help=\"Set unit (Under color bar), has LaTeX functionality. Ex. $\\mu$\",)\n@click.option(\"-cmap\", default=\"planck\", help=\"Choose different color map (string), such as Jet or planck\",)\n@click.option(\"-graticule\", is_flag=True, help=\"Add graticule\",)\n@click.option(\"-log\", is_flag=True, help=\"Add graticule\",)\n@click.option(\"-nobar\", is_flag=True, help=\"remove colorbar\",)\n@click.option(\"-outname\", help=\"Output filename, else, filename with different format.\",)\ndef gnomplot(filename, lon, lat, sig, size, min_, max_, rng, unit, cmap, graticule, log, nobar, outname):\n \"\"\"\n Gnomonic view plotting. \n \"\"\"\n import healpy as hp\n import matplotlib.pyplot as plt\n from src.plotter import fmt\n from functools import partial\n \n from matplotlib import rcParams, rc\n rcParams[\"backend\"] = \"pdf\"\n rcParams[\"legend.fancybox\"] = True\n rcParams[\"lines.linewidth\"] = 2\n rcParams[\"savefig.dpi\"] = 300\n rcParams[\"axes.linewidth\"] = 1\n rc(\"text.latex\", preamble=r\"\\usepackage{sfmath}\",)\n\n if cmap == \"planck\":\n import matplotlib.colors as col\n from pathlib import Path\n if log:\n cmap = Path(__file__).parent / \"planck_cmap_logscale.dat\"\n else:\n cmap = Path(__file__).parent / \"planck_cmap.dat\"\n cmap = col.ListedColormap(np.loadtxt(cmap) / 255.0, \"planck\")\n else:\n try:\n import cmasher\n cmap = eval(f\"cmasher.{cmap}\")\n except:\n cmap = plt.get_cmap(cmap)\n\n xsize = 5000\n reso = size*60/xsize\n fontsize=10\n x = hp.read_map(filename, field=sig, verbose=False, dtype=None)\n nside=hp.get_nside(x)\n\n proj = hp.projector.GnomonicProj(rot=[lon,lat,0.0], coord='G', xsize=xsize, ysize=xsize,reso=reso)\n reproj_im = proj.projmap(x, vec2pix_func=partial(hp.vec2pix, nside))\n\n if rng:\n min_ = -rng\n max_ = rng\n #norm=\"log\" if log else None\n image = plt.imshow(reproj_im, origin='lower', interpolation='nearest', vmin=min_,vmax=max_, cmap=cmap)\n plt.xticks([])\n plt.yticks([])\n\n if not nobar:\n # colorbar\n from matplotlib.ticker import FuncFormatter\n cb = plt.colorbar(image, orientation=\"horizontal\", shrink=0.5, pad=0.03, format=FuncFormatter(fmt))\n cb.ax.tick_params(which=\"both\", axis=\"x\", direction=\"in\", labelsize=fontsize)\n cb.ax.xaxis.set_label_text(unit)\n cb.ax.xaxis.label.set_size(fontsize+2)\n\n if graticule:\n hp.graticule()\n if not outname:\n outname = filename.replace(\".fits\", f\"_gnomonic_{lon}lon{lat}lat_{size}x{size}deg.pdf\")\n\n click.echo(f\"Outputting {outname}\")\n plt.savefig(outname, bbox_inches=\"tight\", pad_inches=0.02, transparent=True, format=\"pdf\",)\n\n\n@commands_plotting.command()\n@click.argument(\"procver\", type=click.STRING)\n@click.option(\"-mask\", type=click.Path(exists=True), help=\"Mask for calculating cmb\",)\n@click.option(\"-defaultmask\", is_flag=True, help=\"Use default dx12 mask\",)\n@click.option(\"-freqmaps\", is_flag=True, help=\" Plot freqmaps\",)\n@click.option(\"-cmb\", is_flag=True, help=\" Plot cmb\",)\n@click.option(\"-cmbresamp\", is_flag=True, help=\" Plot cmbresamp\",)\n@click.option(\"-synch\", is_flag=True, help=\" Plot synch\",)\n@click.option(\"-ame\", is_flag=True, help=\"Plot ame\",)\n@click.option(\"-ff\", is_flag=True, help=\"Plot ff\",)\n@click.option(\"-dust\", is_flag=True, help=\" Plot dust\",)\n@click.option(\"-diff\", is_flag=True, help=\"Creates diff maps to dx12 and npipe\")\n@click.option(\"-diffcmb\", is_flag=True, help=\"Creates diff maps with cmb maps\")\n@click.option(\"-goodness\", is_flag=True, help=\"Plots chisq and residuals\")\n@click.option(\"-goodness_temp\", is_flag=True, help=\"Plots chisq and residuals\")\n@click.option(\"-goodness_pol\", is_flag=True, help=\"Plots chisq and residuals\")\n@click.option(\"-chisq\", is_flag=True, help=\"Plots chisq and residuals\")\n@click.option(\"-spec\", is_flag=True, help=\"Creates emission plot\")\n@click.option(\"-all\", \"all_\", is_flag=True, help=\"Plot all\")\n@click.pass_context\ndef plotrelease(ctx, procver, mask, defaultmask, freqmaps, cmb, cmbresamp, synch, ame, ff, dust, diff, diffcmb, goodness, goodness_temp, goodness_pol, chisq, spec, all_):\n \"\"\"\n Plots all release files.\n \"\"\"\n import os\n if not os.path.exists(\"figs\"):\n os.mkdir(\"figs\")\n\n if all_:\n freqmaps = not freqmaps; cmb = not cmb; synch = not synch; ame = not ame;\n ff = not ff; dust = not dust; diff = not diff; diffcmb = not diffcmb; spec = not spec\n goodness = not goodness; goodness_temp = not goodness_temp; goodness_pol = not goodness_pol\n chisq = not chisq\n\n defaultmask = True if not mask else False\n\n if goodness_temp or goodness_pol or chisq:\n goodness = True\n elif goodness:\n goodness_temp = goodness_pol = chisq = True\n\n size = \"mls\"\n for colorbar in [True, False]:\n if (cmbresamp and mask) or (cmbresamp and defaultmask):\n outdir = \"figs/cmb/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n\n if defaultmask:\n mask = \"/mn/stornext/u3/trygvels/compsep/cdata/like/BP_releases/masks/dx12_v3_common_mask_int_005a_1024_TQU.fits\"\n\n try:\n # CMB I with dip\n ctx.invoke(plot, input=f\"BP_cmb_resamp_I_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, range=3400)\n # CMB I without dip\n ctx.invoke(plot, input=f\"BP_cmb_resamp_I_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, remove_dipole=mask,)\n ctx.invoke(plot, input=f\"BP_cmb_resamp_QU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,1])\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if (cmb and mask) or (cmb and defaultmask):\n outdir = \"figs/cmb/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n\n if defaultmask:\n mask = \"/mn/stornext/u3/trygvels/compsep/cdata/like/BP_releases/masks/dx12_v3_common_mask_int_005a_1024_TQU.fits\"\n \n try:\n # CMB I with dip\n ctx.invoke(plot, input=f\"BP_cmb_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, range=3400)\n # CMB I no dip\n ctx.invoke(plot, input=f\"BP_cmb_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, remove_dipole=mask, )\n ctx.invoke(plot, input=f\"BP_cmb_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, remove_dipole=mask, fwhm=np.sqrt(60.0**2-14**2),)\n ctx.invoke(plot, input=f\"BP_cmb_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, remove_dipole=mask, fwhm=np.sqrt(420.0**2-14**2),range=150)\n\n # CMB QU at 14 arcmin, 1 degree and 7 degree smoothing\n for hehe, fwhm in enumerate([0.0, np.sqrt(60.0**2-14**2), np.sqrt(420.0**2-14**2)]):\n rng = 5 if hehe == 2 else None\n ctx.invoke(plot, input=f\"BP_cmb_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], fwhm=fwhm, range=rng)\n\n # RMS maps\n ctx.invoke(plot, input=f\"BP_cmb_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[3,], min=0, max=30)\n ctx.invoke(plot, input=f\"BP_cmb_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[4, 5,], min=0, max=10)\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if freqmaps:\n outdir = \"figs/freqmaps/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n \n try:\n # 030 GHz IQU\n ctx.invoke(plot, input=f\"BP_030_IQU_n0512_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=3400,)\n ctx.invoke(plot, input=f\"BP_030_IQU_n0512_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], fwhm=60.0, range=30,)\n ctx.invoke(plot, input=f\"BP_030_IQU_n0512_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[3, 4, 5], min=0, max=75)\n ctx.invoke(plot, input=f\"BP_030_IQU_n0512_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[6, 7, 8], min=0, max=2)\n # 044 GHz IQU\n ctx.invoke(plot, input=f\"BP_044_IQU_n0512_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=3400,)\n ctx.invoke(plot, input=f\"BP_044_IQU_n0512_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], fwhm=60.0, range=30,)\n ctx.invoke(plot, input=f\"BP_044_IQU_n0512_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[3,4,5,],min=0, max=75)\n ctx.invoke(plot, input=f\"BP_044_IQU_n0512_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[6,7,8],min=0, max=2)\n # 070 GHz IQU\n ctx.invoke(plot, input=f\"BP_070_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=3400,)\n ctx.invoke(plot, input=f\"BP_070_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], fwhm=60.0, range=30,)\n ctx.invoke(plot, input=f\"BP_070_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[3,4,5,], min=0, max=75)\n ctx.invoke(plot, input=f\"BP_070_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[6, 7, 8], min=0, max=2)\n\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if synch:\n outdir = \"figs/synchrotron/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n \n try:\n # Synch IQU\n ctx.invoke(plot, input=f\"BP_synch_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0, 1, 2, 3,], )\n ctx.invoke(plot, input=f\"BP_synch_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[6,], min=0, max=3)\n ctx.invoke(plot, input=f\"BP_synch_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[7, 8,], min=0, max=5)\n ctx.invoke(plot, input=f\"BP_synch_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[9,], min=0, max=10)\n\n ctx.invoke(plot, input=f\"BP_synch_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[4, 5,], min=-3.2, max=-3.05, mid=[-3.1,-3.15], cmap=\"fusion\" )\n ctx.invoke(plot, input=f\"BP_synch_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[10,11], min=0, mid=[0.05,0.1], max=0.15, cmap=\"neutral_r\")\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if ff:\n outdir = \"figs/freefree/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n try:\n # freefree mean and rms\n ctx.invoke(plot, input=f\"BP_freefree_I_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0, 1,], )\n ctx.invoke(plot, input=f\"BP_freefree_I_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[2,], min=0, max=50)\n #Dont plot te\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if ame:\n outdir = \"figs/ame/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n try:\n # ame mean and rms\n ctx.invoke(plot, input=f\"BP_ame_I_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0, 1,], )\n ctx.invoke(plot, input=f\"BP_ame_I_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[2,], min=0, max=80)\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if dust:\n outdir = \"figs/dust/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n \n try:\n # I Q U P IBETA QUBETA ITMEAN QUTMEAN ISTDDEV QSTDDEV USTDDEV PSTDDEV IBETASTDDEV QUBETASTDDEV ITSTDDEV QUTSTDDEV\n # dust IQU\n ctx.invoke(plot, input=f\"BP_dust_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0, 1, 2, 3, 4, 5, 6, 7,], )\n ctx.invoke(plot, input=f\"BP_dust_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[8,], min=0, max=50)\n ctx.invoke(plot, input=f\"BP_dust_IQU_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[9, 10], min=0, max=3)\n ctx.invoke(plot, input=f\"BP_dust_IQU_full_n1024_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[11,], min=0, max=6)\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if diff:\n outdir = \"figs/freqmap_difference/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n \n try:\n # Plot difference to npipe and dx12\n ctx.invoke(plot, input=f\"diffs/BP_030_diff_npipe_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=10)\n ctx.invoke(plot, input=f\"diffs/BP_030_diff_npipe_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], range=4)\n ctx.invoke(plot, input=f\"diffs/BP_030_diff_dx12_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=10)\n ctx.invoke(plot, input=f\"diffs/BP_030_diff_dx12_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], range=4)\n\n ctx.invoke(plot, input=f\"diffs/BP_044_diff_npipe_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=10)\n ctx.invoke(plot, input=f\"diffs/BP_044_diff_npipe_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], range=4)\n ctx.invoke(plot, input=f\"diffs/BP_044_diff_dx12_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=10)\n ctx.invoke(plot, input=f\"diffs/BP_044_diff_dx12_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], range=4)\n \n ctx.invoke(plot, input=f\"diffs/BP_070_diff_npipe_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=10)\n ctx.invoke(plot, input=f\"diffs/BP_070_diff_npipe_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], range=4)\n ctx.invoke(plot, input=f\"diffs/BP_070_diff_dx12_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], range=10)\n ctx.invoke(plot, input=f\"diffs/BP_070_diff_dx12_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], range=4)\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if diffcmb:\n outdir = \"figs/cmb_difference/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n\n mask = \"/mn/stornext/u3/trygvels/compsep/cdata/like/BP_releases/masks/dx12_v3_common_mask_int_005a_1024_TQU.fits\"\n mask2 = \"/mn/stornext/u3/hke/xsan/commander3/v2/chains_BP8_pol_resamp/mask_BP8_north_n8_v2.fits\" #\"/mn/stornext/u3/trygvels/compsep/cdata/like/paper_workdir/cmbdiffs/mask_dx12_and_BPproc.fits\"\n mask3 = \"/mn/stornext/u3/trygvels/compsep/cdata/like/paper_workdir/cmbdiffs/mask_bp8_full_IQU_n1024_v6.0_LFIPntSrc.fits\"\n for i, method in enumerate([\"Commander\", \"SEVEM\", \"NILC\", \"SMICA\",]):\n try:\n input = f\"diffs/BP_cmb_diff_{method.lower()}_{procver}.fits\"\n ttl = \"$\\mathrm{\"+method+\"}$\"\n ctx.invoke(plot, input=input, size=\"s\", outdir=outdir, colorbar=colorbar, auto=True, remove_dipole=mask3, remove_monopole=mask3, sig=[0,], range=10, title=ttl, ltitle=\" \", mask=mask3, mfill=\"gray\", labelsize=6)\n ctx.invoke(plot, input=input, size=\"s\", outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], remove_monopole=mask2, range=4, title=ttl, ltitle=\" \", mask=mask2, mfill=\"gray\", labelsize=6)\n\n ctx.invoke(plot, input=input, size=\"ml\", outdir=outdir, colorbar=colorbar, auto=True, remove_dipole=mask3, remove_monopole=mask3, sig=[0,], range=10, title=ttl, ltitle=\" \", mask=mask3, mfill=\"gray\",)\n ctx.invoke(plot, input=input, size=\"ml\", outdir=outdir, colorbar=colorbar, auto=True, sig=[1, 2,], remove_monopole=mask2, range=4, title=ttl, ltitle=\" \", mask=mask2, mfill=\"gray\",)\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n \n if goodness:\n import glob\n outdir = \"figs/goodness/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n \n if goodness_temp:\n tbands = [\"030_IQU\", \"044_IQU\", \"070_IQU\", \"030-WMAP_Ka\", \"040-WMAP_Q1\",\"040-WMAP_Q2\",\"060-WMAP_V1\",\"060-WMAP_V1\", \"0.4-Haslam\", \"857\",]\n \n for band in tbands:\n try:\n sig = [0,1] if not band in [\"030\",\"044\",\"070\"] else [0,3]\n b = glob.glob(f'goodness/BP_res_{band}*fits')[0]\n ctx.invoke(plot, input=b, size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=sig,)\n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if goodness_pol:\n pbands = [ \"033-WMAP_Ka_P\", \"041-WMAP_Q_P\", \"061-WMAP_V_P\", \"030_IQU\", \"044_IQU\", \"070_IQU\", \"353\"]\n mask_path='/mn/stornext/u3/trygvels/compsep/cdata/like/paper_workdir/synch/wmap_masks/'\n masks = ['wmap_processing_mask_Ka_r4_9yr_v5_TQU_chisq50.fits', 'wmap_processing_mask_Q_r4_9yr_v5_TQU_chisq50.fits', 'wmap_processing_mask_V_r4_9yr_v5_TQU_chisq50.fits',]\n m = 0\n for band in pbands:\n try:\n sig = [0,1,2,3] if not band in [\"030_IQU\",\"044_IQU\",\"070_IQU\"] else [1,2,4,5]\n b = glob.glob(f'goodness/BP_res_{band}*fits')[0]\n if band in [\"033-WMAP_Ka_P\", \"041-WMAP_Q_P\", \"061-WMAP_V_P\",]:\n ctx.invoke(plot, input=b, size='x', outdir=outdir, colorbar=colorbar, auto=True, sig=sig, mask=mask_path+masks[m], mfill=\"gray\") \n m+=1\n else:\n ctx.invoke(plot, input=b, size='x', outdir=outdir, colorbar=colorbar, auto=True, sig=sig,) \n except Exception as e:\n print(e)\n click.secho(\"Continuing...\", fg=\"yellow\")\n\n if chisq:\n nsides = [16, 16, 16, 512, 512, 1024, 1024]\n scale = 2*(np.sum([(x/16)**2 for x in nsides])-3*(64/16)**2)\n ctx.invoke(plot, input=f\"goodness/BP_chisq_n16_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[1,], scale=scale)\n #ctx.invoke(plot, input=f\"goodness/BP_chisq_n16_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[4,5], min=0.001, max=0.01, scale=scale)\n\n nsides = [512, 512, 1024, 512, 512, 512, 512, 512, 512, 1024]\n scale = (np.sum([(x/16)**2 for x in nsides])-3*(128/16)**2)\n ctx.invoke(plot, input=f\"goodness/BP_chisq_n16_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[0,], scale=scale)\n #ctx.invoke(plot, input=f\"goodness/BP_chisq_n16_{procver}.fits\", size=size, outdir=outdir, colorbar=colorbar, auto=True, sig=[3,], min=0.001, max=0.01, scale=scale)\n\n \n \n if spec: \n print(\"Plotting sky model SED spectrum\")\n print(\"Reading data\")\n import healpy as hp\n maskpath=\"/mn/stornext/u3/trygvels/compsep/cdata/like/sky-model/masks\"\n fg_path=\"/mn/stornext/u3/trygvels/compsep/cdata/like/sky-model/fgs_60arcmin\"\n \n a_cmb = None\n #BP_synch_IQU_n1024_BP8_noMedianFilter.fits\n a_s = hp.read_map(f\"unprocessed/BP_synch_IQU_n1024_{procver}_noMedianFilter.fits\", field=(0,1,2), dtype=None, verbose=False)\n b_s = hp.read_map(f\"BP_synch_IQU_n1024_{procver}.fits\", field=(4,5), dtype=None, verbose=False)\n \n a_ff = hp.read_map(f\"BP_freefree_I_n1024_{procver}.fits\", field=(0,), dtype=None, verbose=False)\n a_ff = hp.smoothing(a_ff, fwhm=arcmin2rad(np.sqrt(60.0**2-30**2)), verbose=False)\n t_e = hp.read_map(f\"BP_freefree_I_n1024_{procver}.fits\", field=(1,), dtype=None, verbose=False)\n \n a_ame1 = hp.read_map(f\"BP_ame_I_n1024_{procver}.fits\", field=(0,), dtype=None, verbose=False)\n #a_ame1 = hp.smoothing(a_ame1, fwhm=arcmin2rad(np.sqrt(60.0**2-30**2)), verbose=False)\n nup = hp.read_map(f\"BP_ame_I_n1024_{procver}.fits\", field=(1,), dtype=None, verbose=False) \n polfrac = 0.01\n a_ame2 = None\n \n a_d = hp.read_map(f\"BP_dust_IQU_n1024_{procver}.fits\", field=(0,1,2), dtype=None, verbose=False)\n a_d = hp.smoothing(a_d, fwhm=arcmin2rad(np.sqrt(60.0**2-10**2)), verbose=False)\n b_d = hp.read_map(f\"BP_dust_IQU_n1024_{procver}.fits\", field=(4,5,), dtype=None, verbose=False) \n t_d = hp.read_map(f\"BP_dust_IQU_n1024_{procver}.fits\", field=(6,7,), dtype=None, verbose=False) \n \n a_co10=f\"{fg_path}/co10_npipe_60arcmin.fits\"\n a_co21=f\"{fg_path}/co21_npipe_60arcmin.fits\"\n a_co32=f\"{fg_path}/co32_npipe_60arcmin.fits\"\n \n mask1=f\"{maskpath}/mask_70GHz_t7.fits\"\n mask2=f\"{maskpath}/mask_70GHz_t100.fits\"\n \n print(\"Data read, making plots, this may take a while\")\n\n for long in [False,True]:\n for pol in [True,False]:\n ctx.invoke(output_sky_model, pol=pol, long=long,\n darkmode=False, png=False,\n nside=64, a_cmb=a_cmb, a_s=a_s, b_s=b_s, a_ff=a_ff,\n t_e=t_e, a_ame1=a_ame1, a_ame2=a_ame2, nup=nup, polfrac=polfrac, a_d=a_d, b_d=b_d,\n t_d=t_d, a_co10=a_co10, a_co21=a_co21, a_co32=a_co32, mask1=mask1,\n mask2=mask2,)\n \n outdir = \"figs/sky-model/\"\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n \n files = os.listdir(\".\")\n for f in files:\n if f.startswith(\"spectrum\"):\n os.rename(f, f\"{outdir}{f}\")\n\n\n@commands_plotting.command()\n@click.argument(\"chainfile\", type=click.STRING)\n@click.argument(\"dataset\", type=click.STRING)\n@click.option('-burnin', default=0, help='Min sample of dataset (burnin)')\n@click.option(\"-maxchain\", default=1, help=\"max number of chains c0005 [ex. 5]\",)\n@click.option('-nbins', default=1, help='Bins for plotting')\n@click.option('-sig', default=\"P\", help='T or P')\n@click.option('-prior', nargs=2, type=float, help='Specify mean and stddev')\ndef hist(chainfile, dataset, burnin, maxchain, nbins,sig, prior):\n \"\"\"\n Make histogram\n \"\"\"\n \n # Check if you want to output a map\n import h5py\n import healpy as hp\n import pandas as pd\n from tqdm import tqdm\n dats = []\n for c in range(1, maxchain + 1):\n chainfile_ = chainfile.replace(\"c0001\", \"c\" + str(c).zfill(4))\n min_=burnin if c>1 else 0\n with h5py.File(chainfile_, \"r\") as f:\n max_ = len(f.keys()) - 1\n print(\"{:-^48}\".format(f\" Samples {min_} to {max_} in {chainfile_} \"))\n for sample in tqdm(range(min_, max_ + 1), ncols=80):\n # Identify dataset\n # HDF dataset path formatting\n s = str(sample).zfill(6)\n # Sets tag with type\n tag = f\"{s}/{dataset}\"\n #print(f\"Reading c{str(c).zfill(4)} {tag}\")\n # Check if map is available, if not, use alms.\n # If alms is already chosen, no problem\n try:\n data = f[tag][()]\n if len(data[0]) == 0:\n print(f\"WARNING! {tag} empty\")\n dats.append(data)\n except:\n print(f\"Found no dataset called {dataset}\")\n # Append sample to list\n \n\n df = pd.DataFrame.from_records(dats,columns=[\"T\",\"P\"])\n df2 = pd.DataFrame(df[sig].to_list())\n import seaborn as sns\n import matplotlib.pyplot as plt\n import plotly.colors as pcol\n from cycler import cycler\n colors=getattr(pcol.qualitative,\"Plotly\")\n sns.set_context(\"notebook\", font_scale=1.5, rc={\"lines.linewidth\": 1.2})\n sns.set_style(\"whitegrid\")\n plt.rcParams[\"mathtext.fontset\"] = \"stix\"\n custom_style = {\n 'grid.color': '0.8',\n 'grid.linestyle': '--',\n 'grid.linewidth': 0.5,\n 'savefig.dpi':300,\n 'axes.linewidth': 1.5,\n 'axes.prop_cycle': cycler(color=colors),\n 'mathtext.fontset': 'stix',\n 'font.family': 'serif',\n 'font.serif': 'times',\n }\n sns.set_style(custom_style)\n fontsize = 14\n x = df2.to_numpy()\n n1, bins, _ = plt.hist(x[:,1],bins=50, histtype='step', density=True, stacked=True)\n for i in range(x.shape[1]):\n plt.hist(x[:,i],bins=bins, histtype='step', density=True, stacked=True)\n plt.legend(frameon=False)\n\n \"\"\"\n if \"synch\" in dataset:\n xmin, xmax = (-3.38,-2.61)\n bins = np.linspace(xmin,xmax,50)\n n1, _, _ = plt.hist(x[:,1],bins=bins, histtype='step', color=\"#636efa\", density=True, stacked=True, linewidth=2, label=r\"$P_{-3.1}(\\beta^{\\mathrm{Spur}}_{\\mathrm{s}}|\\,d)$\")\n #plt.hist(x[:,3],bins=20, histtype='step', color=\"#00cc96\", density=True, stacked=True, linewidth=2, label=r\"$P_{-3.1}(\\beta^{\\mathrm{Plane}}_{\\mathrm{s}}|\\,d, \\omega_{\\mathrm{TOD}})$\")\n #t3 = np.loadtxt(\"sampletrace_t3.csv\",delimiter=\",\",) #\"regdatat3.dat\", delimiter=\",\")\n t3 = np.loadtxt(\"regdatat3.dat\", delimiter=\",\")\n plt.hist(t3[:,4], bins=bins, histtype='step', density=True, stacked=True, linestyle=\"--\", color=\"#ef553b\", label=r\"$P_{-2.8}(\\beta^{\\mathrm{Spur}}_{\\mathrm{s}}|\\,d, \\omega_{\\mathrm{TOD}})$\")\n bp8r = np.loadtxt(\"sampletrace_P_synch-beta_pixreg_val.csv\", delimiter=\",\", skiprows=1)\n plt.hist(bp8r[:,2],bins=bins, histtype='step', density=True, stacked=True, linestyle=\"--\", color=\"#636efa\", label=r\"$P_{-3.1}(\\beta^{\\mathrm{Spur}}_{\\mathrm{s}}|\\,d, \\omega_{\\mathrm{TOD}})$\")\n #n1, bins, _ = plt.hist(x[:,4],bins=20, histtype='step', color=\"#636efa\", label=r\"$P(\\beta^{\\mathrm{Spur}}_{\\mathrm{s}}|\\,d)$\")\n #xmin, xmax = (-3.25,-2.75)\n if prior:\n import scipy.stats as stats\n N = len(x[:,1])\n x = np.linspace(xmin,xmax,N)\n dx = bins[1]-bins[0]\n norm = sum(n1)*dx\n Pprior = stats.norm.pdf(x, -2.8, 0.1)#*norm\n plt.plot(x, Pprior*norm, color=\"#ef553b\", linestyle=\":\", label=r\"$P(\\beta_{\\mathrm{s}})=\\mathcal{N}(-2.8,0.1)$\")\n Pprior = stats.norm.pdf(x, prior[0], prior[1])#*norm\n plt.plot(x, Pprior*norm, color=\"#636efa\", linestyle=\":\", label=r\"$P(\\beta_{\\mathrm{s}})=\\mathcal{N}(-3.1,0.1)$\")\n\n plt.xlabel(r\"Synchrotron index, $\\beta_{\\mathrm{s}}$\", fontsize=fontsize)\n plt.xlim(xmin,xmax,)\n plt.ylim(0,11)\n plt.legend(frameon=False,loc=1, fontsize=13)\n else:\n n, bins, _ = plt.hist(x,bins=20, histtype='step', color=\"black\", label=r\"$P(\\beta_{\\mathrm{d}}|\\,d)$\")\n N = len(x)\n xmin, xmax = (1.46, 1.74)\n if prior:\n import scipy.stats as stats\n N = len(x)\n x = np.linspace(xmin,xmax,N)\n dx = bins[1]-bins[0]\n norm = sum(n)*dx\n Pprior = stats.norm.pdf(x, prior[0], prior[1])*norm\n plt.plot(x, Pprior, color=\"black\", linestyle=\"--\", label=r\"Prior $P(\\beta_{\\mathrm{d}})$\")\n plt.xlabel(r\"Thermal dust index, $\\beta_{\\mathrm{d}}$\", fontsize=fontsize)\n plt.xlim(xmin,xmax)\n plt.legend(frameon=False,loc=2)\n \"\"\"\n #plt.ylabel(r\"Normalized number of samples\", fontsize=fontsize)\n plt.title(\" \")\n\n plt.yticks(rotation=90, va=\"center\", fontsize=fontsize)\n plt.xticks(fontsize=fontsize)\n sns.despine(top=True, right=True, left=True, bottom=True)\n plt.tight_layout()\n plt.savefig(dataset.replace(\"/\",\"-\")+\"_histogram.pdf\", dpi=300, bbox_inches=\"tight\", pad_inches=0.02)\n\n\n@commands_plotting.command()\n@click.argument('filename', type=click.STRING)\n@click.option('-min', default=0, help='Min sample of dataset (burnin)')\n@click.option('-max', default=1000, help='Max sample to inclue')\n@click.option('-nbins', default=1, help='Bins')\n@click.option(\"-cmap\", default=\"Plotly\", help='Sets colorcycler using plotly', type=click.STRING)\ndef traceplot(filename, max, min, nbins, cmap):\n \"\"\"\n Traceplot of samples from .dat. \n Accepts min to max with optional bins.\n Useful to plot sample progression of spectral indexes.\n \"\"\"\n header = ['Prior', 'High lat.', 'Spur',\n 'Center', 'Fan region', 'Anti-center',\n 'Gum nebula']\n cols = [4,5,9,10,11,12,13]\n import pandas as pd\n df = pd.read_csv(filename, sep=r\"\\s+\", usecols=cols, skiprows=range(min), nrows=max)\n df.columns = header\n x = 'MCMC Sample'\n \n traceplotter(df, header, x, nbins, outname=filename.replace(\".dat\",\"_traceplot.pdf\"), min_=min, cmap=cmap)\n\n\n\n@commands_plotting.command()\n@click.argument(\"chainfile\", type=click.STRING)\n@click.argument(\"dataset\", type=click.STRING)\n@click.option('-burnin', default=0, help='Min sample of dataset (burnin)')\n@click.option(\"-maxchain\", default=1, help=\"max number of chains c0005 [ex. 5]\",)\n@click.option('-plot', is_flag=True, default=False, help= 'Plots trace')\n@click.option('-freeze', is_flag=True, help= 'Freeze top regions')\n@click.option('-nbins', default=1, help='Bins for plotting')\n@click.option(\"-f\", \"priorsamp\", multiple=True, help=\"These are sampled around prior and will be marked\",)\n@click.option('-scale', default=0.023, help='scale factor for labels')\n@click.option(\"-cmap\", default=\"Plotly\", help='sets colorcycler using Plotly', type=click.STRING)\ndef pixreg2trace(chainfile, dataset, burnin, maxchain, plot, freeze, nbins, priorsamp, scale,cmap):\n \"\"\"\n Outputs the values of the pixel regions for each sample to a dat file.\n ex. c3pp pixreg2trace chain_c0001.h5 synch/beta_pixreg_val -burnin 30 -maxchain 4 \n \"\"\"\n \n # Check if you want to output a map\n import h5py\n import healpy as hp\n import pandas as pd\n from tqdm import tqdm\n dats = []\n for c in range(1, maxchain + 1):\n chainfile_ = chainfile.replace(\"c0001\", \"c\" + str(c).zfill(4))\n min_=burnin if c>1 else 0\n with h5py.File(chainfile_, \"r\") as f:\n max_ = len(f.keys()) - 1\n print(\"{:-^48}\".format(f\" Samples {min_} to {max_} in {chainfile_} \"))\n for sample in tqdm(range(min_, max_ + 1), ncols=80):\n # Identify dataset\n # HDF dataset path formatting\n s = str(sample).zfill(6)\n # Sets tag with type\n tag = f\"{s}/{dataset}\"\n #print(f\"Reading c{str(c).zfill(4)} {tag}\")\n # Check if map is available, if not, use alms.\n # If alms is already chosen, no problem\n try:\n data = f[tag][()]\n if len(data[0]) == 0:\n print(f\"WARNING! {tag} empty\")\n dats.append(data)\n except:\n print(f\"Found no dataset called {dataset}\")\n # Append sample to list\n \n \n \n if \"bp_delta\" in dataset:\n label = dataset.replace(\"/\",\"-\")\n outname = f\"sampletrace_{label}\"\n\n df = pd.DataFrame.from_records(dats,)\n nregs = len(df[0][0])\n if \"30\" in dataset:\n header = [\"0\",\"27M\", \"27S\", \"28M\", \"28S\"]\n elif \"44\" in dataset:\n header = [\"0\",\"24M\",\"24S\",\"25M\",\"25S\",\"26M\",\"26S\"]\n elif \"70\" in dataset:\n header = [\"0\",\"18M\",\"18S\",\"19M\",\"19S\",\"20M\",\"20S\",\"21M\",\"21S\",\"22M\",\"22S\",\"23M\",\"23S\"]\n else:\n header = [str(i) for i in range(nregs)]\n\n df2 = pd.DataFrame(df[0].to_list(), columns=header)\n df2 = df2.drop(columns=[\"0\",])\n df2 = df2*1e3 # Scale to MHz\n header = header[1:]\n traceplotter(df2, header, \"Gibbs Sample\", nbins, f\"{outname}.pdf\", min_=burnin,ylabel=r\"$\\delta$ bandpass [MHz]\", priorsamp=priorsamp, scale=scale, cmap=cmap, figsize=(12,4), labscale=0.9)\n else:\n sigs = [\"T\",\"P\"]\n df = pd.DataFrame.from_records(dats, columns=sigs)\n nregs = len(df[\"P\"][0])\n \n if nregs == 9:\n header = ['Top left', 'Top right', 'Bot. left', 'Bot. right', 'Spur',\n 'Center', 'Fan region', 'Anti-center',\n 'Gum nebula']\n elif nregs == 6:\n header = ['High lat.', 'Spur',\n 'Center', 'Fan', 'Anti-center',\n 'Gum nebula']\n elif nregs == 4:\n header = ['High lat.', 'Spur',\n 'Gal. center', 'Gal. plane']\n elif nregs == 1:\n header = ['Fullsky',]\n else:\n header = [str(i) for i in range(nregs)]\n \n \n for sig in sigs:\n if sig ==\"T\":\n continue\n label = dataset.replace(\"/\",\"-\")\n outname = f\"sampletrace_{sig}_{label}\"\n\n df2 = pd.DataFrame(df[sig].to_list(), columns=header)\n df2.to_csv(f'{outname}.csv')\n print(df2.shape)\n \n if plot:\n xlabel = 'Gibbs Sample'\n if freeze:\n combined_hilat = 'High lat.'\n df2 = df2.drop(columns=['Top left', 'Top right', 'Bot. left',])\n df2 = df2.rename(columns={'Bot. right':combined_hilat})\n header_ = [combined_hilat] + header[4:]\n else:\n header_ = header.copy()\n \n traceplotter(df2, header_, xlabel, nbins, f\"{outname}.pdf\", min_=burnin, ylabel='Region spectral index', priorsamp=priorsamp, scale=scale, cmap=cmap)\n\ndef traceplotter(df, header, xlabel, nbins, outname, min_,ylabel, cmap=\"Plotly\", priorsamp=None, scale=0.023, figsize=(16,8), labscale=1):\n import seaborn as sns\n import matplotlib.pyplot as plt\n import plotly.colors as pcol\n sns.set_context(\"notebook\", font_scale=1.5, rc={\"lines.linewidth\": 1.2})\n sns.set_style(\"whitegrid\")\n plt.rcParams[\"mathtext.fontset\"] = \"stix\"\n plt.rcParams['font.family'] = 'serif'\n plt.rcParams['font.serif'] = 'Times'\n custom_style = {\n 'grid.color': '0.8',\n 'grid.linestyle': '--',\n 'grid.linewidth': 0.5,\n 'savefig.dpi':300,\n 'font.size': 20, \n 'axes.linewidth': 1.5,\n 'mathtext.fontset': 'stix',\n 'font.family': 'serif',\n 'font.serif': 'Times',\n }\n sns.set_style(custom_style)\n\n #df.columns = y\n N = df.values.shape[0]\n nregs = len(header)\n \"\"\"\n df['Mean'] = df.mean(axis=1)\n header.append('Mean')\n \"\"\"\n df[xlabel] = range(N)\n f, ax = plt.subplots(figsize=figsize)\n \n #cmap = plt.cm.get_cmap('tab20')# len(y))\n import matplotlib as mpl\n # Swap colors around\n colors=getattr(pcol.qualitative,cmap) \n if cmap==\"Plotly\":\n colors.insert(0,colors.pop(-1))\n colors.insert(3,colors.pop(2))\n colors = colors + colors\n\n cmap = mpl.colors.ListedColormap(colors)\n #cmap = plt.cm.get_cmap('tab10')# len(y))\n\n means = df[min_:].mean()\n stds = df[min_:].std()\n # Reduce points\n if nbins>1:\n df = df.groupby(np.arange(len(df))//nbins).mean()\n \n #longestlab = max([len(x) for x in header])\n # scale = 0.075 for 9 regions worked well.\n positions = legend_positions(df, header, scaling=scale)\n c = 0\n for i, (column, position) in enumerate(positions.items()):\n linestyle = ':' if str(i) in priorsamp else '-'\n linewidth = 2\n fontweight = 'normal'\n \"\"\"\n if column == \"Mean\":\n color=\"#a6a6a6\" #\"grey\"\n linewidth = 4\n fontweight='bold'\n else:\n color = cmap(c)#float(i-1)/len(positions))\n c += 1\n \"\"\"\n color = cmap(i)\n \n # Plot each line separatly so we can be explicit about color\n ax = df.plot(x=xlabel, y=column, legend=False, ax=ax, color=cmap(i), linestyle=linestyle, linewidth=linewidth,)\n\n label1 = rf'{column}'\n label2 = rf'{means[i]:.2f}$\\pm${stds[i]:.2f}'\n # Add the text to the right\n plt.text(\n df[xlabel][df[column].last_valid_index()]+N*0.01,\n position, label1, fontsize=15,\n color=color, fontweight=fontweight\n )\n plt.text(\n df[xlabel][df[column].last_valid_index()]+N*0.13*labscale,\n position, label2, fontsize=15,\n color=color, fontweight='normal'\n )\n\n #if min_:\n # plt.xticks(list(plt.xticks()[0]) + [min_])\n\n ax.set_ylabel(ylabel)\n #plt.yticks(rotation=90)\n plt.gca().set_xlim(right=N)\n #ax.axes.xaxis.grid()\n #ax.axes.yaxis.grid()\n # Add percent signs\n #ax.set_yticklabels(['{:3.0f}%'.format(x) for x in ax.get_yticks()])\n sns.despine(top=True, right=True, left=True, bottom=True)\n plt.subplots_adjust(wspace=0, hspace=0.01, right=0.81)\n plt.tight_layout()\n plt.savefig(outname, dpi=300)\n plt.show()\n\n\n@commands_plotting.command()\n@click.argument('dir1', type=click.STRING)\n@click.argument('type1', type=click.Choice(['ml', 'mean']))\n@click.argument('dir2', type=click.STRING)\n@click.argument('type2', type=click.Choice(['ml', 'mean']))\n@click.pass_context\ndef make_diff_plots(ctx, dir1, dir2, type1, type2):\n \"\"\"\n Produces difference maps between output directories.\n \"\"\"\n\n comps = ['030', '044', '070', 'ame', 'cmb', 'freefree', 'synch']\n\n filenames = {dir1:'', dir2:''}\n\n import glob\n import healpy as hp\n\n\n for dirtype, dirloc in zip([type1, type2],[dir1, dir2]):\n if dirtype == 'ml':\n #determine largest sample number\n cmbs = glob.glob(os.path.join(dirloc, 'cmb_c0001_k??????.fits'))\n indexes = [int(cmb[-11:-5]) for cmb in cmbs]\n intdexes = [int(index) for index in indexes]\n index = max(intdexes)\n \n filenames[dirloc] = '_c0001_k' + str(index).zfill(6) + '.fits'\n\n for comp in comps:\n mapn = {dir1:'', dir2:''}\n\n for dirtype, dirloc in zip([type1, type2],[dir1, dir2]): \n print(filenames[dirloc])\n if len(filenames[dirloc]) == 0:\n mapn[dirloc] = glob.glob(os.path.join(dirloc, 'BP_' + comp + '_I*.fits'))[0]\n else:\n if comp in ['ame', 'cmb', 'synch', 'dust']:\n mapn[dirloc] = comp + filenames[dirloc]\n elif comp in ['freefree']:\n mapn[dirloc] = 'ff' + filenames[dirloc]\n else:\n mapn[dirloc] = 'tod_' + comp + '_map' + filenames[dirloc]\n \n print(mapn) \n map1 = hp.read_map(os.path.join(dir1, mapn[dir1]))\n map2 = hp.read_map(os.path.join(dir2, mapn[dir2]))\n\n diff_map = map1 - map2 \n \n from src.plotter import Plotter\n \n Plotter(input=comp + '_diff' + '.fits', dataset='', nside=None, auto=True, min=None, max=None, mid=0.0,\n rng='auto', colorbar=True, lmax=None, fwhm=0.0, mask=None, mfill=None, sig=[0,], remove_dipole=None,\n logscale=None, size='m', white_background=True, darkmode=False, png=False, cmap=None, title=None,\n ltitle=None, unit=None, scale=None, outdir='.', verbose=False, data=diff_map)\n\n@commands_plotting.command()\n@click.option(\"-pol\", is_flag=True, help=\"\",)\n@click.option(\"-long\", is_flag=True, help=\"\",)\n@click.option(\"-darkmode\", is_flag=True, help=\"\",)\n@click.option(\"-png\", is_flag=True, help=\"\",)\n@click.option(\"-nside\", type=click.INT, help=\"\",)\n@click.option(\"-a_cmb\", help=\"\",)\n@click.option(\"-a_s\", help=\"\",)\n@click.option(\"-b_s\", help=\"\",)\n@click.option(\"-a_ff\", help=\"\",)\n@click.option(\"-t_e\", help=\"\",)\n@click.option(\"-a_ame1\",help=\"\",)\n@click.option(\"-a_ame2\", help=\"\",)\n@click.option(\"-nup\", help=\"\",)\n@click.option(\"-polfrac\", help=\"\",)\n@click.option(\"-a_d\", help=\"\",)\n@click.option(\"-b_d\", help=\"\",)\n@click.option(\"-t_d\", help=\"\",)\n@click.option(\"-a_co10\", help=\"\",)\n@click.option(\"-a_co21\", help=\"\",)\n@click.option(\"-a_co32\", help=\"\",)\n@click.option(\"-mask1\", help=\"\",)\n@click.option(\"-mask2\", help=\"\",)\ndef output_sky_model(pol, long, darkmode, png, nside, a_cmb, a_s, b_s, a_ff, t_e, a_ame1, a_ame2, nup, polfrac, a_d, b_d, t_d, a_co10, a_co21, a_co32, mask1, mask2):\n \"\"\"\n Outputs spectrum plots.\n c3pp output-sky-model -a_s synch_c0001_k000100.fits -b_s synch_beta_c0001_k000100.fits -a_d dust_init_kja_n1024.fits -b_d dust_beta_init_kja_n1024.fits -t_d dust_T_init_kja_n1024.fits -a_ame1 ame_c0001_k000100.fits -nup ame_nu_p_c0001_k000100.fits -a_ff ff_c0001_k000100.fits -t_e ff_Te_c0001_k000100.fits -mask1 mask_70GHz_t70.fits -mask2 mask_70GHz_t7.fits -nside 16\n \"\"\"\n from src.spectrum import Spectrum\n \"\"\"\n if not a_cmb:\n a_cmb = 0.67 if pol else 45\n if not a_s:\n a_s = 12 if pol else 76\n if not b_s:\n b_s = -3.1\n if not a_ff:\n a_ff = 30.\n if not t_e:\n t_e = 7000.\n if not a_ame1:\n a_ame1 = 5 if pol else 50\n if not a_ame2:\n a_ame2 = 50.\n if not nup:\n nup = 24\n if not polfrac:\n polfrac = 1\n if not a_d:\n a_d = 8 if pol else 163\n if not b_d:\n b_d = 1.6\n if not t_d:\n t_d = 18.5\n if not a_co10:\n a_co10=50\n if not a_co21:\n a_co21=25\n if not a_co32:\n a_co32=10\n \"\"\"\n if pol:\n # 15, 120, 40, (0,4, 12), (1.2,50)\n p = 0.6 if long else 15\n sd = 2 if long else 70\n foregrounds = {\n \"Synchrotron\" : {\"function\": \"lf\", \n \"params\" : [a_s, b_s,],\n \"position\": 20,\n \"color\" : \"C2\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n \"Thermal Dust\": {\"function\": \"tdust\", \n \"params\": [a_d, b_d, t_d, 353],\n \"position\": 250,\n \"color\": \"C1\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n }, \n \"Sum fg.\" : {\"function\": \"sum\", \n \"params\" : [],\n \"position\": 70,\n \"color\" : \"grey\",\n \"sum\" : False,\n \"linestyle\": \"--\",\n \"gradient\": False,\n },\n r\"BB $r=10^{-2}$\" : {\"function\": \"rspectrum\", \n \"params\" : [0.01, \"BB\",],\n \"position\": p,\n \"color\" : \"grey\",\n \"sum\" : False,\n \"linestyle\": \"dotted\",\n \"gradient\": True,\n },\n r\"BB $r=10^{-4}$\" : {\"function\": \"rspectrum\", \n \"params\" : [1e-4, \"BB\",],\n \"position\": p,\n \"color\" : \"grey\",\n \"sum\" : False,\n \"linestyle\": \"dotted\",\n \"gradient\": True,\n },\n \"CMB EE\": {\"function\": \"rspectrum\", \n \"params\" : [1, \"EE\"],\n \"position\": p,\n \"color\" : \"C5\",\n \"sum\" : False,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n \"Spinning Dust\" : {\"function\": \"sdust\", \n \"params\" : [a_ame1, nup, polfrac],\n \"position\": sd,\n \"color\" : \"C4\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": True,\n },\n\n }\n else:\n #120, 12, 40, (2,57), 20, 70\n p = 3 if long else 65\n td = 10 if long else 17\n foregrounds = {\n \"Synchrotron\" : {\"function\": \"lf\", \n \"params\" : [a_s, b_s,],\n \"position\": 170,\n \"color\" : \"C2\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n \"Thermal Dust\": {\"function\": \"tdust\", \n \"params\": [a_d, b_d, t_d, 545],\n \"position\": td,\n \"color\": \"C1\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n }, \n \"Free-Free\" : {\"function\": \"ff\", \n \"params\" : [a_ff, t_e],\n \"position\": 50,\n \"color\" : \"C0\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n \"Spinning Dust\" : {\"function\": \"sdust\", \n \"params\" : [a_ame1, nup, 1.],\n \"position\": p,\n \"color\" : \"C4\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n r\"CO$_{1\\rightarrow 0}$\": {\"function\": \"line\", \n \"params\" : [a_co10, 115, 11.06],\n \"position\": p,\n \"color\" : \"C9\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n r\"CO$_{2\\rightarrow 1}$\": {\"function\": \"line\", \n \"params\" : [a_co21, 230., 14.01],\n \"position\": p,\n \"color\" : \"C9\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n r\"CO$_{3\\rightarrow 2}$\": {\"function\": \"line\", \n \"params\" : [a_co32, 345., 12.24],\n \"position\": p,\n \"color\" : \"C9\",\n \"sum\" : True,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n \"Sum fg.\" : {\"function\": \"sum\", \n \"params\" : [],\n \"position\": 25,\n \"color\" : \"grey\",\n \"sum\" : False,\n \"linestyle\": \"--\",\n \"gradient\": False,\n },\n \"CMB\": {\"function\": \"rspectrum\", \n \"params\" : [1., \"TT\"],\n \"position\": 70,\n \"color\" : \"C5\",\n \"sum\" : False,\n \"linestyle\": \"solid\",\n \"gradient\": False,\n },\n\n }\n\n Spectrum(pol, long, darkmode, png, foregrounds, [mask1,mask2], nside)\n\n\n\n","sub_path":"src/commands_plotting.py","file_name":"commands_plotting.py","file_ext":"py","file_size_in_byte":58167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"174973986","text":"\n\nclass MaxHeap ():\n def __init__(self):\n self.heap = []\n\n def rightchild(self, i):\n return 2 * i + 2\n\n def leftchild(self, i):\n return 2 * i + 1\n\n def parent(self, i):\n return (i - 1) // 2\n\n\n def insert (self , key) :\n if len(self.heap) == 0 :\n self.heap.append(key)\n return self.heap\n\n self.heap.append(key)\n self.MoveToUp(len(self.heap)-1)\n\n\n def MoveToUp (self,index ) :\n while index>0 and self.heap[self.parent(index)] < self.heap[index] :\n self.swap( self.parent(index) , index)\n index = ((index-1)//2)\n\n return self.heap\n\n def swap(self,i, j):\n temp = self.heap[i]\n self.heap[i] = self.heap[j]\n self.heap[j] = temp\n\n def ExteractMax(self):\n result = self.heap[0]\n self.heap[0] = self.heap[len(self.heap)-1]\n self.MoveToDown(0 , self.heap)\n self.heap.pop()\n return self.heap\n\n def MoveToDown (self , i , Heap) :\n minindex1 = i\n minindex2 = i\n l = self.leftchild(i)\n if (l< len(Heap)-1 ):\n if Heap[l] > Heap[minindex2]:\n self.swap(minindex2, l)\n minindex2 =l\n self.MoveToDown(minindex2, Heap)\n\n\n r = self.rightchild(i)\n if (r< len(Heap)-1) :\n if Heap[r] > Heap[minindex1] :\n self.swap(minindex1 , r )\n minindex1 = r\n self.MoveToDown(minindex1, Heap)\n\n\n if (minindex1 == i and minindex2 == i):\n return Heap\n\n\n def IsMaxHeap(self,Heap): # checking if it is a max heap -> O(n)\n for i in range(len(Heap)//2) :\n try:\n if Heap[i] < Heap[2*i+1] or Heap[i] < Heap[2*i+2] :\n return False\n except :\n break;\n return True\n\n def Minheapify (self , i , Heap ) :\n minindex1 = i\n minindex2 = i\n l = self.leftchild(i)\n if (l < len(Heap) - 1):\n if Heap[l] < Heap[minindex2]:\n self.swap(minindex2, l)\n minindex2 = l\n return self.Minheapify(minindex2, Heap)\n\n r = self.rightchild(i)\n if (r < len(Heap) - 1):\n if Heap[r] < Heap[minindex1]:\n self.swap(minindex1, r)\n minindex1 = r\n return self.Minheapify(minindex1, Heap)\n\n if (minindex1 == i and minindex2 == i):\n return Heap\n\n\n\n def display (self):\n print(\"This is the max heap : \" ,self.heap)\n","sub_path":"tree/Heap.py","file_name":"Heap.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"201051217","text":"import re\nclass Patient:\n \"\"\"\"\n this is a patient object\n \"\"\"\n \n # this helps in initializing new Petient\n def __init__(self, Name, Age, Strand, diabetis, blue_eyes, three_eyes):\n self.name = Name\n self.age = str(Age)\n self.strand = Strand\n self.has_diabetis = diabetis\n self.has_Blue_eyes = blue_eyes\n self.has_Three_eyes = three_eyes\n\n","sub_path":"patient.py","file_name":"patient.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"124671599","text":"#!/usr/bin/env python3\nimport subprocess as sub\nimport os\n\ndef main():\n import argparse\n import sys\n dft='(=%(default)s)'\n parser=argparse.ArgumentParser(sys.argv[0].split('/')[-1])\n parser.add_argument('inpfn',type=str,\n help='QWalk input to be submitted.')\n parser.add_argument('-np',default=12,type=int,\n help='Number of processors per node.'+dft)\n parser.add_argument('-nn',default=1,type=int,\n help='Number of nodes.'+dft)\n parser.add_argument('-t',dest='time',default='500:00:00',type=str,\n help='Time string.'+dft)\n parser.add_argument('-q',dest='queue',default='batch',type=str,\n help='Queue.'+dft)\n parser.add_argument('-l',dest='local',action='store_true',\n help='Run locally'+dft)\n args=parser.parse_args()\n\n qsub(nn=args.nn,np=args.np,time=args.time,inpfn=args.inpfn,queue=args.queue,local=args.local)\n\ndef qsub(inpfn,local=False,nn=1,np=12,time='1:00:00',queue='batch'):\n outlines = [\n \"#!/bin/bash\",\n \"#PBS -l nodes=%d:ppn=%d\"%(nn,np),\n \"#PBS -l walltime=%s\"%time,\n \"#PBS -N %s\"%inpfn,\n \"#PBS -e $PBS_JOBID.err\",\n \"#PBS -o $PBS_JOBID.out\",\n \"#PBS -q %s\"%queue,\n \"cd %s\"%os.getcwd(),\n \"module purge\",\n \"module load gcc\",\n \"module load intel/mkl\",\n \"module load openmpi\",\n \"mpirun -n %d /mnt/home/bbusemeyer/bin/qwalk %s &> %s.out\"%(nn*np,inpfn,inpfn),\n ]\n\n with open('qsub.in','w') as outf:\n outf.write('\\n'.join(outlines))\n\n if local:\n print( sub.check_output(\"bash ./qsub.in\",shell=True).decode() )\n else:\n raise NotImplementedError(\"Need to put slurm options in.\")\n print( sub.check_output(\"sbatch ./qsub.in\",shell=True).decode() )\n\nif __name__=='__main__': main()\n","sub_path":"bin/miscripts/ccq_sub_qwalk.py","file_name":"ccq_sub_qwalk.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"74600221","text":"# -*- coding: utf-8 -*-\nimport os,sys\n\n# log 输出目录\nLOG_PATH = r'C:/Users/kuangwenhao/Desktop/work/home/project/sklearn_eview/log/'\n\ndef mylog(logFileName = None):\n\t\n\timport logging.config\n\tif logFileName == None:\n\t\tlogfile = LOG_PATH + \"log.txt\"\n\t\tlogTotal = LOG_PATH + \"total.log\"\n\telse:\n\t\tlogfile = LOG_PATH + logFileName\n\t\n\tif os.path.isfile(logfile):\n\t\tos.remove(logfile)\n\t\n\tgLogger = logging.getLogger()\n\tformatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')\n\thandler = logging.StreamHandler(sys.stdout)\n\thandler.setFormatter(formatter)\n\tgLogger.addHandler(handler)\n\tformatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')\n\thandler = logging.handlers.RotatingFileHandler(logfile)\n\thandler.setFormatter(formatter)\n\tgLogger.addHandler(handler)\n\tformatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')\n\thandler = logging.handlers.RotatingFileHandler(logTotal)\n\thandler.setFormatter(formatter)\n\tgLogger.addHandler(handler)\n\tgLogger.setLevel(logging.DEBUG)\n\treturn gLogger\n\nlogger = mylog()\n\nif __name__ == '__main__':\n\tlogger.debug('abc')\n\t","sub_path":"script/cherryLogSet.py","file_name":"cherryLogSet.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"79141604","text":"\"\"\"\nTasks for working with the nginx server package.\n\nExamples\n~~~~~~~~\n\nSetup nginx server::\n nginx.setup(\"root\", http=True, ssl=True, php=False)\n\nCreate a new server block::\n nginx.server(\"localhost\", 80,\n owner=\"vagrant\",\n default=True,\n ssl=True,\n ssl_name=\"localhost\",\n php=True)\n\nCreate a new server block for phpMyAdmin::\n nginx.pma_server(\"pma.localhost\", 80,\n owner=\"vagrant\",\n ssl=True,\n ssl_name=\"localhost\",\n pma_user=\"user\",\n pma_pass=\"pass\")\n\nCreate a new server block for GitLab::\n nginx.gitlab_server(\"gitlab.localhost\", 80,\n owner=\"vagrant\",\n ssl=True,\n ssl_name=\"localhost\",\n git_data=\"/media/nfs/gitlab/git-data\",\n backup_path=\"/media/nfs/gitlab/backup\")\n\n\"\"\"\nfrom fabric.api import *\nfrom fabric.contrib.files import sed, upload_template, append, exists\nfrom fmsm import *\nfrom fmsm.ubuntu import templates_dir\nimport fmsm.ubuntu.apt as apt\nimport fmsm.ubuntu.ufw as ufw\n\n\n@task\ndef setup(*args, **kwargs):\n \"\"\"Install nginx server with default configuration on remote host.\n\n Args:\n username (str): Username to add to www-data group.\n\n Kwargs:\n http (bool): Allow HTTP traffic.\n ssl (bool): Allow SSL traffic.\n php (bool): Install and configure PHP dependencies.\n \"\"\"\n username = argkw(0, args, str, \"\", invalid=(\"\",), required=True)\n http = argkw(\"http\", kwargs, bool, True)\n ssl = argkw(\"ssl\", kwargs, bool, False)\n php = argkw(\"php\", kwargs, bool, False)\n\n apt.install((\"nginx\",), update=False)\n if php:\n apt.install((\"php5-fpm\",), update=False)\n sed(\"/etc/php5/fpm/php.ini\", before=\";cgi.fix_pathinfo=1\",\n after=\"cgi.fix_pathinfo=0\", use_sudo=True)\n sudo(\"service php5-fpm restart\")\n\n # Make sure the www-data group exists and root + user is member.\n with settings(warn_only=True):\n sudo(\"groupadd www-data\")\n sudo(\"adduser root www-data\")\n sudo(\"adduser {0} www-data\".format(username))\n\n # Remove the default configuration.\n sudo(\"rm /etc/nginx/sites-enabled/default\")\n sudo(\"rm -rf /var/www/html\")\n\n # Configure firewall to allow nginx traffic.\n if http:\n ufw.allow(80, \"tcp\")\n if ssl:\n ufw.allow(443, \"tcp\")\n\n\n@task\ndef server(*args, **kwargs):\n \"\"\"Create a new server configuration.\n\n WARNING: SSL setup is self-signed only, not for production!\n\n Args:\n name (str): Server name string.\n port (int): Server port number.\n\n Kwargs:\n owner (str): Username owner string for server root.\n default (bool): Whether this is the default server.\n aliases (str): Server name aliases.\n ssl (bool): Whether SSL is included in configuration.\n ssl_name (str): SSL key/certificate file name.\n php (bool): Configure server to work with PHP.\n auth (dict): Directories requiring authentication.\n template (str): Template server configuration to use.\n mkdir (bool): Whether to create the server directory.\n fqdn (str): Fully qualified domain name.\n\n ???:\n nodejs (bool): Configure server to work with NodeJS proxies.\n njs_proxies (dict): NodeJS proxies in format d[\"subdir\"] = port.\n \"\"\"\n name = argkw(0, args, str, \"\", invalid=(\"\",), required=True)\n port = argkw(1, args, int, 0, invalid=(0,), required=True)\n owner = argkw(\"owner\", kwargs, str, \"www-data\", invalid=(\"\",))\n default = argkw(\"default\", kwargs, bool, False)\n aliases = argkw(\"aliases\", kwargs, str, \"\")\n ssl = argkw(\"ssl\", kwargs, bool, False)\n php = argkw(\"php\", kwargs, bool, False)\n auth = argkw(\"auth\", kwargs, dict, {})\n template = argkw(\"template\", kwargs, str, \"nginx_server\", invalid=(\"\",))\n a_mkdir = argkw(\"mkdir\", kwargs, bool, True)\n fqdn = argkw(\"fqdn\", kwargs, str, \"\")\n\n # Get root/site configuration path from server name.\n root = \"/var/www/{0}/html\".format(name)\n site = \"/etc/nginx/sites-available/{0}\".format(name)\n\n # Create a directory in /var/www for new server.\n if a_mkdir:\n sudo(\"mkdir -p {0}\".format(root))\n\n # Add index file based on processor configuration.\n if php:\n sudo(\"echo \\\"\\\" > {0}/index.php\".format(root))\n else:\n sudo(\"echo \\\"Hello, world! \\\" > {0}/index.html\".format(root))\n\n # Assign permissions to server root directory.\n sudo(\"chown -R {0}:www-data {1}\".format(owner, root))\n sudo(\"chmod -R 755 /var/www\")\n\n # Setup additional authentication for directories.\n for sdir in auth:\n aroot = \"/etc/nginx/pma/{0}\".format(name)\n sudo(\"mkdir -p {0}\".format(aroot))\n afile = \"{0}/_{1}\".format(aroot, sdir)\n sudo(\"touch {0}\".format(afile))\n\n for user in auth[sdir]:\n p = auth[sdir][user]\n pw = run(\"openssl passwd {0}\".format(p))\n append(afile, \"{0}:{1}\".format(user, pw),\n use_sudo=True, escape=True)\n\n # Context for server configuration template.\n context = {\n \"name\": name,\n \"port\": port,\n \"default\": default,\n \"root\": root,\n \"aliases\": aliases,\n \"php\": php,\n \"auth\": auth,\n \"ssl\": ssl,\n \"fqdn\": fqdn\n }\n\n if ssl:\n # Setup self-signed SSL certificates (not suitable for production!).\n ssl_name = argkw(\"ssl_name\", kwargs, str, \"\", invalid=(\"\",),\n required=True)\n\n sudo(\"mkdir -p /etc/nginx/ssl\")\n ssl_key = \"/etc/nginx/ssl/{0}.key\".format(ssl_name)\n ssl_crt = \"/etc/nginx/ssl/{0}.crt\".format(ssl_name)\n # If the certificate does not exist, create it now.\n if (not exists(ssl_key)) or (not exists(ssl_crt)):\n s = \"openssl req -x509 -nodes -days 1095 -newkey rsa:2048 -keyout {0} -out {1}\"\n sudo(s.format(ssl_key, ssl_crt))\n\n # Additional context for server configuration template.\n context[\"ssl_key\"] = ssl_key\n context[\"ssl_crt\"] = ssl_crt\n\n # Create server configuration file from template.\n upload_template(template, site, context=context, use_jinja=True,\n use_sudo=True, template_dir=templates_dir)\n\n # Create symbolic link to enable server and restart nginx.\n sudo(\"ln -s {0} /etc/nginx/sites-enabled\".format(site))\n sudo(\"service nginx restart\")\n\n\n@task\ndef pma_server(*args, **kwargs):\n \"\"\"Create a new server configuration for phpMyAdmin.\n\n WARNING: Run 'sudo dpkg-reconfigure phpmyadmin' from shell!\n TODO: Ability to configure phpMyAdmin programatically.\n\n Args:\n name (str): Server name string.\n\n Kwargs:\n ssl (bool): Whether SSL is included in configuration.\n pma_user (str): User for phpMyAdmin authentication.\n pma_pass (str): Password for phpMyAdmin authentication.\n \"\"\"\n name = argkw(0, args, str, \"\", invalid=(\"\",), required=True)\n ssl = argkw(\"ssl\", kwargs, bool, False)\n pma_user = argkw(\"pma_user\", kwargs, str, \"\", invalid=(\"\",), required=True)\n pma_pass = argkw(\"pma_pass\", kwargs, str, \"\", invalid=(\"\",), required=True)\n\n apt.install((\"phpmyadmin\",), update=False)\n\n # phpMyAdmin module dependency.\n sudo(\"php5enmod mcrypt\")\n sudo(\"service php5-fpm restart\")\n\n # Get root path from server name.\n root = \"/var/www/{0}\".format(name)\n\n # Create a symbolic link for phpmyadmin and rename for server.\n sudo(\"mkdir -p {0}\".format(root))\n sudo(\"ln -s /usr/share/phpmyadmin {0}/html\".format(root))\n\n # Additional authentication layer for security.\n auth = {\n \"\": {\n pma_user: pma_pass\n }\n }\n\n # Force SSL connections for security.\n if ssl:\n append(\"/etc/phpmyadmin/config.inc.php\", \"$cfg['ForceSSL'] = true;\",\n use_sudo=True, escape=True)\n\n # Set keyword arguments for internal call.\n kwargs[\"default\"] = False\n kwargs[\"php\"] = True\n kwargs[\"auth\"] = auth\n kwargs[\"mkdir\"] = False\n\n server(*args, **kwargs)\n\n\n@task\ndef gitlab_server(*args, **kwargs):\n \"\"\"Create a new server configuration for GitLab.\n\n INFO: Login with 'root/5iveL!fe' after reconfiguration.\n WARNING: Disable sign up via administrator settings!\n\n Args:\n name (str): Server name string.\n\n Kwargs:\n ssl (bool): Whether SSL is included in configuration.\n ssl_name (str): SSL key/certificate file name.\n git_data (str): Path for Git data storage.\n backup_path (str): Path for GitLab backup storage.\n \"\"\"\n name = argkw(0, args, str, \"\", invalid=(\"\",), required=True)\n ssl = argkw(\"ssl\", kwargs, bool, False)\n git_data = argkw(\"git_data\", kwargs, str, \"\")\n backup_path = argkw(\"backup_path\", kwargs, str, \"\")\n\n # omnibus-gitlab/README.md\n # omnibus-gitlab/doc/settings/nginx.md\n\n sudo(\"apt-get install curl openssh-server ca-certificates postfix\")\n sudo(\"curl https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bash\")\n apt.install((\"gitlab-ce\",), update=False)\n\n gconf = \"/etc/gitlab/gitlab.rb\"\n\n # External URL definition.\n url = \"\"\n if ssl:\n url = \"https://{0}\".format(name)\n else:\n url = \"http://{0}\".format(name)\n\n # Modify external URL configuration.\n # FIXME: Currently breaks other external URLs.\n sed(gconf, before=\"external_url\",\n after=\"external_url \\\"{0}\\\" # \".format(url), use_sudo=True)\n\n # Configure Git data location.\n if git_data != \"\":\n # TODO: Check directory exists.\n sed(gconf, before=\"# git_data_dir\",\n after=\"git_data_dir \\\"{0}\\\" # \".format(git_data),\n use_sudo=True, backup=\"\")\n\n # Custom settings appended.\n append(gconf, \"\\r\\n# Custom settings\", use_sudo=True, escape=True)\n\n # Backup path configuration.\n if backup_path != \"\":\n # TODO: Check directory exists.\n append(gconf, \"gitlab_rails['backup_path'] = \\\"{0}\\\"\".format(backup_path),\n use_sudo=True, escape=True)\n\n # If SSL enabled.\n if ssl:\n ssl_name = argkw(\"ssl_name\", kwargs, str, \"\", invalid=(\"\",),\n required=True)\n\n # Configure redirect to HTTPS\n append(gconf, \"nginx['redirect_http_to_https'] = true\",\n use_sudo=True, escape=True)\n\n # Configure SSL certificate/key locations.\n ssl_crt = \"/etc/nginx/ssl/{0}.crt\".format(ssl_name)\n append(gconf, \"ci_nginx['ssl_certificate'] = \\\"{0}\\\"\".format(ssl_crt),\n use_sudo=True, escape=True)\n\n ssl_key = \"/etc/nginx/ssl/{0}.key\".format(ssl_name)\n append(gconf, \"ci_nginx['ssl_certificate_key'] = \\\"{0}\\\"\".format(ssl_key),\n use_sudo=True, escape=True)\n\n # Disable bundled nginx.\n append(gconf, \"nginx['enable'] = false\", use_sudo=True, escape=True)\n append(gconf, \"ci_nginx['enable'] = false\", use_sudo=True, escape=True)\n\n # Add nginx server user as external in GitLab.\n append(gconf, \"web_server['external_users'] = ['www-data']\",\n use_sudo=True, escape=True)\n\n # Reconfigure GitLab\n sudo(\"gitlab-ctl reconfigure\")\n sudo(\"gitlab-ctl status\")\n\n # Add nginx server user to GitLab group.\n with settings(warn_only=True):\n sudo(\"adduser www-data gitlab-www\")\n\n # Set keyword arguments for internal call.\n kwargs[\"default\"] = False\n kwargs[\"php\"] = False\n kwargs[\"auth\"] = {}\n kwargs[\"template\"] = \"gitlab-omnibus-ssl-nginx.conf\"\n kwargs[\"mkdir\"] = False\n kwargs[\"fqdn\"] = url\n\n server(*args, **kwargs)\n","sub_path":"fmsm/ubuntu/nginx.py","file_name":"nginx.py","file_ext":"py","file_size_in_byte":11705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"222353581","text":"import binascii\nimport queue\nimport threading\nimport time\n\nimport serial # 导入模块\n\n\n# 消息接收与发送\n\n\n# 是否开启了接口\ndef is_opened(func):\n def is_opened_inner(s, send_order, send_data):\n if not s.ser.isOpen():\n s.open()\n\n func(s, send_order, send_data)\n\n return is_opened_inner\n\n\n# 串口连接类\nclass PortManager(object):\n current_device = None\n\n # queue\n read_queue = queue.Queue(maxsize=-1)\n\n # 包序列\n num = 0\n\n # # 16进制字符串 奇偶验证 返回 0 / 1 偶/奇\n # def get_check_result(self, hex_string: str) -> int:\n # check_result_int = 0\n # for s in hex_string:\n # current_result = 0\n # i = int(s, 16)\n # # 位运算\n # for j in range(4):\n # v = i >> j & 1\n # current_result += v\n # check_result_int += current_result\n # return check_result_int % 2\n\n def __init__(self, com_num: str, queue_out: queue, queue_in: queue, pool: list):\n # 线程池\n self.pool = pool\n # 发送到消息处理模块的线路\n self.read_queue = queue_out\n # 接收消息处理模块发来消息的线路\n self.queue_in = queue_in\n # 端口初始化\n self.ser = serial.Serial(com_num, 1000000, timeout=0.5) # 新建ser接口后续通讯使用\n\n # 开始接收消息\n def ready(self):\n t_recv = threading.Thread(target=self.start_recv, args=())\n self.pool.append(t_recv)\n t_send = threading.Thread(target=self.start_send, args=())\n self.pool.append(t_send)\n\n # 打开接口并开始接收\n def open(self):\n if not self.ser.isOpen():\n self.ser.open()\n return self\n\n # if self.current_device is None:\n # self.current_device = Device()\n # 接收数据\n # t_recv = threading.Thread(target=self.start_recv, args=())\n # t_detail = threading.Thread(target=self.unpacking, args=())\n # t_detail.start()\n # t_recv.start()\n # t_detail.join()\n # t_recv.join()\n # print('接收')\n # print(self.ser.readline())\n # print('接收完毕')\n\n def close(self):\n self.ser.close()\n\n # 开始接收数据\n def start_recv(self):\n \"\"\"\n start recv data from BLE\n :return:\n \"\"\"\n print(\"等待接收数据中....\")\n while True:\n time.sleep(0.5)\n\n count = self.ser.inWaiting()\n if count > 0:\n return_str = self.ser.read(count)\n if return_str == b'connected':\n print(\"设备已经连接\")\n elif return_str == b'disconnected':\n print('设备主动断开连接')\n else:\n # put data into queue\n var = str(binascii.b2a_hex(return_str))[2:-1].upper()\n # print(\"var:%s\" % var)\n for s in list(var):\n self.read_queue.put(s)\n\n # 开始发送数据\n def start_send(self):\n while True:\n info = self.queue_in.get(block=True, timeout=None)\n self.send(info)\n\n # @is_opened\n def send(self, ssr: str):\n self.ser.write(bytes.fromhex(ssr))\n","sub_path":"module_comm/comm_manager.py","file_name":"comm_manager.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"540311539","text":"name= input(\"Enter a name: \")\nplace= input(\"Enter a place: \")\nadjective1= input(\"Enter an adjective: \")\nfood1= input(\"Enter a food: \")\nfood2= input(\"Enter another food: \")\nverb= input (\"Enter a verv: \")\nadverb= input(\"Enter an adverb: \")\nnoun= input(\"Enter a noun: \")\nadjective2= input(\"Enter an adjective: \")\n\nprint (\"Let's play Silly Sentences!\")\n\nprint(name + \"was planning a dream vacation to \" + place + \".\")\nprint(name + \"was especially looking forward to trying the local cuisine, including \" + adjective1 + food1 + \"and\" + food2 + \".\")\n\nprint(name + \"will have to practice the language \" + \"to make it easier to \" + verb + \"with people.\")\n\nprint(name + \"has a long list of sights to see, including the \" + noun + \"museum and the \" + adjective2 + \"park.\")","sub_path":"silly_sentences.py","file_name":"silly_sentences.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"121606911","text":"############################################################################# \n#\n# VFRAME\n# MIT License\n# Copyright (c) 2020 Adam Harvey and VFRAME\n# https://vframe.io \n#\n#############################################################################\n\nfrom urllib import request\nfrom tqdm import tqdm\n\nclass DownloadProgressBar(tqdm):\n def update_to(self, b=1, bsize=1, tsize=None):\n if tsize is not None:\n self.total = tsize\n self.update(b * bsize - self.n)\n\ndef download_url(url, output_path):\n with DownloadProgressBar(unit='B', unit_scale=True,\n miniters=1, desc=url.split('/')[-1]) as t:\n request.urlretrieve(url, filename=output_path, reporthook=t.update_to)\n","sub_path":"vframe_cli/vframe/utils/url_utils.py","file_name":"url_utils.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"95333635","text":"def solve(lines):\n inp = [int(x) for x in lines[0].split(',')]\n n = 0\n nums = {}\n last = 0\n for i in range(len(inp)):\n n += 1\n nums[inp[i]] = [n]\n last = inp[i]\n\n\n while n != 2020:\n n += 1\n if len(nums[last]) == 1:\n new = 0\n else:\n new = nums[last][-1] - nums[last][-2]\n if new in nums:\n nums[new].append(n)\n else:\n nums[new] = [n]\n \n last = new\n\n return last\n\nif __name__ == '__main__':\n lines = []\n with open('15.txt') as f:\n for line in f.readlines():\n lines.append(line)\n print(solve(lines))\n","sub_path":"cernael-python/15a.py","file_name":"15a.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"17754192","text":"#!/usr/bin/env python3\n\nfrom flask import Flask\nimport os\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef hello():\n hostname = os.getenv('HOSTNAME')\n return f\"I am: {hostname}\\n\"\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","sub_path":"whoami/rootfs/opt/whoami/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"195861230","text":"from django.urls import path\nfrom django.views.generic.base import TemplateView\n\nfrom . import views\n\napp_name = \"user_app\"\nurlpatterns = [\n #path('test_login/',views.SqlHelper().test_login,name=\"test_login\"),\n path('login/',views.login,name=\"login\"),\n path('signup/',views.signup,name=\"signup\"),\n # path('promtoions/', views.promtoions, name=\"promtoions\"),\n path('dashboard/', views.dashboard, name=\"dashboard\"),\n path('advertise/', views.advertise, name=\"advertise\"),\n path('add_product/', views.add_product, name=\"add_product\"),\n path('get_all_products/', views.get_all_products, name=\"get_all_products\"),\n path('delete_all/', views.delete_all, name=\"delete_all\"),\n # path('matchscreen//', views.matchscreen, name='matchscreen'),\n path('logout/',views.logout,name=\"logout\"),\n # path('get_sql_query/', views.SqlHelper().get_sql_query, name=\"sqlquery\"),\n # path('notify_users/', views.SqlHelper().notify_users, name=\"notify_users\"),\n # path('detailed_report/', views.SqlHelper().detailed_report, name=\"detailed_report\"),\n # path('view_league//', views.view_league, name=\"view_league\"),\n # path('update_league_info/', views.update_league_info, name=\"update_league_info\"),\n # path('state_wise_analytics/', views.SqlHelper().state_wise_analytics, name=\"state_wise_analytics\"),\n # path('match_analytics//', views.SqlHelper().match_analytics, name=\"match_analytics\"),\n # path('mail_state_wise_analytics/', views.SqlHelper().mail_state_wise_analytics, name=\"mail_state_wise_analytics\"),\n # path('mail_general_analytics/', views.SqlHelper().mail_general_analytics, name=\"mail_general_analytics\"),\n # path('mail_analytics_link/', views.SqlHelper().mail_analytics_link, name=\"mail_analytics_link\"),\n # path('//', views.SqlHelper().user_statstics_by_year, name=\"user_statstics_by_year\"),\n # path('///', views.SqlHelper().user_statstics_by_month_year, name=\"user_statstics_by_month_year\"),\n]\n","sub_path":"backend-django-dashboard/favShopy-dashboard/user_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"190011145","text":"# Copyright 2018 iXsystems, Inc.\n# All rights reserved\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted providing that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. 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#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING\n# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n#####################################################################\nimport cam\nimport concurrent.futures\nimport re\nimport subprocess\nimport sys\nimport traceback\n\nfrom middlewared.client import Client\n\n# One cannot simply import collectd in a python interpreter (for various reasons)\n# thus adding this workaround for standalone testing and doctest\nif __name__ == '__main__' or hasattr(sys.modules['__main__'], '_SpoofOut'):\n class CollectdDummy:\n def register_config(self, a):\n # do something\n pass\n\n def register_init(self, a):\n a()\n\n def register_read(self, a, b=10):\n a()\n\n def info(self, msg):\n print(msg)\n\n def warning(self, msg):\n print(msg)\n\n def debug(self, msg):\n print(msg)\n\n def error(self, msg):\n print(msg)\n\n class Values(object):\n def __init__(self, *args, **kwargs):\n self.plugin = ''\n self.plugin_instance = ''\n self.type = None\n self.type_instance = None\n self.values = None\n self.meta = None\n\n def dispatch(self, **kwargs):\n print(f'{self.plugin}:{self.plugin_instance}:{self.type}:{self.type_instance}:{self.values}')\n\n collectd = CollectdDummy()\nelse:\n import collectd\n\n\nREAD_INTERVAL = 300.0\n\n\ncollectd.info('Loading \"disktemp\" python plugin')\n\n\ndef get_temperature(stdout):\n \"\"\"\n >>> get_temperature(\"190 Airflow_Temperature_Cel 0x0022 073 037 045 Old_age Always In_the_past 27 (3 44 30 26 0)\")\n 27\n >>> get_temperature(\"194 Temperature_Celsius 0x0022 049 067 --- Old_age Always - 51 (Min/Max 24/67)\")\n 51\n >>> get_temperature(\"190 Airflow_Temperature_Cel 0x0022 073 037 045 Old_age Always In_the_past 27 (3 44 30 26 0)\\\\n\"\\\n \"194 Temperature_Celsius 0x0022 049 067 --- Old_age Always - 51 (Min/Max 24/67)\")\n 51\n >>> get_temperature(\"194 Temperature_Internal 0x0022 100 100 000 Old_age Always - 26\\\\n\"\\\n \"190 Temperature_Case 0x0022 100 100 000 Old_age Always - 27\")\n 26\n >>> get_temperature(\" 7 Seek_Error_Rate 0x000f 081 060 030 Pre-fail Always - 126511909\\\\n\"\\\n \"190 Airflow_Temperature_Cel 0x0022 062 053 045 Old_age Always - 38 (Min/Max 27/40)\")\n 38\n\n >>> get_temperature(\"Temperature: 40 Celsius\")\n 40\n >>> get_temperature(\"Temperature Sensor 1: 30 Celsius\")\n 30\n\n >>> get_temperature(\"Current Drive Temperature: 31 C\")\n 31\n \"\"\"\n\n # ataprint.cpp\n\n data = {}\n for s in re.findall(r'^((190|194) .+)', stdout, re.M):\n s = s[0].split()\n try:\n data[s[1]] = int(s[9])\n except (IndexError, ValueError):\n pass\n for k in ['Temperature_Celsius', 'Temperature_Internal', 'Drive_Temperature',\n 'Temperature_Case', 'Case_Temperature', 'Airflow_Temperature_Cel']:\n if k in data:\n return data[k]\n\n reg = re.search(r'194\\s+Temperature_Celsius[^\\n]*', stdout, re.M)\n if reg:\n return int(reg.group(0).split()[9])\n\n # nvmeprint.cpp\n\n reg = re.search(r'Temperature:\\s+([0-9]+) Celsius', stdout, re.M)\n if reg:\n return int(reg.group(1))\n\n reg = re.search(r'Temperature Sensor [0-9]+:\\s+([0-9]+) Celsius', stdout, re.M)\n if reg:\n return int(reg.group(1))\n\n # scsiprint.cpp\n\n reg = re.search(r'Current Drive Temperature:\\s+([0-9]+) C', stdout, re.M)\n if reg:\n return int(reg.group(1))\n\n\nclass DiskTemp(object):\n\n def init(self):\n collectd.info('Initializing \"disktemp\" plugin')\n with Client() as c:\n self.disks = [disk['devname'] for disk in c.call('disk.query', [['togglesmart', '=', True],\n # Polling for disk temperature does\n # not allow them to go to sleep\n # automatically\n ['hddstandby', '=', 'ALWAYS ON']])]\n self.powermode = c.call('smart.config')['powermode'].lower()\n\n def dispatch_value(self, name, instance, value, data_type=None):\n val = collectd.Values()\n val.plugin = 'disktemp'\n val.plugin_instance = name\n if data_type:\n val.type = data_type\n val.values = [value, ]\n val.meta = {'0': True}\n val.dispatch(interval=READ_INTERVAL)\n\n def read(self):\n futures = {}\n with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:\n for disk in self.disks:\n futures[executor.submit(self.get_temperature, disk)] = disk\n\n for fut in concurrent.futures.as_completed(futures.keys()):\n disk = futures.get(fut)\n if not disk:\n continue\n try:\n temp = fut.result()\n if temp is None:\n continue\n self.dispatch_value(disk, 'temperature', temp, data_type='temperature')\n except Exception as e:\n collectd.info(traceback.format_exc())\n\n def get_temperature(self, disk):\n if disk.startswith('da'):\n try:\n return cam.CamDevice(disk).get_temperature()\n except Exception:\n pass\n cp = subprocess.run(['/usr/local/sbin/smartctl', '-a', '-n', self.powermode, f'/dev/{disk}'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if (cp.returncode & 0b11) != 0:\n collectd.info(f'Failed to run smartctl for {disk}: {cp.stdout.decode(\"utf8\", \"ignore\")}')\n return None\n\n stdout = cp.stdout.decode('utf8', 'ignore')\n\n return get_temperature(stdout)\n\n\ndisktemp = DiskTemp()\n\ncollectd.register_init(disktemp.init)\ncollectd.register_read(disktemp.read, READ_INTERVAL)\n","sub_path":"src/freenas/usr/local/lib/collectd_pyplugins/disktemp.py","file_name":"disktemp.py","file_ext":"py","file_size_in_byte":7575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"100028579","text":"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport csv\nimport time\n\nurl = 'https://www.findrate.tw/bank/29/#.XwlxJ20zapo'\nheaders = {'user-angent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}\nres = requests.get(url,headers=headers)\nres.encoding = 'utf-8'\nhtml = res.text\nsoup = BeautifulSoup(html, 'html.parser')\nperformance_list = []\nfor index in range(2,21):\n performance_dist = {}\n \n performance_dist['unit_data'] = soup.select(f'#right > table:nth-child(9) > tbody > tr:nth-child({index}) > td.flag > a')[0].text\n performance_dist['unit_price'] = soup.select(f'#right > table:nth-child(9) > tbody > tr:nth-child({index}) > td:nth-child(3)')[0].text\n performance_list.append(performance_dist)\n print( performance_dist)\n\nheaders= ['unit_data','unit_price']\nwith open('performance.csv','w',encoding='utf-8') as output_file:\n dict_writer = csv.DictWriter(output_file,headers)\n dict_writer.writeheader()\n dict_writer.writerows(performance_list)\n\n \n\ntime.sleep(60)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"617620448","text":"from import_parameters import *\n# from validate import data_transforms\n\n\n\n\n\nparser = argparse.ArgumentParser(description = 'All arguments to be used in predicting')\nparser.add_argument ('--checkpoint', default = 'checkpoint.pth', help = 'filename of checkpoint', metavar = '')\nparser.add_argument ('--arch', metavar='ARCH', default='vgg16', help='Chose between two options; densenet161 or vgg16 (default)')\nparser.add_argument ('--image_path', default = \"flowers/test/10/image_07090.jpg\", help = 'Image path of immage to be classified', metavar = '')\nparser.add_argument ('--topk', default = 5, type = int, help = 'The number of highest probabilities for the given prediction (default = 5)')\nparser.add_argument ('--device', default = 'GPU', help = 'Chose which device will be used to predict (default is GPU if available, otherwise CPU)')\nparser.add_argument ('--mapping', default = 'cat_to_name.json', help = 'Chose the mapping file for labeling the flower probabilities (default is cat_to_name.json)')\nparser.add_argument ('--hidden_units', default = 512, type=int, help = 'Number of units in the first hidden layer (default is 512)')\n\nargs = parser.parse_args()\n\nfilepath = args.checkpoint\narch = args.arch\nimage_path = args.image_path\ntopk = args.topk\nmapping = args.mapping\nhidden_units = args.hidden_units\n\n\n\n\n#Loading JSON file with name mapping\nwith open(mapping, 'r') as f:\n cat_to_name = json.load(f)\n\n\n\n\n#defining if model should be run on cpu or GPU\nif args.device == 'cpu':\n device = 'cpu'\n print('Device is set to cpu')\nelif args.device == 'GPU':\n if (torch.cuda.is_available()):\n device = 'cuda'\n print('GPU device is available and will be set to GPU')\n\n else:\n device = 'cpu'\n print ('Device could not be set to GPU, therefore device is cpu')\n\n\n\n\n\n\n\n\n\n\nprint('define model architecture')\n## define model architecture\n#Define model and classifier size dependant on chosen model\narch = args.arch\nmodel = models.__dict__[args.arch](pretrained=True)\nif arch == \"vgg16\":\n layers = [25088, hidden_units, 200, 102]\n\nelif arch == 'densenet161':\n layers = [2208, hidden_units, 200, 102]\n\n\n# don't compute gradients\nfor param in model.parameters():\n param.requires_grad = False\n\n\n\n\n#defining build_classifier\nprint('define build_classifier')\ndef build_classifier(layers):\n\n\n classifier = nn.Sequential(\n nn.Linear(layers[0], layers[1]),\n nn.ReLU(),\n nn.Dropout(0.5), #50 % probability\n nn.Linear(layers[1], layers[2]),\n torch.nn.ReLU(),\n torch.nn.Dropout(0.2), #20% probability\n nn.Linear(layers[2], layers[3]),\n nn.LogSoftmax(dim=1))\n\n return classifier\n\n\n\n\n\n\n\n\n\n\n\n#defining load_checkpoint\nprint('define load_checkpoint')\ndef load_checkpoint(filepath, arch):\n\n checkpoint = torch.load(filepath, map_location=lambda storage, loc: storage)\n model = models.__dict__[arch](pretrained=True)\n\n # Freeze the feature parameters\n for params in model.parameters():\n params.requires_grad = False\n\n #create new classifier\n classifier = build_classifier(layers)\n model.classifier = classifier\n\n\n criterion = nn.NLLLoss()\n\n optimizer = optim.Adam(model.classifier.parameters(), lr = 0.001)\n\n\n model.class_to_idx = checkpoint['class_to_idx']\n\n model.load_state_dict(checkpoint['model_state_dict'])\n\n optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n\n return model, criterion\n\n\n#defining build_classifier\n\n#defining imshow --> Not used\n\n#defining process_image\nprint ('define process_image')\ndef process_image(image):\n ''' Scales, crops, and normalizes a PIL image for a PyTorch model,\n returns an Numpy array\n '''\n #Open image\n im = Image.open(image)\n\n #Resize picture\n # Get dimensions.\n width, height = im.size\n\n # Find shorter size and create settings to crop shortest side to 256\n if width < height:\n size=[256, 999]\n else:\n size=[999, 256]\n\n im.thumbnail(size)\n\n #Crop picture\n crop_size = 244\n center = width/4, height/4\n crop_dimensions = (center[0]-(crop_size/2), center[1]-(crop_size/2), center[0]+(crop_size/2), center[1]+(crop_size/2))\n im = im.crop(crop_dimensions)\n\n #Adjust for number of color chanels\n numpy_img = np.array(im)/255\n\n # Normalize each color channel\n mean = [0.485, 0.456, 0.406]\n std = [0.229, 0.224, 0.225]\n numpy_img = (numpy_img-mean)/std\n\n # Set the color to the first channel\n numpy_img = numpy_img.transpose(2, 0, 1)\n\n return numpy_img\n\n#defining predict\nprint('define predict')\ndef predict(image_path, model, topk=topk):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n '''\n model.to(device)\n model.eval();\n\n # Define model class to IDx\n# model.class_to_idx = image_datasets['train'].class_to_idx\n\n\n #load image in numpy array\n numpy_immage = process_image(image_path)\n\n #Convert numpy array to tensor\n tensor_image = np.expand_dims(numpy_immage, axis=0)\n\n\n #Convert tensor to torch image\n torch_image = torch.from_numpy(tensor_image).type(torch.FloatTensor)\n torch_image = torch_image.to(device)\n\n output = model(torch_image)\n torch.exp_(output)\n\n\n probs, labels = output.topk(topk)\n\n probs = np.array(probs.data)[0]\n labels = np.array(labels)[0]\n\n return probs, labels\n\n#defining display\nprint ('define display')\nmodel = args.arch\n\ndef display (image_path, model = model):\n\n probs, labels = predict(image_path, model)\n processed_image = process_image(image_path)\n\n mapping = {val: key for key, val in\n model.class_to_idx.items()\n }\n\n classes = [mapping[label] for label in labels]\n\n# label_map = {v: k for k, v in model.class_to_idx.items()}\n\n# classes = [cat_to_name[label_map[label]] for label in labels]\n\n\n title = cat_to_name[image_path.split('/')[-2]]\n\n return probs, labels, classes, title\n\n\n\n\n\n\n# args = arg_parser_predict()\n\n# image_path = args.Path\n\n# print(args)\n\n\nmodel, criterion = load_checkpoint(filepath, model)\n\n# image_path = \"flowers/test/10/image_07090.jpg\"\n\n\n\n# probs, labels = predict(image_path, model, topk=5)\n\nprobs, labels, classes, title = display(image_path, model)\nclass_names = [cat_to_name[item] for item in classes]\n\n\n\nnp.set_printoptions(precision=2)\n\n\n\nprint(\"=\"*80)\nprint(\" \"*35 + 'FLOWER PREDICTOR')\nprint(\"=\"*80)\nprint(\"Input label (or labels) = {}\".format(classes))\nprint(\"Probability confidence(s) = {}\".format(probs))\nprint(\"Class(es) name(s) = {}\".format(class_names))\nprint(\"=\"*80)\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":6723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"59380435","text":"from collections import defaultdict, namedtuple\nfrom functools import total_ordering\nimport heapq\n\n\nclass Specificity(\n namedtuple(\"Specificity\", [\"override\", \"positive\", \"negative\", \"wildcard\"])\n):\n __slots__ = ()\n\n def __add__(self, other):\n return Specificity(\n self.override + other.override,\n self.positive + other.positive,\n self.negative + other.negative,\n self.wildcard + other.wildcard,\n )\n\n\nPOS_LIT_SPEC = Specificity(0, 1, 0, 0)\nWILDCARD_SPEC = Specificity(0, 0, 0, 1)\n\n\n# TODO this class really no longer makes sense in this module, it's not\n# even directly present in the dag any longer...\n@total_ordering\nclass Key:\n def __init__(self, name, values=set()):\n self.name = name\n self.values = frozenset(values)\n self.specificity = POS_LIT_SPEC if len(values) else WILDCARD_SPEC\n\n # TODO java code notices if key/val are actually not idents and quotes them\n def __str__(self):\n if len(self.values) > 1:\n val_strs = (f\"{self.name}.{val}\" for val in sorted(self.values))\n return f\"({', '.join(val_strs)})\"\n elif len(self.values) == 1:\n return f\"{self.name}.{next(iter(self.values))}\"\n return self.name\n\n def __eq__(self, other):\n if not other:\n return False\n return self.name == other.name and self.values == other.values\n\n def __lt__(self, other):\n return (self.name, sorted(self.values)) < (other.name, sorted(other.values))\n\n def __hash__(self):\n return hash((self.name, self.values))\n\n\nclass LiteralMatcher:\n def __init__(self):\n self.wildcard = None\n self.positive_values = defaultdict(list)\n self.negative_values = [] # TODO support this\n\n def add_values(self, values, node):\n # because we find the set of unique literals prior to creating these matchers, we\n # don't currently need to worry about the added node representing being redundant.\n # each node will definitely represent a unique set of values for this name. in the\n # event that the node doesn't end up with any local property settings, building a\n # separate node for every combination is overkill. it might be nice to detect this\n # case and elide the subset node, replacing it with individual nodes for each member.\n # on the other hand, whether this is an improvement depends on whether or not those\n # individual nodes will actually end up existing either way, or alternatively on the\n # number of different sets those values appear in. this isn't a tradeoff with an\n # easy obvious answer.\n\n if len(values) == 0:\n assert not self.wildcard\n self.wildcard = node\n\n for value in values:\n self.positive_values[value].append(node)\n # TODO handle negatives\n\n\nclass Node:\n def __init__(self):\n self.children = []\n self.props = []\n self.constraints = []\n self.tally_count = 0 # used for poisoning in case of OrNode\n\n def add_link(self):\n self.tally_count += 1\n\n def accumulate_subclass_stats(self, stats):\n pass\n\n def accumulate_stats(self, stats, visited):\n if self in visited:\n return\n visited.add(self)\n stats.nodes += 1\n stats.props += len(self.props)\n stats.edges += len(self.children)\n stats.fanout_max = max(stats.fanout_max, len(self.children))\n stats.fanout_total += len(self.children)\n self.accumulate_subclass_stats(stats)\n if len(self.children):\n stats.nodes_with_fanout += 1\n for node in self.children:\n node.accumulate_stats(stats, visited)\n\n\nclass AndNode(Node):\n def __init__(self, specificity):\n super().__init__()\n self.specificity = specificity\n\n def accumulate_subclass_stats(self, stats):\n # only include tally stats for and nodes, since the tallies\n # for or nodes are only used for poisoning...\n stats.tally_max = max(stats.tally_max, self.tally_count)\n stats.tally_total += self.tally_count\n\n\nclass OrNode(Node):\n def accumulate_subclass_stats(self, stats):\n pass\n\n\nclass DagStats:\n def __init__(self):\n self.literals = 0\n self.nodes = 0\n self.props = 0\n self.edges = 0\n self.tally_max = 0\n self.fanout_max = 0\n self.tally_total = 0\n self.fanout_total = 0\n self.nodes_with_fanout = 0\n\n def __repr__(self):\n return str(self.__dict__)\n\n def dump(self):\n for name in self.__dict__:\n print(f\"{name}: {getattr(self, name)}\")\n print(f\"tally_avg: {self.tally_total/self.nodes}\")\n print(f\"fanout_avg: {self.fanout_total/self.nodes_with_fanout}\")\n\n\nclass Dag:\n def __init__(self):\n self.children = defaultdict(LiteralMatcher)\n\n def stats(self):\n stats = DagStats()\n visited = set()\n for _, matcher in self.children.items():\n stats.literals += 1\n if matcher.wildcard:\n matcher.wildcard.accumulate_stats(stats, visited)\n for nodes in matcher.positive_values.values():\n for node in nodes:\n node.accumulate_stats(stats, visited)\n # TODO handle negatives as well\n return stats\n\n\n@total_ordering\nclass Rank:\n def __init__(self, elem):\n self.weight = len(elem)\n self.elem = elem\n\n def __eq__(self, other):\n return self.weight == other.weight and self.elem == other.elem\n\n def __lt__(self, other):\n if self.weight == other.weight:\n return self.elem > other.elem\n return self.weight > other.weight\n\n\ndef build(expr, constructor, base_nodes, these_nodes):\n # TODO need a special case for the empty formula\n if len(expr) == 1:\n return base_nodes[expr.first()]\n\n if expr in these_nodes:\n return these_nodes[expr]\n if len(expr) == 2:\n node = constructor()\n for el in expr.elements():\n base_nodes[el].children.append(node)\n node.add_link()\n return node\n\n ranks = defaultdict(list)\n sizes = []\n for c in these_nodes:\n if c.issubset(expr):\n assert len(c) < len(expr), \"exact equality handled above\"\n rank = Rank(c)\n sizes.append(rank)\n for el in c.elements():\n ranks[el].append(rank)\n heapq.heapify(sizes)\n covered = set()\n node = constructor()\n\n while len(sizes) and sizes[0].weight != 0:\n best = heapq.heappop(sizes).elem\n these_nodes[best].children.append(node)\n node.add_link()\n for el in best.elements():\n if el not in covered:\n covered.add(el)\n for rank in ranks[el]:\n rank.weight -= 1\n # TODO this repeated linear heapify is no good, we need a heap that allows us to\n # shuffle elements up and down as needed\n heapq.heapify(sizes)\n\n for el in expr.elements() - covered:\n base_nodes[el].children.append(node)\n node.add_link()\n\n return node\n\n\ndef add_literal(dag, lit):\n # all literals are built with a tally count of one, even if they're set-valued!\n node = AndNode(lit.specificity)\n node.add_link()\n dag.children[lit.name].add_values(lit.values, node)\n return node\n\n\n# TODO handle rule_tree_node with empty formula by adding props as root-level props to dag!\ndef build_dag(rule_tree_nodes):\n dag = Dag()\n lit_nodes = {}\n # obviously there are better ways of gathering the unique literals and unique clauses,\n # if performance needs to be improved...\n sorted_formulae = sorted(rule_tree_nodes, key=lambda n: n.formula)\n all_clauses = [\n c for f in sorted_formulae for c in f.formula.clauses | f.formula.shared\n ]\n for lit in {lit for c in all_clauses for lit in c.elements()}:\n lit_nodes[lit] = add_literal(dag, lit)\n clause_nodes = {}\n for clause in sorted(all_clauses):\n clause_nodes[clause] = build(\n clause, lambda: AndNode(clause.specificity()), lit_nodes, clause_nodes\n )\n form_nodes = {}\n for rule in sorted_formulae:\n node = build(rule.formula, lambda: OrNode(), clause_nodes, form_nodes)\n node.props += rule.props\n node.constraints += rule.constraints\n form_nodes[rule.formula] = node\n return dag\n","sub_path":"src/ccs/dag.py","file_name":"dag.py","file_ext":"py","file_size_in_byte":8458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"159976373","text":"import os, io\nimport numpy as np\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nimport cv2\n\nimport argparse\nfrom datetime import datetime\n\nimport models\n\n\nparser = argparse.ArgumentParser(description='Depth map prediction')\nparser.add_argument('path', type=str, action='store', help='Path to the data.')\n\nargs = parser.parse_args()\n\ndef pyplot2img(plt):\n buf = io.BytesIO()\n plt.axis('off')\n plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=-0.05)\n buf.seek(0)\n rawbuf = np.frombuffer(buf.getvalue(), dtype='uint8')\n im = cv2.imdecode(rawbuf, cv2.IMREAD_COLOR)\n buf.close()\n return im\n\n##Def block\n\n#Checkpoint path\nmodel_data_path = 'ckpt/weights.ckpt'\n\n#Net needed parameters\nheight = 228\nwidth = 304\nchannels = 3\nbatch_size = 1\n\n##Loading Weights\n\n# Create a placeholder for the input image\ninput_node = tf.placeholder(tf.float32, shape=(None, height, width, channels))\n\n# Construct the network\nnet = models.ResNet50UpProj({'data': input_node}, batch_size, 1, False)\n\nstartTime = datetime.now()\n\nsess = tf.Session()\n# Load the converted parameters\nprint('Loading the model')\nsaver = tf.train.Saver() \nsaver.restore(sess, model_data_path)\n\nprint('Time taken:', datetime.now() - startTime)\n\nDATA_PATH = args.path\nRESULT_PATH = os.path.normpath(os.path.join(DATA_PATH, 'result'))\n\nif not os.path.exists(DATA_PATH):\n os.makedirs(DATA_PATH)\nif not os.path.exists(RESULT_PATH):\n os.makedirs(RESULT_PATH)\n\nstartTime = datetime.now()\n\nfor filename in os.listdir(DATA_PATH):\n if filename.endswith('.png') or filename.endswith('.jpg'):\n img = Image.open(os.path.join(DATA_PATH, filename))\n w, h = img.size\n img = img.resize([width,height], Image.ANTIALIAS)\n img = np.array(img).astype('float32')\n img = np.expand_dims(np.asarray(img), axis = 0)\n img = np.array(img)\n pred = sess.run(net.get_output(), feed_dict={input_node: img})\n\n fig = plt.figure()\n ii = plt.imshow(pred[0,:,:,0], interpolation='nearest')\n\n res_img = pyplot2img(plt)\n res_img = cv2.resize(res_img, (w, h))\n\n res_name = os.path.join(os.path.splitext(filename)[0]+'.png')\n\n cv2.imwrite(os.path.join(RESULT_PATH, res_name), res_img)\n \nprint(\"Time taken:\", datetime.now() - startTime) ","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"639500453","text":"import os\nimport random\nimport time\nfrom lk.utils import file_utils\nfrom lk.utils.file_utils import get_filename\n\ndef getFileList(path, file_list):\n parents = os.listdir(path)\n for parent in parents:\n child = os.path.join(path, parent)\n if os.path.isdir(child):\n getFileList(child, file_list)\n else:\n if child.endswith(\"csv\") and os.path.getsize(child) < 1024 * 1024:\n try:\n print(child)\n file_list.append(child)\n except UnicodeEncodeError:\n print(\"err\")\n return\n\n\n\ndef generateFile(out_dir, src_list, level1_dirnum, level2_dirnum, dirfilenum):\n max_index = len(src_list) - 1\n for i in range(level1_dirnum):\n level1_dir = os.path.join(out_dir, str(random.randint(350, 899)))\n file_utils.mkdir(level1_dir)\n print(\"%d:%s\" % (i, level1_dir))\n for j in range(level2_dirnum + random.randint(0, 20)):\n level2_dir = os.path.join(level1_dir, str(random.randint(350, 9999)))\n file_utils.mkdir(level2_dir)\n# print(\"%d:%s\" % (j, level2_dir))\n for k in range(dirfilenum + random.randint(0, 20)):\n srcfile = file_list[random.randint(0, max_index)]\n dstfile = os.path.join(level2_dir, str(random.randint(350, 9999)) + \".csv\")\n print(\"%s->%s\" % (srcfile, dstfile))\n file_utils.copy(srcfile, dstfile)\n# print(\"%d:%s\" % (k, filepath))\n return\n \nif __name__ == '__main__':\n file_list = []\n getFileList(\"/home/samba/ai/tmp/elecm\", file_list)\n generateFile(\"/home/samba/ai/PrivateElecAi/data/dataset/\", file_list, 57, 100, 100)\n# for i in range(len(file_list)):\n# print(file_list[random.randint(0, max_index)])\n","sub_path":"src/tpson/file_generator/elec_dataset.py","file_name":"elec_dataset.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"2451681","text":"import re\nimport datetime\nfrom jsonpickle.handlers import BaseHandler\n\nclass DatetimeHandler(BaseHandler):\n ### better represention of datetime, see https://github.com/jsonpickle/jsonpickle/issues/109 ###\n def flatten(self, obj, data):\n x = {\"date/time\": str(obj)}\n return x\n\nclass regexMatchHandler(BaseHandler):\n ### better represention of datetime, see https://github.com/jsonpickle/jsonpickle/issues/109 ###\n def flatten(self, obj, data):\n return {\n \"py/object\": \"_sre.SRE_Match\",\n \"match\": obj.group(0),\n \"groups\": obj.groups(),\n \"span\": obj.span()\n }\n\nhandlers = [\n {\n 'type':datetime.date,\n 'handler':DatetimeHandler\n },\n {\n 'type':datetime.time,\n 'handler':DatetimeHandler\n },\n {\n 'type':datetime.datetime,\n 'handler':DatetimeHandler\n },\n {\n 'type':type(re.search('','')),\n 'handler':regexMatchHandler\n },\n]","sub_path":"src/python/customHandlers.py","file_name":"customHandlers.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"255277215","text":"from django.utils.functional import lazy\nfrom feedly.structures.hash import BaseRedisHashCache\nfrom feedly.structures.list import BaseRedisListCache\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass RedisSortedSetCache(BaseRedisListCache, BaseRedisHashCache):\n key_format = 'redis:sorted_set_cache:%s'\n\n def count(self):\n '''\n Returns the number of elements in the sorted set\n '''\n key = self.get_key()\n redis_result = self.redis.zcount(key, '-inf', '+inf')\n #lazily convert this to an int, this keeps it compatible with distributed connections\n redis_count = lambda: int(redis_result)\n lazy_factory = lazy(redis_count, int, long)\n lazy_object = lazy_factory()\n return lazy_object\n\n def add_many(self, value_score_pairs):\n '''\n value_key_pairs\n '''\n key = self.get_key()\n results = []\n\n def _add_many(redis, value_score_pairs):\n for value, score in value_score_pairs:\n logger.debug('adding to %s with value %s and score %s',\n key, value, score)\n result = redis.zadd(key, value, score)\n results.append(result)\n\n #start a new map redis or go with the given one\n self._map_if_needed(_add_many, value_score_pairs)\n\n return results\n\n def remove_many(self, values):\n '''\n values\n '''\n key = self.get_key()\n results = []\n\n def _remove_many(redis, values):\n for value in values:\n logger.debug('removing value %s from %s', value, key)\n result = redis.zrem(key, value)\n results.append(result)\n\n #start a new map redis or go with the given one\n self._map_if_needed(_remove_many, values)\n\n return results\n\n def contains(self, value):\n '''\n Uses zscore to see if the given activity is present in our sorted set\n '''\n key = self.get_key()\n result = self.redis.zscore(key, value)\n activity_found = bool(result)\n return activity_found\n\n def trim(self):\n '''\n Trim the sorted set to max length\n zremrangebyscore\n '''\n key = self.get_key()\n end = (self.max_length * -1) - 1\n removed = self.redis.zremrangebyrank(key, 0, end)\n logger.info('cleaning up the sorted set %s to a max of %s items' %\n (key, self.max_length))\n return removed\n","sub_path":"feedly/structures/sorted_set.py","file_name":"sorted_set.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"306238872","text":"# -*- coding: utf-8 -*-\nimport os\nimport shutil\nimport subprocess\nfrom datetime import datetime, timedelta\nfrom threading import Thread\nimport logging\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.contrib.auth.models import Group\nfrom django.core.mail import EmailMessage\nfrom django.core.urlresolvers import reverse\nfrom django.template import Context\nfrom django.template.defaultfilters import slugify\nfrom django.template.loader import get_template\nfrom django.utils.translation import gettext as _\nfrom permission_backend_nonrel.models import UserPermissionList, GroupPermissionList\n\nfrom ikwen.accesscontrol.backends import UMBRELLA\nfrom ikwen.accesscontrol.models import SUDO, Member\nfrom ikwen.billing.models import Invoice, PaymentMean, InvoicingConfig, SupportCode\nfrom ikwen.billing.utils import get_next_invoice_number\nfrom ikwen.conf.settings import STATIC_ROOT, STATIC_URL, CLUSTER_MEDIA_ROOT, CLUSTER_MEDIA_URL\nfrom ikwen.core.models import Service, SERVICE_DEPLOYED, Application\nfrom ikwen.core.tools import generate_django_secret_key, generate_random_key, reload_server\nfrom ikwen.core.utils import add_database_to_settings, add_event, get_mail_content, \\\n get_service_instance\nfrom ikwen.flatpages.models import FlatPage\nfrom ikwen.partnership.models import PartnerProfile\nfrom ikwen.theming.models import Template, Theme\nfrom ikwen_foulassi.foulassi.models import SchoolConfig\n\n\n\nlogger = logging.getLogger('ikwen')\n\n\nif getattr(settings, 'LOCAL_DEV', False):\n CLOUD_HOME = '/home/komsihon/PycharmProjects/CloudTest/'\nelse:\n CLOUD_HOME = '/home/ikwen/Cloud/'\n\nCLOUD_FOLDER = CLOUD_HOME + 'Foulassi/'\nSMS_API_URL = 'http://websms.mobinawa.com/http_api?action=sendsms&username=675187705&password=depotguinness&from=$label&to=$recipient&msg=$text'\n\n# Calculate default back to school date; 1st monday of September\nnow = datetime.now()\nyear = now.year\nback_to_school_date = datetime(year, 9, 1, 7, 30)\n\nwhile back_to_school_date.weekday() != 0:\n back_to_school_date += timedelta(days=1)\n\n\nclass DeploymentForm(forms.Form):\n \"\"\"\n Deployment form of a platform\n \"\"\"\n partner_id = forms.CharField(max_length=24, required=False) # Service ID of the partner retail platform\n customer_id = forms.CharField(max_length=24)\n project_name = forms.CharField(max_length=30)\n billing_plan_id = forms.CharField(max_length=24)\n bundle_id = forms.CharField(max_length=24, required=False)\n setup_cost = forms.FloatField(required=False)\n monthly_cost = forms.FloatField(required=False)\n\n\ndef deploy(member, project_name, billing_plan, theme, monthly_cost, invoice_entries, partner_retailer=None):\n app = Application.objects.using(UMBRELLA).get(slug='foulassi')\n project_name_slug = slugify(project_name) # Eg: slugify('Great School') = 'great-school'\n ikwen_name = project_name_slug.replace('-', '') # Eg: great-school --> 'greatschool'\n pname = ikwen_name\n i = 0\n while True:\n try:\n Service.objects.using(UMBRELLA).get(project_name_slug=pname)\n i += 1\n pname = \"%s%d\" % (ikwen_name, i)\n except Service.DoesNotExist:\n ikwen_name = pname\n break\n api_signature = generate_random_key(30, alpha_num=True)\n while True:\n try:\n Service.objects.using(UMBRELLA).get(api_signature=api_signature)\n api_signature = generate_random_key(30, alpha_num=True)\n except Service.DoesNotExist:\n break\n database = ikwen_name\n domain = 'go.' + pname + '.ikwen.com'\n domain_type = Service.SUB\n is_naked_domain = False\n url = 'http://go.ikwen.com/' + pname\n admin_url = url + '/ikwen/staffRouter/'\n now = datetime.now()\n expiry = now + timedelta(days=60)\n\n # Create a copy of template application in the Cloud folder\n app_folder = CLOUD_HOME + '000Tpl/AppSkeleton'\n website_home_folder = CLOUD_FOLDER + ikwen_name\n media_root = CLUSTER_MEDIA_ROOT + ikwen_name + '/'\n media_url = CLUSTER_MEDIA_URL + ikwen_name + '/'\n images_folder = CLOUD_FOLDER + '000Tpl/images/000Default'\n if theme:\n theme_images_folder = CLOUD_FOLDER + '000Tpl/images/%s/%s' % (theme.template.slug, theme.slug)\n if os.path.exists(theme_images_folder):\n images_folder = theme_images_folder\n if os.path.exists(images_folder):\n if os.path.exists(media_root):\n shutil.rmtree(media_root)\n shutil.copytree(images_folder, media_root)\n logger.debug(\"Media folder '%s' successfully created from '%s'\" % (media_root, images_folder))\n elif not os.path.exists(media_root):\n os.makedirs(media_root)\n logger.debug(\"Media folder '%s' successfully created empty\" % media_root)\n icons_folder = media_root + 'icons'\n if not os.path.exists(icons_folder):\n os.makedirs(icons_folder)\n if os.path.exists(website_home_folder):\n shutil.rmtree(website_home_folder)\n shutil.copytree(app_folder, website_home_folder)\n logger.debug(\"Service folder '%s' successfully created\" % website_home_folder)\n\n settings_template = 'foulassi/cloud_setup/settings.html'\n\n service = Service(member=member, app=app, project_name=project_name, project_name_slug=ikwen_name, domain=domain,\n database=database, url=url, domain_type=domain_type, expiry=expiry, admin_url=admin_url,\n billing_plan=billing_plan, billing_cycle=Service.YEARLY, monthly_cost=monthly_cost,\n version=Service.TRIAL, api_signature=api_signature, home_folder=website_home_folder,\n settings_template=settings_template, retailer=partner_retailer)\n service.save(using=UMBRELLA)\n logger.debug(\"Service %s successfully created\" % pname)\n\n # Re-create settings.py file as well as apache.conf file for the newly created project\n secret_key = generate_django_secret_key()\n allowed_hosts = '\"go.ikwen.com\"'\n settings_tpl = get_template(settings_template)\n settings_context = Context({'secret_key': secret_key, 'ikwen_name': ikwen_name, 'service': service,\n 'static_root': STATIC_ROOT, 'static_url': STATIC_URL,\n 'media_root': media_root, 'media_url': media_url,\n 'allowed_hosts': allowed_hosts, 'debug': getattr(settings, 'DEBUG', False)})\n settings_file = website_home_folder + '/conf/settings.py'\n fh = open(settings_file, 'w')\n fh.write(settings_tpl.render(settings_context))\n fh.close()\n logger.debug(\"Settings file '%s' successfully created\" % settings_file)\n\n # Import template database and set it up\n db_folder = CLOUD_FOLDER + '000Tpl/DB/000Default'\n if theme:\n theme_db_folder = CLOUD_FOLDER + '000Tpl/DB/%s/%s' % (theme.template.slug, theme.slug)\n if os.path.exists(theme_db_folder):\n db_folder = theme_db_folder\n\n host = getattr(settings, 'DATABASES')['default'].get('HOST', '127.0.0.1')\n from ikwen.core.log import ikwen_error_log_filename\n eh = open(ikwen_error_log_filename, 'a')\n subprocess.call(['mongorestore', '--host', host, '-d', database, db_folder], stderr=eh)\n logger.debug(\"Database %s successfully created on host %s from %s\" % (database, host, db_folder))\n\n add_database_to_settings(database)\n for group in Group.objects.using(database).all():\n try:\n gpl = GroupPermissionList.objects.using(database).get(group=group)\n group.delete()\n group.save(using=database) # Recreate the group in the service DB with a new id.\n gpl.group = group # And update GroupPermissionList object with the newly re-created group\n gpl.save(using=database)\n except GroupPermissionList.DoesNotExist:\n group.delete()\n group.save(using=database) # Re-create the group in the service DB with anyway.\n new_sudo_group = Group.objects.using(database).get(name=SUDO)\n\n for s in member.get_services():\n db = s.database\n add_database_to_settings(db)\n collaborates_on_fk_list = member.collaborates_on_fk_list + [service.id]\n customer_on_fk_list = member.customer_on_fk_list + [service.id]\n group_fk_list = member.group_fk_list + [new_sudo_group.id]\n Member.objects.using(db).filter(pk=member.id).update(collaborates_on_fk_list=collaborates_on_fk_list,\n customer_on_fk_list=customer_on_fk_list,\n group_fk_list=group_fk_list)\n\n member.collaborates_on_fk_list = collaborates_on_fk_list\n member.customer_on_fk_list = customer_on_fk_list\n member.group_fk_list = group_fk_list\n\n member.is_iao = True\n member.save(using=UMBRELLA)\n\n member.is_bao = True\n member.is_staff = True\n member.is_superuser = True\n\n app.save(using=database)\n member.save(using=database)\n logger.debug(\"Member %s access rights successfully set for service %s\" % (member.username, pname))\n\n from ikwen.billing.mtnmomo.views import MTN_MOMO\n # Copy payment means to local database\n for mean in PaymentMean.objects.using(UMBRELLA).all():\n if mean.slug == MTN_MOMO:\n mean.is_main = True\n mean.is_active = True\n else:\n mean.is_main = False\n mean.is_active = True\n mean.save(using=database)\n logger.debug(\"PaymentMean %s created in database: %s\" % (mean.slug, database))\n\n # Copy themes to local database\n webnode = Application.objects.using(UMBRELLA).get(slug='webnode')\n template_list = list(Template.objects.using(UMBRELLA).filter(app=webnode))\n for template in template_list:\n template.save(using=database)\n for th in Theme.objects.using(UMBRELLA).filter(template__in=template_list):\n th.save(using=database)\n logger.debug(\"Templates and themes successfully saved for service: %s\" % pname)\n\n FlatPage.objects.using(database).get_or_create(url=FlatPage.AGREEMENT, title=FlatPage.AGREEMENT)\n FlatPage.objects.using(database).get_or_create(url=FlatPage.LEGAL_MENTIONS, title=FlatPage.LEGAL_MENTIONS)\n\n # Add member to SUDO Group\n obj_list, created = UserPermissionList.objects.using(database).get_or_create(user=member)\n obj_list.group_fk_list.append(new_sudo_group.id)\n obj_list.save(using=database)\n logger.debug(\"Member %s successfully added to sudo group for service: %s\" % (member.username, pname))\n\n mail_signature = \"%s \" \\\n \"%s \" % (project_name, 'http://' + domain, domain)\n config = SchoolConfig(service=service, ikwen_share_rate=billing_plan.tx_share_rate,\n theme=theme, currency_code='XAF', currency_symbol='XAF', decimal_precision=0,\n signature=mail_signature, company_name=project_name, contact_email=member.email,\n contact_phone=member.phone, sms_api_script_url=SMS_API_URL,\n back_to_school_date=back_to_school_date)\n config.save(using=UMBRELLA)\n base_config = config.get_base_config()\n base_config.save(using=UMBRELLA)\n\n service.save(using=database)\n theme.save(using=database) # Causes theme to be routed to the newly created database\n config.save(using=database)\n logger.debug(\"Configuration successfully added for service: %s\" % pname)\n\n # Apache Server cloud_setup\n go_apache_tpl = get_template('foulassi/cloud_setup/apache.conf.local.html')\n apache_context = Context({'is_naked_domain': is_naked_domain, 'domain': domain, 'ikwen_name': ikwen_name})\n fh = open(website_home_folder + '/go_apache.conf', 'w')\n fh.write(go_apache_tpl.render(apache_context))\n fh.close()\n\n vhost = '/etc/apache2/sites-enabled/go_ikwen/' + pname + '.conf'\n subprocess.call(['sudo', 'ln', '-sf', website_home_folder + '/go_apache.conf', vhost])\n logger.debug(\"Apache Virtual Host '%s' successfully created\" % vhost)\n\n # Send notification and Invoice to customer\n number = get_next_invoice_number()\n now = datetime.now()\n invoice_total = 0\n for entry in invoice_entries:\n invoice_total += entry.total\n invoice = Invoice(subscription=service, member=member, amount=invoice_total, number=number, due_date=expiry,\n last_reminder=now, reminders_sent=1, is_one_off=True, entries=invoice_entries,\n months_count=billing_plan.setup_months_count)\n invoice.save(using=UMBRELLA)\n vendor = get_service_instance()\n\n from daraja.models import DARAJA\n if member != vendor.member:\n add_event(vendor, SERVICE_DEPLOYED, member=member, object_id=invoice.id)\n if partner_retailer and partner_retailer.app.slug != DARAJA:\n partner_profile = PartnerProfile.objects.using(UMBRELLA).get(service=partner_retailer)\n try:\n Member.objects.get(pk=member.id)\n except Member.DoesNotExist:\n member.is_iao = False\n member.is_bao = False\n member.is_staff = False\n member.is_superuser = False\n member.save(using='default')\n service.save(using='default')\n config.save(using='default')\n sender = '%s ' % (partner_profile.company_name, partner_retailer.domain)\n sudo_group = Group.objects.get(name=SUDO)\n ikwen_sudo_gp = Group.objects.using(UMBRELLA).get(name=SUDO)\n add_event(vendor, SERVICE_DEPLOYED, group_id=ikwen_sudo_gp.id, object_id=invoice.id)\n else:\n sender = 'ikwen Foulassi '\n sudo_group = Group.objects.using(UMBRELLA).get(name=SUDO)\n add_event(vendor, SERVICE_DEPLOYED, group_id=sudo_group.id, object_id=invoice.id)\n invoice_url = 'http://www.ikwen.com' + reverse('billing:invoice_detail', args=(invoice.id,))\n subject = _(\"Your platform %s was created\" % project_name)\n html_content = get_mail_content(subject, template_name='core/mails/service_deployed.html',\n extra_context={'service_activated': service, 'invoice': invoice,\n 'member': member, 'invoice_url': invoice_url})\n msg = EmailMessage(subject, html_content, sender, [member.email])\n bcc = ['contact@ikwen.com', 'support@ikwen.com']\n if vendor.config.contact_email:\n bcc.append(vendor.config.contact_email)\n msg.bcc = list(set(bcc))\n msg.content_subtype = \"html\"\n Thread(target=lambda m: m.send(), args=(msg, )).start()\n logger.debug(\"Notice email submitted to %s\" % member.email)\n Thread(target=reload_server).start()\n logger.debug(\"Apache Scheduled to reload in 5s\")\n return service\n","sub_path":"foulassi/cloud_setup.py","file_name":"cloud_setup.py","file_ext":"py","file_size_in_byte":14690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"382481635","text":"import math\n\nfrom think import Location, Module\n\n\nclass Mouse(Module):\n\n def __init__(self, hands, vision):\n super().__init__(\"mouse\", hands.agent)\n self.hands = hands\n self.vision = vision\n self.worker = hands.worker\n self.loc = Location(0, 0)\n self.move_fns = []\n self.click_fns = []\n self.init_time = .050\n self.burst_time = .050\n self.fitts_coeff = .100\n self.min_fitts_time = .100\n\n def add_move_fn(self, fn):\n self.move_fns.append(fn)\n return self\n\n def add_click_fn(self, fn):\n self.click_fns.append(fn)\n return self\n\n def fitts(self, coeff, d, w):\n if w <= 0:\n w = 1 # vis.Vision.pixel_to_degree(1.0)\n f = math.log((d / w) + .5) / math.log(2)\n return max(self.min_fitts_time, coeff * f)\n\n # this is only movement, what about all time?\n def movement_time(self, from_loc, to_area):\n d = self.vision.display.pixels_to_inches(from_loc.distance_to(to_area))\n w = self.vision.display.pixels_to_inches(\n to_area.approach_width_from(from_loc))\n return self.init_time + max(self.burst_time, self.fitts(self.fitts_coeff, d, w))\n\n def calc_move_time(self, loc1, loc2):\n d = self.vision.display.pixels_to_degrees(loc1.distance_to(loc2))\n w = self.vision.display.pixels_to_degrees(\n loc2.approach_width_from(loc1))\n return self.init_time + max(self.burst_time, self.fitts(self.fitts_coeff, d, w))\n\n def start_move_to(self, visual):\n self.worker.acquire()\n self.think(\"move mouse {}\".format(visual))\n self.log(\"moving mouse {}\".format(visual))\n self.vision.start_encode(visual)\n duration = self.calc_move_time(self.loc, visual)\n\n def fn():\n self.loc = visual\n for fn in self.move_fns:\n fn(visual)\n self.worker.run(duration, \"moved mouse {}\".format(visual), fn)\n\n def move_to(self, visual):\n self.start_move_to(visual)\n self.worker.wait_until_free()\n return self\n\n def calc_click_time(self):\n return self.init_time + 2 * self.burst_time\n\n def start_click(self):\n self.worker.acquire()\n self.think(\"click mouse\")\n self.log(\"clicking mouse\")\n duration = self.calc_click_time()\n\n def fn():\n if self.loc is not None:\n for visual in self.vision.visuals:\n if visual.contains(self.loc):\n for fn in self.click_fns:\n fn(visual)\n self.worker.run(duration, \"click mouse {}\".format(self.loc), fn)\n\n def click(self):\n self.start_click()\n self.worker.wait_until_free()\n\n def point_and_click(self, visual):\n self.move_to(visual)\n self.vision.get_encoded()\n self.click()\n","sub_path":"think/modules/mouse.py","file_name":"mouse.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"56348395","text":"def mdc(m, n):\n while m%n != 0:\n oldm = m\n oldn = n\n m = oldn\n n = oldm%oldn\n return n\n\ndef mesmaFracao(f1, f2):\n return (f1.getNum() == f2.getNum()) and (f1.getDen() == f2.getDen()) \n\nclass Fracao:\n \n def __init__(self, num, den):\n self.__num = num \n self.__den = den \n\n def __str__(self):\n return str(self.__num) + \"/\" + str(self.__den)\n\n def getNum(self):\n return self.__num\n\n def getDen(self):\n return self.__den \n\n def simplifica(self):\n divComum = mdc(self.__num, self.__den)\n self.__num = self.__num // divComum\n self.__den = self.__den // divComum \n\n def __add__(self,outraFrac):\n novoNum = self.__num * outraFrac.getDen() + self.__den * outraFrac.getNum()\n novoDen = self.__den * outraFrac.getDen()\n divComum = mdc(novoNum, novoDen)\n novaFracao = Fracao(novoNum//divComum, novoDen//divComum) \n if novaFracao.getNum() / novaFracao.getDen() < 1:\n return novaFracao\n\n elif novaFracao.getNum() % novaFracao.getDen() == 0:\n return novaFracao.getNum() / novaFracao.getDen()\n\n else:\n inteiro = novaFracao.getNum() // novaFracao.getDen()\n newNum = novaFracao.getNum() - inteiro * novaFracao.getDen()\n F = fracaoMista(inteiro, newNum, novaFracao.getDen())\n return F\n \nclass fracaoMista(Fracao):\n\n def __init__(self, parteInteira, num, den):\n super().__init__(num, den)\n self.__parteInteira = parteInteira\n\n def getPartInteira(self):\n return self.__parteInteira\n\n def __str__(self):\n return str(self.__parteInteira) + ' ' + str(self.getNum()) + '/' + str(self.getDen())\n\n def __add__(self, secunfunc):\n novoNum1 = self.getPartInteira() * self.getDen() + self.getNum()\n PrimeiraFracao = Fracao(novoNum1, self.getDen())\n novoNum2 = secunfunc.getPartInteira() * secunfunc.getDen() + secunfunc.getNum()\n SecundaFracao = Fracao(novoNum2, secunfunc.getDen())\n return PrimeiraFracao + SecundaFracao\n \n\nfrac1 = Fracao (7, 6)\nfrac2 = Fracao(13, 7)\nfrac3 = frac1 + frac2\nprint(frac3)\n\nprint()\n\nfrac1 = Fracao (1, 3)\nfrac2 = Fracao(2, 3)\nfrac3 = frac1 + frac2\nprint(frac3)\n\nprint()\n\nfrac1 = fracaoMista (3, 1, 2)\nfrac2 = fracaoMista (4, 2, 3)\nfrac3 = frac1 + frac2\n\nprint(frac3)","sub_path":"Trabalho-6/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"166895319","text":"from measurement import Helper\nfrom measurement import MeasurementCsvAnalyzer\nfrom client import ApiClient\nfrom common import Logger\nfrom datetime import datetime, timedelta\nimport os\nimport csv\n\nclass CommunityMeteorologyHelper(Helper):\n \n def __init__(self, api_client:ApiClient, logger:Logger) -> None:\n self.__api_client__ :ApiClient = api_client\n self.__logger__ :Logger = logger\n\n def get_extension(self) -> str:\n return '.csv'\n\n def get_section_size(self):\n return 20\n\n def get_thread_number(self):\n return 30\n\n def get_usable_file_content(self, file_path:str) -> list:\n # Check file exists\n if not os.path.isfile(file_path):\n raise Exception('File does not exists')\n\n # Open file\n with open(file_path) as csv_file:\n reader = csv.reader(csv_file, delimiter=';')\n return list(reader)[1:]\n\n def get_data_content(self, row:str) -> dict:\n items = dict()\n town_id = int(row[1])\n station_id = row[2]\n magnitude_id = row[3]\n year = int(row[5])\n month = int(row[6])\n day = int(row[7])\n date = datetime(year, month, day)\n for hour in range(0, 24):\n index = 8 + (hour * 2)\n validation_code = row[index + 1].strip()\n if validation_code == 'N':\n break\n data = float(row[index])\n measurement_datetime = date + timedelta(hours=hour + 1)\n item_key = self. __get__insertable__object__key__(town_id, measurement_datetime,magnitude_id,station_id)\n items[item_key] = self.__get_insertable_object__(town_id, measurement_datetime,magnitude_id,station_id, data, validation_code) \n return items\n\n def upload_data(self, items_to_upload:list) -> None:\n # Upload items to API\n self.__api_client__.create_measurements(items_to_upload)\n\n def pre_upload(self, file_path:str) -> None:\n # Analyze data, upload missing stations and magnitudes, get dates\n measurement_analyzer : MeasurementAnalyzer = MeasurementCsvAnalyzer(self.__logger__)\n measurement_analyzer.analyze_file(file_path)\n\n # Get data from analyzer\n stations :list = measurement_analyzer.stations\n magnitudes :list = measurement_analyzer.magnitudes\n first_date :datetime = measurement_analyzer.first_date\n last_date :datetime = measurement_analyzer.last_date\n\n # Check the existence of stations and magnitudes\n missing_stations = self.__api_client__.station_existence(list(stations))\n missing_magnitudes = self.__api_client__.magnitude_existence(list(magnitudes))\n\n # Create missing station and magnitudes\n self.__api_client__.create_stations(missing_stations)\n self.__api_client__.create_magnitudes(missing_magnitudes)\n\n def __get__insertable__object__key__(self, town_id:int, datetime:datetime, magnitude_id:int, station_id:int):\n return f'{town_id}{datetime.strftime(\"%Y-%m-%d %H:%M:%S\")}{station_id}{magnitude_id}'\n\n def __get_insertable_object__(self, town_id:int, datetime:datetime, magnitude_id:int, station_id:int, data:float, validation_code:str):\n return {\"townId\": town_id, \"datetime\": datetime.strftime(\"%Y-%m-%d %H:%M:%S\"),\"magnitudeId\": magnitude_id, \"stationId\": station_id, \"data\": data, \"validationCode\": validation_code}\n","sub_path":"Borealis.Parser/meteorology/community_meteorology_helper.py","file_name":"community_meteorology_helper.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"570288221","text":"'''\nImplement an algorithm to determine if a string has all unique characters.\nWhat if you cannot use additional data structures? \n'''\n\n\ndef is_unique_1(string):\n chars = [False for i in range(256)]\n for c in string:\n if chars[ord(c) - 1]:\n return False\n else:\n chars[ord(c) - 1] = True\n\n return True\n\n\ndef is_unique_2(string):\n chars = set()\n for c in string:\n if c in chars:\n return False\n else:\n chars.add(c)\n return True\n\n\nif __name__ == \"__main__\":\n print(is_unique_2(\"OMARR\"))\n","sub_path":"CTCI/arrays_strings/is_unique.py","file_name":"is_unique.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"393656334","text":"import QieyunEncoder\nimport sys\nfrom xml.dom.minidom import parseString\n\nwith open('index.html') as f:\n\tfor i, line in enumerate(f):\n\t\ttry:\n\t\t\troot = parseString(line)\n\t\texcept Exception as e:\n\t\t\tprint('Line', i, e, file=sys.stderr)\n\t\t\texit(1)\n\n\t\tfor rt in root.getElementsByTagName('rt'):\n\t\t\t描述 = rt.firstChild.data\n\t\t\ttry:\n\t\t\t\t# this function will perform checks on 描述\n\t\t\t\tQieyunEncoder.音韻地位.from描述(描述)\n\t\t\texcept Exception as e:\n\t\t\t\tprint(描述, e, file=sys.stderr)\n\t\t\t\texit(1)\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"298038388","text":"import discord\nimport os\nimport requests\nimport json\nimport random\nfrom replit import db\nimport handlers\nfrom keep_alive import keep_alive\n\nclient = discord.Client()\nlistener = \"$\"\n\n@client.event\nasync def on_ready():\n print('We have logged in as {0.user}'.format(client))\n \n\n@client.event\nasync def on_message(message):\n if message.author == client:\n return \n\n msg = message.content\n\n if msg.startswith(listener+'pokemon show'):\n name = msg.split()[2]\n pkmn = handlers.get_pokemon(name)\n if pkmn == None:\n await message.reply(\"Oak's words echoed... There's a time and place for everything, but not now.\")\n else:\n embed = discord.Embed(title=pkmn[0]) #https://pokeapi.co/api/v2/version/1/\n embed.set_image(url=pkmn[1])\n response = await message.reply(embed = embed)\n #response = await message.reply(\"*\"+pkmn[0]+\"*\")\n #pic = (await message.channel.send(\"\"+pkmn[1]).id)\n await response.add_reaction(\"⬅️\")\n await response.add_reaction(\"➡️\")\n return\n if msg.startswith(listener+'misu'):\n await message.reply(handlers.get_misu())\n return\n if msg.startswith(listener+'help'):\n await message.reply(\"All right! Check your private messages.\")\n await message.author.send(handlers.get_commands())\n return\n \n \n \n\nkeep_alive()\nclient.run(os.getenv('TOKEN'))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"402039881","text":"#(4) 하노이의 탑\n\ndef hanoi(num, start, to, mid, answer):\n if num == 1:\n return answer.append([start, to])\n hanoi(num-1, start, mid, to, answer)\n answer.append([start, to])\n hanoi(num-1, mid, to, start, answer)\n \ndef solution(n):\n answer = []\n hanoi(n, 1, 3, 2, answer)\n return answer\n\t\n#다른 코드\n'''\n## first\ndef hanoi(n):\n\n def _hanoi(m, s, b, d):\n if m == 1:\n yield [s, d]\n else:\n yield from _hanoi(m-1, s, d, b)\n yield [s, d]\n yield from _hanoi(m-1, b, s, d)\n\n ans = list(_hanoi(n, 1, 2, 3))\n return ans\n\n\t\n## second\ndef move_n_disk(n, i, f):\n if n==1: return [[i, f]]\n return move_n_disk(n-1, i, 6-i-f) + move_n_disk(1, i, f) + move_n_disk(n-1, 6-i-f, f)\n\ndef hanoi(n):\n answer = move_n_disk(n, 1, 3)\n return answer\n'''","sub_path":"level3/level3_ex04.py","file_name":"level3_ex04.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"503166605","text":"import numpy as np\r\nimport sounddevice as sd\r\nfrom scipy.io.wavfile import write\r\n\r\ndef main():\r\n\r\n fs = 44100 # Частота дискретизации\r\n seconds = 3 # Продолжительность записи\r\n print('Начать')\r\n myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=1)\r\n sd.wait() # Дождитесь окончания записи\r\n write('output.wav', fs, myrecording) # Сохранить как WAV файл\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"waves.py","file_name":"waves.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"304664238","text":" #Function definition \ndef collatz(number):\n if number % 2 == 0:\n return number // 2\n else:\n return 3*number + 1\n return result\n #Ask for input integer\ntry:\n n = int(input(\"Enter number: \"))\n while n != 1:\n print(n)\n n = collatz(abs(n))\n if n == 1:\n print(n)\nexcept ValueError:\n print('Error: Try again.')\n \n \n","sub_path":"atbswp-PROGRAM#1 collatz.py","file_name":"atbswp-PROGRAM#1 collatz.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"333669338","text":"\"\"\"\nHelper funcs for tests\n\"\"\"\nimport os\nfrom inputfiles import get_filepath\nfrom junit2htmlreport import runner\n\n\ndef run_runner(tmpdir, filename):\n \"\"\"\n Run the junit2html program against the given report and produce a html doc\n :param tmpdir:\n :param filename:\n :return:\n \"\"\"\n testfile = get_filepath(filename=filename)\n outfile = os.path.join(tmpdir.strpath, \"report.html\")\n runner.run([testfile, outfile])\n assert os.path.exists(outfile)\n\n\ndef test_runner_simple(tmpdir):\n \"\"\"\n Test the stand-alone app with a simple fairly empty junit file\n :param tmpdir: py.test tmpdir fixture\n :return:\n \"\"\"\n run_runner(tmpdir, \"junit-simple_suites.xml\")\n","sub_path":"junit2htmlreport/tests/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"387195376","text":"from collections import defaultdict\nimport plotly.plotly as py\nimport plotly.graph_objs as go\nimport numpy as np\n\nwith open('./branches_report.txt') as f:\n lines = f.readlines()\n\ntrials = defaultdict(list)\nfor line in lines:\n values = line.split(',')\n bytes_used = float(values[4])\n num_nodes = float(values[5])\n trials[num_nodes].append(bytes_used / num_nodes)\n\nx = sorted(trials.keys())\ny = []\nerror_y = []\nfor num_nodes in x:\n bytes_list = np.array(trials[num_nodes])\n mean = np.mean(bytes_list)\n std = np.std(bytes_list)\n y.append(mean)\n error_y.append(std)\n\n\ndata = [\n go.Scatter(\n x=x,\n y=y,\n error_y=dict(\n type='data',\n array=error_y,\n visible=True\n )\n )\n]\n\nlayout = go.Layout(\n title='Performance of Git Branches',\n xaxis=dict(\n title='Number of Branches',\n ),\n yaxis=dict(\n title='Bytes of Overhead Per Branch'\n )\n)\n\nfig = go.Figure(data=data, layout=layout)\nplot_url = py.plot(fig, filename='branch-bytes')\n","sub_path":"branches_chart.py","file_name":"branches_chart.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"530412739","text":"'''\nCreated on 5 May 2011\n\n@author: ms705\n'''\n\nimport ciel\nimport logging\nimport subprocess\n\nclass SarProfiler:\n\n def __init__(self, blockstore):\n \n self.proc = None\n self.test = False\n \n if not self.test:\n self.test = test_profiler([\"test\", \"-f\", \"/usr/lib/sysstat/sadc\"], \"sar\")\n if not self.test:\n ciel.log(\"Profiler test failed, is sar installed?\", \"PROFILER\", logging.WARNING)\n \n \n def start(self, outputfile):\n ciel.log(\"Profiler logging to %s\" % outputfile, \"PROFILER\", logging.INFO)\n dn = open(\"/dev/null\", \"w\")\n args = [\"/usr/lib/sysstat/sadc\", \"-S\", \"DISK\", \"1\", outputfile]\n self.proc = subprocess.Popen(args, stdout=dn)\n \n def stop(self):\n ciel.log(\"Profiler stopping\", \"PROFILER\", logging.INFO)\n self.proc.terminate()\n self.proc.wait()\n \ndef test_profiler(args, friendly_name):\n try:\n proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n (outstr, errstr) = proc.communicate()\n if proc.returncode == 0:\n ciel.log.error(\"Successfully tested %s: executed '%s'\" % (friendly_name, multi_to_single_line(outstr)), \"PROFILER\", logging.INFO)\n return True\n else:\n ciel.log.error(\"Can't run %s: returned %d, stdout: '%s', stderr: '%s'\" % (friendly_name, proc.returncode, outstr, errstr), \"PROFILER\", logging.WARNING)\n return False\n except Exception as e:\n ciel.log.error(\"Can't run %s: exception '%s'\" % (friendly_name, e), \"PROFILER\", logging.WARNING)\n return False\n\ndef multi_to_single_line(s):\n lines = s.split(\"\\n\")\n lines = filter(lambda x: len(x) > 0, lines)\n s = \" // \".join(lines)\n if len(s) > 100:\n s = s[:99] + \"...\"\n return s\n","sub_path":"src/python/skywriting/runtime/util/profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"332103715","text":"from WebsiteZiroom import *\nfrom EmailSender import *\nimport schedule\nimport time\n\nREFERSH_INTERVAL = 60\nHOME_SPIDER = None\nOLD_ALL_HOUSE_LIST = []\n\n\ndef check_and_send_ziroom():\n global HOME_SPIDER, OLD_ALL_HOUSE_LIST\n print(time.strftime(\"%Y-%m-%d %H:%M:%S is running\", time.localtime()))\n all_house_list, res = HOME_SPIDER.get_all_house_list()\n if res is False:\n print(\"Get all houses error\")\n return False\n if len(OLD_ALL_HOUSE_LIST) < 1:\n OLD_ALL_HOUSE_LIST = all_house_list\n return True\n new_houses = set(all_house_list) - set(OLD_ALL_HOUSE_LIST)\n for new_house in new_houses:\n try:\n sender = EmailSender()\n sender.default_login()\n sender.ziroom_send_house_link(new_house)\n print(new_house)\n except Exception as e:\n print('SMTP connected error: ' + repr(e))\n return False\n return True\n\n\nload_email_configure()\nHOME_SPIDER = ZiroomSpider(TARGET_URL)\ncheck_and_send_ziroom()\nschedule.every(REFERSH_INTERVAL).seconds.do(check_and_send_ziroom)\nwhile True:\n schedule.run_pending()\n time.sleep(1)\n\n","sub_path":"code/MainZiroom.py","file_name":"MainZiroom.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"179863374","text":"# coding=utf-8\n\nmargin = 3\n\n\ndef computar_maximos_bp(data):\n # busco el maximo\n max_value = -1e5\n\n for i in range(len(data[\"abs\"])):\n max_value = max(max_value, data[\"abs\"][i])\n f1 = -1\n f2 = -1\n\n for i in range(len(data[\"abs\"])):\n if f1 == -1 and data[\"abs\"][i] > max_value - margin:\n f1 = data[\"f\"][i]\n elif f1 != -1 and f2 == -1 and data[\"abs\"][i] < max_value - margin:\n f2 = data[\"f\"][i]\n\n return {\"max\": max_value, \"f1\": f1, \"f2\": f2}\n\n\ndef computar_notch(data):\n min_value = 1e5\n notch_f = -1\n for i in range(len(data[\"abs\"])):\n if data[\"abs\"][i] < min_value:\n notch_f = data[\"f\"][i]\n min_value = min(min_value, data[\"abs\"][i])\n\n f1 = -1\n f2 = -1\n for i in range(len(data[\"abs\"])):\n if f1 == -1 and data[\"abs\"][i] < -margin:\n f1 = data[\"f\"][i]\n elif f1 != -1 and f2 == -1 and data[\"abs\"][i] > -margin:\n f2 = data[\"f\"][i]\n return {\"notch_f\": notch_f, \"f1\": f1, \"f2\": f2, \"min\": min_value}\n\n\ndef conseguir_fp(data, cuttoff):\n for i in range(len(data[\"abs\"])):\n if data[\"abs\"][i] < cuttoff:\n return (data[\"f\"][i] + data[\"f\"][i-1]) / 2\n return -1\n\n","sub_path":"TPs Viejos/2018 2 (Marce)/histogramas/computar_maximos.py","file_name":"computar_maximos.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"199898042","text":"import numpy as np\n\nsamples = np.random.normal(size = (4, 4))\nsamples\n\n\nnp.random.normal(size = 1000000)\nnp.random.seed(1)\nnp.random.randint(0, 2, size = (4, 4))\n\n\n\n### random walks\n# using standard library\n\nimport random\nposition = 0\nwalk = [position]\nsteps = 1000\nfor x in range(steps):\n step = 1 if random.randint(0, 1) else -1\n position += step\n walk.append(position)\n\n\n## using numpy\n\nnsteps = 1000\ndraws = np.random.randint(0, 2, size = nsteps)\nsteps = np.where(draws > 0, 1, -1)\nwalk = steps.cumsum()\nwalk.min()\nwalk.max()\n\n(np.abs(walk) >= 10).argmax()\n\n\n### many walks\nnwalks = 5000\nnsteps = 1000\ndraws = np.random.randint(0, 2, size = (nwalks, nsteps))\nsteps = np.where(draws > 0, 1, -1)\nwalks = steps.cumsum(1)\nwalks.max()\nwalks.min()\n\n\nhits30 = (np.abs(walks) >= 30).any(1)\nhits30\nhits30.sum()\n\ncrossing_times = (np.abs(walks[hits30]) >= 30).argmax(1)\ncrossing_times\ncrossing_times.mean()\n","sub_path":"np_random1.py","file_name":"np_random1.py","file_ext":"py","file_size_in_byte":910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"545453964","text":"import sys\nimport os\nimport pytest\nimport tempfile\nimport pyethereum.processblock as processblock\nimport pyethereum.blocks as blocks\nimport pyethereum.transactions as transactions\nimport pyethereum.utils as utils\nfrom pyethereum.db import DB as DB\nimport pyethereum.chainmanager as chainmanager\n\nblocks.INITIAL_DIFFICULTY = 2 ** 16\n\ntempdir = tempfile.mktemp()\n\n\n@pytest.fixture(scope=\"module\")\ndef accounts():\n k = utils.sha3('cow')\n v = utils.privtoaddr(k)\n k2 = utils.sha3('horse')\n v2 = utils.privtoaddr(k2)\n return k, v, k2, v2\n\n\ndef mine_next_block(parent, coinbase=None, transactions=[]):\n # advance one block\n m = chainmanager.Miner(parent, coinbase or parent.coinbase)\n for tx in transactions:\n m.add_transaction(tx)\n blk = m.mine(steps=1000 ** 2)\n return blk\n\n\n@pytest.fixture(scope=\"module\")\ndef get_transaction():\n k, v, k2, v2 = accounts()\n tx = transactions.Transaction(0, gasprice=0, startgas=10000,\n to=v2, value=utils.denoms.finney * 10, data='').sign(k)\n return tx\n\n\ndef set_db(name=''):\n if name:\n utils.data_dir.set(os.path.join(tempdir, name))\n else:\n utils.data_dir.set(tempfile.mktemp())\nset_db()\n\n\ndef db_store(blk):\n db = DB(utils.get_db_path())\n db.put(blk.hash, blk.serialize())\n db.commit()\n assert blocks.get_block(blk.hash) == blk\n\n\ndef test_db():\n db = DB(utils.get_db_path())\n assert 'test' not in db\n\n\ndef test_genesis():\n k, v, k2, v2 = accounts()\n set_db()\n blk = blocks.genesis({v: utils.denoms.ether * 1})\n db_store(blk)\n assert blk in set([blk])\n assert blk == blocks.Block.deserialize(blk.serialize())\n\n\ndef test_mine_block():\n k, v, k2, v2 = accounts()\n set_db()\n blk = blocks.genesis({v: utils.denoms.ether * 1})\n db_store(blk)\n blk2 = mine_next_block(blk, coinbase=v)\n db_store(blk2)\n assert blk2.get_balance(v) == blocks.BLOCK_REWARD + blk.get_balance(v)\n assert blk.state.db.db == blk2.state.db.db\n assert blk2.get_parent() == blk\n\n\ndef test_mine_block_with_transaction():\n k, v, k2, v2 = accounts()\n set_db()\n blk = blocks.genesis({v: utils.denoms.ether * 1})\n db_store(blk)\n tx = get_transaction()\n blk2 = mine_next_block(blk, coinbase=v, transactions=[tx])\n db_store(blk2)\n assert blocks.get_block(blk2.hash) == blk2\n assert tx.gasprice == 0\n assert blk2.get_balance(\n v) == blocks.BLOCK_REWARD + blk.get_balance(v) - tx.value\n assert blk.state.db.db == blk2.state.db.db\n assert blk2.get_parent() == blk\n assert tx in blk2.get_transactions()\n assert not tx in blk.get_transactions()\n\n\ndef test_block_serialization_same_db():\n k, v, k2, v2 = accounts()\n set_db()\n blk = blocks.genesis({v: utils.denoms.ether * 1})\n assert blk.hex_hash() == \\\n blocks.Block.deserialize(blk.serialize()).hex_hash()\n db_store(blk)\n blk2 = mine_next_block(blk)\n assert blk.hex_hash() == \\\n blocks.Block.deserialize(blk.serialize()).hex_hash()\n assert blk2.hex_hash() == \\\n blocks.Block.deserialize(blk2.serialize()).hex_hash()\n\n\ndef test_block_serialization_other_db():\n k, v, k2, v2 = accounts()\n # mine two blocks\n set_db()\n a_blk = blocks.genesis()\n db_store(a_blk)\n a_blk2 = mine_next_block(a_blk)\n db_store(a_blk2)\n\n # receive in other db\n set_db()\n b_blk = blocks.genesis()\n assert b_blk == a_blk\n db_store(b_blk)\n b_blk2 = b_blk.deserialize(a_blk2.serialize())\n assert a_blk2.hex_hash() == b_blk2.hex_hash()\n db_store(b_blk2)\n assert a_blk2.hex_hash() == b_blk2.hex_hash()\n\n\ndef test_block_serialization_with_transaction_other_db():\n #k, v, k2, v2 = accounts()\n # mine two blocks\n set_db()\n a_blk = blocks.genesis()\n db_store(a_blk)\n tx = get_transaction()\n a_blk2 = mine_next_block(a_blk, transactions=[tx])\n assert tx in a_blk2.get_transactions()\n db_store(a_blk2)\n # receive in other db\n set_db()\n b_blk = blocks.genesis()\n assert b_blk == a_blk\n db_store(b_blk)\n b_blk2 = b_blk.deserialize(a_blk2.serialize())\n assert a_blk2.hex_hash() == b_blk2.hex_hash()\n assert tx in b_blk2.get_transactions()\n db_store(b_blk2)\n assert a_blk2.hex_hash() == b_blk2.hex_hash()\n assert tx in b_blk2.get_transactions()\n\n\ndef test_transaction():\n k, v, k2, v2 = accounts()\n set_db()\n blk = blocks.genesis({v: utils.denoms.ether * 1})\n tx = get_transaction()\n assert not tx in blk.get_transactions()\n success, res = processblock.apply_tx(blk, tx)\n assert tx in blk.get_transactions()\n assert blk.get_balance(v) == utils.denoms.finney * 990\n assert blk.get_balance(v2) == utils.denoms.finney * 10\n\n\ndef test_transaction_serialization():\n k, v, k2, v2 = accounts()\n tx = get_transaction()\n assert tx in set([tx])\n assert tx.hex_hash() == \\\n transactions.Transaction.deserialize(tx.serialize()).hex_hash()\n assert tx.hex_hash() == \\\n transactions.Transaction.hex_deserialize(tx.hex_serialize()).hex_hash()\n assert tx in set([tx])\n","sub_path":"tests/test_chain.py","file_name":"test_chain.py","file_ext":"py","file_size_in_byte":5067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"411788510","text":"import friendly_traceback\n\nitems = (\n \"header\",\n \"message\",\n \"generic\",\n \"parsing_error\",\n \"parsing_error_source\",\n \"cause_header\",\n \"cause\",\n \"last_call_header\",\n \"last_call_source\",\n \"last_call_variables\",\n \"exception_raised_header\",\n \"exception_raised_source\",\n \"exception_raised_variables\",\n)\n\n\ndef make_empty_dict():\n \"\"\"Ensures that all required entries are defined and no KeyError raised\"\"\"\n d = {}\n for item in items:\n d[item] = \"\"\n return d\n\n\nbegin_html = \"\"\"\n\n\n\n\n\n\"\"\"\n\ntemplate = \"\"\"\n{header} \n{message} \n{parsing_error}
\n{parsing_error_source}
\n{cause_header} \n{cause}
\n{last_call_header}\n{last_call_source} \n{last_call_variables} \n{exception_raised_header}\n{exception_raised_source} \n{exception_raised_variables} \n\"\"\"\n\nend_html = \"\"\n\n\ndef html_formatter(info, level=None):\n items = make_empty_dict()\n for key in info:\n items[key] = info[key]\n\n return template.format(**items)\n\n\nfriendly_traceback.set_formatter(formatter=html_formatter)\n\ntry:\n b = a + c # noqa\nexcept Exception:\n friendly_traceback.explain(redirect=\"capture\")\n\nresult = begin_html + friendly_traceback.get_output() + end_html\n\nwith open(\"test.html\", \"w\") as f:\n f.write(result)\n","sub_path":"demos/custom_formatter.py","file_name":"custom_formatter.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"628231804","text":"# Copyright 2016 Antony Lee. All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n\n# 2. 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# THIS SOFTWARE IS PROVIDED BY ANTONY LEE ``AS IS'' AND ANY EXPRESS OR IMPLIED\n# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n# EVENT SHALL ANTONY LEE OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE\n# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# The views and conclusions contained in the software and documentation are those\n# of the authors and should not be interpreted as representing official policies,\n# either expressed or implied, of Antony Lee.\n\nfrom contextlib import contextmanager\nimport logging\nimport shutil\nfrom subprocess import Popen, PIPE\nfrom tempfile import TemporaryFile\n\nfrom PyQt4.QtGui import QImage\n\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass FFMpegWriter:\n def __init__(self, path, *, fps=24, quality=1):\n self._path = path\n self._fps = fps\n self._quality = quality\n self._tempfile = None\n self._popen = None\n\n def __enter__(self):\n self._tempfile = TemporaryFile()\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n try:\n popen = self._popen\n if not popen:\n return\n self._tempfile.seek(0)\n shutil.copyfileobj(self._tempfile, popen.stdin)\n popen.stdin.close()\n popen.wait()\n out = popen.stdout.read()\n if out:\n LOGGER.warning(\"ffmpeg stdout: %s\", out)\n err = popen.stderr.read()\n if err:\n LOGGER.warning(\"ffmpeg stderr: %s\", err)\n if popen.returncode:\n raise RuntimeError(\"ffmpeg failed\")\n finally:\n self._tempfile.close()\n self._tempfile = self._popen = None\n\n def _create_popen(self, qsize):\n self._size = qsize\n args = [\"ffmpeg\",\n \"-loglevel\", \"warning\",\n \"-y\", # Overwrite existing.\n \"-f\", \"rawvideo\",\n \"-vcodec\", \"rawvideo\",\n \"-s\", \"{}x{}\".format(qsize.width(), qsize.height()), # Size.\n \"-pix_fmt\", \"bgra\", # Format.\n \"-r\", str(self._fps), # FPS.\n \"-i\", \"-\", # Input pipe.\n \"-an\", # No audio.\n \"-vcodec\", \"mpeg4\",\n \"-q\", str(self._quality), # Quality.\n str(self._path)]\n self._popen = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)\n\n def add_qimage(self, qimage):\n if self._popen is None:\n self._create_popen(qimage.size())\n else:\n if self._size != qimage.size():\n raise ValueError(\"Image size changed: was {}, now {}\".format(\n self._size, qimage.size()))\n bits = qimage.convertToFormat(QImage.Format_RGB32).constBits()\n bits.setsize(qimage.byteCount())\n self._tempfile.write(bytes(bits))","sub_path":"code/ffmpeg.py","file_name":"ffmpeg.py","file_ext":"py","file_size_in_byte":3882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"331739221","text":"from PySide2.QtWidgets import QWidget, QPushButton, QVBoxLayout, QHBoxLayout\nfrom PySide2.QtCore import Slot\nfrom modules.carousel.carousel import Carousel\nimport glob\nimport json\n\n\nclass PublicityView(QWidget):\n def __init__(self):\n QWidget.__init__(self)\n self.saved_images_file = './data/saved_images.json'\n\n carousel_images = glob.glob('./images/*')\n self.carousel = Carousel(carousel_images)\n\n self._create_buttons()\n self._create_layout()\n\n def _create_buttons(self):\n self.btn_save = QPushButton('Guardar')\n self.btn_save.setStyleSheet('background-color: green; color: white')\n\n self.btn_reject = QPushButton('Rechazar')\n self.btn_reject.setStyleSheet('background-color: red; color: white')\n\n self.btn_reject.clicked.connect(self.carousel.next_image)\n self.btn_save.clicked.connect(self.save_publicity)\n\n def _create_layout(self):\n self.options = QHBoxLayout()\n self.options.addWidget(self.btn_reject)\n self.options.addWidget(self.btn_save)\n\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.carousel.poster)\n self.layout.addLayout(self.options)\n self.setLayout(self.layout)\n\n @Slot()\n def save_publicity(self):\n saved_images = self._get_my_publicity()\n\n if self.carousel.current_image not in saved_images:\n saved_images.append(self.carousel.current_image)\n with open(self.saved_images_file, 'w+', encoding='utf-8') as f:\n json.dump(saved_images, f)\n\n self.carousel.next_image()\n\n def _get_my_publicity(self):\n try:\n with open(self.saved_images_file, 'r', encoding='utf-8') as f:\n saved_images = json.load(f)\n except (FileNotFoundError, ValueError):\n saved_images = []\n return saved_images\n\n\nclass GaleryView(QWidget):\n def __init__(self):\n QWidget.__init__(self)\n self.saved_images_file = './data/saved_images.json'\n\n carousel_images = self._get_my_publicity()\n self.carousel = Carousel(carousel_images)\n\n self._create_buttons()\n self._create_layout()\n\n def _create_buttons(self):\n self.btn_delete = QPushButton('Eliminar Publicidad')\n self.btn_delete.setStyleSheet('background-color: red; color: white')\n\n self.left_arrow = QPushButton('Anterior')\n self.left_arrow.setStyleSheet('background-color: #192c6f; color: white')\n\n self.right_arrow = QPushButton('Siguiente')\n self.right_arrow.setStyleSheet('background-color: #192c6f; color: white')\n\n self.left_arrow.clicked.connect(self.carousel.prev_image)\n self.right_arrow.clicked.connect(self.carousel.next_image)\n self.btn_delete.clicked.connect(self.delete_publicity)\n\n def _create_layout(self):\n self.controls = QHBoxLayout()\n self.controls.addWidget(self.btn_delete)\n self.controls.addWidget(self.left_arrow)\n self.controls.addWidget(self.right_arrow)\n\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.carousel.poster)\n self.layout.addLayout(self.controls)\n self.setLayout(self.layout)\n\n @Slot()\n def delete_publicity(self):\n self._delete_publicity_from_file()\n self.carousel.delete_current_image()\n\n def _delete_publicity_from_file(self):\n \"\"\" Removes the current publicity from user's file of saved publicities \"\"\"\n saved_images = self._get_my_publicity()\n if saved_images:\n saved_images.remove(self.carousel.current_image)\n with open(self.saved_images_file, 'w', encoding='utf-8') as f:\n json.dump(saved_images, f)\n\n def _get_my_publicity(self):\n try:\n with open(self.saved_images_file, 'r', encoding='utf-8') as f:\n saved_images = json.load(f)\n except (FileNotFoundError, ValueError):\n saved_images = []\n return saved_images\n\n\nclass MapView(QWidget):\n def __init__(self):\n QWidget.__init__(self)\n self.carousel = Carousel(['./map/mapa_La_Plata.png'])\n self._create_layout()\n\n def _create_layout(self):\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.carousel.poster)\n self.setLayout(self.layout)\n","sub_path":"publicity-app/app/modules/widgets/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"513096530","text":"import random,time\nimport pandas as pd\ndata_list = []\nfor user_id in range(1,10001):\n for x in range(20,100):\n item_id = random.randint(1,100001)\n if random.randint(1,2)==1:\n data_list.append([user_id,item_id,'click',1,int(time.time())])\n if random.randint(1,5)==1:\n data_list.append([user_id,item_id,'like',1,int(time.time())])\n if random.randint(1,5)==1:\n data_list.append([user_id,item_id,'comment',random.randint(1,3),int(time.time())])\n if random.randint(1,10)==1:\n data_list.append([user_id,item_id,'share',1,int(time.time())])\ncolumn = ['USER_ID','ITEM_ID','EVENT_TYPE','EVENT_VALUE','TIMESTAMP']\ntest=pd.DataFrame(columns=column,data=data_list)\ntest.to_csv('data.csv') \nprint(\"finish_Interactions\")\n\ndata_list = []\nfor item_id in range(1,100001):\n\t#月销售\n\tbuy_cnt = random.randint(1,500)\n\t#月曝光\n\t# pv_cnt = random.randint(500,5000)\n\t#分类id\n\tcategory_id = random.randint(1,100)\n\t#分类等级\n\t# category_level = random.randint(1,4)\n\t#月收藏\n\tlike_cnt = random.randint(50,1000)\n\t#月评论数\n\tcomment_cnt = random.randint(1,100)\n\t# 特征\n\tfeatures = random.choice(['Red','yellow','blue','green','white','black'])\n\t# 品牌\n\t# brand = random.choice(['xiaoMi','apple','sanxing','huawei','xiaolajiao','nubia','oppo','vivo','iqiq'])\n\t# 标题\n\t# title = brand+str(category_id)+features\n\t# 商家\n\t# business = random.choice(['huipu','xiaomidian','sanxingdian','huawei1','huawei2','nubiadian','oppodian'])\n\n\tdata_list.append([item_id,buy_cnt,category_id,like_cnt,comment_cnt,features])\n\n\ncolumn = ['ITEM_ID','BUY_CNT','CATEGORY_ID','LIKE_CNT','COMMENT_CNT','FEATURES']\ntest=pd.DataFrame(columns=column,data=data_list)\ntest.to_csv('items.csv') \n\ndata_list = []\nfor user_id in range(1,10001):\n\t# 年龄\n age = random.randint(16,36)\n # 性别\n gender = random.choice(['male','female','unknown'])\n # 城市\n city = random.choice(['nanning','guangzhou','shanghai','shenzhen','beijing','chognqing','sichuan'])\n # 爱好\n hobby = random.choice(['daqiu','tiqiu','tiaowu','shuijiao','nvsheng','nansheng','yundong'])\n # 个人简介\n # remark = ''\n # 昵称\n # nickname = ''\n data_list.append([user_id,age,gender,city,hobby])\n \n\ncolumn = ['USER_ID','AGE','GENDER','CITY','HOBBY']\ntest=pd.DataFrame(columns=column,data=data_list)\ntest.to_csv('users.csv') ","sub_path":"aws_python/out_csv.py","file_name":"out_csv.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"470085272","text":"import os\r\nimport time\r\nimport csv\r\nimport sys\r\n\r\nclass Menu:\r\n __userT=\"uTesorero\"\r\n __passwT=\"ag@74ck\"\r\n __userG=\"uGerente\"\r\n __passwG=\"ufC77#!1\"\r\n\r\n \r\n __switcher = None\r\n def __init__ (self):\r\n self.__switcher = {1:self.opcion1 ,\r\n 2:self.opcion2 ,\r\n 3:self.opcion3,\r\n 4:self.opcion4,\r\n 5:self.opcion5,\r\n 6:self.opcion6,\r\n 0:self.salir\r\n }\r\n def getSwitcher ( self ):\r\n return self. __switcher\r\n def opcion ( self , op, colec):\r\n func = self . __switcher . get ( op , lambda:print( \"Opción no válida\" ))\r\n func (colec)\r\n time.sleep(.6)\r\n\r\n def salir(self,colec):\r\n print('Cerrando sistema...')\r\n time.sleep(1)\r\n\r\n def opcion1(self,colec):\r\n dni=input(\"Ingrese el DNI del empleado: \")\r\n try:\r\n dni=int(dni)\r\n empl=colec.BuscarDNI(dni)\r\n if((empl!=0) and (empl!=-1)):\r\n horas=int(input(\"Ingrese cantidad de horas: \"))\r\n try:\r\n nuevo= horas + empl.getHoras()\r\n empl.setHoras(nuevo)\r\n ban=True\r\n if(ban==True):\r\n os.system('cls')\r\n print(\"Horas Registradas.\")\r\n print(\"Cantidad total de horas: {}\" .format(empl.getHoras()))\r\n print(\"Empleado: {}\".format(empl.getNom()))\r\n input(\"\")\r\n except:\r\n print(\"No se ha podido registrar horas.\")\r\n print(\"Es posible que el empleado no trabaje por horas.\")\r\n input(\"\")\r\n else:\r\n if(empl==-1):\r\n print(\"ERROR! Es posible que el empleado no esté registrado o no trabaje por horas\")\r\n input(\"\")\r\n else:\r\n print(\"EMPLEADO NO ENCONTRADO!\")\r\n input(\"\")\r\n except ValueError:\r\n print(\"Debe ingresar un dni valido\")\r\n input(\"\")\r\n\r\n def opcion2(self,colec):\r\n os.system('cls')\r\n tarea=input(\"Ingrese tarea: \")\r\n tarea=tarea.lower()\r\n colec.BuscarTarea(tarea)\r\n \r\n\r\n def opcion3(self,colec):\r\n colec.AyudaSolid()\r\n\r\n def opcion4(self,colec):\r\n os.system('cls')\r\n colec.MuestraSueldos()\r\n time.sleep(1)\r\n\r\n\r\n def opcion5(self,colec):\r\n ban=False\r\n while(ban==False):\r\n us=input(\"Usuario: \")\r\n ps=input(\"Contraseña: \")\r\n if(us==self.__userT and ps==self.__passwT):\r\n ban=True\r\n dni=input(\"Ingrese DNI: \")\r\n try:\r\n dni=int(dni)\r\n colec.gastosSueldoPorEmpleado(dni)\r\n except ValueError:\r\n print(\"Debe ingresar un valor Numerico.\")\r\n time.sleep(1)\r\n else:\r\n print(\"Usuario o contraseña incorrecto. Intente nuevamente.\")\r\n time.sleep(1)\r\n input(\"Presione ENTER para continuar.\")\r\n\r\n def opcion6(self,colec):\r\n os.system('cls')\r\n ban=False\r\n while(ban==False):\r\n us=input(\"Usuario: \")\r\n ps=input(\"Contraseña: \")\r\n if(us==self.__userG and ps==self.__passwG):\r\n ban=True\r\n dni=input(\"Ingrese el DNI: \")\r\n try:\r\n dni=int(dni)\r\n print(\"1. Modificar Basico E. Planta\")\r\n print(\"2. Modificar Viatico E. Externo\")\r\n print(\"3. Modificar Valor E. Por Hora\")\r\n print(\"0. Menu principal. \")\r\n op=int(input(\"Ingrese su opcion: \"))\r\n while(op!=0):\r\n if(op==1):\r\n os.system('cls')\r\n nuevo=int(input(\"Ingrese el nuevo valor del básico: \"))\r\n colec.modificarBasicoEPlanta(dni,nuevo)\r\n input(\"Presione ENTER para continuar.\")\r\n if(op==2):\r\n os.system('cls')\r\n nuevo=int(input(\"Ingrese el nuevo valor del Viatico: \"))\r\n colec.modificarViaticoEExterno(dni,nuevo)\r\n input(\"Presione ENTER para continuar.\")\r\n if(op==3):\r\n os.system('cls')\r\n nuevo=int(input(\"Ingrese el nuevo valor de hora: \"))\r\n colec.modificarValorEPorHora(dni,nuevo)\r\n input(\"Presione ENTER para continuar.\")\r\n\r\n print(\"1. Modificar Basico E. Planta\")\r\n print(\"2. Modificar Viatico E. Externo\")\r\n print(\"3. Modificar Valor E. Por Hora\")\r\n print(\"0. Menu principal. \")\r\n op=int(input(\"Ingrese su opcion: \"))\r\n \r\n except ValueError:\r\n os.system('cls')\r\n print(\"Debe ingresar un valor Numerico.\")\r\n time.sleep(1)\r\n else:\r\n print(\"Usuario o contraseña incorrecto. Intente nuevamente.\")\r\n time.sleep(1)\r\n input(\"Presione ENTER para continuar.\")","sub_path":"Ejercicio 8/Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":5586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"202409403","text":"#! /usr/bin/python\n\n#\tThe MIT License (MIT)\n#\t\n#\tCopyright (c) 2015 Nathan Koester\n#\t\n#\tPermission is hereby granted, free of charge, to any person obtaining a copy\n#\tof this software and associated documentation files (the \"Software\"), to deal\n#\tin the Software without restriction, including without limitation the rights\n#\tto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n#\tcopies of the Software, and to permit persons to whom the Software is\n#\tfurnished to do so, subject to the following conditions:\n#\t\n#\tThe above copyright notice and this permission notice shall be included in all\n#\tcopies or substantial portions of the Software.\n#\t\n#\tTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n#\tIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n#\tFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n#\tAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n#\tLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n#\tOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n#\tSOFTWARE.\n\nimport sys\n\nimport pickle\nfrom PySide import QtCore, QtGui\n\nimport camera\nimport lights\nimport multimedia\nimport obdii\nimport settings\n\nclass TruckUI(QtGui.QWidget):\n\n\tdef __init__(self, parent=None):\n\t\tsuper(TruckUI, self).__init__(parent)\n\n\t\t#\tDefine button size for quick change\n\t\tbSize = 128\n\n\t\t#\tBegin initializing buttons\n\t\tsettingsButton = QtGui.QPushButton()\n\t\tsettingsIcon = QtGui.QIcon(\"./Icons/Settings.png\")\n\t\tsettingsButton.setIcon(settingsIcon)\n\t\tsettingsButton.setIconSize(QtCore.QSize(bSize, bSize))\n\n\t\tlightsButton = QtGui.QPushButton()\n\t\tlightsIcon = QtGui.QIcon(\"./Icons/Bulb.png\")\n\t\tlightsButton.setIcon(lightsIcon)\n\t\tlightsButton.setIconSize(QtCore.QSize(bSize, bSize))\n\n\t\tmediaButton = QtGui.QPushButton()\n\t\tmediaIcon = QtGui.QIcon(\"./Icons/Multimedia.png\")\n\t\tmediaButton.setIcon(mediaIcon)\n\t\tmediaButton.setIconSize(QtCore.QSize(bSize, bSize))\n\n\t\tOBDIIButton = QtGui.QPushButton()\n\t\tOBDIIIcon = QtGui.QIcon(\"./Icons/Hardware.png\")\n\t\tOBDIIButton.setIcon(OBDIIIcon)\n\t\tOBDIIButton.setIconSize(QtCore.QSize(bSize, bSize))\n\n\t\tcameraButton = QtGui.QPushButton()\n\t\tcameraIcon = QtGui.QIcon(\"./Icons/Monitor.png\")\n\t\tcameraButton.setIcon(cameraIcon)\n\t\tcameraButton.setIconSize(QtCore.QSize(bSize, bSize))\t\n\n\t\tcameraButton.clicked.connect(self.showCamera)\n\t\tlightsButton.clicked.connect(self.showLights)\n\t\tmediaButton.clicked.connect(self.showMultimedia)\n\t\tsettingsButton.clicked.connect(self.showSettings)\n\t\tOBDIIButton.clicked.connect(self.showOBDII)\n\n\t\t#\tCreate the additional pages/frames\n\t\t\n\t\tself.camera = camera.CameraFrame()\n\t\tself.lights = lights.LightsFrame()\n\t\tself.media = multimedia.MultimediaFrame()\n\t\tself.obdii = obdii.OBDIIFrame()\n\t\tself.settings = settings.SettingsFrame()\n\n\t\t#\tSet the layout. To add more, just increment Column\n\t\tmainLayout = QtGui.QGridLayout()\n\t\tmainLayout.addWidget(lightsButton, 0, 0)\n\t\tmainLayout.addWidget(cameraButton, 0, 1)\n\t\tmainLayout.addWidget(OBDIIButton, 0, 2)\n\t\tmainLayout.addWidget(settingsButton, 0, 3)\n\t\tmainLayout.addWidget(mediaButton, 1, 0)\n\n\t\tself.setLayout(mainLayout)\n\n\t#\tButton command to show the Camera Page\n\tdef showCamera(self):\n\t\tself.camera.showFullScreen()\n\n\t#\tButton command to show the Lights Control Page\n\tdef showLights(self):\n\t\tself.lights.showFullScreen()\n\n\t#\tButton command to show the Multimedia Page\n\tdef showMultimedia(self):\n\t\tself.media.showFullScreen()\n\n\t#\tButton command to show the OBDII Page\n\tdef showOBDII(self):\n\t\tself.obdii.showFullScreen()\n\n\t#\tButton command to show the Settings Page\n\tdef showSettings(self):\n\t\tself.settings.showFullScreen()\n\n\nif __name__ == '__main__':\n\n\t# Hack to change the style sheet without passing the command line args. Makes run command cleaner\n\targs = sys.argv\n\targs.append('-stylesheet')\n\targs.append('./Resources/ui.qss')\n\n\tapp = QtGui.QApplication(sys.argv)\n\tapp.setStyle(\"Plastique\")\n\n\tTruckUI = TruckUI()\n\tTruckUI.showFullScreen()\n\n\tsys.exit(app.exec_())\n","sub_path":"truckUI.py","file_name":"truckUI.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"170924390","text":"# Copyright 2017 The UNIC Project Developers.\n#\n# See the COPYRIGHT file at the top-level directory of this distribution.\n#\n# Licensed under the Apache License, Version 2.0 or the MIT license , at your option. This file may not be\n# copied, modified, or distributed except according to those terms.\n\n\nimport os\nimport sys\n\nfrom collections import OrderedDict\nfrom itertools import chain\n\nimport common\n\nfrom unicode_utils import is_surrogate, codepoints_from_string\n\n\nINDENT_COUNT = 4\nINDENT = \" \" * INDENT_COUNT\n\n\nPREAMBLE = \"// WARNING: Auto-generated by `%s`. DO NOT EDIT MANUALLY!\\n\"\n\n\ndef char_escape(cp):\n assert not is_surrogate(cp), \"Trying to output a surrogate codepoint!\"\n return \"\\\\u{%x}\" % cp\n\n\ndef char_literal(cp):\n return \"'%s'\" % char_escape(cp)\n\n\ndef string_literal(codepoints):\n return '\"' + ''.join([char_escape(cp) for cp in codepoints]) + '\"'\n\n\ndef title_case(name):\n return name.strip().replace('_', ' ').title().replace(' ', '')\n\n\ndef get_rel_path(path):\n return os.path.relpath(path, common.ROOT_DIR)\n\n\ndef emit_preamble(\n script_path,\n output_file,\n):\n output_file.write(PREAMBLE % get_rel_path(script_path))\n\n\ndef emit_value(\n script_path,\n output_file,\n value,\n print_fun=lambda x: \"%s\" % x,\n):\n emit_preamble(script_path, output_file)\n output_file.write(print_fun(value))\n output_file.write(\"\\n\")\n\n\ndef emit_strings(\n script_path,\n output_file,\n strings,\n print_fun=lambda x: \"%s\" % x,\n):\n codepoints = chain(*[codepoints_from_string(st) for st in strings])\n emit_value(\n script_path,\n output_file,\n \"\\\\\\n\".join(char_escape(cp) for cp in codepoints),\n print_fun=lambda x: '\"\\\\\\n%s\\\\\\n\"' % x,\n )\n\n\ndef _write_row(\n output_file,\n value,\n print_fun=lambda x: \"%s\" % x,\n):\n output_file.write(\"%s%s,\\n\" % (INDENT, print_fun(value)))\n\n\ndef _write_rows(\n output_file,\n data,\n print_fun=lambda x: \"%s\" % x,\n):\n for value in data:\n _write_row(output_file, value, print_fun)\n\n\ndef emit_table(\n script_path,\n output_file,\n data,\n print_fun=lambda x: \"%s\" % x,\n):\n emit_preamble(script_path, output_file)\n output_file.write(\"&[\\n\")\n _write_rows(output_file, data, print_fun)\n output_file.write(\"]\\n\")\n\n\ndef emit_class(\n script_path,\n output_file,\n data,\n print_fun=lambda x: \"%s\" % x,\n):\n emit_preamble(script_path, output_file)\n output_file.write(\"{\\n\")\n _write_rows(output_file, data, print_fun)\n output_file.write(\"}\\n\")\n\n\ndef emit_lookup_tables(\n script_path,\n lookup_file,\n values_file,\n data,\n value_fun=None,\n value_print_fun=char_literal,\n):\n keys = data.keys()\n keys.sort()\n\n if value_fun is None:\n def value_fun(x): return data[x]\n\n lookup = OrderedDict()\n values = OrderedDict()\n values.offset = 0\n\n for k in keys:\n value = tuple(value_fun(k))\n if value not in values:\n values[value] = (values.offset, len(value))\n values.offset += len(value)\n lookup[k] = values[value]\n\n emit_table(\n script_path,\n lookup_file,\n lookup,\n print_fun=lambda v:\n \"(%s, Slice { offset: %d, length: %d })\"\n % (char_literal(v), lookup[v][0], lookup[v][1])\n )\n\n emit_table(\n script_path,\n values_file,\n values.keys(),\n print_fun=lambda v: \", \".join(value_print_fun(c) for c in v)\n )\n","sub_path":"tools/pylib/rustout.py","file_name":"rustout.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"433399057","text":"import unittest\n\nfrom frugal.context import FContext, _DEFAULT_TIMEOUT\n\n\nclass TestContext(unittest.TestCase):\n\n correlation_id = \"fooid\"\n\n def test_correlation_id(self):\n context = FContext(\"fooid\")\n self.assertEqual(\"fooid\", context.correlation_id)\n self.assertEqual(_DEFAULT_TIMEOUT, context.timeout)\n\n def test_timeout(self):\n # Check default timeout (5 seconds).\n context = FContext()\n self.assertEqual(5000, context.timeout)\n self.assertEqual(\"5000\", context.get_request_header(\"_timeout\"))\n\n # Set timeout and check expected values.\n context.set_timeout(10000)\n self.assertEqual(10000, context.timeout)\n self.assertEqual(\"10000\", context.get_request_header(\"_timeout\"))\n\n # Check timeout passed to constructor.\n context = FContext(timeout=1000)\n self.assertEqual(1000, context.timeout)\n self.assertEqual(\"1000\", context.get_request_header(\"_timeout\"))\n\n def test_op_id(self):\n context = FContext(self.correlation_id)\n context._set_request_header(\"_opid\", \"12345\")\n self.assertEqual(self.correlation_id, context.correlation_id)\n self.assertEqual(\"12345\", context.get_request_header(\"_opid\"))\n\n def test_request_header(self):\n context = FContext(self.correlation_id)\n self.assertEqual(context, context.set_request_header(\"foo\", \"bar\"))\n self.assertEqual(\"bar\", context.get_request_header(\"foo\"))\n self.assertEqual(self.correlation_id,\n context.get_request_header(\"_cid\"))\n\n def test_response_header(self):\n context = FContext(self.correlation_id)\n self.assertEqual(context, context.set_response_header(\"foo\", \"bar\"))\n self.assertEqual(\"bar\", context.get_response_header(\"foo\"))\n self.assertEqual(self.correlation_id,\n context.get_request_header(\"_cid\"))\n\n def test_request_headers(self):\n context = FContext(self.correlation_id)\n context.set_request_header(\"foo\", \"bar\")\n headers = context.get_request_headers()\n self.assertEqual(\"bar\", headers.get('foo'))\n\n def test_response_headers(self):\n context = FContext(self.correlation_id)\n context.set_response_header(\"foo\", \"bar\")\n headers = context.get_response_headers()\n self.assertEqual(\"bar\", headers.get('foo'))\n\n def test_request_header_put_allows_string_unicode(self):\n context = FContext(self.correlation_id)\n self.assertRaises(TypeError, context.set_request_header, 1, \"foo\")\n self.assertRaises(TypeError, context.set_request_header, \"foo\", 3)\n context.set_request_header(u'foo', u'bar')\n\n def test_response_header_put_allows_string_unicode(self):\n context = FContext(self.correlation_id)\n self.assertRaises(TypeError, context.set_response_header, 1, \"foo\")\n self.assertRaises(TypeError, context.set_response_header, \"foo\", 3)\n context.set_request_header(u'foo', u'bar')\n\n def test_cant_set_cid_public_method(self):\n context = FContext(self.correlation_id)\n context.set_request_header(\"_cid\", \"foo\")\n self.assertEqual(context.correlation_id, self.correlation_id)\n\n def test_cant_set_opid_public_method(self):\n context = FContext(self.correlation_id)\n context.set_request_header(\"_opid\", \"foo\")\n self.assertNotEqual(context.get_request_header(\"_opid\"), \"foo\")\n","sub_path":"lib/python/frugal/tests/test_context.py","file_name":"test_context.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"135660445","text":"import requests, os, time, json, io, warnings\nimport argparse, sys\nfrom datetime import datetime\n\n\nfrom multiprocessing import Pool\n\npostListGlobal = []\n\n\n##########################################################################################################\ndef getRequests(url):\n\n requests_result = requests.get(url, headers={'Connection':'close'}).json()\n time.sleep(0.01)\n return requests_result\n\n##########################################################################################################\ndef getFeedIds(feeds, feed_list):\n\n feeds = feeds['feed'] if 'feed' in feeds else feeds\n\n for feed in feeds['data']:\n feed_list.append(feed['id'])\n if not stream:\n print('Feed found: ' + feed['id'] + '\\n')\n #log.write('Feed found: ' + feed['id'] + '\\n')\n \n if 'paging' in feeds and 'next' in feeds['paging']:\n feeds_url = feeds['paging']['next']\n feed_list = getFeedIds(getRequests(feeds_url), feed_list)\n return feed_list\n\n##########################################################################################################\ndef getComments(comments, comments_count):\n\n # If comments exist.\n comments = comments['comments'] if 'comments' in comments else comments\n if 'data' in comments:\n\n if not stream:\n comments_dir = 'comments/'\n if not os.path.exists(comments_dir):\n os.makedirs(comments_dir)\n\n for comment in comments['data']:\n\n comment_content = {\n 'id': comment['id'],\n 'user_id': comment['from']['id'],\n 'user_name': comment['from']['name'] if 'name' in comment['from'] else None,\n 'message': comment['message'],\n 'like_count': comment['like_count'] if 'like_count' in comment else None,\n 'created_time': comment['created_time']\n }\n\n comments_count+= 1\n\n if stream:\n print(comment_content)\n else:\n #print('Processing comment: ' + comment['id'] + '\\n')\n comment_file = open(comments_dir + comment['id'] + '.json', 'w')\n comment_file.write(json.dumps(comment_content, indent = 4, ensure_ascii = False))\n comment_file.close()\n #log.write('Processing comment: ' + feed_id + '/' + comment['id'] + '\\n')\n\n # Check comments has next or not.\n if 'next' in comments['paging']:\n comments_url = comments['paging']['next']\n comments_count = getComments(getRequests(comments_url), comments_count)\n\n return comments_count\n\n##########################################################################################################\ndef getReactions(reactions, reactions_count_dict):\n # If reactions exist.\n reactions = reactions['reactions'] if 'reactions' in reactions else reactions\n if 'data' in reactions:\n\n if not stream:\n reactions_dir = 'reactions/'\n if not os.path.exists(reactions_dir):\n os.makedirs(reactions_dir)\n\n for reaction in reactions['data']:\n\n if reaction['type'] == 'LIKE':\n reactions_count_dict['like']+= 1\n elif reaction['type'] == 'LOVE':\n reactions_count_dict['love']+= 1\n elif reaction['type'] == 'HAHA':\n reactions_count_dict['haha']+= 1\n elif reaction['type'] == 'WOW':\n reactions_count_dict['wow']+= 1\n elif reaction['type'] == 'SAD':\n reactions_count_dict['sad']+= 1\n elif reaction['type'] == 'ANGRY':\n reactions_count_dict['angry']+= 1\n\n if stream:\n print(reaction)\n else:\n #bleh print('Processing reaction: ' + reaction['id'] + '\\n')\n reaction_file = open(reactions_dir + reaction['id'] + '.json', 'w')\n reaction_file.write(json.dumps(reaction, indent = 4, ensure_ascii = False))\n reaction_file.close()\n #log.write('Processing reaction: ' + feed_id + '/' + reaction['id'] + '\\n')\n\n # Check reactions has next or not.\n if 'next' in reactions['paging']:\n reactions_url = reactions['paging']['next']\n # print(\"REAC CHECK: \" + str(getRequests(reactions_url), reactions_count_dict))\n reactions_count_dict = getReactions(getRequests(reactions_url), reactions_count_dict)\n \n return reactions_count_dict\n\n##########################################################################################################\ndef getFollowerCount(followerCount_req):\n followerCount_req = followerCount_req['followerCount_req'] if 'followerCount_req' in followerCount_req else followerCount_req\n #print(followerCount_req)\n return followerCount_req['fan_count']\n\n\n##########################################################################################################\ndef getAttachments(attachments, attachments_content):\n\n # If attachments exist.\n attachments = attachments['attachments'] if 'attachments' in attachments else attachments\n if 'data' in attachments:\n attachments_content['title'] = attachments['data'][0]['title'] if 'title' in attachments['data'][0] else ''\n attachments_content['description'] = attachments['data'][0]['description'] if 'description' in attachments['data'][0] else ''\n attachments_content['target'] = attachments['data'][0]['target']['url'] if 'target' in attachments['data'][0] and 'url' in attachments['data'][0]['target'] else ''\n\n return attachments_content\n\n##########################################################################################################\ndef getFeedType(feedType_req):\n feedType_req = feedType_req['feedType_req'] if 'feedType_req' in feedType_req else feedType_req\n return feedType_req['type']\n\n##########################################################################################################\ndef getMessage(message_req):\n message_req = message_req['message_req'] if 'message_req' in message_req else message_req\n return message_req['message']\n\n##########################################################################################################\ndef getOptimizedReactions(opt_reactions):\n opt_reactions = opt_reactions['opt_reactions'] if 'opt_reactions' in opt_reactions else opt_reactions\n #print(\"USER THIS: \", opt_reactions)\n like = ((opt_reactions['LIKE'])['summary'])['total_count']\n #print(\"LIKE: \", like)\n love = ((opt_reactions['LOVE'])['summary'])['total_count']\n haha = ((opt_reactions['HAHA'])['summary'])['total_count']\n wow = ((opt_reactions['WOW'])['summary'])['total_count']\n sad = ((opt_reactions['SAD'])['summary'])['total_count']\n angry =((opt_reactions['ANGRY'])['summary'])['total_count']\n\n reactions_count_dict1 = {\n 'like': like,\n 'love': love,\n 'haha': haha,\n 'wow': wow,\n 'sad': sad,\n 'angry': angry\n }\n\n\n return reactions_count_dict1\n\n##########################################################################################################\ndef getFeed(feed_id):\n\n global postListGlobal\n\n feed_url = 'https://graph.facebook.com/v2.7/' + feed_id\n accessable_feed_url = feed_url + '?' + tokenGlobal\n #print(\"accessable \" + accessable_feed_url)\n message_feed_url = feed_url +'?fields=message&' + tokenGlobal\n #print(\"message: \" + message_feed_url)\n\n post = dict()\n feed_type_url = feed_url + '?fields=type&' + tokenGlobal\n feed_type = getFeedType(getRequests(feed_type_url))\n #print(\"type\" + feed_type)\n post['type'] = feed_type\n #print(\"Feed type: \" + feed_type)\n\n message = getMessage(getRequests(message_feed_url))\n #print(type(message))\n post['message'] = message\n # message.decode('utf-8')\n\n\n\n if not stream:\n feed_dir = feed_id + '/'\n if not os.path.exists(feed_dir):\n os.makedirs(feed_dir)\n\n os.chdir(feed_dir)\n\n print('\\nProcessing feed: ' + feed_id + '\\nAt: ' + datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S') + '\\n')\n log = open('../log', 'a')\n log.write('\\nProcessing feed: ' + feed_id + '\\nAt: ' + datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S') + '\\n')\n log.close()\n\n # For comments.\n comments_url = feed_url + '?fields=comments.limit(100)&' + token\n \n comments_count = getComments(getRequests(comments_url), 0)\n post['comment count'] = comments_count\n\n\n reactions_summary_url = feed_url + '?fields=reactions.type(LIKE).limit(0).summary(true).as(LIKE),reactions.type(LOVE).limit(0).summary(true).as(LOVE),\\\n reactions.type(HAHA).limit(0).summary(true).as(HAHA),reactions.type(WOW).limit(0).summary(true).as(WOW),\\\n reactions.type(SAD).limit(0).summary(true).as(SAD),reactions.type(ANGRY).limit(0).summary(true).as(ANGRY)&' + token\n\n opt = getOptimizedReactions(getRequests(reactions_summary_url))\n #print(\"DIC 1: \" , opt)\n\n #print(\"YAAAA: \", reactions_summary_url)\n\n # For reactions.\n # if get_reactions:\n # reactions_count_dict = {\n # 'like': 0,\n # 'love': 0,\n # 'haha': 0,\n # 'wow': 0,\n # 'sad': 0,\n # 'angry': 0\n # }\n # reactions_url = feed_url + '?fields=reactions.limit(100)&' + token\n # test = feed_url + 'fields=reactions.type(like)&' + token\n # #print('TESTTTT', test)\n # reactions_count_dict = getReactions(getRequests(reactions_url), reactions_count_dict)\n # post['reactions'] = reactions_count_dict\n post['reactions'] = opt\n \n\n # print(\"DIC: \" , reactions_count_dict)\n #postListGlobal.append(post)\n\n \n\n #print(data)\n\n\n # For attachments.\n attachments_content = {\n 'title': '',\n 'description': '',\n 'target': ''\n }\n attachments_url = feed_url + '?fields=attachments&' + token\n attachments_content = getAttachments(getRequests(attachments_url), attachments_content)\n\n # For feed content.\n feed = getRequests(feed_url + '?' + token)\n\n if 'message' in feed:\n feed_content = {\n 'id': feed['id'],\n 'message': feed['message'],\n 'link': feed['link'] if 'link' in feed else None,\n 'created_time': feed['created_time'],\n 'comments_count': comments_count\n }\n\n feed_content.update(attachments_content)\n\n if get_reactions:\n feed_content.update(opt)\n\n if stream:\n print(feed_content)\n else:\n feed_file = open(feed_id + '.json', 'w')\n feed_file.write(json.dumps(feed_content, indent = 4, ensure_ascii = False))\n feed_file.close()\n\n if not stream:\n os.chdir('../')\n\n return post\n\n##########################################################################################################\ndef getTarget(target):\n \n if not stream:\n target_dir = target + '/'\n if not os.path.exists(target_dir):\n os.makedirs(target_dir)\n os.chdir(target_dir)\n\n log = open('log', 'w')\n start_time = datetime.now()\n execution_start_time = time.time()\n print('Task start at:' + datetime.strftime(start_time, '%Y-%m-%d %H:%M:%S') + '\\nTaget: ' + target + '\\nSince: ' + since + '\\nUntil: ' + until + '\\n')\n log.write('Task start at:' + datetime.strftime(start_time, '%Y-%m-%d %H:%M:%S') + '\\nTaget: ' + target + '\\nSince: ' + since + '\\nUntil: ' + until + '\\n')\n log.close()\n\n #Get list of feed id from target.\n feeds_url = 'https://graph.facebook.com/v2.7/' + target + '/?fields=feed.limit(100).since(' + since + ').until(' + until + '){id}&' + token\n feed_list = []\n try:\n feed_list = getFeedIds(getRequests(feeds_url), [])\n except:\n print(\"No posts in specified range for \"+target+\". Please expand the time range to allow for more posts\")\n\n #feed_list = getFeedIds(getRequests(feeds_url), [])\n\n if not stream:\n feed_list_file = open('feed_ids', 'w')\n for id in feed_list:\n feed_list_file.write(id + '\\n')\n feed_list_file.close()\n\n \n \n\n feed_list = [str(i) for i in feed_list] \n # print(\"Feed LIST: \" + feed_list)\n \n\n #Get message, comments and reactions from feed.\n target_pool = Pool()\n postList = target_pool.map(getFeed, feed_list)\n #print(postList) \n\n\n followerCount_url = 'https://graph.facebook.com/'+target+'/?fields=fan_count&'+token\n followerCount = getFollowerCount(getRequests(followerCount_url))\n\n #print(postListGlobal)\n data = {\n 'Artist Name' : 'x',\n 'Artist Login' : target ,\n 'File create date/time' : str(datetime.now()), \n 'Follower Count' : followerCount,\n 'Posts': postList\n }\n\n #print(data)\n\n with io.open (target +'.json', 'w', encoding = \"utf-8\") as fp:\n json.dump(data, fp, indent = 4, ensure_ascii=False)\n\n\n target_pool.close()\n\n if not stream:\n end_time = datetime.now()\n cost_time = time.time() - execution_start_time\n print('\\nTask end Time: ' + datetime.strftime(end_time, '%Y-%m-%d %H:%M:%S') + '\\nTime Cost: ' + str(cost_time))\n log = open('log', 'a')\n log.write('\\nTask end Time: ' + datetime.strftime(end_time, '%Y-%m-%d %H:%M:%S') + '\\nTime Cost: ' + str(cost_time))\n log.close()\n os.chdir('../')\n\n\n##########################################################################################################\nif __name__ == '__main__':\n\n\n # Set crawler target and parameters.\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"target\", help=\"Set the target fans page(at least one) you want to crawling. Ex: 'appledaily.tw' or 'appledaily.tw, ETtoday'\")\n parser.add_argument(\"since\", help=\"Set the start date you want to crawling. Format: 'yyyy-mm-dd HH:MM:SS'\")\n parser.add_argument(\"until\", help=\"Set the end date you want to crawling. Format: 'yyyy-mm-dd HH:MM:SS'\")\n\n parser.add_argument(\"-r\", \"--reactions\", help=\"Collect reactions or not. Default is no.\")\n parser.add_argument(\"-s\", \"--stream\", help=\"If yes, this crawler will turn to streaming mode.\")\n\n args = parser.parse_args()\n\n target = str(args.target) #artist fb name\n global targGlobal \n targGlobal = target\n\n\n since = str(args.since)\n until = str(args.until)\n\n if args.reactions == 'yes':\n get_reactions = True\n else:\n get_reactions = False\n\n if args.stream == 'yes':\n stream = True\n else:\n stream = False\n\n app_id = '157949204752963'\n app_secret = '2aa1ebdf5aa5cb1e190ffdc21b032c99'\n\n token = 'access_token=' + app_id + '|' + app_secret\n\n global tokenGlobal\n tokenGlobal = token\n\n #Create a directory to restore the result if not in stream mode.\n if not stream:\n result_dir = 'Result/'\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n os.chdir(result_dir)\n\n if target.find(',') == -1:\n #followerCount_url = 'https://graph.facebook.com/'+target+'/?fields=fan_count&'+token\n #print(\"FOLLOWWWWW:\" + followerCount_url)\n #followerCount = getFollowerCount(getRequests(followerCount_url))\n #print(\"COUNT \" + str(followerCount))\n print(\"TARGET: \", target)\n getTarget(target)\n \n\n #For follower Count\n \n else:\n #followerCount_url = 'https://graph.facebook.com/'+target+'/?fields=fan_count&'+token\n #followerCount = getFollowerCount(getRequests(followerCount_url))\n\n #print(\"FOLLOWWWWW: \" + str(followerCount_url))\n target = target.split(',')\n for t in target :\n getTarget(t)\n\n #print(postListGlobal)\n \n\n\n","sub_path":"Facebook_Page_Crawler.py","file_name":"Facebook_Page_Crawler.py","file_ext":"py","file_size_in_byte":15899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"483300204","text":"# Github >> yogeshsinghgit <<< \n# Follow me on Instagram @dynamic.coding \n\n\nfrom tkinter import *\nfrom tkinter.filedialog import asksaveasfilename, askopenfilename\nimport subprocess, os\nfrom tkinter import messagebox\nfrom idlelib.percolator import Percolator\nfrom idlelib.colorizer import ColorDelegator\n\ncompiler = Tk()\ncompiler.title('PyCode - Dynamic Coding')\nfile_path = ''\n\n\n\ndef set_file_path(path):\n global file_path\n file_path = path\n\n\ndef open_file():\n path = askopenfilename(filetypes=[('Python Files', '*.py')])\n # print(\"Open Path\",path)\n with open(path, 'r') as file:\n code = file.read()\n editor.delete('1.0', END)\n editor.insert('1.0', code)\n set_file_path(path)\n\n\ndef save_as():\n if file_path == '':\n path = asksaveasfilename(filetypes=[('Python Files', '*.py')])\n else:\n path = file_path\n with open(path, 'w') as file:\n code = editor.get('1.0', END)\n file.write(code)\n set_file_path(path)\n\n\ndef run():\n if file_path == '':\n messagebox.showwarning(\"Pycode Warning\",'Please save your code')\n return\n file_name = os.path.basename(file_path)\n #print(f\"File Name : {file_name}\")\n command = f'python {file_name}'\n #print(\"command :\",command)\n process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n output, error = process.communicate()\n # print(\"Output : \",output)\n # print(\"Error : \",error)\n code_output.insert('1.0', output)\n code_output.insert('1.0', error)\n\n\nmenu_bar = Menu(compiler)\n\nfile_menu = Menu(menu_bar, tearoff=0)\nfile_menu.add_command(label='Open', command=open_file)\nfile_menu.add_command(label='Save', command=save_as)\nfile_menu.add_command(label='Save As', command=save_as)\nfile_menu.add_command(label='Exit', command=exit)\nmenu_bar.add_cascade(label='File', menu=file_menu)\n\nrun_bar = Menu(menu_bar, tearoff=0)\nrun_bar.add_command(label='Run', command=run)\nmenu_bar.add_cascade(label='Run', menu=run_bar)\n\ncompiler.config(menu=menu_bar)\n\neditor = Text()\neditor.pack()\nPercolator(editor).insertfilter(ColorDelegator())\n\ncode_output = Text(height=10,fg='blue')\ncode_output.pack()\n\ncompiler.mainloop()\n","sub_path":"PyCode/pycodeV1.py","file_name":"pycodeV1.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"311493405","text":"import torch\nimport torch.nn as nn\nimport torchvision\nfrom datetime import datetime\nimport models.WGANGP as WGANGP\nimport os\nfrom collections import OrderedDict\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# load the model\nMODEL_PATH = os.path.dirname(os.path.realpath(__file__)) + '/../saved_models/'\nMODEL_NAME = 'wgangp-model-epoch300.pth'\nZ_DIM = 100\nG = WGANGP.Generator(\n channels=[Z_DIM, 256, 128, 64, 1],\n kernels=[None, 7, 5, 4, 4],\n strides=[None, 1, 1, 2, 2],\n paddings=[None, 0, 2, 1, 1],\n batch_norm=True,\n internal_activation=nn.ReLU(),\n output_activation=nn.Tanh()\n)\n# reference: https://discuss.pytorch.org/t/solved-keyerror-unexpected-key-module-encoder-embedding-weight-in-state-dict/1686/3\n# loading a model that was wrapped by nn.DataParallel for training\ncheckpoint = torch.load(MODEL_PATH + MODEL_NAME, map_location=device)\nold_G_state_dict = checkpoint.get('G_state_dict')\n# if the model was wrapped by nn.DataParallel\nif 'module.' in list(old_G_state_dict.keys())[0]:\n new_G_state_dict = OrderedDict()\n for key, value in old_G_state_dict.items():\n # remove \"module.\" from each key\n name = key[7:]\n new_G_state_dict[name] = value\n # load the newly created state dict\n G.load_state_dict(new_G_state_dict)\nelse:\n G.load_state_dict(old_G_state_dict)\n\n# generate new image\nsample = torch.randn((1, Z_DIM))\nprint(f'Sample: {sample}\\n')\nsample = sample.view((-1, Z_DIM, 1, 1))\nsample = G(sample)\nfilename = datetime.now().strftime('%d_%m_%Y_%H%M%S')\ntorchvision.utils.save_image(sample, f'{filename}.png')","sub_path":"code/wgangp_app.py","file_name":"wgangp_app.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"623829776","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 ('myapplication', '0003_publickey'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ReportFile',\n fields=[\n ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),\n ('file', models.FileField(upload_to='')),\n ('reporter', models.ForeignKey(to='myapplication.Report')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='report',\n name='encrypted',\n field=models.BooleanField(default=False),\n preserve_default=True,\n ),\n ]\n","sub_path":"myapplication/migrations/0004_auto_20160417_2156.py","file_name":"0004_auto_20160417_2156.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"324605267","text":"#########\n# Copyright (c) 2014 GigaSpaces Technologies Ltd. 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 copy\nimport re\n\nfrom cloudify import ctx\nfrom cloudify.exceptions import NonRecoverableError\n\nfrom openstack_plugin_common import (\n get_resource_id,\n use_external_resource,\n delete_resource_and_runtime_properties,\n validate_resource,\n validate_ip_or_range_syntax,\n OPENSTACK_ID_PROPERTY,\n OPENSTACK_TYPE_PROPERTY,\n OPENSTACK_NAME_PROPERTY,\n COMMON_RUNTIME_PROPERTIES_KEYS\n)\n\nSECURITY_GROUP_OPENSTACK_TYPE = 'security_group'\n\n# Runtime properties\nRUNTIME_PROPERTIES_KEYS = COMMON_RUNTIME_PROPERTIES_KEYS\n\nNODE_NAME_RE = re.compile('^(.*)_.*$') # Anything before last underscore\n\n\ndef build_sg_data(args=None):\n security_group = {\n 'description': None,\n 'name': get_resource_id(ctx, SECURITY_GROUP_OPENSTACK_TYPE),\n }\n\n args = args or {}\n security_group.update(ctx.node.properties['security_group'], **args)\n\n return security_group\n\n\ndef process_rules(client, sgr_default_values, cidr_field_name,\n remote_group_field_name, min_port_field_name,\n max_port_field_name):\n rules_to_apply = ctx.node.properties['rules']\n security_group_rules = []\n for rule in rules_to_apply:\n security_group_rules.append(\n _process_rule(rule, client, sgr_default_values, cidr_field_name,\n remote_group_field_name, min_port_field_name,\n max_port_field_name))\n\n return security_group_rules\n\n\ndef use_external_sg(client):\n return use_external_resource(ctx, client,\n SECURITY_GROUP_OPENSTACK_TYPE)\n\n\ndef set_sg_runtime_properties(sg, client):\n ctx.instance.runtime_properties[OPENSTACK_ID_PROPERTY] =\\\n client.get_id_from_resource(sg)\n ctx.instance.runtime_properties[OPENSTACK_TYPE_PROPERTY] =\\\n SECURITY_GROUP_OPENSTACK_TYPE\n ctx.instance.runtime_properties[OPENSTACK_NAME_PROPERTY] = \\\n client.get_name_from_resource(sg)\n\n\ndef delete_sg(client, **kwargs):\n delete_resource_and_runtime_properties(ctx, client,\n RUNTIME_PROPERTIES_KEYS)\n\n\ndef sg_creation_validation(client, cidr_field_name, **kwargs):\n validate_resource(ctx, client, SECURITY_GROUP_OPENSTACK_TYPE)\n\n ctx.logger.debug('validating CIDR for rules with a {0} field'.format(\n cidr_field_name))\n for rule in ctx.node.properties['rules']:\n if cidr_field_name in rule:\n validate_ip_or_range_syntax(ctx, rule[cidr_field_name])\n\n\ndef _process_rule(rule, client, sgr_default_values, cidr_field_name,\n remote_group_field_name, min_port_field_name,\n max_port_field_name):\n ctx.logger.debug(\n \"Security group rule before transformations: {0}\".format(rule))\n\n sgr = copy.deepcopy(sgr_default_values)\n if 'port' in rule:\n rule[min_port_field_name] = rule['port']\n rule[max_port_field_name] = rule['port']\n del rule['port']\n sgr.update(rule)\n\n if (remote_group_field_name in sgr) and sgr[remote_group_field_name]:\n sgr[cidr_field_name] = None\n elif ('remote_group_node' in sgr) and sgr['remote_group_node']:\n _, remote_group_node = _capabilities_of_node_named(\n sgr['remote_group_node'])\n sgr[remote_group_field_name] = remote_group_node[OPENSTACK_ID_PROPERTY]\n del sgr['remote_group_node']\n sgr[cidr_field_name] = None\n elif ('remote_group_name' in sgr) and sgr['remote_group_name']:\n sgr[remote_group_field_name] = \\\n client.get_id_from_resource(\n client.cosmo_get_named(\n SECURITY_GROUP_OPENSTACK_TYPE, sgr['remote_group_name']))\n del sgr['remote_group_name']\n sgr[cidr_field_name] = None\n\n ctx.logger.debug(\n \"Security group rule after transformations: {0}\".format(sgr))\n return sgr\n\n\ndef _capabilities_of_node_named(node_name):\n result = None\n caps = ctx.capabilities.get_all()\n for node_id in caps:\n match = NODE_NAME_RE.match(node_id)\n if match:\n candidate_node_name = match.group(1)\n if candidate_node_name == node_name:\n if result:\n raise NonRecoverableError(\n \"More than one node named '{0}' \"\n \"in capabilities\".format(node_name))\n result = (node_id, caps[node_id])\n if not result:\n raise NonRecoverableError(\n \"Could not find node named '{0}' \"\n \"in capabilities\".format(node_name))\n return result\n","sub_path":"openstack_plugin_common/security_group.py","file_name":"security_group.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"241922367","text":"import argparse\nimport os\n\nfrom plastic_agent.plastic.policy import Policy\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--models_dir', type=str, default=None)\n parser.add_argument('--team_name', type=str, default=None)\n args = parser.parse_args()\n\n directory = args.models_dir\n team_name = args.team_name\n if os.path.isdir(directory):\n print(f\"[Set Up Policies] Dir FOUND: {directory};\")\n else:\n print(f\"[Set Up Policies] Dir Not Found: {directory};\")\n raise NotADirectoryError(directory)\n\n policies = list()\n if os.path.isdir(os.path.join(directory)):\n policy = Policy.create(team_name=team_name, directory=directory)\n\n print(f\"\\n\\n!!!!!!!!! Set Up Policies Done !!!!!!!!!!!!\\n\\n\")\n","sub_path":"plastic_agent/plastic/set_up/set_up_policies.py","file_name":"set_up_policies.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"98164408","text":"\"\"\"empty message\n\nRevision ID: 87e9e89a0b4d\nRevises: 07d78838a3ef\nCreate Date: 2020-12-26 12:38:41.596892\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '87e9e89a0b4d'\ndown_revision = '07d78838a3ef'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('artists', sa.Column('website', sa.String(length=120), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('artists', 'website')\n # ### end Alembic commands ###\n","sub_path":"01_fyyur/migrations/versions/87e9e89a0b4d_.py","file_name":"87e9e89a0b4d_.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"475525805","text":"import yaml\n\nCONF_DIR = \"conf/\"\nCONF_FILE = \"prod.yml\"\nconf_dict = yaml.safe_load(open(CONF_DIR + CONF_FILE, 'r'))\n\nRUN_MODES = conf_dict[\"run\"][\"modes\"].split(\",\")\nLOG_LEVEL = conf_dict[\"run\"][\"level\"]\nLOG_FILE_PATH = conf_dict[\"directories\"][\"logging_path\"]\n\nprocessing_dict = conf_dict[\"run\"][\"mode_options\"][\"processing\"]\nINDEXATION_MODE = processing_dict[\"indexation_mode\"]\nINDEX_READ = processing_dict[\"index\"]\nPROCESSED_INDEX = INDEX_READ + \"_\" + INDEXATION_MODE\nFORCE_REWRITE = processing_dict[\"force_rewrite\"]\nFIELDS_TO_INDEX = processing_dict[\"fields_to_index\"].split(\",\")\nFIELDS_TO_KEEP = processing_dict[\"supplementary_fields\"].split(\",\") + FIELDS_TO_INDEX\nID_FIELD = processing_dict[\"id_field\"]\n\nsearching_dict = conf_dict[\"run\"][\"mode_options\"][\"searching\"]\nSEARCHING_INDEX = searching_dict[\"index\"]\nQUERY = searching_dict[\"query\"]\nPOPULARITY_FIELD = searching_dict[\"popularity_field\"]\nFUZZINESS = searching_dict[\"fuzziness\"]\nFIELDS_TO_SEARCH = searching_dict[\"fields_to_search\"]\n\nnlp_dict = conf_dict[\"run\"][\"mode_options\"][\"nlp\"]\nFIELD_TO_EMBED = nlp_dict[\"field_to_embed\"]\nRETRAIN_MODEL = nlp_dict[\"retrain_model\"]\nMODEL_PATH = nlp_dict[\"model_path\"]\n","sub_path":"docker/comet-usecase/search/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"639246280","text":"import os, re, sys\n\nproject_directory = os.getcwd()\npattern = r'data_\\w*_r.dt'\npattern_res = r'Time\\sMatrix-Vector\\smultiplication\\sin\\s*\\n([a-zA-Z\\-_()]*):\\s*(\\d*\\.\\d*)\\s*\\n\\w*\\s\\w*\\s\\w*\\s(\\d*\\.\\d*)'\ntime_list = []\n\nfor dirs, node, files in os.walk(project_directory):\n for file in files:\n if re.search(pattern, file) != None:\n file_path = os.path.abspath(dirs)\n file_path = os.path.abspath(file_path + '/' + file)\n file_obj = open(file_path)\n file_string = ''\n for line in file_obj:\n file_string = file_string + line\n time_res = re.search(pattern_res, file_string) \n if time_res != None:\n name_format = time_res.group(1)\n time_mult = time_res.group(2)\n diff = time_res.group(3)\n if time_list.count(name_format) == 0:\n time_list.append(name_format)\n temp_list = [time_mult, diff]\n time_list.append(temp_list)\n if time_list.count(name_format) == 1:\n index = time_list.index(name_format)\n temp_list = time_list.pop(index + 1)\n time_list.pop(index)\n temp_list.append(time_mult) \n temp_list.append(diff)\n time_list.append(name_format)\n time_list.append(temp_list)\n\ni = 0\nfor elem in time_list:\n if i % 2 == 0: \n print(elem)\n else:\n j = 0 \n temp_str = ''\n for time_elem in elem:\n if j % 2 == 0:\n temp_str = '--- Time: ' + time_elem\n else: \n print(temp_str + ' Diff: ' + time_elem)\n j = j + 1 \n i = i + 1\n\n","sub_path":"SparseNew/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"563664435","text":"\nfrom machine import *\n\ndef callback(p):\n \n print('pin change',p)\n\np0=Pin(33,mode=Pin.IN,pull=Pin.PULL_UP)\np1=Pin(32,mode=Pin.IN,pull=Pin.PULL_UP)\n\n\np0.irq(trigger=Pin.IRQ_FALLING, handler=callback)\np1.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=callback)","sub_path":"examples/temp/GPIO/irq.py","file_name":"irq.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"81963982","text":"import dash_table as dt\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_bootstrap_components as dbc\n\ndef get(id):\n table_content = html.Div(\n [\n dt.DataTable(\n id = id + '-data-table',\n data = [{}],\n )\n ],\n\n className = 'data-table-container',\n id = id + '-table-container',\n )\n\n modal = html.Div([\n dbc.Modal(\n [\n dbc.ModalHeader(\n dbc.Button(\"Close\", id=id + \"-table-close\", className=\"ml-auto\")\n ),\n dbc.ModalBody(table_content),\n ],\n id= id + \"-table-modal\",\n size = 'lg',\n scrollable = True,\n backdrop='static',\n is_open = True # This ensures that the table will render (will close modal on page loading)\n ),\n ])\n return modal\n\ndef get_table(id):\n return html.Div([\n dt.DataTable(\n id = id,\n data = [{}],\n )\n ],\n\n className = 'data-table-container',\n id = id + '-container',\n style = dict(display = 'none')\n )\n","sub_path":"src/layouts/global_layout/data_table.py","file_name":"data_table.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"579069953","text":"import os\n\"\"\"\n用*替换找到的敏感词\n\"\"\"\ndef filewalk():\n curdir=os.scandir(path='.')\n for file in curdir:\n if file.is_file() and file.name.split('.')[1]=='txt':\n return file.path\n\nfile=open(filewalk(),'r',encoding='utf-8')\ndef replace(inputword):\n for i in file.read().split():\n if i in inputword:\n new=inputword.replace(i,'*'*len(i))\n inputword=new\n return inputword\n\n\nif __name__ == '__main__':\n while True:\n print(replace(input('write some thing:')))\n","sub_path":"py0012/sr_words.py","file_name":"sr_words.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"160518371","text":"import hashlib\n\nfrom utils import hash_util\nfrom wallet import Wallet\n\n\nclass Verification:\n\t@classmethod\n\tdef verify_chain(cls, blockchain):\n\t\tfor (index, block) in enumerate(blockchain):\n\t\t\tif index == 0:\n\t\t\t\tcontinue\n\t\t\tif block.previous_hash != hash_util.hash_block(blockchain[index - 1]):\n\t\t\t\treturn False\n\t\t\tif not cls.validate_proof(block.transactions[:-1], block.previous_hash, block.proof):\n\t\t\t\tprint(\"Proof of work is invalid\")\n\t\t\t\treturn False\n\t\treturn True\n\n\t@staticmethod\n\tdef verify_transaction(transaction, get_balance, check_funds=True):\n\t\tif check_funds:\n\t\t\tsender_balance = get_balance()\n\t\t\treturn sender_balance >= transaction.amount > 0 and Wallet.verify_transaction(transaction)\n\t\telse:\n\t\t\treturn Wallet.verify_transaction(transaction)\n\n\t@classmethod\n\tdef verify_transactions(cls, open_transactions, get_balance):\n\t\treturn all([cls.verify_transaction(tx, get_balance, False) for tx in open_transactions])\n\n\t@staticmethod\n\tdef validate_proof(transactions, last_hash, proof):\n\t\tguess = (str([tx.convert_to_ordered_dict() for tx in transactions]) + str(last_hash) + str(proof)).encode()\n\t\tguess_hash = hashlib.sha256(guess).hexdigest()\n\t\treturn guess_hash[0:2] == \"00\"\n","sub_path":"utils/verification.py","file_name":"verification.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"542003957","text":"import asyncio\nimport datetime\nimport os\nimport traceback\nfrom typing import Any\n\nimport aiohttp\nimport discord\nfrom discord import AsyncWebhookAdapter, Webhook\nfrom discord.ext import commands, flags\nfrom dotenv import load_dotenv\n\nfrom app import utils\nfrom app.i18n import t_\n\nfrom ... import errors\nfrom ...classes.bot import Bot\n\nload_dotenv()\n\nIGNORED_ERRORS = [commands.CommandNotFound, errors.AllCommandsDisabled]\nSEND_HELP = [\n commands.MissingRequiredArgument,\n discord.InvalidArgument,\n commands.BadArgument,\n flags.ArgumentParsingError,\n]\nEXPECTED_ERRORS = [\n errors.ConversionError,\n errors.DoesNotExist,\n errors.AlreadyExists,\n errors.CommandDisabled,\n commands.MissingRequiredArgument,\n commands.ChannelNotFound,\n commands.RoleNotFound,\n commands.NotOwner,\n commands.CommandOnCooldown,\n commands.ExpectedClosingQuoteError,\n commands.BotMissingPermissions,\n discord.Forbidden,\n discord.InvalidArgument,\n commands.BadArgument,\n commands.NoPrivateMessage,\n commands.UserNotFound,\n commands.RoleNotFound,\n flags.ArgumentParsingError,\n]\nUPTIME = os.getenv(\"UPTIME_HOOK\")\nERROR = os.getenv(\"ERROR_HOOK\")\nGUILD = os.getenv(\"GUILD_HOOK\")\n\n\nclass BaseEvents(commands.Cog):\n def __init__(self, bot: Bot) -> None:\n self.bot = bot\n\n self.session: aiohttp.ClientSession = None\n self.guild_webhook: Webhook = None\n self.error_webhook: Webhook = None\n self.uptime_webhook: Webhook = None\n\n self.type_map = {\n \"error\": {\"color\": self.bot.error_color, \"title\": \"Error\"},\n \"info\": {\"color\": self.bot.theme_color, \"title\": \"Info\"},\n }\n\n def cog_unload(self):\n asyncio.ensure_future(self.session.close())\n\n async def get_session(self) -> None:\n if self.session:\n return\n self.session = aiohttp.ClientSession()\n\n async def uptime_log(self, content: str) -> None:\n if not UPTIME:\n return\n await self.get_session()\n if not self.uptime_webhook:\n self.uptime_webhook = Webhook.from_url(\n UPTIME, adapter=AsyncWebhookAdapter(self.session)\n )\n await self.uptime_webhook.send(content, username=\"Starboard Uptime\")\n\n async def error_log(self, content: str) -> None:\n if not ERROR:\n return\n await self.get_session()\n if not self.error_webhook:\n self.error_webhook = Webhook.from_url(\n ERROR, adapter=AsyncWebhookAdapter(self.session)\n )\n await self.error_webhook.send(content, username=\"Starboard Errors\")\n\n async def join_leave_log(self, embed: discord.Embed) -> None:\n if not GUILD:\n return\n await self.get_session()\n if not self.guild_webhook:\n self.guild_webhook = Webhook.from_url(\n GUILD, adapter=AsyncWebhookAdapter(self.session)\n )\n await self.guild_webhook.send(\n embed=embed, username=\"Starboard Guild Log\"\n )\n\n @commands.Cog.listener()\n async def on_guild_join(self, guild: discord.Guild) -> None:\n embed = discord.Embed(\n title=f\"Joined **{guild.name}**\",\n description=f\"**{guild.member_count} members**\",\n color=self.bot.theme_color,\n )\n embed.timestamp = datetime.datetime.utcnow()\n await self.join_leave_log(embed)\n\n @commands.Cog.listener()\n async def on_guild_remove(self, guild: discord.Guild) -> None:\n embed = discord.Embed(\n title=f\"Left **{guild.name}**\",\n description=f\"**{guild.member_count} members**\",\n color=self.bot.dark_theme_color,\n )\n embed.timestamp = datetime.datetime.utcnow()\n await self.join_leave_log(embed)\n\n @commands.Cog.listener()\n async def on_log_error(\n self,\n title: str,\n error: Exception,\n args: list[Any] = [],\n kwargs: dict = {},\n ) -> None:\n p = commands.Paginator(prefix=\"```python\")\n\n p.add_line(title)\n p.add_line(empty=True)\n p.add_line(f\"{type(error)}: {error}\")\n p.add_line(empty=True)\n p.add_line(f\"Args: {args}\")\n p.add_line(f\"Kwargs: {kwargs}\")\n p.add_line(empty=True)\n\n tb = traceback.format_tb(error.__traceback__)\n for line in tb:\n p.add_line(line=line)\n\n for page in p.pages:\n await self.error_log(page)\n\n @commands.Cog.listener()\n async def on_shard_ready(self, shard_id: int) -> None:\n self.bot.log.info(\n f\"[Cluster#{self.bot.cluster_name}] Shard {shard_id} ready\"\n )\n\n @commands.Cog.listener()\n async def on_ready(self) -> None:\n self.bot.log.info(f\"[Cluster#{self.bot.cluster_name}] Ready\")\n await self.uptime_log(\n f\":green_circle: Cluster **{self.bot.cluster_name}** ready!\"\n )\n try:\n self.bot.pipe.send(1)\n except BrokenPipeError:\n pass\n\n @commands.Cog.listener()\n async def on_message(self, message: discord.Message) -> None:\n await self.bot.set_locale(message)\n if message.author.bot:\n return\n if message.content.replace(\"!\", \"\") == self.bot.user.mention:\n p = utils.escmd((await self.bot.get_prefix(message))[0])\n await message.channel.send(t_(\"My prefix is `{0}`.\").format(p))\n else:\n await self.bot.process_commands(message)\n\n @commands.Cog.listener()\n async def on_command_error(\n self, ctx: commands.Context, e: Exception\n ) -> None:\n try:\n e = e.original\n except AttributeError:\n pass\n if type(e) in IGNORED_ERRORS:\n return\n elif type(e) in EXPECTED_ERRORS:\n try:\n if type(e) in SEND_HELP:\n p = utils.clean_prefix(ctx)\n await ctx.send(\n f\"{e}\\n\\n```{p}{ctx.command} \"\n f\"{ctx.command.signature}```\"\n )\n else:\n await ctx.send(e)\n except discord.Forbidden:\n await ctx.message.author.send(\n t_(\n \"I don't have permission to send messages in \"\n \"{0}, so I can't respond to your command.\"\n ).format(ctx.channel.mention)\n )\n else:\n embed = discord.Embed(\n title=\"Something's Not Right\",\n description=t_(\n \"Something went wrong while \"\n \"running this command. If the \"\n \"problem persists, please report \"\n \"this in the support server.\"\n ),\n color=self.bot.error_color,\n )\n tb = \"\".join(traceback.format_tb(e.__traceback__))\n full_tb = f\"{e}\\b\" f\"```{tb}```\"\n if len(full_tb) > 1024:\n to_remove = (len(full_tb) - 1024) + 10\n full_tb = f\"{e}\\n```...{tb[to_remove:]}```\"\n embed.add_field(name=e.__class__.__name__, value=full_tb)\n try:\n await ctx.send(embed=embed)\n except discord.Forbidden:\n pass\n\n self.bot.dispatch(\n \"log_error\", \"Command Error\", e, ctx.args, ctx.kwargs\n )\n\n @commands.Cog.listener()\n async def on_guild_log(\n self, message: str, log_type: str, guild: discord.Guild\n ) -> None:\n sql_guild = await self.bot.db.guilds.get(guild.id)\n if sql_guild[\"log_channel\"] is None:\n return\n log_channel = guild.get_channel(int(sql_guild[\"log_channel\"]))\n if not log_channel:\n return\n\n embed = discord.Embed(\n title=self.type_map[log_type][\"title\"],\n description=message,\n color=self.type_map[log_type][\"color\"],\n )\n embed.timestamp = datetime.datetime.utcnow()\n await log_channel.send(embed=embed)\n\n @commands.Cog.listener()\n async def on_level_up(\n self, guild: discord.Guild, user: discord.User, level: int\n ) -> None:\n sql_guild = await self.bot.db.guilds.get(guild.id)\n if sql_guild[\"level_channel\"] is None:\n return\n level_channel = guild.get_channel(int(sql_guild[\"level_channel\"]))\n if not level_channel:\n return\n embed = discord.Embed(\n title=t_(\"{0} Leveled up!\").format(user.name),\n description=t_(\"They are now level **{0}**!\").format(level),\n color=self.bot.theme_color,\n ).set_author(name=str(user), icon_url=user.avatar_url)\n embed.timestamp = datetime.datetime.utcnow()\n await level_channel.send(\n content=f\"{user.mention}\" if sql_guild[\"ping_user\"] else \"\",\n embed=embed,\n allowed_mentions=discord.AllowedMentions(users=True),\n )\n\n\ndef setup(bot: Bot) -> None:\n bot.add_cog(BaseEvents(bot))\n\n @bot.before_invoke\n async def create_data(message: discord.Message) -> None:\n if message.guild is None:\n return\n await bot.db.guilds.create(message.guild.id)\n await bot.db.users.create(message.author.id, message.author.bot)\n await bot.db.members.create(message.author.id, message.guild.id)\n","sub_path":"app/cogs/base/base_events.py","file_name":"base_events.py","file_ext":"py","file_size_in_byte":9387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"289478987","text":"#!/usr/bin/python3\n# coding: utf8\nimport os\nimport random\n\n\n\t\nclass chatbot():\n\tdef __init__(self,config={'learn':False,'learn_file':'learn.py','debug':False}):\n\t\tself.config = config\n\t\tage = 15\n\t\tself.genre = 'homme'\n\t\tself.phrase = 'courant'\n\t\tself.format = {'sexe':'homme'}\n\t\tself.format['nom']= 'jules'\n\t\tif self.format['sexe'] == 'homme':\n\t\t\tself.format['civilite'] = 'monsieur'\n\t\telse :\n\t\t\tself.format['civilite'] = 'madame'\n\t\tself.rep=[]\n\t\t\n\t\t\n\tdef reponce(self,rep) :\n\t\tif type(rep) == str :\n\t\t\treturn rep.format(**self.format) # Si la reponce est une chaine de caracteres , on la lui renvoie avec les information nécésaires\n\t\telif type(rep) == dict:\n\t\t\treturn (self.reponce(rep[self.phrase])) # Si la reponce est un dictionnair , on lui renvoie la liste avec le type de langage choisi\n\t\telif type(rep) == list:\n\t\t\treturn (random.choice(rep).format(**self.format)) # Si la reponce est une liste , on lui renvoie une des chaine de caracteres avec les information nécésairesif type(self.rep) == str :\n\t\t\n\tdef learn(self):\n\t\tmots = input('mots a apprendre au format dict >>')\n\t\tself.reponce = input('self.reponce a donner >>')\n\t\t#nws = input('nowordsuprime [None/True] >>')\n\t\toutput = \"\\nquery(mots=\"+mots+\",reponce=\"+str(self.reponce)+\",msg=msg,learn=False,nowordsuprime=None)\\n\"\n\t\tfile_learn_output = open(self.config['learn_file'], \"w\")\n\t\tfile_learn_output.write(output)\n\t\tfile_learn_output.close() \n\t\t\n\tdef debug(self,text):\n\t\tif text:\n\t\t\tif self.config['debug'] == True:\n\t\t\t\tprint(\"[debug]: {}\".format(text))\n\t\t\t\t\t\n\tdef query(self,mots,reponce,msg,learn=False,nowordsuprime=None):\n\t\t\"\"\"\n\t\t# Set : Tous les mots doivent etre présent\n\t\t# Str : \n\t\t\"\"\"\n\t\tif mots and msg:\n\t\t\tif type(mots) == set :\n\t\t\t\tnb_de_mots = len(mots) # on défini le nombre de mots obligatoires\n\t\t\t\tnb_mots_detectes = 0\n\t\t\t\tfor mots_obliges in mots : # Pour chaque mots obligatoir dans la phrase\n\t\t\t\t\tstat , etat_start_query = 0 , 0 # On initialise les variable de verifiquation\n\t\t\t\t\tif (mots_obliges in msg): # Si le mots est présent dans la phrase\n\t\t\t\t\t\tnb_mots_detectes = nb_mots_detectes + 1\n\t\t\t\t\t\tif not nowordsuprime :\n\t\t\t\t\t\t\tmsg.remove(mots_obliges)\n\t\t\t\t\tif nb_mots_detectes == nb_de_mots:\n\t\t\t\t\t\tif reponce != None : # Si on a défini une self.reponce \n\t\t\t\t\t\t\treponce = self.reponce(reponce) # on stocke une réponce\n\t\t\t\t\t\t\tself.debug('Ajoute de \"'+ reponce + '\"') # On .debug la réponce donnée\n\t\t\t\t\t\t\tself.rep.append(reponce) # On ajoute la réponce a la varible self.rep (Qui stocke toutes les réponces)\n\t\t\t\t\t\t\treturn True\t\t\n\t\t\telse: \n\t\t\t\tstat , etat_start_query = 0 , 0 # On initialise les variable de verifiquation\n\t\t\t\tfor mot in mots: # Pour chaque élements dans 'mots' (la phrase)\n\t\t\t\t\tif (mot in msg) and (stat == 0): # Si le mots est présent dans la phrase\n\t\t\t\t\t\tif reponce != None : # Si on a défini une self.reponce \n\t\t\t\t\t\t\treponce = self.reponce(reponce) # on stocke une réponce\n\t\t\t\t\t\t\tself.debug('Ajoute de \"'+ reponce + '\"') # On debug la réponce donnée\n\t\t\t\t\t\t\tself.rep.append(reponce) # On ajoute la réponce a la varible self.rep (Qui stocke toutes les réponces)\n\t\t\t\t\t\tstat = stat + 1\n\t\t\t\t\t\tif not nowordsuprime :\n\t\t\t\t\t\t\tmsg.remove(mot)\n\t\t\t\tif stat != 0:\n\t\t\t\t\treturn stat\n\t\t\t\telse :\n\t\t\t\t\treturn None\n\n\tdef init(self,msg):\n\t\t#Fonction de self.debug\n\t\tlearn_file = open(self.config['learn_file'], \"r\")\n\t\tself.rep =[]\n\t\t#for i in [\"?\",\"-\",\";\",\",\",\"!\",\"'\"]: # On supprime la ponctation\n\t\t\t#if i in msg:\n\t\t\t\t#msg.remove(i)\n\t\n\t\n\t\tmsg=msg.lower()\n\t\n\t\tif \"le\" in msg:\n\t\t\tmsg = msg.self.replace(\"le \",\"l \")\n\t\n\t\tif \"la\" in msg:\n\t\t\tmsg = msg.self.replace(\"la \",\"l \")\n\t\t\t\n\t\tif \",\" in msg:\n\t\t\tself.rep.append(\",\")\n\t\n\t\tmsg=msg.replace(\" \",\"/-/\")\n\t\tmsg=msg.split('/-/')\n\t\n\t\n\t\tfor x in msg:\n\t\t\tif x == \"\":\n\t\t\t\tmsg.remove(x)\n\t\n\t\texec(str(learn_file.read())) # On execute ce qui a été appris\n\t\t\n\t\tif self.query(['herve'],None,msg) : \n\t\t\tif self.query([\"cucu\",\"bonjour\",\"plop\",\"salut\",\"slt\",\"hey\",\"hello\",\"yop\"],\n\t None,msg) :\n\t\t\t\tself.rep.append(self.reponce({\n\t'soutenu' :['bonjour {civilite}','mes salutations {civilite}'],\n\t'courant' : [\"plop\",\"salut\",\"slt\",\"hey\",\"hello\",\"yop\",]}))\n\t\t\telse :\n\t\t\t\tself.rep.append(self.reponce(\"oui {civilite} ?\"))\n\t\n\t\tself.query([\"cucu\",\"bonjour\",\"plop\",\"salut\",\"slt\",\"hey\",\"hello\",\"yop\"],\n\t {'soutenu' :['bonjour {civilite}','mes salutations {civilite}'],\n\t 'courant' : [\"plop\",\"salut\",\"slt\",\"hey\",\"hello\",\"yop\",]},msg)\n\t\n\t\tqueryreturnforcomment = self.query(mots=[\"comment\",\"coment\",\"commen\",\"comen\"],msg=msg,reponce=None,learn=False,nowordsuprime=None)\n\t\tif (queryreturnforcomment ) != None:\n\t\n\t\t\tif self.query(mots=[\"tu\"],msg=msg,reponce=\"je\",learn=False,nowordsuprime=None) != None:\n\t\t\t\t\n\t\n\t\t\t\tif \"vas\" in msg:\n\t\t\t\t\tmsg.remove(\"vas\")\n\t\t\t\t\tself.rep.append(\"vais bien merci\")\n\t\n\t\t\t\tif \"va\" in msg:\n\t\t\t\t\tself.rep.append(\"De qui parlez vous ?\")\n\t\n\t\t\tif \"faire\" in msg:\n\t\t\t\tremovedtext= [queryreturnforcomment,\"faire\"]\n\t\t\t\t#for x in removedtext:\n\t\t\t\t#\tmsg.remove(x)\n\t\t\t\t\n\t\t\t\tself.rep.extend(msg)\n\t\t\t\tmsg.extend(removedtext)\n\t\t\t\tself.rep.append(self.reponce([\"je recherche tout de suite comment faire\",\"je recherche cela tout de suite\",\"je recherche cela de suite {civilite}\",\"je recherche cela de suite {nom}\"]))\n\t\n\t\tif (self.query(mots=[\"/restart\"],reponce=None,msg=msg,learn=False,nowordsuprime=None)):\n\t\t\tself.rep.append(' ')\n\t\t\tself.debug(\"self.rep:\")\n\t\t\tprint (self.rep)\n\t\t\tself.debug(\"Redémarrage de l’IA\")\n\t\t\t#os.system('python3 __init__.py')\n\t\tif(self.query(mots=[\"/learn\"],reponce=None,msg=msg,learn=False,nowordsuprime=None)):\n\t\t\tself.learn()\n\t\tif self.query(mots=['allume'],reponce=None,msg=msg,learn=False,nowordsuprime=None):\n\t\t\taction = 1\n\t\t\tif self.query(mots=['lumiere','lampe'],reponce=None,msg=msg,learn=False,nowordsuprime=None):\n\t\t\t\tif \"la\" in msg :\n\t\t\t\t\tmsg.remove(\"la\")\n\t\t\t\tself.rep.append(self.reponce(['La lampe '+ \" \".join(msg) + ' est allumée','La lumière '+ \" \".join(msg) + ' est allumée']))\n\t\t\t\tdevice_to_control= \"lumiere\"\n\t\t\t\tphrase = \" \".join(msg)\n\t\t\t\t\n\t\tself.query(mots={'je','aime','t'},reponce=\"mais je ne suis qu'un ecosysteme\",msg=msg,learn=False,nowordsuprime=None)\t\t\n\t\t\t\n\t\tif \"je\" in msg:\n\t\t\tif \"suis\" in msg:\n\t\t\t\t\n\t\t\t\tremovedtext = [\"je\",\"suis\"]\n\t\t\t\tfor x in removedtext:\n\t\t\t\t\tmsg.remove(x)\n\t\t\t\t\n\t\t\t\tif msg != \"\":\n\t\t\t\t\tself.rep.extend(msg)\n\t\t\t\t\n\t\n\t\tif \"sais\" in msg:\n\t\t\tself.rep.append(\"non ,je ne sais pas\")\n\t\n\t\tif (\"est-ce\" in msg) and (\"que\" in msg):\n\t\t\tremovedtext= [\"est-ce\",\"que\"]\n\t\n\t\t\tfor x in removedtext:\n\t\t\t\tmsg.remove(x)\n\t\t\t\n\t\t\tself.rep.extend(msg)\n\t\t\tmsg.extend(removedtext)\n\t\t\tself.rep.append(\"Non je ne pence pas.Je vais vérifier sur Internet\")\n\t\n\t\tquery_return_for_quel = self.query(mots=[\"quel\"],msg=msg,reponce=None,learn=False,nowordsuprime=True)\n\t\tif query_return_for_quel != None:\n\t\n\t\t\tquery_return_for_est=self.query(mots=[\"est\",\"etais\"],msg=msg,reponce=None,learn=False,nowordsuprime=True)\n\t\n\t\t\tif query_return_for_est != None:\n\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tif msg != \"\":\n\t\t\t\t\t#self.rep.append('D\\'apres internet , ' + ''.join(msg) + ' ' + query_return_for_est + ' ' + str(search_searx(''.join(msg))[0]['content']))\n\t\t\t\t\tself.rep.append(\"je ne sais pas quel {} {} mais je vais vous lancer la recherche\".format(query_return_for_est,msg))\n\t\n\t\tquery_return_for_qui = self.query(mots=[\"qui\"],msg=msg,reponce=None,learn=False,nowordsuprime=True)\n\t\tif query_return_for_qui != None:\n\t\t\tquery_return_for_est=self.query(mots=[\"est\",\"etais\",\"sera\",'suis-je'],msg=msg,reponce=None,learn=False,nowordsuprime=True)\n\t\t\tquery_retun_for_ponctuation = self.query(mots=[\"?\",\",\",\".\"],msg=msg,reponce=None,learn=False,nowordsuprime=True)\n\t\t\t#if query_retun_for_ponctuation != None:\n\t\t\t#\tmsg.remove(query_retun_for_ponctuation)\n\t\t\tif query_return_for_est != None:\n\t\t\t\t#removedtext = [query_return_for_qui,query_return_for_est]\n\t\t\t\t#for x in removedtext:\n\t\t\t\t#\tmsg.remove(x)\n\t\t\t\tif msg != \"\":\n\t\t\t\t\tif \"jules\" in msg and \"michael\" in msg:\n\t\t\t\t\t\tself.rep.append(\"Mon createur !\")\n\t\t\t\t\t\tmsg.remove(\"jules\")\n\t\t\t\t\t\tmsg.remove(\"michael\")\n\t\t\t\t\telse:\n\t\n\t\t\t\t\t\t#self.rep.append('D\\'apres Wikipédia , '+''.join(msg)+query_return_for_est+str(search_searx(''.join(msg))[0]['content']))\n\t\t\t\t\t\tself.rep.append(\"Je ne sais pas qui {} {} mais je vais vous lancer la recherche\".format(query_return_for_est,msg))\n\t\t\t\t\t\tself.debug(\"[simulation]: Lancement de la recherche sur le Mac\")\n\t\t\t\t\t\t#for i in msg :\n\t\t\t\t\t\t#\tmsg.remove(i)\n\t\t\t\t\t\t#mac.search(\"qui {} {}\".format(query_return_for_est,msg))\n\t\n\t\tif '' in msg:\n\t\t\tmsg.remove('')\n\t\n\t\t\n\t\tif msg != []:\n\t\t\tself.debug('Msg juste avant learn :'+str(msg))\n\t\t\tif self.config['learn'] == True : \n\t\t\t\tself.learn() \n\t\t\n\t\t\n\t\tif self.rep != []:\n\t\t\t#self.debug(\"Le résulta sous forme de liste ressemble a {}\".format(self.rep))\n\t\t\tself.rep = \" \".join(self.rep)\n\t\t\tself.rep = self.rep.capitalize()\n\t\t\t#self.debug(\"Le résulta sous forme de phrase plus ou moins correct ressemble a '{}'\".format(self.rep))\n\t\t\t\n\t\telse :\n\t\t\treturn (\"[erreur] :Aucune réponses n'a pu être trouvés , demandez aux développeurs d'ajouter \\\"{}\\\" a ma base de données\".format(msg),0)\n\t\t# return msg\n\t\treturn (self.rep,1)\n\t\t\n","sub_path":"brain2.py","file_name":"brain2.py","file_ext":"py","file_size_in_byte":9010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"176024694","text":"# -*- coding: utf-8 -*-\n# NoJoy_DI (c) 2016 by Andre Karlsson\n#\n# This file is part of NoJoy_DI.\n#\n# NoJoy_DI 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# Foobar 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 Foobar. If not, see .\n#\n# Filename: by: andrek\n# Timesamp: 5/1/16 :: 10:25 PM\n\nimport sys\nfrom src.utils.NoJoy_DI.utils import *\nfrom src.utils.NoJoy_DI.patterns import *\nfrom functools import wraps\nfrom importlib import import_module\n\ntry:\n\tfrom inspect import signature, Parameter\n\tsignature_empty = Parameter.empty\nexcept ImportError:\n\tfrom src.utils.funcsigs import signature\n\tfrom src.utils.funcsigs import _empty as signature_empty\n\n\nclass Service(object):\n\n\t_mypattern = DefaultPattern\n\t_factory = None\n\n\t_classification = None\n\t_classification_getter = None\n\t_inject_signature = False\n\n\t_locked = False\n\n\tdef __init__(self, mycallable, classification=None):\n\t\tsuper(Service, self).__init__()\n\n\t\tself._input = {}\n\t\tself._sets = {}\n\t\tself._callers = []\n\t\tself._injectors = []\n\t\tself._arguments_injectors = []\n\n\t\tself.name = object_name_standard(mycallable)\n\n\t\tif classification:\n\t\t\tself._classification = classification\n\t\telse:\n\t\t\tif callable(mycallable):\n\t\t\t\tself._classification = mycallable\n\t\t\telse:\n\t\t\t\tself._classification_getter = self._lazy_loader(mycallable)\n\n\tdef _get_classification(self):\n\t\tif self._classification:\n\t\t\treturn self._classification\n\t\tif self._classification_getter:\n\t\t\tself._classification = self._classification_getter()\n\t\t\treturn self._classification\n\n\t\traise Exception()\n\n\tdef _lazy_loader(self, class_hierarchy):\n\t\tmodule, cls = class_hierarchy.split('.', 1)\n\t\t@wraps(self._lazy_loader)\n\t\tdef wrapper(*args, **kwargs):\n\t\t\treturn getattr(import_module(module), cls)\n\t\treturn wrapper\n\n\tdef _lazymarker(self, myclone=None, myservice=None, myfunction=None, myvariable=None):\n\t\tif myclone is not None:\n\t\t\treturn myclone\n\t\telif myservice or myvariable:\n\t\t\treturn LazyMarker(service=myservice, function=myfunction, variable=myvariable)\n\n\tdef _input_maker(self, kwargs):\n\t\ttypes = {}\n\t\tfor key, value in kwargs.items():\n\t\t\tif key.endswith(\"__svc\"):\n\t\t\t\ttypes[key[:-5]] = self._lazymarker(myservice=value)\n\t\t\telif key.endswith(\"__param\"):\n\t\t\t\ttypes[key[:-7]] = self._lazymarker(myvariable=value)\n\t\t\telse:\n\t\t\t\ttypes[key] = value\n\t\treturn types\n\n\t@private\n\tdef set_classification(self, value):\n\t\t\"\"\"\n\t\tClassify the service callable\n\n\t\t:param value:A callable method/function to be classified as service main callable\n\t\t:return:\n\t\t\"\"\"\n\t\tself._classification = value\n\n\t@private\n\tdef set_factory(self, service=None, function=None, acallable=None):\n\t\t\"\"\"\n\t\tCreate a factory callable to by assigning a Factory to a Service(Class)\n\t\tand set the private factroy accordingly\n\n\t\t>>> di.set(AFactory_Class)\n\t\t>>> di.set(A_Class).set_factory(service=AFactory_Class, function=\"return_class_method\")\n\n\t\t:param service: The factory Service(class) it self\n\t\t:param function: Function/method to be called in the factory\n\t\t:param acallable: A already created LazyMarker\n\t\t:return:\n\t\t\"\"\"\n\t\tself._factory = self._lazymarker(myclone=acallable, myservice=service, myfunction=function)\n\n\t@private\n\tdef input(self, **kwargs):\n\t\t\"\"\"\n\t\tAdd constructor args for the service\n\n\t\t>>> di.set(AFactory_Class)\n\t\t>>> di.set(A_Class).set_factory(service=AFactory_Class, function=\"return_class_method\").input(variable=\"abc\")\n\n\t\t:param kwargs: Input arguments for the Service\n\t\t:return:\n\t\t\"\"\"\n\t\tself._input.update(self._input_maker(kwargs))\n\n\t@private\n\tdef call(self, function, arg=False, **kwargs):\n\t\t\"\"\"\n\t\tCall method adds a method call with arguments on an existing Service\n\n\t\t:param function: The callable function/method\n\t\t:param arg: If True Argements will be detected using signature (used with set_signature) Default:False\n\t\t:param kwargs: Arguments for function/method\n\t\t:return:\n\t\t\"\"\"\n\t\tif isinstance(arg, bool):\n\t\t\tself._callers.append((arg, function, self._input_maker(kwargs)))\n\t\telse:\n\t\t\traise Exception(\"Undefined Argument (arg)\")\n\n\n\t@private\n\tdef set(self, **kwargs):\n\t\t\"\"\"\n\t\tUsing setattr to set the values to the instanstiated service\n\n\t\t>>> di.set(A_Class).set(variable=\"abc\")\n\n\t\t:param kwargs: KeyWord arguments for the Service\n\t\t:return:\n\t\t\"\"\"\n\t\tself._sets.update(self._input_maker(kwargs))\n\n\t@private\n\tdef injector(self, service=None, function=None, function_args=None,\n\t acallable=None, callable_args=None):\n\t\t\"\"\"\n\t\tInjects a Service or callable into self Service\n\n\t\t>>> di.set(AnInjector_Class)\n\t\t>>> di.set(A_Class).injector(service=AnInjector, function=\"a_method\", function_args=\"a_method_with_kwargs\")\n\n\t\t:param service: Service to be injected to self\n\t\t:param function: method to to called for injected service\n\t\t:param function_args: method to to called WITH INPUTS for injected service\n\t\t:param acallable: callable to to called for injected service\n\t\t:param callable_args: callable to to called WITH INPUTS for injected service\n\t\t:return:\n\t\t\"\"\"\n\t\tif function or acallable:\n\t\t\tself._injectors.append(self._lazymarker(myclone=acallable, myservice=service, myfunction=function))\n\t\tif function_args or callable_args:\n\t\t\tself._arguments_injectors.append(self._lazymarker(myclone=callable_args,\n\t\t\t myservice=service,\n\t\t\t myfunction=function_args))\n\n\t@private\n\tdef set_signature(self):\n\t\tself._inject_signature = True\n\n\t@private\n\tdef set_pattern(self, pattern_cls):\n\t\tself._mypattern = pattern_cls\n\n","sub_path":"src/utils/NoJoy_DI/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"574916258","text":"from sklearn import svm\nimport cvxpy as cvx\nimport numpy as np\nimport math\nimport numpy.linalg as linalg\nfrom sklearn.cross_validation import train_test_split\nimport pandas as pd\nimport math\nfrom sklearn.decomposition import PCA\nimport cvxopt\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.externals import joblib\n\nsigma=1\n\ndef cal(a,b):\n s=0.0\n for i in range(len(a)):\n s=s+(a[i]-b[i])*(a[i]-b[i])\n s=s*-1;\n s/=2*(sigma*sigma);\n s=math.exp(s)\n return s\n\ndef dis(a,b):\n r=0\n for i in range(len(a)):\n r+=(a[i]-b[i])*(a[i]-b[i])\n return r\n\n\ndef one_class_svm(X_train,X_test,y_train,y_test,digit):\n print('For digit '+str(digit))\n clf = svm.OneClassSVM(kernel='rbf', gamma=0.00001, nu=0.01)\n clf.fit(X_train, y_train)\n print('Built in classifiers accuracy is ' + str(accuracy_score(y_train, clf.predict(X_train)) * 100) + '% '+ str(accuracy_score(y_test, clf.predict(X_test)) * 100) + '%')\n #print()\n joblib.dump(clf, 'Model_final_' + str(digit) + '.pkl')\n return\n\n\nX=[]\ny=[]\nf=[]\n\nfor i in range(10):\n #X.append([])\n #y.append([])\n f.append(open('features_more_'+str(i)+'.txt','r'))\n\n#print(f)\nrang=[]\ngc=0\nfor it in range(10):\n fp=f[it]\n start=-1\n end=-1\n for line in fp:\n #print(line)\n arr=[]\n s=\"\"\n for i in range(len(line)):\n if line[i]==',':\n arr.append(int(s))\n s=\"\"\n else:\n s=s+line[i]\n #print(type(s),s)\n if start==-1:\n #print(start)\n start=gc\n arr.append(int(s))\n gc=gc+1\n X.append(arr[0:494])\n y.append(arr[494])\n end=gc-1\n rang.append([start,end])\n\nX=np.array(X)\nprint(rang)\n\n\n\nfor i in range(10):\n yi=[-1 for i in range(len(y))]\n yi=np.array(yi);\n yi[rang[i][0]:rang[i][1]+1]=1\n X_train=X[rang[i][0]:rang[i][1]+1]\n X_test=X\n y_train=[1.0 for i in range(rang[i][1]-rang[i][0]+1)]\n y_test=yi\n one_class_svm(X_train,X_test,y_train,y_test,i)\n\n","sub_path":"Mini/Final Demo.py","file_name":"Final Demo.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"433232400","text":"# Copyright 2022 The GPflow Contributors. 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\n# pylint: disable=unused-argument # Bunch of fake functions below has unused arguments.\n# pylint: disable=no-member # PyLint struggles with TensorFlow.\n\nfrom pathlib import Path\nfrom time import perf_counter\nfrom typing import Any, Callable, Optional\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nfrom packaging.version import Version\n\nfrom gpflow.base import AnyNDArray\nfrom gpflow.experimental.check_shapes import check_shape as cs\nfrom gpflow.experimental.check_shapes import (\n check_shapes,\n disable_check_shapes,\n inherit_check_shapes,\n)\nfrom gpflow.experimental.check_shapes.exceptions import ShapeMismatchError\n\n\ndef test_check_shapes__numpy() -> None:\n @check_shapes(\n \"a: [d1, d2]\",\n \"b: [d1, d3] if b is not None\",\n \"return: [d2, d3]\",\n )\n def f(a: AnyNDArray, b: AnyNDArray) -> AnyNDArray:\n return np.zeros((3, 4))\n\n f(np.zeros((2, 3)), np.zeros((2, 4))) # Don't crash...\n\n\ndef test_check_shapes__tensorflow() -> None:\n @check_shapes(\n \"a: [d1, d2]\",\n \"b: [d1, d3] if b is not None\",\n \"return: [d2, d3]\",\n )\n def f(a: tf.Tensor, b: tf.Tensor) -> tf.Tensor:\n return tf.zeros((3, 4))\n\n f(tf.zeros((2, 3)), tf.zeros((2, 4))) # Don't crash...\n\n\ndef test_check_shapes__tensorflow__keras() -> None:\n # pylint: disable=arguments-differ,abstract-method,no-value-for-parameter,unexpected-keyword-arg\n\n @check_shapes(\n \"x: [*]\",\n \"return: [*]\",\n )\n def f(x: tf.Tensor) -> tf.Tensor:\n return x + 3\n\n class SuperLayer(tf.keras.layers.Layer):\n def __init__(self) -> None:\n super().__init__()\n self._b = tf.Variable(0.0)\n\n @check_shapes(\n \"x: [batch, input_dim]\",\n \"y: [batch, 1]\",\n \"return: [batch, input_dim]\",\n tf_decorator=True,\n )\n def call(self, x: tf.Tensor, y: tf.Tensor) -> tf.Tensor:\n return f(x) + y + self._b\n\n class SubLayer(SuperLayer):\n @inherit_check_shapes\n def call(self, x: tf.Tensor, y: tf.Tensor) -> tf.Tensor:\n return x - y + self._b\n\n class MyModel(tf.keras.Model):\n def __init__(self, join: SuperLayer) -> None:\n super().__init__()\n self._join = join\n\n @check_shapes(\n \"xy: [batch, input_dim_plus_one]\",\n \"return: [batch, input_dim]\",\n tf_decorator=True,\n )\n def call(self, xy: tf.Tensor) -> tf.Tensor:\n x = cs(xy[:, :-1], \"[batch, input_dim]\")\n y = cs(xy[:, -1:], \"[batch, 1]\")\n return self._join(x, y)\n\n x = tf.ones((32, 3))\n y = tf.zeros((32, 1))\n xy = tf.concat([x, y], axis=1)\n y_bad = tf.zeros((32, 2))\n targets = tf.ones((32, 3))\n\n def test_layer(join: SuperLayer) -> None:\n join(x, y)\n\n with pytest.raises(ShapeMismatchError):\n join(x, y_bad)\n\n model = MyModel(join)\n model.compile(\n optimizer=tf.keras.optimizers.SGD(learning_rate=0.25),\n loss=\"mean_squared_error\",\n )\n model.fit(x=xy, y=targets)\n\n test_layer(SuperLayer())\n test_layer(SubLayer())\n\n\n_Err = Callable[[tf.Tensor, tf.Tensor], tf.Tensor]\n_Loss = Callable[[], tf.Tensor]\n\n_ID_WRAPPER = lambda x: x\n_TF_FUNCTION = tf.function\n_SHAPED_TF_FUNCTION_ERR = tf.function(\n input_signature=[\n tf.TensorSpec(shape=[None], dtype=tf.float64),\n tf.TensorSpec(shape=[], dtype=tf.float64),\n ]\n)\n\n_SHAPED_TF_FUNCTION_LOSS = tf.function(input_signature=[])\n_UNSHAPED_TF_FUNCTION_ERR = tf.function(\n input_signature=[\n tf.TensorSpec(shape=None, dtype=tf.float64),\n tf.TensorSpec(shape=None, dtype=tf.float64),\n ]\n)\n_UNSHAPED_TF_FUNCTION_LOSS = tf.function(input_signature=[])\n_RELAXED_TF_FUNCTION = tf.function(experimental_relax_shapes=True)\n\n_NONE_SHAPE = None\n_TARGET_SHAPE = tf.TensorShape([])\n_V_SHAPE = tf.TensorShape([50])\n_UNKNOWN_SHAPE = tf.TensorShape(None)\n\n\n@pytest.mark.parametrize(\n \"err_wrapper,loss_wrapper\",\n [\n (_ID_WRAPPER, _ID_WRAPPER),\n (_TF_FUNCTION, _TF_FUNCTION),\n (_SHAPED_TF_FUNCTION_ERR, _SHAPED_TF_FUNCTION_LOSS),\n (_UNSHAPED_TF_FUNCTION_ERR, _UNSHAPED_TF_FUNCTION_LOSS),\n (_RELAXED_TF_FUNCTION, _RELAXED_TF_FUNCTION),\n ],\n)\n@pytest.mark.parametrize(\"target_shape\", [_NONE_SHAPE, _TARGET_SHAPE, _UNKNOWN_SHAPE])\n@pytest.mark.parametrize(\"v_shape\", [_NONE_SHAPE, _V_SHAPE, _UNKNOWN_SHAPE])\ndef test_check_shapes__tensorflow_compilation(\n err_wrapper: Callable[[_Err], _Err],\n loss_wrapper: Callable[[_Loss], _Loss],\n target_shape: Optional[tf.TensorShape],\n v_shape: Optional[tf.TensorShape],\n) -> None:\n # Yeah, this test seems to be pushing the limits of TensorFlow compilation (which is probably\n # good), but a bunch of this is fragile.\n tf_version = Version(tf.__version__)\n\n if (target_shape is _UNKNOWN_SHAPE) or (v_shape is _UNKNOWN_SHAPE):\n if (err_wrapper is _TF_FUNCTION) or (err_wrapper is _RELAXED_TF_FUNCTION):\n if Version(\"2.7.0\") <= tf_version < Version(\"2.8.0\"):\n pytest.skip(\"TensorFlow 2.7.* segfaults when trying to compile this.\")\n if Version(\"2.8.0\") <= tf_version < Version(\"2.9.0\"):\n pytest.skip(\"TensorFlow 2.8.* is missing a TraceType(?) when trying compile this.\")\n\n # See: https://github.com/tensorflow/tensorflow/issues/56414\n if err_wrapper is _RELAXED_TF_FUNCTION:\n if Version(\"2.9.0\") <= tf_version < Version(\"2.11.0\"):\n err_wrapper = _TF_FUNCTION\n\n if Version(tf.__version__) < Version(\"2.5.0\"):\n # TensorFlow < 2.5.0 doesn't like the optional `z` argument:\n\n class SqErr:\n @check_shapes(\n \"x: [broadcast n...]\",\n \"y: [broadcast n...]\",\n \"return: [n...]\",\n )\n def __call__(self, x: tf.Tensor, y: tf.Tensor) -> tf.Tensor:\n return (x - y) ** 2\n\n else:\n\n class SqErr: # type: ignore[no-redef]\n @check_shapes(\n \"x: [broadcast n...]\",\n \"y: [broadcast n...]\",\n \"z: [broadcast n...]\",\n \"return: [n...]\",\n )\n def __call__(\n self, x: tf.Tensor, y: tf.Tensor, z: Optional[tf.Tensor] = None\n ) -> tf.Tensor:\n # z only declared to test the case of `None` arguments.\n return (x - y) ** 2\n\n sq_err = err_wrapper(SqErr())\n\n dtype = np.float64\n target = tf.Variable(0.5, dtype=dtype, shape=target_shape)\n v = tf.Variable(np.linspace(0.0, 1.0), dtype=dtype, shape=v_shape)\n\n @loss_wrapper\n @check_shapes(\n \"return: [1]\",\n )\n def loss() -> tf.Tensor:\n # keepdims is just to add an extra dimension to make the check more interesting.\n return tf.reduce_sum(sq_err(v, target), keepdims=True)\n\n optimiser = tf.keras.optimizers.SGD(learning_rate=0.25)\n for _ in range(10):\n optimiser.minimize(loss, var_list=[v])\n\n np.testing.assert_allclose(target, v.numpy(), atol=0.01)\n\n\n@pytest.mark.parametrize(\"func_wrapper\", [lambda x: x, tf.function], ids=[\"none\", \"tf.function\"])\ndef test_check_shapes__disable__speed(func_wrapper: Callable[[Any], Any]) -> None:\n if func_wrapper is tf.function:\n pytest.skip(\n \"This test is super flaky with tf.function, because the overhead of compiling\"\n \" seems to dominate any difference caused by check_shapes. However we probably\"\n \" do want some kind of test of the speed with tf.function, so we keep this\"\n \" skipped test around to remind us.\"\n )\n\n x = tf.zeros((3, 4, 5))\n y = tf.ones((3, 4, 5))\n\n def time_no_checks() -> float:\n before = perf_counter()\n\n def f(a: tf.Tensor, b: tf.Tensor) -> tf.Tensor:\n return a + b\n\n f = func_wrapper(f)\n for _ in range(10):\n f(x, y)\n\n after = perf_counter()\n return after - before\n\n def time_disabled_checks() -> float:\n with disable_check_shapes():\n before = perf_counter()\n\n @check_shapes(\n \"a: [d...]\",\n \"b: [d...]\",\n \"return: [d...]\",\n )\n def f(a: tf.Tensor, b: tf.Tensor) -> tf.Tensor:\n return a + b\n\n f = func_wrapper(f)\n for _ in range(10):\n f(x, y)\n\n after = perf_counter()\n return after - before\n\n def time_with_checks() -> float:\n before = perf_counter()\n\n @check_shapes(\n \"a: [d...]\",\n \"b: [d...]\",\n \"return: [d...]\",\n )\n def f(a: tf.Tensor, b: tf.Tensor) -> tf.Tensor:\n return a + b\n\n f = func_wrapper(f)\n for _ in range(10):\n f(x, y)\n\n after = perf_counter()\n return after - before\n\n time_no_checks() # Warm-up.\n t_no_checks = time_no_checks()\n\n time_disabled_checks() # Warm-up.\n t_disabled_checks = time_disabled_checks()\n\n time_with_checks() # Warm-up.\n t_with_checks = time_with_checks()\n\n assert t_no_checks < t_with_checks\n assert t_disabled_checks < t_with_checks\n\n\ndef test_issue_1864() -> None:\n @tf.function\n @check_shapes(\n \"x: [*]\",\n \"return: [*]\",\n )\n def f(x: tf.Tensor) -> tf.Tensor:\n for _ in tf.range(3):\n x = x + 1.0\n return x\n\n x = tf.constant(7.0)\n f(x)\n\n\ndef test_issue_1936() -> None:\n @tf.function\n @check_shapes(\n \"x: [*]\",\n \"return: [*]\",\n )\n def f_if(x: tf.Tensor) -> tf.Tensor:\n if tf.size(x) == 0:\n return x\n else:\n return x + x\n\n @tf.function\n @check_shapes(\n \"x: [*]\",\n \"return: [*]\",\n )\n def f_tf_cond(x: tf.Tensor) -> tf.Tensor:\n return tf.cond(tf.size(x) == 0, lambda: x, lambda: x + x)\n\n x = tf.constant(7.0)\n f_tf_cond(x)\n f_if(x)\n\n\n@pytest.mark.parametrize(\"model_type\", [\"SuperModel\", \"SubModel\"])\ndef test_tf_saved_model(model_type: str, tmp_path: Path) -> None:\n class SuperModel:\n @check_shapes(\n \"x: [any...]\",\n \"return: [any...]\",\n )\n def f(self, x: tf.Tensor) -> tf.Tensor:\n return x\n\n class SubModel(SuperModel):\n @inherit_check_shapes\n def f(self, x: tf.Tensor) -> tf.Tensor:\n return x + 1\n\n x = np.arange(5)\n model = eval(model_type)()\n out_module = tf.Module()\n out_module.f = tf.function(\n model.f,\n input_signature=[tf.TensorSpec(shape=[None], dtype=tf.float64)],\n )\n tf.saved_model.save(out_module, str(tmp_path))\n\n in_module = tf.saved_model.load(str(tmp_path))\n\n np.testing.assert_allclose(\n model.f(x),\n in_module.f(x),\n )\n","sub_path":"tests/gpflow/experimental/check_shapes/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":11442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"588162600","text":"import numpy as np \nimport subprocess\n\ndata_input = np.zeros((20,20))\ndata_input[-1,:] = 1\n\nexpected = np.zeros(20)\nexpected[-1]=1\n\nnp.savetxt(\"brain_sample.csv\", data_input, fmt='%d', delimiter = ',')\n\nsubprocess.run([\"python\",\"sagital_brain.py\"])\n\nresult = np.loadtxt('brain_average.csv', delimiter=',')\n\nnp.testing.assert_array_equal(result, expected)\n\n\n\n\n##Run these to automate git bisect process\n##git bisect start\n\n##git bisect bad master\n\n##git bisect good [HASHNUMBER]\n\n##git bisect run test_sagital_brain.py","sub_path":"test_sagital_brain.py","file_name":"test_sagital_brain.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"426922657","text":"import numpy as np\n\n# Sorting along an axis:\na = np.array([[4, 3, 5], [1, 2, 1]])\nb = np.sort(a, axis=1)\nprint(b)\n# array([[3, 4, 5],\n# [1, 1, 2]])\n# Note Sorts each row separately!\n# In-place sort:\na.sort(axis=1)\nprint(a)\n# array([[3, 4, 5],\n# [1, 1, 2]])\n\n\n# Sorting with fancy indexing:\na = np.array([4, 3, 1, 2])\nj = np.argsort(a)\nprint(j)\n# array([2, 3, 1, 0])\nprint(a[j])\n# array([1, 2, 3, 4])\n\n\n# Finding minima and maxima:\na = np.array([4, 3, 1, 2])\nj_max = np.argmax(a)\nj_min = np.argmin(a)\nprint(j_max, j_min)\n# (0, 2)","sub_path":"numpy/tutorial/sorting.py","file_name":"sorting.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"467503736","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: /emmo/quantity.py\n# Compiled at: 2020-04-11 02:20:29\n# Size of source mod 2**32: 4778 bytes\n\"\"\"A module for working with EMMO-based quantities and units.\"\"\"\nimport owlready2\n\ndef isquantity(q):\n \"\"\"Return true if `q` is an EMMO Quantity.\"\"\"\n o = q.namespace.ontology\n return isinstance(q, owlready2.ThingClass) and issubclass(q, q.namespace.world[(f\"{o.Quantity.iri}\")])\n\n\ndef _deepest_class(classes):\n \"\"\"Return the class in `classes` that is the descendant of all the\n other classes. Return None if no such class exists.\"\"\"\n print('===', classes)\n for cls in classes:\n print(' ', cls, all((issubclass(cls, c) for c in classes)))\n if all((issubclass(cls, c) for c in classes)):\n return cls\n\n\ndef physics_dimension_of_quantity(q):\n \"\"\"Return the physics dimension of quantity `q`.\n\n None is returned if `q` is not a quantity or don't have a physics dimension.\n \"\"\"\n dim = []\n o = q.namespace.ontology\n w = q.namespace.world\n b = owlready2.base\n for s1, p1, o1 in o.get_triples(s=(q.storid), p=(b.rdfs_subclassof)):\n for s2, p2, o2 in o.get_triples(s=o1, p=(b.rdf_type), o=(b.owl_restriction)):\n for s3, p3, o3 in o.get_triples(s=o1, p=(b.owl_onproperty), o=(o.hasReferenceUnit)):\n for s4, p4, o4 in o.get_triples(s=o1, p=(b.ONLY)):\n for s5, p5, o5 in o.get_triples(s=o4,\n p=(b.owl_onproperty),\n o=(o.hasPhysicsDimension)):\n for s6, p6, o6 in o.get_triples(s=o4, p=(b.ONLY)):\n dim.append(w[w._unabbreviate(o6)])\n\n if dim:\n return dim[0]\n\n\ndef physics_dimension_of_unit(u):\n \"\"\"Return the physics dimension of unit `u`.\n\n None is returned if `u` is not a unit or don't have a physics dimension.\n \"\"\"\n dim = []\n o = u.namespace.ontology\n w = u.namespace.world\n b = owlready2.base\n for s1, p1, o1 in o.get_triples(s=(u.storid), p=(b.rdfs_subclassof)):\n for s2, p2, o2 in o.get_triples(s=o1, p=(b.rdf_type), o=(b.owl_restriction)):\n for s3, p3, o3 in o.get_triples(s=o1, p=(b.owl_onproperty), o=(o.hasPhysicsDimension)):\n for s4, p4, o4 in o.get_triples(s=o1, p=(b.ONLY)):\n try:\n dim.append(w[w._unabbreviate(o4)])\n except KeyError:\n pass\n\n if dim:\n return dim[0]\n\n\ndef get_units(q):\n \"\"\"Returns a list with all possible units for quantity `q`.\n\n An empty list is returned if `q` is not a quantity.\n \"\"\"\n o = q.namespace.ontology\n dim = physics_dimension_of_quantity(q)\n if dim is None:\n return\n return [u for u in o.ReferenceUnit.descendants() if physics_dimension_of_unit(u) is dim]\n\n\ndef get_units_sparql(q):\n \"\"\"Returns a list with all possible units for quantity `q`.\n\n An empty list is returned if `q` is not a quantity.\n \"\"\"\n g = q.namespace.world.as_rdflib_graph()\n o = q.namespace.ontology\n w = q.namespace.world\n query = f\"\\n PREFIX rdfs: \\n PREFIX owl: \\n SELECT ?unit\\n WHERE {{\\n <{q.iri}> rdfs:subClassOf [\\n a owl:Restriction;\\n owl:onProperty <{o.hasReferenceUnit.iri}>;\\n owl:allValuesFrom [\\n a owl:Restriction;\\n owl:onProperty <{o.hasPhysicsDimension.iri}>;\\n owl:allValuesFrom ?dim\\n ]\\n ] .\\n ?unit rdfs:subClassOf+ <{o.ReferenceUnit.iri}>;\\n rdfs:subClassOf [\\n a owl:Restriction;\\n owl:onProperty <{o.hasPhysicsDimension.iri}>;\\n owl:allValuesFrom ?dim\\n ] .\\n }}\\n \"\n return [r[0] for r in g.query_owlready(query)]\n\n\nclass Quantity(object):\n __doc__ = 'A class offering extra attributes and methods for a quantity.'\n\n def __new__(cls, q):\n for k, v in cls.__dict__.items():\n setattr(q, k, v)\n\n return q","sub_path":"pycfiles/EMMO-1.0.0a10-py3-none-any/quantity.cpython-37.opt-1.py","file_name":"quantity.cpython-37.opt-1.py","file_ext":"py","file_size_in_byte":4290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"624981094","text":"\"\"\"\n业务相关配置\n\"\"\"\n\n# 云之讯短信平台配置\nYZX_SMS_URL = 'https://open.ucpaas.com/ol/sms/sendsms'\n\nYZX_SMS_PARAMS = {\n 'sid': '22ac8d51a958dc580d8503173199845c',\n 'token': '8f44a2423cba9bf316d6197e88bfd3ac',\n 'appid': '14595d89fddf4bbfa633f497a673a0b8',\n 'templateid': '481679',\n 'param': None,\n 'mobile': None\n}\n\n# 七牛云存储配置\nQN_ACCESS_KEY = 'ktgbAUqxq6D2WZ0PXRhRY4s5TvW2W_NcpuspuhcG'\nQN_SECRET_KEY = 'XmsJZNH9LgCySF667ZtF-QZI1P6iI2tZXTwZw9ea'\nQN_BUCKET_NAME = 'swiper'\nQN_HOST = 'http://pu420clqe.bkt.clouddn.com'\n\n# 社交系统\nSWIPE_LIMIT = 3 # 每日滑动上限\nSWIPE_SCORES = {\n 'like': 5,\n 'superlike': 8,\n 'dislike': 0\n}\n\n\n","sub_path":"common/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"153243808","text":"from sys import argv as args\r\nfrom bs4 import BeautifulSoup\r\nimport os\r\nimport requests\r\nfrom shutil import copyfile\r\n\r\ncookie = {\"PHPSESSID\": \"4fba35473a18f4798bd604a4a1b57fd8\"}\r\n\r\nmainfunc = \"\"\"\r\nint main(int argc, char** argv) {\r\n\treturn 0;\r\n}\r\n\"\"\"\r\n\r\ndef main():\r\n\tif len(args) != 2:\r\n\t\tprint(\"invalid number of arguments\")\r\n\t\treturn\r\n\r\n\tif not args[1].isnumeric():\r\n\t\tprint(\"non numeric argument\")\r\n\t\treturn\r\n\t\r\n\tbaseurl = \"https://projecteuler.net/problem=\"\r\n\tres = requests.get(baseurl + args[1], cookies=cookie)\r\n\tif res.status_code != 200:\r\n\t\tprint(\"scrape error: invalid return code\")\r\n\t\treturn\r\n\r\n\tsoup = BeautifulSoup(res.text, \"html.parser\")\r\n\r\n\tquery = soup.select(\".problem_content\")[0]\r\n\tif query == None:\r\n\t\tprint(\"scrape error: format change?\")\r\n\t\treturn\r\n\tquery = query.text\r\n\r\n\ttry:\r\n\t\tos.makedirs(args[1])\r\n\texcept:\r\n\t\tpass\r\n\tof = open(args[1]+\"/main.cpp\", \"w+\", encoding=\"utf-8\")\r\n\tof.write(\"/*\" + query + \"\\n\" + baseurl + args[1] + \"\\n\\nANSWER: \\n*/\\n\\n#include \\n\" + mainfunc)\r\n\tof.close()\r\n\r\n\tcopyfile(\"makefile\", args[1] + \"/makefile\")\r\n\r\n\tprint(\"done.\")\r\n\r\nmain()\r\n","sub_path":"genproblem.py","file_name":"genproblem.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"470895168","text":"import numpy as np\nfrom psopy.minimize import minimize_qpso,minimize\nfrom psopy import init_feasible\nfrom scipy.optimize import rosen\nimport time\nimport pandas as pd\nfrom statistics import mean,stdev\nfrom tqdm import tqdm\nimport multiprocessing as mp\nimport itertools as it\nimport dill\nimport csv\n\ndef rosen_def(x):\n '''\n cons = ({'type': 'ineq', 'fun': lambda x: -x[0]**2 - x[1]**2 + 2},)\n low = -1.5\n high=1.5\n shape = (1000,2)\n sol = np.array([1.,1.])\n '''\n return (1 - x[0])**2 + 100*(x[1] - x[0]**2)**2\ndef mishra(x):\n '''\n cons = ({'type': 'ineq', 'fun': lambda x: 25 - np.sum((x + 5) ** 2)},)\n low = -10\n high = 0\n shape = (1000,2)\n sol = np.array([-3.130, -1.582])\n\n '''\n cos = np.cos(x[0])\n sin = np.sin(x[1])\n return sin*np.e**((1 - cos)**2) + cos*np.e**((1 - sin)**2) + \\\n (x[0] - x[1])**2\n\ndef unconstrained(x):\n '''\n x0 = np.random.uniform(0, 2, (1000, 5))\n sol = np.array([1., 1., 1., 1., 1.])\n '''\n return rosen(x)\n\n\ndef constrained(x):\n '''\n cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},\n {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},\n {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2},\n {'type': 'ineq', 'fun': lambda x: x[0]},\n {'type': 'ineq', 'fun': lambda x: x[1]})\n low = 0\n high = 2\n shape(1000,2)\n stable_iter = 50\n sol = np.array([1.4, 1.7])\n\n '''\n return (x[0] - 1)**2 + (x[1] - 2.5)**2\n\ndef ackley(x):\n '''\n x0 = np.random.uniform(-5, 5, (1000, 2))\n sol = np.array([0., 0.])\n\n \n '''\n return -20 * np.exp(-.2 * np.sqrt(0.5 * (x[0]**2 + x[1]**2))) - \\\n np.exp(.5 * (np.cos(2*np.pi*x[0]) + np.cos(2*np.pi*x[1]))) + \\\n np.e + 20\ndef levi(x):\n '''\n x0 = np.random.uniform(-10, 10, (1000, 2))\n sol = np.array([1., 1.])\n\n '''\n\n sin3x = np.sin(3*np.pi*x[0]) ** 2\n sin2y = np.sin(2*np.pi*x[1]) ** 2\n return sin3x + (x[0] - 1)**2 * (1 + sin3x) + \\\n (x[1] - 1)**2 * (1 + sin2y)\n\n\ndef test_generic(args):\n \"\"\"Test against the General function\"\"\"\n (tol,cons,sol,test_func,low,high,shape) = args\n #if shape == 0:\n #x0 = np.random.uniform(0, 2, (1000, 5))\n #print('here')\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n t0 = time.time()\n res = minimize_qpso(test_func, x0, tol=tol)\n t1= time.time()\n converged = res.success\n qpso_converged = 0\n qpso_nit = res.nit\n try:\n np.testing.assert_array_almost_equal(sol, res.x, 3)\n except:\n qpso_converged = 1\n # if high is None:\n #x0 = np.random.uniform(0, 2, (1000, 5))\n # else:\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n t2= time.time()\n res = minimize(test_func,x0, tol=tol)\n t3 = time.time()\n converged = res.success\n pso_converged = 0\n pso_nit = res.nit\n assert converged, res.message\n try:\n np.testing.assert_array_almost_equal(sol, res.x, 3)\n except:\n pso_converged = 1\n \n return qpso_converged, qpso_nit ,t1-t0, pso_converged , pso_nit , t3-t2\n\n\n\ndef stats_func(test_func,file_name,cons,high,low,shape,sol):\n #tol = [1e-1,1e-2,1e-3,1e-4,1e-5,1e-6,1e-7,1e-8,1e-9,1e-10]\n tol = [1e-1]\n qpso_fai1l = []\n pso_fail = []\n mean_qpso_nit = []\n stddev_qpso_nit = []\n mean_qpso_time = []\n stddev_qpso_time = []\n mean_pso_time = []\n stddev_pso_time = []\n mean_pso_nit = []\n stddev_pso_nit = []\n p = mp.Pool(4)\n for to in tqdm(tol):\n stats_list = [[],[],[],[]]\n qpso_conv = 0\n pso_conv = 0\n results = []\n test_generic([to,cons,sol,test_func,low,high,shape])\n r = p.map_async(test_generic,it.repeat([to,cons,sol,test_func,low,high,shape],100),callback=results.append)\n r.get()\n #test_generic([to,cons,sol,test_func,low,high,shape])\n #print(results[0])\n for i in results[0]:\n #for it in tqdm(range(10)):\n # qpso_converged, qpso_nit ,time_qpso,pso_converged,pso_nit,time_pso = test_generic(to,cons,sol,test_func,low,high,shape)\n qpso_conv+=i[0]\n pso_conv+=i[3]\n stats_list[0].append(i[1])\n stats_list[1].append(i[2])\n stats_list[2].append(i[4])\n stats_list[3].append(i[5])\n qpso_fail.append(qpso_conv)\n pso_fail.append(pso_conv)\n mean_qpso_nit.append(mean(stats_list[0]))\n stddev_qpso_nit.append(stdev(stats_list[0]))\n mean_qpso_time.append(mean(stats_list[1]))\n stddev_qpso_time.append(stdev(stats_list[1]))\n mean_pso_nit.append(mean(stats_list[2]))\n stddev_pso_nit.append(stdev(stats_list[2]))\n mean_pso_time.append(mean(stats_list[3]))\n stddev_pso_time.append(stdev(stats_list[3]))\n stats = {\n 'tol' : tol,\n 'qpso_fail' : qpso_fail,\n 'mean_qpso_nit' : mean_qpso_nit,\n 'stddev_qpso_nit' : stddev_qpso_nit,\n 'mean_qpso_time' : mean_qpso_time,\n 'stddev_qpso_time' : stddev_qpso_time,\n 'pso_fail' : pso_fail,\n 'mean_pso_nit' : mean_pso_nit,\n 'stddev_pso_nit' : stddev_pso_nit,\n 'mean_pso_time' : mean_pso_time,\n 'stddev_pso_time' : stddev_pso_time\n }\n df = pd.DataFrame(data=stats)\n df.to_csv(file_name)\n\ndef constraint_1(x):\n return -x[0]**2 - x[1]**2 + 2\n\nif __name__ == '__main__':\n mp.freeze_support()\n fd = open('qpso_levy.csv','a')\n low = -1.5\n high=1.5\n shape = (1000,2)\n sol = np.array([1.,1.])\n\n \n print(\"Testing qpso with levy\")\n print(\"rosen\")\n fd = open('qpso_levy_rosen.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': rosen},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(rosen, x0, options={'levy_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]]\n wr.writerow(res_p)\n fd.close()\n print(\"rosen_def\")\n fd = open('qpso_levy_rosen_def.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': rosen_def},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(rosen_def, x0, options={'levy_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]]\n wr.writerow(res_p)\n fd.close()\n print(\"mishra\")\n fd = open('qpso_levy_mishra.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': mishra},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(mishra, x0, options={'levy_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]] \n wr.writerow(res_p)\n fd.close()\n print(\"ackley\")\n fd = open('qpso_levy_ackley.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': ackley},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(ackley, x0, options={'levy_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]] \n wr.writerow(res_p)\n fd.close()\n print(\"levi\")\n fd = open('qpso_levy_levi.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': levi},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(levi, x0, options={'levy_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]] \n wr.writerow(res_p)\n fd.close()\n #-----------------------------------------------------\n \n print(\"Testing qpso with levy and decay\")\n print(\"rosen\")\n fd = open('qpso_levy_decay_rosen.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': rosen},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(rosen, x0, options={'levy_rate':1, 'decay_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]] \n wr.writerow(res_p)\n fd.close()\n print(\"rosen_def\")\n fd = open('qpso_levy_decay_rosen_def.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': rosen_def},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(rosen_def, x0, options={'levy_rate':1, 'decay_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]] \n wr.writerow(res_p)\n fd.close()\n print(\"mishra\")\n fd = open('qpso_levy_decay_mishra.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': mishra},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(mishra, x0, options={'levy_rate':1, 'decay_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]] \n wr.writerow(res_p)\n fd.close()\n print(\"ackley\")\n fd = open('qpso_levy_decay_ackley.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': ackley},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(ackley, x0, options={'levy_rate':1, 'decay_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]] \n wr.writerow(res_p)\n fd.close()\n print(\"levi\")\n fd = open('qpso_levy_decay_levi.csv','a') \n wr = csv.writer(fd, dialect='excel')\n for i in range(30):\n print(i)\n cons = ({'type': 'ineq', 'fun': levi},)\n x0 = init_feasible(cons, low=low, high=high, shape=shape)\n res = minimize_qpso(levi, x0, options={'levy_rate':1, 'decay_rate':1})\n res_p = [res.fun, res.nit, res.nsit, res.status, res.success, res.x[0], res.x[1]] \n wr.writerow(res_p)\n fd.close()\n\n #-------------------------------------------------------------------------\n\n #x0 = np.random.uniform(-5, 5, (1000, 2))\n #x0 = np.random.uniform(0, 2, (1000, 5))\n #res = minimize(rosen, x0)\n #converged = res.success\n #stats_func(rosen,\"test_levy.csv\",cons,low,high,shape,sol)\n print(\"Done!\")\n print(\"-------------------------------------------------\")\n #test_generic(to,cons,sol,test_func,low,high,shape)","sub_path":"tests/tests_1.py","file_name":"tests_1.py","file_ext":"py","file_size_in_byte":10877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"135596843","text":"'''\nmap: 映射\n map(函数地址, 可迭代对象) ---> map对象\n map会将可迭代对象中的每一个值进行修改,然后映射一个map对象中,\n 可以再将map对象转换成列表/元组。\n 注意: 只能转一次。\n\nreduce: 合并\n reduce(函数地址, 可迭代对象, 默认为0)\n reduce(函数地址, 可迭代对象, 初始值)\n\nfilter: 过滤\n filter(函数地址, 可迭代对象) --> filter 对象\n'''\n# def func():\n# pass\n# map(func)\n# 姓名列表\n# name_list = ['egon', 'jason', 'sean', '大饼', 'tank']\n# map_obj = map(lambda name: name + '喜欢吃生蚝' if name == 'tank' else name + 'DJB', name_list)\n# print(map_obj) # map_obj ---> list/tuple\n# print(list(map_obj)) # map_obj ---> 生成器(迭代器) ---> 用完后,不能再取了\n# print(tuple(map_obj))\n\n\n# reduce\n# from functools import reduce\n# 每次从可迭代对象中获取两个值进行合并,\n# 初始值: 执行reduce函数时,都是从初始值开始合并\n# reduce(lambda x, y: x + y, range(1, 101), 0)\n\n# 需求: 求1——100的和\n# 普通\n# init = 1000\n# for line in range(1, 101):\n# init += line\n#\n# # print(init) # 5050\n# print(init) # 6050\n\n# reduce\n# res = reduce(lambda x, y: x + y, range(1, 101), 1000)\n# print(res) # 6050\n\n\n# filter\nname_list = ['egon_dsb', 'jason_dsb',\n 'sean_dsb', '大饼_dsb', 'tank']\n# filter_obj = filter(lambda x: x, name_list)\n\n# 将后缀为_dsb的名字 “过滤出来”\n# filter会将函数中返回的结果为True 对应 的参数值 “过滤出来”\n# 过滤出来的值会添加到 filter对象中\nfilter_obj = filter(lambda name: name.endswith('_dsb'), name_list)\nprint(filter_obj)\nprint(list(filter_obj)) #\n# print(tuple(filter_obj))\n\n","sub_path":"2.python/0.python基础/day14/代码/02 剩余内置函数.py","file_name":"02 剩余内置函数.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"303837506","text":"\n\n\nimport numpy as np \nimport os\nimport cv2\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib as mpl \n# mpl.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfrom functools import reduce\nfrom tqdm import tqdm\n\ndef Linear_transform(dirname = \"train\", save2dir=\"./output/output9_x_linear_tf\"):\n\tdirpath = os.path.join(save2dir, dirname)\n\tif not os.path.exists(dirpath):\n\t\tos.makedirs(dirpath)\n\n\tprint(\"Loading CT images...\")\n\t# img_CT = np.load(\"./output/output8/{}/bodys.npy\".format(dirname))\n\t# img_CT = np.load(\"./output/output12/{}/bodys.npy\".format(dirname))\n\timg_CT = np.load(\"./output/output21_1/{}/bodys.npy\".format(\"train\"))\n\tprint(\"+ Done.\")\n\tn_sample_CT = len(img_CT)\n\tintensity_CT = np.mean(img_CT.reshape(n_sample_CT, -1), axis=-1)\n\tprint(\"Max value (pixel) of CT: {}\".format(np.max(img_CT)))\n\tprint(\"Min value (pixel) of CT: {}\".format(np.min(img_CT)))\n\tprint(\"Mean value (pixel) of CT: {}\".format(np.mean(img_CT)))\n\tprint(\"Loading XperCT images...\")\n\t# img_XperCT = np.load(\"./output/output5_x_128/{}/bodys.npy\".format(dirname))\n\t# img_XperCT = np.load(\"./output/output20_x_128_test/{}/bodys.npy\".format(dirname))\n\timg_XperCT = np.load(\"./output/output20_x_128/{}/bodys.npy\".format(\"train\")) # whole dataset\n\tprint(\"+ Done.\")\n\n\tn_sample_XperCT = len(img_XperCT)\n\tintensity_XperCT = np.mean(img_XperCT.reshape(n_sample_XperCT, -1), axis=-1)\n\t\n\timg_shape = img_XperCT.shape\n\n\tprint(\"Max value (pixel) of XperCT: {}\".format(np.max(img_XperCT)))\n\tprint(\"Min value (pixel) of XperCT: {}\".format(np.min(img_XperCT)))\n\tprint(\"Mean value (pixel) of XperCT: {}\".format(np.mean(img_XperCT)))\n\tn_sample = np.min((n_sample_CT, n_sample_XperCT))\n\tintensity_CT = np.random.choice(intensity_CT, n_sample, replace=False)\n\tintensity_XperCT = np.random.choice(intensity_XperCT, n_sample, replace=False)\n\tintensity_CT.sort()\n\tintensity_XperCT.sort()\n\n\treg = LinearRegression()\n\treg.fit(intensity_XperCT.reshape(-1,1), intensity_CT.reshape(-1,1))\n\tprint(\"Predicting...\")\n\timg_XperCT_linear_transformed = reg.predict(img_XperCT.reshape(-1,1)).reshape(img_shape)\n\tintensity_XperCT_transformed = np.mean(img_XperCT_linear_transformed.reshape(-1,1), axis = -1)\n\tprint(\"+ Done.\")\n\tprint(\"Max value (pixel) of XperCT transformed: {}\".format(np.max(img_XperCT_linear_transformed)))\n\tprint(\"Min value (pixel) of XperCT transformed: {}\".format(np.min(img_XperCT_linear_transformed)))\n\tprint(\"Mean value (pixel) of XperCT transformed: {}\".format(np.mean(img_XperCT_linear_transformed)))\n\n\n\tprint(\"Saving file to path: {}\".format(os.path.join(dirpath,\"bodys.npy\")))\n\tnp.save(os.path.join(dirpath,\"bodys.npy\"), img_XperCT_linear_transformed)\n\tprint(\"+ Done.\")\n\tplt.figure()\n\tplt.title(\"Images mean intensity comparison: {} datasets\".format(dirname))\n\tplt.hist(intensity_CT.ravel(), 256, [-1, 2.0], density=True, label=\"CT\", alpha=0.8)\n\tplt.hist(intensity_XperCT.ravel(), 256, [-1, 2.0], density=True, label=\"XperCT\", alpha=0.5)\n\tplt.hist(intensity_XperCT_transformed.ravel(), 256, [-1, 2.0], density=True, label=\"XperCT_transformed\", alpha=0.3)\n\tplt.legend(loc=\"best\")\n\tplt.savefig(os.path.join(dirpath, \"histogram.png\"))\n\tplt.show()\n\tplt.close()\n\n\treturn intensity_CT, intensity_XperCT, intensity_XperCT_transformed\n\n####### Useless ###########\n# def Linear_transform2(dirname = \"train\", save2dir=\"./output/output9_x_linear_tf\"):\n# \tdirpath = os.path.join(save2dir, dirname)\n# \tif not os.path.exists(dirpath):\n# \t\tos.makedirs(dirpath)\n\n# \tprint(\"Loading CT images...\")\n# \timg_CT = np.load(\"./output/output8/{}/bodys.npy\".format(dirname))\n# \tprint(\"+ Done.\")\n# \tn_sample_CT = len(img_CT)\n# \tintensity_CT = np.mean(img_CT.reshape(n_sample_CT, -1), axis=-1)\n# \tcontrast_CT = np.std(img_CT.reshape(n_sample_CT, -1), axis=-1)\n\n# \tprint(\"Max value (pixel) of CT: {}\".format(np.max(img_CT)))\n# \tprint(\"Min value (pixel) of CT: {}\".format(np.min(img_CT)))\n# \tprint(\"Mean value (pixel) of CT: {}\".format(np.mean(img_CT)))\n# \tprint(\"Loading XperCT images...\")\n# \timg_XperCT = np.load(\"./output/output5_x_128/{}/bodys.npy\".format(dirname))\n# \tprint(\"+ Done.\")\n\n# \tn_sample_XperCT = len(img_XperCT)\n# \tintensity_XperCT = np.mean(img_XperCT.reshape(n_sample_XperCT, -1), axis=-1)\n# \tcontrast_XperCT = np.std(img_XperCT.reshape(n_sample_XperCT, -1), axis=-1)\n\n\n# \timg_shape = img_XperCT.shape\n\n# \tprint(\"Max value (pixel) of XperCT: {}\".format(np.max(img_XperCT)))\n# \tprint(\"Min value (pixel) of XperCT: {}\".format(np.min(img_XperCT)))\n# \tprint(\"Mean value (pixel) of XperCT: {}\".format(np.mean(img_XperCT)))\n# \tn_sample = np.min((n_sample_CT, n_sample_XperCT))\n# \tindex_CT = np.random.choice(n_sample_CT, n_sample, replace=False)\n# \tindex_XperCT = np.random.choice(n_sample_XperCT, n_sample, replace=False)\n\n# \tintensity_CT = intensity_CT[index_CT]\n# \tcontrast_CT = contrast_CT[index_CT]\n# \tintensity_XperCT = intensity_XperCT[index_XperCT]\n# \tcontrast_XperCT = contrast_XperCT[index_XperCT]\n\n# \tind_argsort_CT = np.argsort(intensity_CT, axis=0)\n# \tind_argsort_XperCT = np.argsort(intensity_XperCT, axis=0)\n# \tA = np.hstack([intensity_CT[ind_argsort_CT], contrast_CT[ind_argsort_CT]])\n# \tB = np.hstack([intensity_XperCT[ind_argsort_XperCT], contrast_XperCT[ind_argsort_XperCT]])\n\n\n# \treg = LinearRegression()\n# \t# reg.fit(intensity_XperCT.reshape(-1,1), intensity_CT.reshape(-1,1))\n# \treg.fit(B, A)\n\n# \tprint(\"Predicting...\")\n# \timg_XperCT_linear_transformed = reg.predict(img_XperCT.reshape(-1,1)).reshape(img_shape)\n# \tintensity_XperCT_transformed = np.mean(img_XperCT_linear_transformed.reshape(-1,1), axis = -1)\n# \tprint(\"+ Done.\")\n# \tprint(\"Max value (pixel) of XperCT transformed: {}\".format(np.max(img_XperCT_linear_transformed)))\n# \tprint(\"Min value (pixel) of XperCT transformed: {}\".format(np.min(img_XperCT_linear_transformed)))\n# \tprint(\"Mean value (pixel) of XperCT transformed: {}\".format(np.mean(img_XperCT_linear_transformed)))\n\n\t\n# \tprint(\"Saving file to path: {}\".format(os.path.join(dirpath,\"bodys.npy\")))\n# \tnp.save(os.path.join(dirpath,\"bodys.npy\"), img_XperCT_linear_transformed)\n# \tprint(\"+ Done.\")\n# \tplt.figure()\n# \tplt.title(\"Images mean intensity comparison: {} datasets\".format(dirname))\n# \tplt.hist(intensity_CT.ravel(), 256, [-1, 2.0], density=True, label=\"CT\", alpha=0.8)\n# \tplt.hist(intensity_XperCT.ravel(), 256, [-1, 2.0], density=True, label=\"XperCT\", alpha=0.5)\n# \tplt.hist(intensity_XperCT_transformed.ravel(), 256, [-1, 2.0], density=True, label=\"XperCT_transformed\", alpha=0.3)\n# \tplt.legend(loc=\"best\")\n# \tplt.savefig(os.path.join(dirpath, \"histogram.png\"))\n# \tplt.show()\n# \tplt.close()\n\n# \treturn intensity_CT, intensity_XperCT, intensity_XperCT_transformed\n\t\ndef Linear_translation(dirname = \"train\", save2dir=\"./output/output9_x_linear_tl\"):\n\tdirpath = os.path.join(save2dir, dirname)\n\tif not os.path.exists(dirpath):\n\t\tos.makedirs(dirpath)\n\n\tprint(\"Loading CT images...\")\n\t# img_CT = np.load(\"./output/output8/{}/bodys.npy\".format(dirname))\n\timg_CT = np.load(\"./output/output21_1/{}/bodys.npy\".format(\"train\"))\n\tprint(\"+ Done.\")\n\tn_sample_CT = len(img_CT)\n\tintensity_CT = np.mean(img_CT.reshape(n_sample_CT, -1), axis=-1)\n\tprint(\"Max value (pixel) of CT: {}\".format(np.max(img_CT)))\n\tprint(\"Min value (pixel) of CT: {}\".format(np.min(img_CT)))\n\tprint(\"Mean value (pixel) of CT: {}\".format(np.mean(img_CT)))\n\n\tprint(\"Loading XperCT images...\")\n\t# img_XperCT = np.load(\"./output/output5_x_128/{}/bodys.npy\".format(dirname))\n\timg_XperCT = np.load(\"./output/output20_x_128/{}/bodys.npy\".format(\"train\")) # whole dataset\n\tprint(\"+ Done.\")\n\n\tn_sample_XperCT = len(img_XperCT)\n\tintensity_XperCT = np.mean(img_XperCT.reshape(n_sample_XperCT, -1), axis=-1)\n\t\n\timg_shape = img_XperCT.shape\n\n\tprint(\"Max value (pixel) of XperCT: {}\".format(np.max(img_XperCT)))\n\tprint(\"Min value (pixel) of XperCT: {}\".format(np.min(img_XperCT)))\n\tprint(\"Mean value (pixel) of XperCT: {}\".format(np.mean(img_XperCT)))\n\n\n\tpixel_value_translation = np.mean(intensity_CT) - np.mean(intensity_XperCT)\n\n\tprint(\"Applying pixel value translation (by adding {})...\".format(pixel_value_translation))\n\n\timg_XperCT_linear_transformed = img_XperCT + pixel_value_translation\n\n\tintensity_XperCT_transformed = np.mean(img_XperCT_linear_transformed.reshape(-1,1), axis = -1)\n\tprint(\"+ Done.\")\n\tprint(\"Max value (pixel) of XperCT transformed: {}\".format(np.max(img_XperCT_linear_transformed)))\n\tprint(\"Min value (pixel) of XperCT transformed: {}\".format(np.min(img_XperCT_linear_transformed)))\n\tprint(\"Mean value (pixel) of XperCT transformed: {}\".format(np.mean(img_XperCT_linear_transformed)))\n\n\tprint(\"Saving file to path: {}\".format(os.path.join(dirpath,\"bodys.npy\")))\n\tnp.save(os.path.join(dirpath,\"bodys.npy\"), img_XperCT_linear_transformed)\n\tprint(\"+ Done.\")\n\tplt.figure()\n\tplt.title(\"Images mean intensity comparison: {} datasets\".format(dirname))\n\tplt.hist(intensity_CT.ravel(), 256, [-1, 2.0], density=True, label=\"CT\", alpha=0.8)\n\tplt.hist(intensity_XperCT.ravel(), 256, [-1, 2.0], density=True, label=\"XperCT\", alpha=0.5)\n\tplt.hist(intensity_XperCT_transformed.ravel(), 256, [-1, 2.0], density=True, label=\"XperCT_transformed\", alpha=0.3)\n\tplt.legend(loc=\"best\")\n\tplt.savefig(os.path.join(dirpath, \"histogram_translation.png\"))\n\tplt.show()\n\tplt.close()\n\n\treturn intensity_CT, intensity_XperCT, intensity_XperCT_transformed\n\n\ndef transform(img):\n\timg = img[:,:,0]\n\tlower = np.min(img)\n\t\n\timg = img -lower\n\tupper = np.max(img)\n\timg /= upper\n\timg *= 255.\n\n\treturn img.astype(np.uint8)\n\ndef demo_equalizeHist():\n\timgs = np.load(\"./output/output5_x/test/bodys.npy\")\n\tprint(imgs.shape)\n\n\ti = 0\n\tlength = len(imgs)\n\n\twhile True:\n\t\timg = transform(imgs[i])\n\t\tequ = cv2.equalizeHist(img)\n\t\t\n\t\tcv2.imshow('equalization', np.hstack((img, equ)))\n\t\tkey = cv2.waitKey(0)\n\n\t\tif key == 27:\n\t\t\tbreak\n\t\telif key == -1:\n\t\t\tprint(\"key == -1\") # ??? useless\n\t\t\tbreak\n\t\t\t# continue\n\t\telif key == 83:\n\t\t\tif i < length-1:\n\t\t\t\ti = i+1\n\t\t\telse:\n\t\t\t\tbreak\n\t\telif key == 81:\n\t\t\tif i > 0:\n\t\t\t\ti = i-1\n\t\t\telse:\n\t\t\t\tbreak\n\t\telif key == 32:\n\t\t\ti = (i+10) % length\n\t\telse:\n\t\t\t# print(key)\n\t\t\tpass\n\tcv2.destroyAllWindows()\n\n\t\t\n\n\n\n\ndef demo_adaptive_equalizeHist():\n\t\"\"\"\n\tadaptive_equalizeHist\n\t\"\"\"\n\tclahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n\n\n\t\n\timgs = np.load(\"./output/output5_x/test/bodys.npy\")\n\tprint(imgs.shape)\n\n\tfor img in imgs:\n\n\t\t# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t\timg = transform(img)\n\t\t# equ = cv2.equalizeHist(img)\n\t\tcl1 = clahe.apply(img)\n\t\tcv2.imshow('equalization', np.hstack((img, cl1)))\n\t\tcv2.waitKey(0)\n\tcv2.destroyAllWindows()\n\n\ndef demo(datapath = \"./output/output5_x/test/bodys.npy\", clipLimit=2.0, tileGridSize=(8, 8)):\n\timgs = np.load(datapath)\n\tprint(imgs.shape)\n\tprint(np.max(imgs))\n\tprint(np.min(imgs))\n\tclahe = cv2.createCLAHE(clipLimit=clipLimit, tileGridSize=tileGridSize)\n\t# for img in imgs:\n\n\t# \t# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t# \timg = transform(img)\n\t# \tequ = cv2.equalizeHist(img)\n\t# \tcl1 = clahe.apply(img)\n\t# \tcv2.imshow('equalization', np.hstack((img, equ, cl1)))\n\t# \tcv2.waitKey(0)\n\n\ti = 0\n\tlength = len(imgs)\n\n\twhile True:\n\t\timg = transform(imgs[i])\n\t\tequ = cv2.equalizeHist(img)\n\t\tcl1 = clahe.apply(img)\n\t\tcv2.namedWindow(\"equalization\", cv2.WINDOW_NORMAL)\n\t\tcv2.resizeWindow('equalization', 1500,500)\n\t\tcv2.imshow('equalization', np.hstack((img, equ, cl1)))\n\t\t\n\t\tkey = cv2.waitKey(0)\n\n\t\tif key == 27:\n\t\t\tbreak\n\t\telif key == -1:\n\t\t\tprint(\"key == -1\") # ??? useless\n\t\t\tbreak\n\t\t\t# continue\n\t\telif key == 83:\n\t\t\tif i < length-1:\n\t\t\t\ti = i+1\n\t\t\telse:\n\t\t\t\tbreak\n\t\telif key == 81:\n\t\t\tif i > 0:\n\t\t\t\ti = i-1\n\t\t\telse:\n\t\t\t\tbreak\n\t\telif key == 32:\n\t\t\ti = (i+10) % length\n\t\telse:\n\t\t\t# print(key)\n\t\t\tpass\n\tcv2.destroyAllWindows()\n\ndef demo2(datapath = \"./output/output17_x_128/train/bodys.npy\", clipLimit=2.0, tileGridSize=(8, 8)):\n\timgs = np.load(datapath)\n\tprint(imgs.shape)\n\tprint(np.max(imgs))\n\tprint(np.min(imgs))\n\tclahe = cv2.createCLAHE(clipLimit=clipLimit, tileGridSize=tileGridSize)\n\t# for img in imgs:\n\n\t# \t# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t# \timg = transform(img)\n\t# \tequ = cv2.equalizeHist(img)\n\t# \tcl1 = clahe.apply(img)\n\t# \tcv2.imshow('equalization', np.hstack((img, equ, cl1)))\n\t# \tcv2.waitKey(0)\n\n\ti = 4203#0\n\tlength = len(imgs)\n\n\twhile True:\n\t\t\n\t\t\n\t\tkey = cv2.waitKey(0)\n\t\tcv2.namedWindow(\"equalization\", cv2.WINDOW_NORMAL)\n\t\tcv2.resizeWindow('equalization', 1500,500)\n\t\tprint(key)\n\t\timg = transform(imgs[i])\n\t\tequ = cv2.equalizeHist(img)\n\t\tcl1 = clahe.apply(img)\n\t\tcv2.imshow('equalization', np.hstack((img, equ, cl1)))\n\t\tif key == 27:\n\t\t\tbreak\n\t\telif key == -1:\n\t\t\tprint(\"key == -1\") # ??? useless\n\t\t\tbreak\n\t\t\t# continue\n\t\telif key == 83:\n\t\t\tif i < length-1:\n\t\t\t\ti = i+1\n\t\t\telse:\n\t\t\t\tbreak\n\t\telif key == 81:\n\t\t\tprint(key)\n\t\t\tif i > 0:\n\t\t\t\ti = i-1\n\t\t\telse:\n\t\t\t\tbreak\n\t\telif key == 32:\n\t\t\ti = (i+10) % length\n\t\telse:\n\t\t\tprint(key)\n\t\t\tpass\n\t\t\n\t\t\n\tcv2.destroyAllWindows()\ndef show_img_distribution(i, dataset, clipLimit=2.0, tileGridSize=(8, 8), figsize=(20,30)):\n\tclahe = cv2.createCLAHE(clipLimit=clipLimit, tileGridSize=tileGridSize)\n\t# for img in imgs:\n\n\t# \t# img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\t# \timg = transform(img)\n\t# \tequ = cv2.equalizeHist(img)\n\t# \tcl1 = clahe.apply(img)\n\t# \tcv2.imshow('equalization', np.hstack((img, equ, cl1)))\n\t# \tcv2.waitKey(0)\n\t\n\timg = transform(dataset[i])\n\tequ = cv2.equalizeHist(img)\n\tcl1 = clahe.apply(img)\n\t# print(equ.shape)\n\t# print(cl1.shape)\n\tf, axes = plt.subplots(2,3, figsize=figsize)\n\taxes[0,0].set_title(\"Origin\")\n\taxes[0,0].imshow(img, cmap='gray')# np.hstack((img, equ, cl1))\n\taxes[0,1].set_title(\"Equalize histogram\")\n\taxes[0,1].imshow(equ, cmap='gray')\n\taxes[0,2].set_title(\"Adaptive equalize histogram\")\n\taxes[0,2].imshow(cl1, cmap='gray')\n\n\taxes[1,0].hist(img.ravel(), 256, [0,256], density=True, color = \"b\", alpha=0.7)\n\taxes[1,1].hist(equ.ravel(), 256, [0,256], density=True, color = \"b\", alpha=0.7)\n\taxes[1,2].hist(cl1.ravel(), 256, [0,256], density=True, color = \"b\", alpha=0.7)\n\n\n\ndef find_liver_bbox_per_slice(mask, debug=False, line_size=5):\n\t\"\"\"\n\tSupport both shape (y, x), (y, x, 1) and (y, x, 3)\n\tcopy original mask; DO NOTHING on the original image (mask)\n\t\"\"\"\n\tassert len(mask.shape) == 3\n\t# print(mask.dtype)\n\t# suppose array shape (X, Y, 1)\n\t## x-axis bbox\n\tliver_size = np.sum(np.sum(mask, axis=-1), axis=-1)\n\tbbmin_x = np.argmax(liver_size>0) # include\n\tbbmax_x = len(liver_size) - np.argmax((liver_size>0)[::-1]) # not includes\n\t## y-axis bbox\n\tliver_size = np.sum(np.sum(mask, axis=-1), axis=0)\n\tbbmin_y = np.argmax(liver_size>0) # include\n\tbbmax_y = len(liver_size) - np.argmax((liver_size>0)[::-1]) # not includes\n\n\tx,y,w,h = bbmin_y, bbmin_x, (bbmax_y-bbmin_y), (bbmax_x-bbmin_x)\n\t# if len(mask.shape) == 2:\n\t# \tmymask = np.expand_dims(mask, axis=-1)\n\t# \tmymask = np.repeat(mymask, 3, axis=-1)\n\t# elif len(mask.shape) == 3:\n\t# \tif mask.shape[-1] == 1:\n\t# \t\tmymask = np.repeat(mask, 3, axis=-1)\n\t# \telse:\n\t# \t\tmymask = mask.copy()\n\t# else:\n\t# \traise ValueError(\"Wrong shape !! Not implemented error.\")\n\t# mymask = mymask.astype(\"uint8\")\n\t# gray_mask = cv2.cvtColor(mymask,cv2.COLOR_BGR2GRAY) # Make sur that image has shape (y, x)\n\t# _, contours, hierarchy = cv2.findContours(gray_mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)\n\t# if len(contours) != 1:\n\t# \tprint(\"Find {} contours\".format(len(contours)))\n\t# \tcontours_buffer = []\n\t# \tfor contour in contours:\n\t# \t\t[x,y,w,h] = cv2.boundingRect(contour)\n\t# \t\tcontours_buffer.append(np.array([x,y,w,h, w*h]))\n\t# \trectangles = np.array(contours_buffer) \n\t# \tind_sort = np.argsort(rectangles[:, -1])\n\t# \trectangles = rectangles[ind_sort]\n\t# \tx,y,w,h,_ = rectangles[-1] ### bounding box with largest area\n\t# else:\n\t# \t[x,y,w,h] = cv2.boundingRect(contours[0])\n\n\tif debug:\n\t\tcv2.rectangle(mymask, (x,y),(x+w,y+h),(0,0,255),line_size)\n\t\treturn np.array([x,y,w,h]), mymask\n\t\n\treturn np.array([x,y,w,h])\n\n\ndef distribution_transform2D(X1, X2, debug=False):\n\t\"\"\"\n\tTransform cloud1 (X1) to cloud2 (X2) by: cloud1*A + m ~= cloud2\n\t##########################################\n\tUsege: cloud.dot(A) + m = New cloud\n\t##########################################\n\n\tD, P = np.linalg.eig(A)\n\tA = reduce(np.dot, [P, np.diag(D), P.T]) # if A is symmetric\n\t\"\"\"\n\tassert X1.shape[-1] == 2 ### cloud.shape = (N, 2)\n\n\tcenter1 = np.mean(X1, axis=0)\n\tcloud1 = X1-center1\n\tCov1 = cloud1.T.dot(cloud1)/len(cloud1)\n\tvals1, vecs1 = np.linalg.eig(Cov1)\n\tvals1 = np.real(vals1)\n\tvecs1 = np.real(vecs1)\n\t\n\tcenter2 = np.mean(X2, axis=0)\n\tcloud2 = X2 -center2\n\tCov2 = cloud2.T.dot(cloud2)/len(cloud2)\n\t\n\t\n\tvals2, vecs2 = np.linalg.eig(Cov2)\n\tvals2 = np.real(vals2)\n\tvecs2 = np.real(vecs2)\n\t\n\tdelta = np.diag(np.sqrt(vals2/vals1))\n\n\tA = reduce(np.dot, [vecs1, delta, vecs2.T])\n\tcloud_t = np.dot(cloud1, A)\n\n\tif debug:\n\t\tprint(\"Center 1: {}\".format(center1))\n\t\tprint(\"Center 2: {}\".format(center2))\n\t\tprint(\"Covariance matrix of target: {}\".format(Cov2))\n\t\tprint(\"Transform cov matrix: {}\".format(reduce(np.dot, [A.T, Cov1,A])))\n\t\tprint(cloud_t.T.dot(cloud_t)/len(cloud_t))\n\t\treturn cloud_t+center2\n\tm = center2\n\t\n\treturn cloud_t+m, A, m\n\ndef analyze_liver_position(dirnames=[\"output17\", \"output5_x_128\"], save2dir=\"./output/analysis/liver_positions\",subdirname=\"test\", show=False):\n\tif not os.path.exists(save2dir):\n\t\tos.makedirs(save2dir)\n\n\tdef calculate_liver_pos_cloud(dirname):\n\t\tprint(\"Loading images from folder {}...\".format(dirname))\n\t\timgs_X = np.load(\"./output/{}/{}/bodys.npy\".format(dirname, subdirname))\n\t\tmasks_X = np.load(\"./output/{}/{}/liver_masks.npy\".format(dirname, subdirname))\n\t\tprint(\"+ Done.\")\n\t\tbbox_buffer = []\n\t\tfor msk in masks_X:\n\t\t\t### bbox = np.array([x,y,w,h])\n\t\t\tbbox = find_liver_bbox_per_slice(msk, debug=False)\n\t\t\tbbox_buffer.append(bbox)\n\t\tbbox_buffer = np.stack(bbox_buffer)\n\n\n\t\tbbox_center_x = bbox_buffer[:, 0]+bbox_buffer[:, 2]/2\n\t\tbbox_center_y = bbox_buffer[:, 1]+bbox_buffer[:, 3]/2\n\t\tbbox_center_x = bbox_center_x.astype(int)\n\t\tbbox_center_y = bbox_center_y.astype(int)\n\t\tbbox_center = np.hstack([bbox_center_x.reshape(-1,1), bbox_center_y.reshape(-1,1)])\n\t\tcloud_filepath = os.path.join(save2dir, \"liver_pos_clouds_{}.npy\".format(dirname))\n\t\tprint(\"Saving liver position clouds to path: {} ...\".format(cloud_filepath))\n\t\tnp.save(cloud_filepath, bbox_center)\n\t\tprint(\"+ Done.\")\n\t\treturn bbox_center\n\n\tdatasets_name = [\"CT\", \"XperCT\"]\n\tplt.figure()\n\tplt.title(\"Liver bbox centers positions\")\n\tplt.xlim([0,128])\n\tplt.ylim([0,128])\n\tbbox_center_clouds = {}\n\tfor i in range(2):\n\t\tbbox_center = calculate_liver_pos_cloud(dirnames[i])\n\t\tbbox_center_clouds[i] = bbox_center\n\t\tplt.scatter(bbox_center[:,0], 128-bbox_center[:,1], label=\"{}\".format(datasets_name[i]), s=10)\n\t\n\tnew_cloud, _, _ = distribution_transform2D(bbox_center_clouds[0], bbox_center_clouds[1], debug=False)\n\t\n\tplt.scatter(new_cloud[:,0], 128-new_cloud[:,1], label=\"{}\".format(\"CT transformed\"), s=10)\n\n\tplt.legend(loc=\"best\")\n\tplt.savefig(os.path.join(save2dir, \"liver_clouds.png\"))\n\tif show:\n\t\tplt.show()\n\tnew_cloud_filepath = os.path.join(save2dir, \"new_liver_pos_clouds.npy\")\n\ttranslations_filepath = os.path.join(save2dir, \"translations.npy\")\n\tprint(\"Saving new liver position clouds to path: {} ...\".format(new_cloud_filepath))\n\tnp.save(new_cloud_filepath, new_cloud)\n\tprint(\"Saving translations to path: {}...\".format(translations_filepath))\n\tnp.save(translations_filepath, new_cloud-bbox_center_clouds[0])\n\tprint(\"+ Done.\")\n\n\n\ndef get_liver_position_proba(liver_mask_path=None, dirnames=[\"output16_x_128\"],subdirname=\"train\", save2dir=\"./output/analysis/liver_positions\", show=False):\n\tassert len(dirnames) == 1, \"Not implemented error\"\n\n\tif not os.path.exists(save2dir):\n\t\tos.makedirs(save2dir)\n\n\tdef calculate_liver_pos_cloud(dirname, liver_mask_path=None):\n\t\tif liver_mask_path is None:\n\t\t\tprint(\"Loading images from folder {}...\".format(dirname))\n\t\t\tmasks_X = np.load(\"./output/{}/{}/liver_masks.npy\".format(dirname, subdirname))\n\t\telse:\n\t\t\tprint(\"Loading images from path {}...\".format(liver_mask_path))\n\t\t\tmasks_X = np.load(liver_mask_path)\n\t\t## sanity check:\n\t\t# if np.any((masks_X>0.0001)*(masks_X<0.5)) or np.any((masks_X<0.9999)*(masks_X>0.5)):\n\t\t# \tprint(\"Find value between 0 and 1. Considering this as raw liver prediction.\")\n\t\t# \tprint(\"Processing with np.round...\")\n\t\t# \tmasks_X = np.round(masks_X)\n\t\t# \tprint(\"+ Done.\")\n\t\t# else:\n\t\t# \tprint(\"Didn't find any value between 0.0001 and 0.9999.\")\n\t\tprint(\"Processing with np.round...\")\n\t\tmasks_X = np.round(masks_X)\n\n\t\tprint(\"+ Done.\")\n\t\tbbox_buffer = []\n\t\tfor msk in masks_X:\n\t\t\t### bbox = np.array([x,y,w,h])\n\t\t\tbbox = find_liver_bbox_per_slice(msk, debug=False)\n\t\t\tbbox_buffer.append(bbox)\n\t\tbbox_buffer = np.stack(bbox_buffer)\n\n\n\t\tbbox_center_x = bbox_buffer[:, 0]+bbox_buffer[:, 2]/2\n\t\tbbox_center_y = bbox_buffer[:, 1]+bbox_buffer[:, 3]/2\n\t\tbbox_center_x = bbox_center_x.astype(int)\n\t\tbbox_center_y = bbox_center_y.astype(int)\n\t\tbbox_center = np.hstack([bbox_center_x.reshape(-1,1), bbox_center_y.reshape(-1,1)])\n\t\tcloud_filepath = os.path.join(save2dir, \"liver_pos_clouds_{}.npy\".format(dirname))\n\t\tprint(\"Saving liver position clouds to path: {} ...\".format(cloud_filepath))\n\t\tnp.save(cloud_filepath, bbox_center)\n\t\tprint(\"+ Done.\")\n\t\treturn bbox_center\n\n\tdatasets_name = [\"XperCT\"]\n\tplt.figure()\n\tplt.title(\"Liver bbox centers positions\")\n\tplt.xlim([0,128])\n\tplt.ylim([0,128])\n\tbbox_center_clouds = {}\n\tfor i in range(1):\n\t\tbbox_center = calculate_liver_pos_cloud(dirnames[i], liver_mask_path=liver_mask_path)\n\t\tbbox_center_clouds[i] = bbox_center\n\t\tplt.scatter(bbox_center[:,0], 128-bbox_center[:,1], label=\"{}\".format(datasets_name[i]), s=10)\n\n\tplt.legend(loc=\"best\")\n\tplt.savefig(os.path.join(save2dir, \"liver_clouds.png\"))\n\tif show:\n\t\tplt.show()\n\t\n\tMEAN = np.mean(bbox_center_clouds[0], axis=0)\n\tcentered = bbox_center_clouds[0] - MEAN\n\tCov = centered.T.dot(centered)/len(centered)\n\tcov_path = os.path.join(save2dir, \"cov.npy\")\n\tmean_path = os.path.join(save2dir, \"mean.npy\")\n\tprint(\"Saving matrice 'Mean' and 'Cov' ...\")\n\tnp.save(mean_path, MEAN)\n\tnp.save(cov_path, Cov)\n\tprint(\"+ Done.\")\n\nif __name__==\"__main__\":\n\tprint(\"Start.\")\n\n\n\t# img_CT = np.load(\"./output/output8/train/bodys.npy\")\n\t\n\t# img_CT = np.random.random((20, 5))\n\t# n_sample_CT = len(img_CT)\n\t# intensity_CT = np.mean(img_CT.reshape(n_sample_CT, -1), axis=-1)\n\t# print(intensity_CT)\n\t# img_XperCT = np.load(\"./output/output5_x_128/train/bodys.npy\")\n\n\t# img_XperCT = np.random.random((10, 5))\n\t# n_sample_XperCT = len(img_XperCT)\n\t# intensity_XperCT = np.mean(img_XperCT.reshape(n_sample_XperCT, -1), axis=-1)\n\n\t\n\t# n_sample = np.min((n_sample_CT, n_sample_XperCT))\n\n\n\t# intensity_CT = np.random.choice(intensity_CT, n_sample, replace=False)\n\t# intensity_XperCT = np.random.choice(intensity_XperCT, n_sample, replace=False)\n\t# intensity_CT.sort()\n\t# intensity_XperCT.sort()\n\n\t# print(intensity_XperCT)\n\t# reg = LinearRegression()\n\t# import ipdb; ipdb.set_trace()\t\n\t# X = np.arange(10).reshape(-1,1)\n\t# Y = 2*X +17\n\n\t# reg.fit(intensity_XperCT.reshape(-1,1), intensity_CT.reshape(-1,1))\n\t\n\t# print(reg.predict(np.arange(24).reshape(-1,1)))\n\n\n\t# img_XperCT = np.load(\"./output/output5_x_128/train/bodys.npy\")\n\t# print(img_XperCT.shape)\n\n\t# Linear_transform(dirname = \"train\")\n\t# Linear_transform(dirname = \"valid\")\n\t# Linear_transform(dirname = \"test\")\n\t# intensity_CT, intensity_XperCT, intensity_XperCT_transformed = Linear_transform(dirname = \"test\")\n\t# plt.figure()\n\t# plt.title(\"Images intensity comparison: {} datasets\".format(\"test\"))\n\t# plt.hist(intensity_CT.ravel(), 100, [-1, 2.0], label=\"CT\", alpha=0.8)\n\t# plt.hist(intensity_XperCT.ravel(), 50, [-1, 2.0], label=\"XperCT\", alpha=0.5)\n\t# plt.hist(intensity_XperCT_transformed.ravel(), 50, [-1, 2.0], label=\"XperCT_transformed\", alpha=0.3)\n\t# plt.legend(loc=\"best\")\n\t# plt.savefig(os.path.join(dirpath, \"histrogram.png\"))\n\t# plt.show()\n\t\n\n\t\n\t# Linear_transform(dirname = \"test\", save2dir=\"./output/output12_x_linear_tf\")\n\t# Linear_translation(dirname = \"test\", save2dir=\"./output/output9_x_linear_tl\")\n\t\n\n\t# demo_equalizeHist()\n\n\t# demo(datapath = \"./output/output5/test/bodys.npy\")\n\t# demo(datapath = \"./output/output11/test/bodys.npy\")\n\t\n\t# demo(clipLimit=2.0, tileGridSize=(8, 8))\n\n\tdef One_time_code(dirname = \"test\", save2dir=\"./output/output12_x_linear_tf\"):\n\t\txperCT_tf = np.load(os.path.join(save2dir,dirname, \"bodys.npy\"))\n\t\timage = xperCT_tf*4096.\n\n\t\tind_sup = image>200\n\t\tind_inf = image<-200\n\t\timage[ind_sup] = 200\n\t\timage[ind_inf] = -200\n\t\timage = (image + 200)/400.# * RGB\n\t\t\n\t\tprint(image.shape)\n\t\tif not os.path.exists(\"./output/output12_x_linear_tf_clipped/test\"):\n\t\t\tos.makedirs(\"./output/output12_x_linear_tf_clipped/test\")\n\t\tnp.save(\"./output/output12_x_linear_tf_clipped/test/bodys.npy\", image)\n\n\t# One_time_code()\n\t\n\t# import ipdb; ipdb.set_trace()\n\n\n\n\n\t# analyze_liver_position(subdirname=\"test\", save2dir=\"./output/analysis/liver_positions_test\")\n\t# demo2()\n\n\n\t####\n\t# get_liver_position_proba(dirnames=[\"output20_x_128\"], save2dir=\"./output/analysis/debug\",subdirname=\"train\")\n\t\n\tdef two_time_code(save2dir=\"output30\"):\n\t\tif not os.path.exists(\"./output/{}\".format(save2dir)):\n\t\t\tos.makedirs(\"./output/{}\".format(save2dir))\n\t\t\tos.makedirs(\"./output/{}/train\".format(save2dir))\n\n\t\tfolders = [\"output30_1\", \"output30_2\", \"output30_3\", \"output30_4\", \"output30_5\"]\n\t\tnpy_files = [\"bodys.npy\", \"liver_masks.npy\", \"patients_index.npy\", \"spacing.npy\"]\n\t\tdirpath = \"./output/{}/train\".format(save2dir)\n\t\tfor file in tqdm(npy_files):\n\t\t\tnpy_buffer = []\n\t\t\tfor folder in folders:\n\t\t\t\tpath = \"./output/{}/train\".format(folder)\n\t\t\t\tif file == \"patients_index.npy\":\n\t\t\t\t\tnpy_buffer.append(np.load(os.path.join(path, file))[:, np.newaxis])\n\t\t\t\telse:\t\n\t\t\t\t\tnpy_buffer.append(np.load(os.path.join(path, file)))\n\t\t\tnpy_buffer = np.vstack(npy_buffer)\n\t\t\tprint(len(npy_buffer))\n\t\t\tnp.save(os.path.join(dirpath, file), npy_buffer)\n\ttwo_time_code()\n\n\n\n\t# Linear_transform(dirname = \"all\", save2dir=\"./output/output20_x_linear_tf\") ## 27/6/2018\n\t# Linear_translation(dirname = \"all\", save2dir=\"./output/output20_x_linear_tl\") ## 27/6/2018\n\t# get_liver_position_proba(liver_mask_path=\"./output/output20_x_128/results/Exp1_CT2XperCT/liver_masks_predict.npy\", save2dir=\"./output/analysis/output20_x_linear_tf\", dirnames=[\"output20_x_128\"], subdirname=\"train\")\n\n\n","sub_path":"HOG_linear_tf.py","file_name":"HOG_linear_tf.py","file_ext":"py","file_size_in_byte":26030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"146046781","text":"# -*- coding: utf-8 -*-\nfrom flask import Blueprint, render_template, redirect, url_for, request\nfrom flask.ext.login import current_user\n\nimport moneypenny\n\nBP_NAME = __name__.split('.')[-2]\nblueprint = Blueprint(BP_NAME, __name__, url_prefix='/',\n template_folder='templates', static_folder='static',\n static_url_path=\"/{}/static\".format(BP_NAME))\n\n\n@blueprint.route('/')\ndef index():\n \"\"\"First page of the site.\"\"\"\n if current_user.is_authenticated:\n return redirect(url_for('sample.dashboard'))\n else:\n next_url = request.args.get('next')\n return render_template('index.html', version=moneypenny.__version__,\n next_url=next_url)\n\n\n@blueprint.route('/admin')\ndef admin():\n \"\"\"Show admin view.\"\"\"\n return render_template('admin/master.html')\n","sub_path":"moneypenny/server/blueprints/public/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"458232910","text":"import edrlog\nimport edtime\nfrom edri18n import _, _c\n\nEDRLOG = edrlog.EDRLog()\n\nclass EDRCmdrDexProfile(object):\n @staticmethod \n def alignments():\n return [u\"outlaw\", u\"neutral\", u\"enforcer\"]\n \n def __init__(self, dex_dict=None):\n if dex_dict is None:\n dex_dict = {}\n self._alignment = dex_dict.get(\"alignment\", None)\n self.tags = set([self.__tagify(t) for t in dex_dict.get(\"tags\", [])])\n self._friend = dex_dict.get(\"friend\", False)\n self._memo = dex_dict.get(\"memo\", None)\n\n now = edtime.EDTime.js_epoch_now()\n self.created = dex_dict.get(\"created\", now)\n self.updated = dex_dict.get(\"updated\", now)\n\n @property\n def alignment(self):\n lut = { u\"outlaw\": _(u\"outlaw\"), u\"neutral\": _(u\"neutral\"), u\"enforcer\": _(u\"enforcer\") }\n return lut.get(self._alignment, None)\n\n @alignment.setter\n def alignment(self, new_alignment):\n now = edtime.EDTime.js_epoch_now()\n if (new_alignment is None):\n self._alignment = None\n self.updated = now\n return\n\n if (new_alignment not in EDRCmdrDexProfile.alignments()):\n return\n if (new_alignment == self._alignment):\n return\n self._alignment = new_alignment\n self.updated = now\n\n \n @property\n def friend(self):\n return self._friend\n\n @friend.setter\n def friend(self, is_friend):\n if is_friend == self._friend:\n return False\n self._friend = is_friend\n self.updated = edtime.EDTime.js_epoch_now()\n return True\n\n def is_useless(self):\n return (not self.friend) and (self.alignment is None) and (self.memo is None) and (not self.tags)\n\n @property\n def memo(self):\n return self._memo\n\n @memo.setter\n def memo(self, message):\n self._memo = message\n self.updated = edtime.EDTime.js_epoch_now()\n return True\n\n def __all_tags(self):\n all_tags = []\n if self.alignment:\n all_tags.append(self.alignment)\n \n if self.tags:\n all_tags += self.tags\n return all_tags\n\n\n @staticmethod\n def __tagify(tag):\n tag = tag.lower()\n return tag.replace(u\" \", u\"\")\n\n def tag(self, tag):\n tag = EDRCmdrDexProfile.__tagify(tag)\n\n if tag == u\"friend\" and not self._friend:\n self.friend = True\n return True\n elif tag in EDRCmdrDexProfile.alignments() and self._alignment != tag:\n self.alignment = tag\n return True\n elif tag not in self.tags:\n self.tags.add(tag)\n self.updated = edtime.EDTime.js_epoch_now()\n return True\n\n return False\n\n def untag(self, tag):\n tag = EDRCmdrDexProfile.__tagify(tag)\n if tag == u\"friend\" and self._friend:\n self.friend = False\n return True\n elif tag == self._alignment:\n self.alignment = None\n return True\n elif tag in self.tags:\n self.tags.remove(tag)\n self.updated = edtime.EDTime.js_epoch_now()\n return True\n\n return False\n\n\nclass EDRCmdrProfile(object):\n @staticmethod\n def max_karma():\n return 1000\n\n @staticmethod\n def min_karma():\n return -1000\n \n def __init__(self):\n self.cid = None\n self._name = None\n self.squadron = None\n self.role = None\n self._karma = 0\n self.alignment_hints = None\n self.patreon = None\n self.dex_profile = None\n self.powerplay = None\n \n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, new_name):\n if new_name is None:\n self._name = None\n return\n \n self._name = new_name\n \n @property\n def karma(self):\n return self._karma\n\n @karma.setter\n def karma(self, new_karma):\n self._karma = min(max(EDRCmdrProfile.min_karma(), new_karma), EDRCmdrProfile.max_karma())\n\n def from_inara_api(self, json_cmdr):\n self.name = json_cmdr.get(\"userName\", \"\")\n wing = json_cmdr.get(\"commanderWing\", None)\n self.squadron = None if wing is None else wing[\"wingName\"] \n self.role = json_cmdr.get(\"preferredGameRole\", None)\n self.powerplay = json_cmdr.get(\"preferredPowerName\", None)\n self.karma = 0 #not supported by Inara\n self.alignment_hints = None #not supported by Inara\n self.patreon = None\n self.dex_profile = None\n\n def from_dict(self, json_cmdr):\n self.name = json_cmdr.get(\"name\", \"\")\n self.squadron = json_cmdr.get(\"squadron\", None)\n self.role = json_cmdr.get(\"role\", None)\n self.karma = json_cmdr.get(\"karma\", 0)\n self.alignment_hints = json_cmdr.get(\"alignmentHints\", None)\n self.patreon = json_cmdr.get(\"patreon\", None)\n self.dex_profile = None\n self.powerplay = None\n \n def complement(self, other_profile):\n if self.name.lower() != other_profile.name.lower():\n EDRLOG.log(u\"Can't complement profile since it doesn't match: {} vs. {}\".format(other_profile.name, self.name), \"DEBUG\")\n return False\n\n if self.squadron is None or self.squadron == \"\":\n self.squadron = other_profile.squadron\n\n if self.role is None or self.role == \"\":\n self.role = other_profile.role\n\n if self.powerplay is None or self.powerplay == \"\":\n self.powerplay = other_profile.powerplay\n\n def dex(self, dex_dict):\n if dex_dict is None:\n return False\n\n if self.name.lower() != dex_dict.get(\"name\", \"\").lower():\n EDRLOG.log(u\"Can't augment with CmdrDex profile since it doesn't match: {} vs. {}\".format(dex_dict.get(\"name\", \"\"), self.name), \"DEBUG\")\n return False\n\n self.dex_profile = EDRCmdrDexProfile(dex_dict)\n\n def dex_dict(self):\n if self.dex_profile is None:\n return None\n\n json_friendly_tags = list(self.dex_profile.tags)\n return {\n u\"name\": self.name,\n u\"alignment\": self.dex_profile._alignment,\n u\"tags\": json_friendly_tags,\n u\"friend\": self.dex_profile.friend,\n u\"memo\": self.dex_profile.memo,\n u\"created\": self.dex_profile.created,\n u\"updated\": self.dex_profile.updated\n }\n\n def tag(self, tag):\n if self.dex_profile is None:\n self.dex_profile = EDRCmdrDexProfile({})\n\n return self.dex_profile.tag(tag)\n\n def untag(self, tag):\n if self.dex_profile is None:\n return False\n if tag is None:\n self.dex_profile = None\n return True\n return self.dex_profile.untag(tag)\n\n def memo(self, memo):\n if self.dex_profile is None:\n self.dex_profile = EDRCmdrDexProfile({})\n \n self.dex_profile.memo = memo\n return True\n\n def remove_memo(self):\n if self.dex_profile is None:\n return False\n \n self.dex_profile.memo = None\n if self.dex_profile.is_useless():\n self.dex_profile = None\n return True\n \n def is_dangerous(self):\n if self.dex_profile:\n return self.dex_profile._alignment == \"outlaw\"\n if self._karma <= -250:\n return True\n if self.alignment_hints and self.alignment_hints[\"outlaw\"] > 0:\n total_hints = sum([hints for hints in self.alignment_hints.values()])\n return (total_hints > 10 and self.alignment_hints[\"outlaw\"] / total_hints > .5)\n\n def karma_title(self):\n mapped_index = int(10*(self._karma + self.max_karma()) / (2.0*self.max_karma()))\n lut = [_(u\"Wanted ++++\"), _(u\"Wanted +++\"), _(u\"Wanted ++\"), _(u\"Wanted +\"), _(u\"Wanted\"), _(u\"Neutral\"), _(u\"Enforcer\"), _(u\"Enforcer +\"), _(u\"Enforcer ++\"), _(u\"Enforcer +++\"), _(u\"Enforcer ++++\")]\n karma = lut[mapped_index]\n\n if self.dex_profile is None:\n return karma\n\n alignment = self.dex_profile.alignment\n if alignment:\n return u\"{} #{}\".format(karma, alignment)\n\n return karma\n\n def crowd_alignment(self):\n if self.alignment_hints is None:\n return None\n\n total_hints = float(sum([hints for hints in self.alignment_hints.values()]))\n #TODO increase threshold by an order of magnitude when there are more EDR users\n if (total_hints < 10):\n return u\"[!{} ?{} +{}]\".format(self.alignment_hints[\"outlaw\"], self.alignment_hints[\"neutral\"], self.alignment_hints[\"enforcer\"])\n return u\"[!{:.0%} ?{:.0%} +{:.0%}]\".format(self.alignment_hints[\"outlaw\"] / total_hints, self.alignment_hints[\"neutral\"] / total_hints, self.alignment_hints[\"enforcer\"] / total_hints)\n\n def short_profile(self):\n result = u\"{name}: {karma}\".format(name=self.name, karma=self.karma_title())\n\n alignment = self.crowd_alignment()\n if not (alignment is None or alignment == \"\"):\n result += u\" {}\".format(alignment)\n\n if not (self.squadron is None or self.squadron == \"\"):\n result += u\", {squadron}\".format(squadron=self.squadron)\n\n if not (self.role is None or self.role == \"\"):\n result += u\", {role}\".format(role=self.role)\n\n if not (self.powerplay is None or self.powerplay == \"\"):\n result += u\", {powerplay}\".format(powerplay=self.powerplay)\n\n if not (self.patreon is None or self.patreon == \"\"):\n result += u\", Patreon:{patreon}\".format(patreon=self.patreon)\n\n if self.dex_profile:\n if self.dex_profile.friend:\n result += _(u\" [friend]\")\n\n tags = self.dex_profile.tags\n if tags:\n result += u\", #{}\".format(\" #\".join(tags))\n \n memo = self.dex_profile.memo\n if memo:\n result += u\", {}\".format(memo)\n \n updated_jse = self.dex_profile.updated\n if updated_jse:\n updated_edt = edtime.EDTime()\n updated_edt.from_js_epoch(updated_jse)\n result += u\" ({})\".format(updated_edt.as_immersive_date())\n\n return result","sub_path":"edr/edrcmdrprofile.py","file_name":"edrcmdrprofile.py","file_ext":"py","file_size_in_byte":10301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"614660131","text":"\nfrom botocore.session import get_session\nfrom botocore.client import Config\nfrom base64 import b64decode\nfrom docker import client, errors\nfrom docker.utils import kwargs_from_env\nimport sys\nfrom utils import log_push, log_build\n\ndef log(*arg, **kw):\n return\n\n\nclass IRegistry():\n \"\"\" Based interface fot registry plugin. \"\"\"\n builder = \"IBuilder object.\"\n\n def get_registry_name(self):\n raise NotImplemented\n\n def login(self):\n raise NotImplemented\n\n def build(self, repo_dir, repo_name, forced_tag=None):\n raise NotImplemented\n\n def publish(self, repo_dir, name, tag):\n raise NotImplemented\n\n# TODO: factorize common registry work in super class: log outputing included.\nclass ECRRegistry(IRegistry):\n def __init__(self, builder, region):\n self.builder = builder\n self.region = region\n self.docker_client = get_docker_client()\n\n def _get_registry_info(self):\n ecr_client = get_session().create_client('ecr', self.region, config=Config(signature_version='v4'))\n result = ecr_client.get_authorization_token()\n auth = result['authorizationData'][0]\n auth_token = b64decode(auth['authorizationToken']).decode()\n username, password = auth_token.split(':')\n return username, password, 'none', auth['proxyEndpoint']\n\n def get_registry_name(self):\n _, _, _, endpoint = self._get_registry_info()\n if endpoint.startswith('https://'):\n return endpoint[8:]\n elif endpoint.startswith('http://'):\n return endpoint[7:]\n else:\n return endpoint\n\n def login(self):\n credentials = self._get_registry_info()\n reg = credentials[3]\n try:\n result = self.docker_client.login(*credentials, reauth=True)\n except (errors.APIError, errors.DockerException) as e:\n log(\"Login to registry '{0}' failed:\".format(reg), fg='red')\n log(repr(e), fg='red')\n sys.exit(1)\n else:\n log(\"Login to registry '{0}': {1}\".format(reg, result['Status']), fg='green')\n\n def build(self, repo_dir, repo_name, tag=None):\n name = \":\".join([repo_name, tag])\n log(\"Running pre_build_hook ...\")\n self.builder.pre_build_hook()\n\n log(\"Running build for '{0}'\".format(name))\n result = self.docker_client.build(repo_dir, name, quiet=False, forcerm=True, stream=True, decode=True)\n image_id = log_build(result, log)\n\n return image_id\n\n def publish(self, repo_dir, repo_name, forced_tag=None, create_repo=False):\n tag = forced_tag if forced_tag else self.builder.get_tag()\n log(\"Tag value: {0}\".format(tag))\n\n image_id = self.build(repo_dir, repo_name, tag)\n if not image_id:\n return\n\n full_name = '/'.join([self.get_registry_name(), repo_name])\n self.docker_client.tag(image_id, full_name, tag, True)\n\n self.login()\n if create_repo:\n # TODO: add ability to create the repo on ecr if we have the right.\n pass\n\n log('Pushing images {0}:{1}'.format(full_name, tag))\n result = self.docker_client.push(full_name, tag, stream=True)\n log_push(result, log)\n\n\ndef get_docker_client():\n kwargs = kwargs_from_env()\n if 'tls' in kwargs:\n # TODO, add an option to force tls.\n kwargs['tls'].assert_hostname = False\n return client.Client(version='auto', **kwargs)\n\ndef get_logger():\n return lambda x: x","sub_path":"atlasutils/registries.py","file_name":"registries.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"113312652","text":"# Python program to implement Morse Code encoder.\n# Morse code values represented in form of dictionary\nMorse_Code_values = {'A': '.-', 'B': '-...',\n 'C': '-.-.', 'D': '-..', 'E': '.',\n 'F': '..-.', 'G': '--.', 'H': '....',\n 'I': '..', 'J': '.---', 'K': '-.-',\n 'L': '.-..', 'M': '--', 'N': '-.',\n 'O': '---', 'P': '.--.', 'Q': '--.-',\n 'R': '.-.', 'S': '...', 'T': '-',\n 'U': '..-', 'V': '...-', 'W': '.--',\n 'X': '-..-', 'Y': '-.--', 'Z': '--..',\n '1': '.----', '2': '..---', '3': '...--',\n '4': '....-', '5': '.....', '6': '-....',\n '7': '--...', '8': '---..', '9': '----.',\n '0': '-----', ', ': '--..--', '.': '.-.-.-',\n '?': '..--..', '/': '-..-.', '-': '-....-',\n '(': '-.--.', ')': '-.--.-'}\n\n\n# Function to encrypt the string i.e. converting message to morse code\ndef encrypt(message):\n english_to_morse = '' # it stores the morse translated form of the english string\n for char in message:\n if char != ' ':\n\n # Search the above dictionary and assign the\n # indicated morse code to individual character of the string entered.\n # With proper spacing betweeen words.\n english_to_morse += Morse_Code_values[char] + ' '\n else:\n # 1 space for different characters\n # and 2 space for different words\n english_to_morse += ' '\n\n return english_to_morse\n\n\ndef main_function(): # driver function\n message = input(\"Enter the message you want to encrypt: \")\n output = encrypt(message.upper())\n print(output)\n\n\nif __name__ == '__main__':\n main_function()\n","sub_path":"python/morse_code.py","file_name":"morse_code.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"314530513","text":"\"\"\"\nConversion functions\n--------------------\n\nThese functions convert the :class:`.BinaryQuadraticModel` to other datatypes.\n\n\"\"\"\n\nfrom dimod.compatibility23 import iteritems\nfrom dimod.binary_quadratic_model import BinaryQuadraticModel\nfrom dimod.vartypes import Vartype\n\n__all__ = ['to_networkx_graph',\n 'to_ising',\n 'to_qubo',\n 'to_numpy_matrix',\n 'to_pandas_dataframe',\n 'from_ising',\n 'from_qubo',\n 'from_numpy_matrix',\n 'from_pandas_dataframe']\n\n\ndef to_networkx_graph(bqm, node_attribute_name='bias', edge_attribute_name='bias'):\n \"\"\"Return the BinaryQuadraticModel as a NetworkX graph.\n\n Args:\n node_attribute_name (hashable):\n The attribute name for the linear biases.\n edge_attribute_name (hashable):\n The attribute name for the quadratic biases.\n\n Returns:\n :class:`networkx.Graph`: A NetworkX with the biases stored as\n node/edge attributes.\n\n Examples:\n >>> import networkx as nx\n >>> bqm = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5},\n ... {(0, 1): .5, (1, 2): 1.5},\n ... 1.4,\n ... dimod.SPIN)\n >>> BQM = dimod.to_networkx_graph(bqm)\n >>> BQM[0][1]['bias']\n 0.5\n >>> BQM.node[0]['bias']\n 1\n\n Also, if the preferred notation is 'weights'\n\n >>> import networkx as nx\n >>> bqm = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5},\n ... {(0, 1): .5, (1, 2): 1.5},\n ... 1.4,\n ... dimod.SPIN)\n >>> BQM = dimod.to_networkx_graph(bqm, edge_attribute_name='weight')\n >>> BQM[0][1]['weight']\n 0.5\n\n\n \"\"\"\n import networkx as nx\n\n BQM = nx.Graph()\n\n vartype = bqm.vartype\n\n # add the linear biases\n BQM.add_nodes_from(((v, {node_attribute_name: bias, 'vartype': vartype})\n for v, bias in iteritems(bqm.linear)))\n\n # add the quadratic biases\n BQM.add_edges_from(((u, v, {edge_attribute_name: bias}) for (u, v), bias in iteritems(bqm.quadratic)))\n\n # set the offset and vartype properties for the graph\n BQM.offset = bqm.offset\n BQM.vartype = vartype\n\n return BQM\n\n\ndef to_ising(bqm):\n \"\"\"Converts the binary quadratic model into the (h, J, offset) Ising format.\n\n If the binary quadratic model's vartype is not spin, it is converted.\n\n Args:\n bqm (:class:`.BinaryQuadraticModel`):\n A binary quadratic model.\n\n Returns:\n tuple: A 3-tuple:\n\n dict: The linear biases.\n\n dict: The quadratic biases.\n\n number: The offset.\n\n \"\"\"\n return bqm.spin.linear, bqm.spin.quadratic, bqm.spin.offset\n\n\ndef from_ising(h, J, offset=0.0):\n \"\"\"Build a binary quadratic model from an Ising problem.\n\n\n Args:\n h (dict[variable, bias]/list[bias]):\n The linear biases of the Ising problem. If a list, the indices of the list are treated\n as the variable labels.\n\n J (dict[(variable, variable), bias]):\n The quadratic biases of the Ising problem.\n\n offset (optional, default=0.0):\n The constant offset applied to the model.\n\n Returns:\n :class:`.BinaryQuadraticModel`\n\n \"\"\"\n if isinstance(h, list):\n h = dict(enumerate(h))\n\n return BinaryQuadraticModel(h, J, offset, Vartype.SPIN)\n\n\ndef to_qubo(bqm):\n \"\"\"Converts the binary quadratic model into the (Q, offset) QUBO format.\n\n If the binary quadratic model's vartype is not binary, it is converted.\n\n Args:\n bqm (:class:`.BinaryQuadraticModel`):\n A binary quadratic model.\n\n Returns:\n tuple: A 2-tuple:\n\n dict: The qubo biases. A dict where the keys are pairs of variables and the values\n are the associated linear or quadratic bias.\n\n number: The offset.\n\n \"\"\"\n qubo = {}\n\n for v, bias in iteritems(bqm.binary.linear):\n qubo[(v, v)] = bias\n\n for edge, bias in iteritems(bqm.binary.quadratic):\n qubo[edge] = bias\n\n return qubo, bqm.binary.offset\n\n\ndef from_qubo(Q, offset=0.0):\n \"\"\"Build a binary quadratic model from a qubo.\n\n Args:\n Q (dict):\n The qubo coefficients.\n\n offset (optional, default=0.0):\n The constant offset applied to the model.\n\n Returns:\n :class:`.BinaryQuadraticModel`\n\n \"\"\"\n linear = {}\n quadratic = {}\n for (u, v), bias in iteritems(Q):\n if u == v:\n linear[u] = bias\n else:\n quadratic[(u, v)] = bias\n\n return BinaryQuadraticModel(linear, quadratic, offset, Vartype.BINARY)\n\n\ndef to_numpy_matrix(bqm, variable_order=None):\n \"\"\"Return the binary quadratic model as a matrix.\n\n Args:\n bqm (:class:`.BinaryQuadraticModel`):\n A binary quadratic model. Should either be index-labeled from 0 to N-1 or variable_order\n should be provided.\n\n variable_order (list, optional):\n If variable_order is provided, the rows/columns of the numpy array are indexed by\n the variables in variable_order. If any variables are included in variable_order that\n are not in `bqm`, they will be included in the matrix.\n\n Returns:\n :class:`numpy.matrix`: The binary quadratic model as a matrix. The matrix has binary\n vartype.\n\n Notes:\n The matrix representation of a binary quadratic model only makes sense for binary models.\n For a binary sample x, the energy of the model is given by:\n\n .. math::\n\n E(x) = x^T Q x\n\n\n The offset is dropped when converting to a numpy matrix.\n\n \"\"\"\n import numpy as np\n\n if variable_order is None:\n # just use the existing variable labels, assuming that they are [0, N)\n num_variables = len(bqm)\n mat = np.zeros((num_variables, num_variables), dtype=float)\n\n try:\n for v, bias in iteritems(bqm.binary.linear):\n mat[v, v] = bias\n except IndexError:\n raise ValueError((\"if 'variable_order' is not provided, binary quadratic model must be \"\n \"index labeled [0, ..., N-1]\"))\n\n for (u, v), bias in iteritems(bqm.binary.quadratic):\n if u < v:\n mat[u, v] = bias\n else:\n mat[v, u] = bias\n\n else:\n num_variables = len(variable_order)\n idx = {v: i for i, v in enumerate(variable_order)}\n\n mat = np.zeros((num_variables, num_variables), dtype=float)\n\n try:\n for v, bias in iteritems(bqm.binary.linear):\n mat[idx[v], idx[v]] = bias\n except KeyError as e:\n raise ValueError((\"variable {} is missing from variable_order\".format(e)))\n\n for (u, v), bias in iteritems(bqm.binary.quadratic):\n iu, iv = idx[u], idx[v]\n if iu < iv:\n mat[iu, iv] = bias\n else:\n mat[iv, iu] = bias\n\n return np.asmatrix(mat)\n\n\ndef from_numpy_matrix(mat, variable_order=None, offset=0.0, interactions=[]):\n \"\"\"Build a binary quadratic model from a numpy matrix.\n\n Args:\n mat (:class:`numpy.matrix`):\n A square numpy matrix. The coefficients of a qubo.\n\n variable_order (list, optional):\n If variable_order is provided, provides the labels for the variables in the binary\n quadratic program, otherwise the row/column indices will be used. If variable_order\n is longer than the matrix, the extra values are ignored.\n\n offset (optional, default=0.0):\n The constant offset for the binary quadratic program.\n\n interactions (iterable, optional, default=[]):\n Any additional 0.0-bias interactions to be added to the binary quadratic model.\n\n Returns:\n :class:`.BinaryQuadraticModel`\n\n \"\"\"\n import numpy as np\n\n if mat.ndim != 2:\n raise ValueError(\"expected input mat to be a square matrix\") # pragma: no cover\n\n num_row, num_col = mat.shape\n if num_col != num_row:\n raise ValueError(\"expected input mat to be a square matrix\") # pragma: no cover\n\n if variable_order is None:\n variable_order = list(range(num_row))\n\n bqm = BinaryQuadraticModel({}, {}, offset, Vartype.BINARY)\n\n for (row, col), bias in np.ndenumerate(mat):\n if row == col:\n bqm.add_variable(variable_order[row], bias)\n elif bias:\n bqm.add_interaction(variable_order[row], variable_order[col], bias)\n\n for u, v in interactions:\n bqm.add_interaction(u, v, 0.0)\n\n return bqm\n\n\ndef to_pandas_dataframe(bqm):\n \"\"\"Return the binary quadratic model as a pandas DataFrame.\n\n Args:\n bqm (:class:`.BinaryQuadraticModel`):\n A binary quadratic model. Should either be index-labeled from 0 to N-1 or variable_order\n should be provided.\n\n Returns:\n :class:`pandas.DataFrame`: The binary quadratic model as a DataFrame. The DataFrame has\n binary vartype. The rows and columns are labeled by the variables in the binary quadratic\n model.\n\n Notes:\n The DataFrame representation of a binary quadratic model only makes sense for binary models.\n For a binary sample x, the energy of the model is given by:\n\n .. math::\n\n E(x) = x^T Q x\n\n\n The offset is dropped when converting to a pandas DataFrame.\n\n \"\"\"\n import pandas as pd\n\n try:\n variable_order = sorted(bqm.linear)\n except TypeError:\n variable_order = list(bqm.linear)\n\n return pd.DataFrame(to_numpy_matrix(bqm, variable_order=variable_order),\n index=variable_order,\n columns=variable_order) # let it choose its own datatype\n\n\ndef from_pandas_dataframe(bqm_df, offset=0.0, interactions=[]):\n \"\"\"Build a binary quadratic model from a pandas dataframe.\n\n Args:\n bqm_df (:class:`pandas.DataFrame`):\n A pandas dataframe. The row and column indices should be that variables of the binary\n quadratic program. The values should be the coefficients of a qubo.\n\n offset (optional, default=0.0):\n The constant offset for the binary quadratic program.\n\n interactions (iterable, optional, default=[]):\n Any additional 0.0-bias interactions to be added to the binary quadratic model.\n\n Returns:\n :class:`.BinaryQuadraticModel`\n\n \"\"\"\n bqm = BinaryQuadraticModel({}, {}, offset, Vartype.BINARY)\n\n for u, row in bqm_df.iterrows():\n for v, bias in row.iteritems():\n if u == v:\n bqm.add_variable(u, bias)\n elif bias:\n bqm.add_interaction(u, v, bias)\n\n for u, v in interactions:\n bqm.add_interaction(u, v, 0.0)\n\n return bqm\n","sub_path":"dimod/binary_quadratic_model_convert.py","file_name":"binary_quadratic_model_convert.py","file_ext":"py","file_size_in_byte":11015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"375377609","text":"import math\nimport random\n\n\ndef dct():\n N = 60\n x = []\n X = []\n \n for i in xrange(N): \n tmp = [random.uniform(0,20) for i in xrange(0,N)]\n x.append(tmp)\n tmp = [0.0] * N\n X.append(tmp)\n \n \n for k1 in xrange(N):\n for k2 in xrange(N):\n \n s1=0\n \n for n1 in xrange(N):\n s2=0\n for n2 in xrange(N):\n s2+=x[n1][n2]*math.cos( (n2+0.5)*math.pi*k2/N)* math.cos( (n1+0.5)*math.pi*k1/N)\n s1+=s2\n X[k1][k2] = s1\n \n \n\nif __name__=='__main__':\n dct()\n \n \n'''\npython2 -m timeit -n 25 'import dct_double'\n25 loops, best of 3: 1.16 usec per loop\n'''\n","sub_path":"2DDCT/dct_double.py","file_name":"dct_double.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"56154027","text":"import numpy as np\nimport matplotlib.pylab as plt\nfname = \"data/ex2data1.txt\"\ndata = np.loadtxt(fname, delimiter=',', usecols=(0, 1, 2), unpack=True)\nX = np.transpose(np.array(data[:-1, :]))\ny = np.transpose(np.array(data[-1:, :]))\nm = len(y)\nX = np.insert(X, 0, 1, axis=1)\nprint(\"X.shape:\")\nprint(X.shape)\nprint(\"y.shape:\")\nprint(y.shape)\n\n#Visualizing the data\npos = np.where(y.reshape(m,) == 1)\nneg = np.where(y.reshape(m,) == 0)\nplt.figure()\nplt.plot(X[pos, 1], X[pos, 2], \"k+\", markersize=5, label=\"Admitted\")\nplt.plot(X[neg, 1], X[neg, 2], \"ro\", markersize=5, label=\"Not admitted\")\nplt.xlim(30, 100)\nplt.ylim(30, 100)\nplt.grid(True)\nplt.xlabel(\"Exam 1 score\")\nplt.ylabel(\"Exam 2 score\")\n\n\n#implementtataion\ndef g(z):\n return 1./(1+np.exp(-z))\n\n\ndef h(theta, X): # theat(n*1), X(m*n)\n return g(np.dot(X, theta))\n\n#show g(z)\nz = np.arange(-10, 10, 0.5)\nplt.figure()\nplt.plot(z, g(z))\n#plt.show()\n\n#Cost function and gradient\ndef costFunction(theta, X, y):\n return np.mean((-y)*np.log(h(theta, X))-(1-y)*np.log(1-h(theta, X)))\n\ndef gradient(theta, X, y):\n return (np.dot(X.T, h(theta, X) - y)/len(y))\n# print(\"-------------\")\ntheta = np.zeros((X.shape[1], 1))\nprint(\"theta.shape:\")\nprint(theta.shape)\ncost = costFunction(theta, X, y)\ngrad = gradient(theta, X, y)\nprint(\"cost:\")\nprint(cost)\nprint(\"gradient:\")\nprint(grad)\n\n# test_theta = np.array((-24, 0.2, 0.2)).reshape(3, 1)\n# cost = costFunction(test_theta, X, y)\n# grad = gradient(test_theta, X, y)\n# print(\"cost:\")\n# print(cost)\n# print(\"gradient:\")\n# print(grad)\n\n\nfrom scipy import optimize\ndef optimizeThete(theta, X, y):\n result = optimize.fmin(costFunction, x0=theta, args=(X, y), maxiter=400, full_output=True)\n return result[0], result[1]","sub_path":"ex2/logistic.py","file_name":"logistic.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"244684554","text":"import canvas\nimport random\nimport math\n\nfrom devices import *\nfrom kuler import *\n\nrandom.seed()\n\nwidth, height = iphone_5_ios7\ntriangle_side = 256.0\npalette = random.choice(themes)\n\ncanvas.begin_updates()\n\ncanvas.set_size(width, height)\ncanvas.set_fill_color(*palette.darkest)\ncanvas.fill_rect(0, 0, width, height)\n\ndef draw_triangle(x, y, size, num_remaining):\n\tif num_remaining > 0:\n\t\tcanvas.set_fill_color(*shade_of(random.choice(palette.colors)))\n\t\tcanvas.set_stroke_color(*shade_of(random.choice(palette.colors)))\n\t\tcanvas.set_line_width(random.random() * 0.5 + 0.5)\n\t\tstep = math.sqrt(size**2 - (size / 2.0)**2)\n\t\tcanvas.move_to(x - step, y - (size / 2.0))\n\t\tcanvas.add_line(x, y + size)\n\t\tcanvas.add_line(x + step, y - (size / 2.0))\n\t\tcanvas.add_line(x - step, y - (size / 2.0))\n\t\tcanvas.fill_path()\n\t\tcanvas.draw_line(x - step, y - (size / 2.0), x, y + size)\n\t\tcanvas.draw_line(x, y + size, x + step, y - (size / 2.0))\n\t\tcanvas.draw_line(x + step, y - (size / 2.0), x - step, y - (size / 2.0))\n\t\tcanvas.draw_line(x, y, x - (step / 2.0), y + (size / 4.0))\n\t\tcanvas.draw_line(x, y, x + (step / 2.0), y + (size / 4.0))\n\t\tcanvas.draw_line(x, y, x, y - (size / 2.0))\n\t\tcanvas.draw_line(x - (step / 2.0), y + (size / 4.0), x + (step / 2.0), y + (size / 4.0))\n\t\tcanvas.draw_line(x + (step / 2.0), y + (size / 4.0), x, y - (size / 2.0))\n\t\tcanvas.draw_line(x, y - (size / 2.0), x - (step / 2.0), y + (size / 4.0))\n\t\tdraw_triangle(random.random() * width, random.random() * height, random.random() * triangle_side, num_remaining - 1)\n\nx = width / 2.0\ny = height / 3.0 # figger\ndraw_triangle(x, y, triangle_side, 100)\n\ncanvas.end_updates()\n","sub_path":"canvas/triangles.py","file_name":"triangles.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"346667748","text":"#!/usr/bin/python\n#-*-coding:utf-8-*-\n\nimport sys\n\nthreshold = int(sys.argv[2])\ncnt = 0\nf = open(sys.argv[1])\nline = f.readlines()\nline.reverse()\n\nfor i in range(threshold):\n\tprint(line[threshold - i -1].strip())\n\n","sub_path":"p06.py","file_name":"p06.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"32762501","text":"\nfrom django.conf.urls import url\n\nfrom users import views\n\nurlpatterns = [\n # 注册\n url(r'^register/', views.register, name='register'),\n # 登录\n url(r'^login/', views.login, name='login'),\n # 退出\n url('logout/', views.logout, name='logout'),\n # 登录验证,获取登录系统的用户\n url('is_login/', views.is_login, name='is_login'),\n # 个人信息中心\n url('user_center_order/', views.user_center_order, name='user_center_order'),\n # 收货地址\n url('user_address/', views.address, name='user_address'),\n]\n\n","sub_path":"qf_1805/1.django/day15/代码/fresh_shop/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"552152437","text":"# Vikram Sunil Bajaj (vsb259)\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom urllib.parse import urlparse, urljoin\r\nimport urllib.robotparser\r\nimport threading\r\nfrom nltk.corpus import wordnet\r\nfrom nltk import word_tokenize, pos_tag\r\nfrom nltk.stem import WordNetLemmatizer\r\nimport datetime\r\nfrom url_normalize import url_normalize\r\nimport time\r\nimport string\r\nimport collections\r\n\r\n# global list for errors\r\nerrors = []\r\n\r\n\r\n# class to implement priority queue\r\n# the queue contains items in the format: [page_promise, url]\r\nclass PriorityQueue:\r\n\r\n def __init__(self):\r\n self.condition = threading.Condition() # allows threads to wait until they are notified by another thread\r\n self.queue = []\r\n\r\n # find the index at which the new item will be stored\r\n # (using binary search)\r\n # descending order of page_promise is used\r\n def calculate_index(self, item, start, end):\r\n if len(self.queue) > 0:\r\n if start < end:\r\n index = int((start + end) / 2)\r\n if item[0] == self.queue[index][0]:\r\n return index\r\n elif item[0] > self.queue[index][0]:\r\n return self.calculate_index(item, start, index - 1)\r\n elif item[0] < self.queue[index][0]:\r\n return self.calculate_index(item, index + 1, end)\r\n elif start == end:\r\n if end != len(self.queue):\r\n if item[0] > self.queue[start][0]:\r\n return start\r\n else:\r\n return start + 1\r\n else:\r\n if item[0] < self.queue[end - 1][0]:\r\n return end\r\n else:\r\n return end - 1\r\n else:\r\n return start\r\n else:\r\n return start\r\n\r\n # display the contents of the queue.\r\n def display_queue(self):\r\n print(\"Queue:\")\r\n for item in self.queue:\r\n print(item)\r\n\r\n # add an item to the queue\r\n def enqueue(self, item):\r\n self.condition.acquire(True)\r\n\r\n if item not in self.queue:\r\n index = self.calculate_index(item, 0, len(self.queue)) # calculate index for new element\r\n self.queue.insert(index, item) # insert element at index\r\n self.condition.notifyAll()\r\n self.condition.release()\r\n\r\n # pop an item from the queue\r\n def dequeue(self):\r\n self.condition.acquire(True)\r\n\r\n while len(self.queue) <= 0:\r\n self.condition.wait()\r\n\r\n item = self.queue[0] # item with highest promise\r\n del self.queue[0] # remove item from the queue\r\n self.condition.release()\r\n return item\r\n\r\n # Returns the size of the queue\r\n def get_size(self):\r\n return len(self.queue)\r\n\r\n # delete the item from the queue\r\n def delete(self, index):\r\n self.condition.acquire(True)\r\n item = self.queue[index]\r\n del self.queue[index] # delete item at index\r\n self.condition.release()\r\n return item\r\n\r\n # find a url in the queue\r\n def find(self, url):\r\n i = -1\r\n self.condition.acquire(True)\r\n\r\n for index in range(len(self.queue)):\r\n if self.queue[index][1] == url:\r\n i = index\r\n self.condition.release()\r\n return i\r\n\r\n # update the promise of a url if it is found while parsing another page\r\n def update_queue(self, url, parent_relevance):\r\n self.condition.acquire()\r\n\r\n index = self.find(url)\r\n if index != -1:\r\n item = self.queue[index]\r\n del self.queue[index] # remove item from queue\r\n item[0] += 0.25 * parent_relevance # update promise\r\n\r\n # index = self.calculate_index(item, 0, len(self.queue)) # compute new index for item\r\n # self.queue.insert(index, item) # insert at index\r\n self.enqueue(item) # recompute the index (using the updated promise) and insert item at index\r\n\r\n self.condition.notifyAll()\r\n self.condition.release()\r\n\r\n\r\n# class to implement the parsed_urls dictionary\r\n# the dictionary has visited urls as keys and values as a list of [links_found, promise, len, time]\r\n# links_found are the links found while parsing the page\r\n# promise is the page relevance promise\r\n# len is the page length\r\n# time is the time at which the page was parsed\r\nclass ParsedURLs:\r\n def __init__(self):\r\n self.lock = threading.Lock()\r\n self.parsed_urls = collections.OrderedDict() # to remember the order in which URLs (keys) were added\r\n\r\n def add_item(self, url, links_found, promise, relevance, len, status_code, time): # add an item into the dictionary\r\n self.lock.acquire()\r\n self.parsed_urls[url] = [links_found, promise, relevance, len, status_code, time]\r\n self.lock.release()\r\n\r\n def find(self, url): # check if item already exists\r\n return url in self.parsed_urls\r\n\r\n def display(self): # display URLs in dictionary i.e. the keys\r\n print(self.parsed_urls.keys())\r\n\r\n def get_keys(self): # return all the keys of the dictionary\r\n return self.parsed_urls.keys()\r\n\r\n def get_item(self, key): # return the number of links found, promise, page len, timestamp for a given key\r\n return len(self.parsed_urls[key][0]), self.parsed_urls[key][1], self.parsed_urls[key][2], \\\r\n self.parsed_urls[key][3], self.parsed_urls[key][4], self.parsed_urls[key][5]\r\n\r\n\r\n# class to keep track of page count i.e. number of pages crawled\r\nclass PageCount:\r\n def __init__(self):\r\n self.lock = threading.Lock()\r\n self.page_num = 0\r\n\r\n def increment(self):\r\n self.lock.acquire()\r\n self.page_num += 1\r\n self.lock.release()\r\n\r\n def get_page_num(self):\r\n return self.page_num\r\n\r\n\r\npage_count = PageCount()\r\n\r\n\r\n# class to perform multi-threaded crawling\r\nclass CrawlerThread(threading.Thread):\r\n def __init__(self, links_to_parse, parsed_urls, query, pages, page_link_limit, mode):\r\n # initializing all the thread attributes\r\n threading.Thread.__init__(self)\r\n self.links_to_parse = links_to_parse\r\n self.parsed_urls = parsed_urls\r\n self.query = query\r\n self.stoprequest = threading.Event() # to stop a thread\r\n self.pages = pages\r\n self.page_link_limit = page_link_limit\r\n self.mode = mode\r\n\r\n def join(self, timeout=None): # waits for the thread to finish executing or until timeout occurs\r\n super(CrawlerThread, self).join(timeout)\r\n\r\n def run(self):\r\n item = self.links_to_parse.dequeue() # get first item (highest promise) from the queue, item = [promise,url]\r\n print('Dequeued: ', item)\r\n url = item[1]\r\n html_text, links = visit_url(url, self.page_link_limit) # read the HTML content of the URL, extract links\r\n while (html_text, links) == (None, None): # keep trying till visit_url() returns non-None values\r\n item = self.links_to_parse.dequeue()\r\n url = item[1]\r\n html_text, links = visit_url(url)\r\n\r\n page_count.increment() # increment the page counter\r\n print(page_count.get_page_num())\r\n\r\n relevance = get_relevance(html_text, self.query) # get relevance of a URL after visiting it\r\n # will use it to compute promise of its child links\r\n\r\n self.parsed_urls.add_item(url, links, item[0], relevance, len(html_text), requests.get(url).status_code, str(\r\n datetime.datetime.now().time())) # add the crawled URL and details into the dictionary parsed_urls\r\n print('Parsed: ', item)\r\n\r\n for index in range(len(links)): # add all the links present in the page to the queue\r\n if links[index] in self.parsed_urls.get_keys():\r\n continue\r\n else:\r\n id = self.links_to_parse.find(links[index]) # check if the URL is already present in the queue\r\n if id != -1:\r\n # URL already present in the queue\r\n if self.mode == 'bfs':\r\n pass\r\n else: # for focused crawling, update the promise of the link using parent's relevance\r\n self.links_to_parse.update_queue(links[index], relevance) # update item, pass parent relevance\r\n else:\r\n # URL not in the queue\r\n if validate_link(links[index]):\r\n promise = get_promise(self.query, links[index], self.mode, relevance) # relevance is of parent\r\n new_item = [promise, links[index]]\r\n self.links_to_parse.enqueue(new_item)\r\n\r\n\r\ndef get_start_pages(query, num_start_pages=10):\r\n \"\"\" get start pages by performing a Google search \"\"\"\r\n\r\n res = requests.get('https://www.google.com/search', params={'q': query})\r\n soup = BeautifulSoup(res.content, 'lxml')\r\n links = soup.find_all('a')\r\n\r\n initial_links = []\r\n count = 0\r\n\r\n for link in links:\r\n href = link.get('href')\r\n if \"url?q=\" in href and \"webcache\" not in href:\r\n l_new = href.split(\"?q=\")[1].split(\"&sa=U\")[0]\r\n if validate_link(url_normalize(l_new)): # checking if normalized URL is crawlable\r\n count += 1\r\n if count <= num_start_pages:\r\n initial_links.append(url_normalize(l_new))\r\n else:\r\n break\r\n return list(set(initial_links))\r\n\r\n\r\ndef validate_link(url):\r\n \"\"\" checks if website is crawlable (status code 200) and if its robots.txt allows crawling\r\n also checks for file types in the url and for a list of words to be excluded \"\"\"\r\n\r\n excluded_words = ['download', 'upload', 'javascript', 'cgi', 'file']\r\n excluded_types = [\".asx\", \".avi\", \".bmp\", \".css\", \".doc\", \".docx\",\r\n \".flv\", \".gif\", \".jpeg\", \".jpg\", \".mid\", \".mov\",\r\n \".mp3\", \".ogg\", \".pdf\", \".png\", \".ppt\", \".ra\",\r\n \".ram\", \".rm\", \".swf\", \".txt \", \".wav\", \".wma\",\r\n \".wmv\", \".xml\", \".zip\", \".m4a\", \".m4v\", \".mov\",\r\n \".mp4\", \".m4b\", \".cgi\", \".svg\", \".ogv\", \".dmg\", \".tar\", \".gz\"]\r\n\r\n for ex_word in excluded_words:\r\n if ex_word in url.lower():\r\n errors.append('Link contains excluded terms')\r\n return False\r\n\r\n for ex_type in excluded_types:\r\n if ex_type in url.lower():\r\n errors.append('Link contains excluded type')\r\n return False\r\n\r\n # checking if the url returns a status code 200\r\n try:\r\n r = requests.get(url)\r\n if r.status_code == 200:\r\n pass # website returns status code 200, so check for robots.txt\r\n else:\r\n print(url, r.status_code, 'failed')\r\n errors.append(r.status_code)\r\n return False\r\n except:\r\n print(url, 'request failed') # request failed\r\n errors.append('Request Failed')\r\n return False\r\n\r\n # checking if the website has a robots.txt, and then checking if I am allowed to crawl it\r\n domain = urlparse(url).scheme + '://' + urlparse(url).netloc\r\n\r\n try:\r\n rp = urllib.robotparser.RobotFileParser()\r\n rp.set_url(domain + '/robots.txt')\r\n rp.read()\r\n if not rp.can_fetch('*', url): # robots.txt mentions that the link should not be parsed\r\n print('robots.txt does not allow to crawl', url)\r\n errors.append('Robots Exclusion')\r\n return False\r\n except:\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef get_input():\r\n \"\"\" get query, number of start pages, number of pages to be returned and mode \"\"\"\r\n\r\n query = input('Enter your query (default: \"wildfires california\"): ').strip()\r\n num_start_pages = input(\"Enter the number of start pages (default: 10): \").strip()\r\n n = input(\"Enter the number of pages to be returned (at least 10, default: 1000): \").strip()\r\n page_link_limit = input(\"Enter the max. no. of links to be fetched from each page (at least 10, default: 30): \")\\\r\n .strip()\r\n mode = input(\"Enter mode 'bfs' or 'focused' (default: 'bfs'): \").strip()\r\n\r\n print('\\nObtaining start pages...\\n')\r\n # checking if values are input correctly, otherwise use defaults\r\n if len(query) == 0:\r\n query = 'wildfires california'\r\n\r\n if len(num_start_pages) == 0 or int(num_start_pages) <= 0:\r\n num_start_pages = 10\r\n\r\n if len(n) == 0 or int(n) < 10:\r\n n = 1000\r\n\r\n if len(page_link_limit) == 0 or int(page_link_limit) < 10:\r\n page_link_limit = 30\r\n\r\n if len(mode) == 0 or mode.lower() not in {'bfs', 'focused'}:\r\n mode = 'bfs'\r\n\r\n return query, int(num_start_pages), int(n), int(page_link_limit), mode\r\n\r\n\r\ndef get_promise(query, url, mode, parent_relevance):\r\n \"\"\" returns the promise of a URL, based on which URLs are placed on the priority queue \"\"\"\r\n if mode.lower() == 'bfs':\r\n return 1 # all pages have the same promise in a simple bfs crawl since we do not compute relevance\r\n else:\r\n # calculate promise based on the link\r\n promise = 0\r\n\r\n # remove punctuation from query\r\n punctuation = set(string.punctuation)\r\n query = ''.join(x for x in query if x not in punctuation)\r\n\r\n query_terms = [q.lower() for q in query.strip().split()]\r\n\r\n # checking if all or any of the terms are in the link, if synonyms are present, if lemmatized words are present\r\n synonyms, lemmatized_words = get_synonyms_and_lemmatized(query.lower())\r\n\r\n # synonyms is a dict with a list of synonyms per query term\r\n # creating a combined list of synonyms, without duplicates\r\n synonyms_list = list(set([s for sublist in list(synonyms.values()) for s in sublist]))\r\n\r\n if all([x in url.lower() for x in query_terms]): # all query terms are in the URL\r\n promise += 0.5\r\n elif any([x in url.lower() for x in query_terms]): # at least 1 query term in URL, but not all\r\n promise += 0.25\r\n else: # no query term in URL\r\n pass # keep promise as is\r\n\r\n # checking for synonyms\r\n if all([x in url.lower() for x in synonyms_list]): # all synonyms are in the URL\r\n promise += 0.4\r\n elif any([x in url.lower() for x in synonyms_list]): # at least 1 synonym is in URL, but not all\r\n promise += 0.2\r\n else: # no synonym in URL\r\n pass # keep promise as is\r\n\r\n # checking for lemmatized words\r\n if all([x in url.lower() for x in lemmatized_words]): # all lemmatized words are in the URL\r\n promise += 0.4\r\n elif any([x in url.lower() for x in lemmatized_words]): # at least 1 lemmatized word is in URL, but not all\r\n promise += 0.2\r\n else: # no lemmatized word in URL\r\n pass # keep promise as is\r\n\r\n promise += 0.25 * parent_relevance # giving a certain weight to URL's parent's relevance\r\n promise /= len(url) # to penalize longer URLs\r\n return promise\r\n\r\n\r\ndef get_relevance(html_text, query):\r\n \"\"\" returns the relevance of a page after crawling it \"\"\"\r\n\r\n # remove punctuation from query\r\n punctuation = set(string.punctuation)\r\n query = ''.join(x for x in query if x not in punctuation)\r\n\r\n query_terms = query.lower().strip().split()\r\n relevance = 0\r\n\r\n synonyms, lemmatized_words = get_synonyms_and_lemmatized(query)\r\n synonyms_list = list(set([s for sublist in list(synonyms.values()) for s in sublist]))\r\n\r\n soup = BeautifulSoup(html_text, 'lxml')\r\n\r\n if soup.title:\r\n # TITLE\r\n title = soup.title.text.lower()\r\n # checking query terms -----------------------------------------\r\n if all([q in title for q in query_terms]): # all terms in title\r\n relevance += 0.25\r\n elif any([q in title for q in query_terms]): # at least one term in title but not all\r\n relevance += 0.15\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking synonyms_list terms ----------------------------------\r\n if all([q in title for q in synonyms_list]): # all terms in title\r\n relevance += 0.2\r\n elif any([q in title for q in synonyms_list]): # at least one term in title but not all\r\n relevance += 0.1\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking lemmatized words -----------------------------------------\r\n if all([q in title for q in lemmatized_words]): # all terms in title\r\n relevance += 0.2\r\n elif any([q in title for q in lemmatized_words]): # at least one term in title but not all\r\n relevance += 0.1\r\n else:\r\n pass # keep relevance as is\r\n\r\n if soup.find('h1'):\r\n # FIRST HEADING\r\n h1 = soup.find('h1').text.lower() # first h1 heading\r\n\r\n # checking query terms -----------------------------------------\r\n if all([q in h1 for q in query_terms]): # all terms in first heading\r\n relevance += 0.5\r\n elif any([q in h1 for q in query_terms]): # at least one term in heading but not all\r\n relevance += 0.25\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking synonyms_list terms ----------------------------------\r\n if all([q in h1 for q in synonyms_list]): # all terms in first heading\r\n relevance += 0.45\r\n elif any([q in h1 for q in synonyms_list]): # at least one term in heading but not all\r\n relevance += 0.2\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking lemmatized words -----------------------------------------\r\n if all([q in h1 for q in lemmatized_words]): # all terms in first heading\r\n relevance += 0.45\r\n elif any([q in h1 for q in lemmatized_words]): # at least one term in heading but not all\r\n relevance += 0.2\r\n else:\r\n pass # keep relevance as is\r\n\r\n if soup.find_all('a'):\r\n # ANCHOR TAGS TEXT\r\n a_text = ' '.join(list(set([a.text.lower() for a in soup.find_all('a')]))) # anchor tags text combined\r\n\r\n # checking query terms -----------------------------------------\r\n if all([q in a_text for q in query_terms]): # all terms in anchor text\r\n relevance += 0.25\r\n elif any([q in a_text for q in query_terms]): # at least one term in anchor text but not all\r\n relevance += 0.15\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking synonyms_list terms ----------------------------------\r\n if all([q in a_text for q in synonyms_list]): # all terms in anchor text\r\n relevance += 0.2\r\n elif any([q in a_text for q in synonyms_list]): # at least one term in anchor text but not all\r\n relevance += 0.1\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking lemmatized words -----------------------------------------\r\n if all([q in a_text for q in lemmatized_words]): # all terms in anchor text\r\n relevance += 0.2\r\n elif any([q in a_text for q in lemmatized_words]): # at least one term in anchor text but not all\r\n relevance += 0.1\r\n else:\r\n pass # keep relevance as is\r\n\r\n if soup.find_all('b'):\r\n # BOLD TEXT\r\n bold = ' '.join(list(set([b.text.lower() for b in soup.find_all('b')]))) # bold text combined\r\n\r\n # checking query terms -----------------------------------------\r\n if all([q in bold for q in query_terms]): # all terms in bold text\r\n relevance += 0.25\r\n elif any([q in bold for q in query_terms]): # at least one term in bold text but not all\r\n relevance += 0.15\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking synonyms_list terms ----------------------------------\r\n if all([q in bold for q in synonyms_list]): # all terms in bold text\r\n relevance += 0.2\r\n elif any([q in bold for q in synonyms_list]): # at least one term in bold text but not all\r\n relevance += 0.1\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking lemmatized words -----------------------------------------\r\n if all([q in bold for q in lemmatized_words]): # all terms in bold text\r\n relevance += 0.2\r\n elif any([q in bold for q in lemmatized_words]): # at least one term in bold text but not all\r\n relevance += 0.1\r\n else:\r\n pass # keep relevance as is\r\n\r\n # REMAINING PAGE TEXT\r\n remove_checked = [s.extract() for s in soup(['title', 'b', 'a', 'h1'])] # remove title, anchors, h1 and bold text\r\n page_text = soup.text.replace('\\n', '').lower() # page text (after extracting already checked tags)\r\n\r\n # checking query terms -----------------------------------------\r\n if all([q in page_text for q in query_terms]): # all terms in remaining text\r\n relevance += 0.5\r\n elif any([q in page_text for q in query_terms]): # at least one term in remaining text but not all\r\n relevance += 0.25\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking synonyms_list terms ----------------------------------\r\n if all([q in page_text for q in synonyms_list]): # all terms in remaining text\r\n relevance += 0.45\r\n elif any([q in page_text for q in synonyms_list]): # at least one term in remaining text but not all\r\n relevance += 0.2\r\n else:\r\n pass # keep relevance as is\r\n\r\n # checking lemmatized words -----------------------------------------\r\n if all([q in page_text for q in lemmatized_words]): # all terms in remaining text\r\n relevance += 0.45\r\n elif any([q in page_text for q in lemmatized_words]): # at least one term in remaining text but not all\r\n relevance += 0.2\r\n else:\r\n pass # keep relevance as is\r\n\r\n return relevance\r\n\r\n\r\ndef get_synonyms_and_lemmatized(query):\r\n \"\"\" returns a dict with a list of synonyms per word in the query \"\"\"\r\n words = word_tokenize(query)\r\n pos = {}\r\n for word in words:\r\n pos.update({word: pos_tag([word], tagset='universal')[0][1]})\r\n\r\n simplified_pos_tags = {}\r\n\r\n for x in pos.keys():\r\n if pos[x] == 'NOUN':\r\n simplified_pos_tags.update({x: 'n'})\r\n elif pos[x] == 'VERB':\r\n simplified_pos_tags.update({x: 'v'})\r\n elif pos[x] == 'ADJ':\r\n simplified_pos_tags.update({x: 'a'})\r\n elif pos[x] == 'ADV':\r\n simplified_pos_tags.update({x: 'r'})\r\n else:\r\n simplified_pos_tags.update({x: 'n'}) # consider everything else to be a noun\r\n\r\n synonyms = {}\r\n for w in words:\r\n synonyms[w] = []\r\n\r\n for w in words:\r\n if len(wordnet.synsets(w, pos=simplified_pos_tags[w])) != 0:\r\n s = [x.lower().replace('_', ' ') for x in wordnet.synsets(w, pos=simplified_pos_tags[w])[0].lemma_names() if\r\n x.lower() != w]\r\n for x in s:\r\n if x not in synonyms[w]:\r\n synonyms[w].append(x)\r\n\r\n wordnet_lemmatizer = WordNetLemmatizer()\r\n # lemmatize all words, return only those which aren't the same as the word\r\n lemmatized_words = [wordnet_lemmatizer.lemmatize(w, simplified_pos_tags[w]) for w in words if\r\n wordnet_lemmatizer.lemmatize(w, simplified_pos_tags[w]) != w]\r\n\r\n return synonyms, list(set(lemmatized_words))\r\n\r\n\r\ndef visit_url(url, page_link_limit):\r\n \"\"\" parses a page to extract text and first k links; returns HTML text and normalized links \"\"\"\r\n\r\n try:\r\n res = requests.get(url)\r\n if res.status_code == 200 and 'text/html' in res.headers['Content-Type']: # also checking MIME type\r\n html_text = res.text\r\n soup = BeautifulSoup(res.content, 'lxml')\r\n f_links = soup.find_all('frame')\r\n a_links = soup.find_all('a')\r\n\r\n # check if the page has a tag to get the base URL for relative links\r\n base = soup.find('base')\r\n if base is not None:\r\n base_url = base.get('href')\r\n else:\r\n # construct the base URL\r\n scheme = urlparse(url).scheme\r\n domain = urlparse(url).netloc\r\n base_url = scheme + '://' + domain\r\n\r\n src = [urljoin(base_url, f.get('src')) for f in f_links]\r\n href = [urljoin(base_url, a.get('href')) for a in a_links]\r\n\r\n links = list(set(src + href))[:page_link_limit]\r\n links = [url_normalize(l) for l in links if validate_link(url_normalize(l))]\r\n\r\n return html_text, links\r\n else:\r\n return None, None\r\n except:\r\n return None, None\r\n\r\n\r\ndef get_harvest_rate(parsed_urls, threshold):\r\n \"\"\" return harvest rate i.e. # relevant links/# total links parsed \"\"\"\r\n\r\n total_parsed = len(parsed_urls.get_keys())\r\n total_relevant = 0\r\n\r\n for link in parsed_urls.get_keys():\r\n if parsed_urls.get_item(link)[2] >= threshold:\r\n total_relevant += 1\r\n\r\n harvest_rate = total_relevant/total_parsed\r\n\r\n return harvest_rate\r\n\r\n\r\ndef create_log(parsed_urls, query, num_start_pages, num_crawled, page_link_limit, n, mode, harvest_rate, threshold,\r\n total_time):\r\n \"\"\" creates a log file for the crawler \"\"\"\r\n file = open('crawler_log.txt', 'w')\r\n\r\n total_size = 0\r\n\r\n file.write('Query: ' + query + '\\n')\r\n file.write('Number of Crawlable Start Pages: ' + str(num_start_pages) + '\\n')\r\n file.write('Number of URLs to be Crawled: ' + str(n) + '\\n')\r\n file.write('Max. Number of Links to be Scraped per Page: ' + str(page_link_limit) + '\\n')\r\n file.write('Crawl Mode: ' + mode + '\\n')\r\n file.write('Number of URLs Crawled: ' + str(num_crawled) + '\\n\\n')\r\n\r\n file.write('URLs Crawled:\\n')\r\n file.write('-------------\\n\\n')\r\n\r\n counter = 0\r\n for p in parsed_urls.get_keys():\r\n file.write(str(counter+1) + '. \\n')\r\n file.write('URL:' + p + '\\n')\r\n num_links, page_promise, relevance, page_size, status_code, timestamp = parsed_urls.get_item(p)\r\n total_size += page_size\r\n\r\n file.write('Number of Links in Page:' + str(num_links) + '\\n')\r\n file.write('Page Size:' + str(page_size) + '\\n')\r\n file.write('Page Promise: ' + str(page_promise) + '\\n')\r\n file.write('Page Relevance: ' + str(relevance) + '\\n')\r\n file.write('Status Code: ' + str(status_code) + '\\n')\r\n file.write('Crawled at:' + str(timestamp) + '\\n')\r\n file.write('\\n\\n')\r\n counter += 1\r\n file.write('Total Size of all Pages Crawled: ' + str(total_size) + '\\n')\r\n if total_time < 1: # convert to seconds\r\n total_time *= 60\r\n file.write('Total Time Elapsed: ' + str(total_time) + ' sec\\n')\r\n else:\r\n file.write('Total Time Elapsed: ' + str(total_time) + ' min\\n')\r\n\r\n file.write('Harvest Rate: ' + str(harvest_rate) + ' at Threshold: ' + str(threshold) + '\\n')\r\n\r\n unique_errors = list(set(errors))\r\n file.write('Errors: \\n')\r\n for e in unique_errors:\r\n file.write(str(e) + ': ' + str(errors.count(e)) + '\\n')\r\n\r\n\r\ndef main():\r\n query, num_start_pages, n, page_link_limit, mode = get_input()\r\n start_time = time.time()\r\n start_pages = get_start_pages(query, num_start_pages)\r\n\r\n links_to_parse = PriorityQueue()\r\n parsed_urls = ParsedURLs()\r\n\r\n print('Found %d crawlable start pages:\\n' % len(start_pages))\r\n # enqueue the start pages after computing their promises\r\n for s in start_pages:\r\n promise = get_promise(query, s, mode, 0) # initially, parent_relevance is 0\r\n links_to_parse.enqueue([promise, s])\r\n\r\n # display the queue\r\n links_to_parse.display_queue()\r\n print('\\n')\r\n\r\n threads = []\r\n\r\n for i in range(n): # creating threads for faster crawling\r\n threads.append(CrawlerThread(links_to_parse, parsed_urls, query, n, page_link_limit, mode))\r\n threads[i].daemon = True # daemon threads allow the program to quit even if they are still running\r\n threads[i].start()\r\n\r\n while True:\r\n if page_count.get_page_num() == n or links_to_parse == []: # crawled n pages (or) priority queue empty\r\n end_time = time.time()\r\n total_time = (end_time - start_time)/60 # minutes\r\n\r\n # compute harvest rate\r\n threshold = 3 # relevance threshold\r\n harvest_rate = get_harvest_rate(parsed_urls, threshold)\r\n\r\n # create a crawler log file\r\n create_log(parsed_urls, query, len(start_pages), len(parsed_urls.get_keys()), page_link_limit, n, mode,\r\n harvest_rate, threshold, total_time)\r\n break\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"spidey_multiThread.py","file_name":"spidey_multiThread.py","file_ext":"py","file_size_in_byte":29065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"328003170","text":"import time\nimport urllib.request \nimport json\nimport shutil\n\nimport os\n\nimport win32com.client\n\n\nimport inquirer\nfrom rich.console import Console\n\n\nstart = time.time()\n\nconsole = Console()\n\nconsole.print(\"\"\"[cyan1]\n █████╗ ██╗ ██╗████████╗ ██████╗ ███████╗████████╗ █████╗ ██████╗ ████████╗\n██╔══██╗██║ ██║╚══██╔══╝██╔═══██╗ ██╔════╝╚══██╔══╝██╔══██╗██╔══██╗╚══██╔══╝\n███████║██║ ██║ ██║ ██║ ██║ ███████╗ ██║ ███████║██████╔╝ ██║ \n██╔══██║██║ ██║ ██║ ██║ ██║ ╚════██║ ██║ ██╔══██║██╔══██╗ ██║ \n██║ ██║╚██████╔╝ ██║ ╚██████╔╝ ███████║ ██║ ██║ ██║██║ ██║ ██║ \n╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ \n Developer: Ghoul#6066 \n[cyan1]\"\"\")\n\nconsole.print(\"[cyan1]I will now ask you a few questions so we can get started.\\n\")\n\nconsole.print(\"[cyan1]Before We Get Started I am Going To Check For Updates.\")\n\nTHIS_VERSION = \"1.0.5\"\n\nwith urllib.request.urlopen(\"https://api.github.com/repos/:author/:repo/releases/latest\") as url:\n data = json.loads(url.read().decode())\n latest = data['tag_name'][1:] # \"v2.3.6\" -> \"2.3.6\"\n patchNotes = data['body']\n\nconsole.print(\"[cyan1]FOR THE CHOICES, AN EXAMPLE WOULD BE:\\n\\nDrive: [red]C[/red]\\nProgram Name: [red]discord(MUST MATCH EXACTLY)[/red][/cyan1]\\n\\n\")\n\ndrive = console.input(\"[cyan1]Drive: [/cyan1]\", markup=True)\n\nprogram_name = console.input(\"[cyan1]Program Name: [/cyan1]\", markup=True)\n\nquestions = [\n inquirer.List('folder',\n message=\"Where Should I Search?\",\n choices=['Program Files', 'Program Files (x86)', 'AppData'],\n ),\n]\nanswer = inquirer.prompt(questions)\n\nconsole.print(f\"\\n\\n[cyan1]Good Job Answering!, I will now start to search for [red]{program_name}.exe[/red] in Drive [red]{drive.upper()}:/[/red]\\n\\n\")\n\nconsole.print(f\"[red]NOTE: THIS PROCESS WILL SEARCH YOUR ENTIRE DRIVE(It Will Exlude Some Directories And File Types.), IT WILL NOT FINISH 'FAST', YOU WILL NEED TO BE PATIENT[/red]\")\n\nusername = os.getlogin()\n\nexclude = set(['Windows', 'Microsoft', 'Intel', 'Google', 'dotnet', 'ImageGlass', 'Inno Setup 6', 'Microsoft Visual Studio', 'Internet Explorer', 'Microsoft Visual Studio Tools for Unity', 'Microsoft SQL Server', 'Windows Portable Devices', 'Windows Media Player', 'Windows Multimedia Platform', 'Common Files', 'Microsoft Analysis Services', 'Microsoft Office', 'Microsoft SDKs', 'MSBuild', 'Windows NT', 'Windows Kits', 'Windows Photo Viewer', 'Windows Defender', 'WinRar', 'Windows Defender Advanced Threat Protection', 'Windows Security', 'WindowsApps', 'Microsoft.NET', 'K-Lite Codec Pack', 'Reference Assemblies'])\n\nfor root, dirs, files in os.walk(f\"{drive.upper()}:/Users/{username}/{answer['folder']}\" if answer[\"folder\"] == \"AppData\" else f\"{drive.upper()}:/{answer['folder']}\" if answer[\"folder\"] == 'Program Files' or 'Program Files (x86)' else None, onerror=None, topdown=True):\n\n [dirs.remove(d) for d in list(dirs) if d in exclude]\n\n if any(f.endswith(('.dll', '.txt', '.api', '.htm', '.html', '.py', '.js', '.ts', '.cmake', 'LICENSE', '.rst', '.ttf', '.xml', '.css', '.po', '.mo', '.pak', '.json', '.vdf', '.layout', '.pdf', '.mpp', '.jar', '.otf', '.md', '.pmp', '.png', '.gif', '.webp', '.jpg', '.maifest', '.TXT', '.tex', '.h', '.cpp', '.vbs', '.msg', '.lib', '.c', '.lua', '.mlua', '.wlua', '.dlua', '.mp4', '.mp3', '.so', '.dat', '.policy', '.properties', '.svg', '.conf', '.bin', '.frag', '.vert', '.bat', '.in', '.enc', '.tcl', '.sample', '.crt', '.pm', '.pl', '.code-snippets', '.env', '.rsh', '.bc', '.b', '.out', '.java')) for f in files):\n continue\n \n for file in files:\n s = file\n print(len(s) * \" \", '\\r', s, end='')\n time.sleep(0.1)\n if file.startswith(f\"{program_name}\"):\n found_file = (os.path.join(root, file))\n console.print(f\"\\n\\n[cyan1]After searching For [red]{program_name}.exe[/red], I found [red]{found_file}[/red]![/cyan1]\\n\\n\")\n time.sleep(1)\n console.print(\"[cyan1]Alright!, I'm going to go ahead and get the wheels spinning...[/cyan1]\\n\\n\")\n time.sleep(1)\n console.print(\"[cyan1]GETTING PROGRAMS MENU[/cyan1]\")\n objShell = win32com.client.Dispatch(\"WScript.Shell\")\n UserProgramsMenu = objShell.SpecialFolders(\"AllUsersPrograms\")\n time.sleep(1)\n console.print(\"\\n[cyan1]FETCH PROGRAMS MENU: COMPLETE[/cyan1]\")\n time.sleep(1)\n console.print(\"\\n[cyan1] Copying File...[/cyan1]\")\n shutil.copy(found_file, UserProgramsMenu)\n console.print(\"\\n[cyan1]File Has Been Copied, Restart Your Computer And Watch The Magic Happen.\")\n end = time.time()\n elasped_time = end - start\n console.print(f\"\\n[cyan1]This Process Took [red]{elasped_time}[/red] Seconds.\")\n time.sleep(2)\n raise SystemExit\n\n \n\n","sub_path":"auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":5710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"561550551","text":"\nimport core\nimport pyglet\nfrom pyglet.window import key \nfrom core import GameElement\nimport sys\n\n#### DO NOT TOUCH ####\nGAME_BOARD = None\nDEBUG = False\nKEYBOARD = None\nPLAYER = None\n######################\n\nGAME_WIDTH = 8\nGAME_HEIGHT = 8\n\n#### Put class definitions here ####\n\nclass Rock(GameElement):\n IMAGE = \"Rock\"\n SOLID = True\n def interact(self, player): \n if PLAYER.GEM: \n next_x = self.x + PLAYER.NEXT_X - PLAYER.x \n next_y = self.y + PLAYER.NEXT_Y - PLAYER.y \n\n if (not check_bound(next_x, next_y) or \n GAME_BOARD.get_el(next_x, next_y)) : \n GAME_BOARD.draw_msg(\"Can't move there!\")\n\n else: \n\n GAME_BOARD.del_el(self.x, self.y) \n GAME_BOARD.set_el(next_x, next_y, self)\n GAME_BOARD.del_el(PLAYER.x, PLAYER.y) \n GAME_BOARD.set_el(PLAYER.NEXT_X, PLAYER.NEXT_Y, PLAYER) \n\n else:\n GAME_BOARD.draw_msg(\"You need a gem to move the rocks!\") \n\n\nclass Tree(GameElement):\n IMAGE = \"ShortTree\"\n SOLID = True\n\nclass Girl(GameElement): \n IMAGE = \"Girl\"\n KEY = False \n POWER = False \n GEM = False\n NEXT_X = None\n NEXT_Y = None\n\n def __init__(self): \n GameElement.__init__(self)\n self.inventory = [] \n\n def next_pos(self, direction): \n if direction == \"up\":\n return (self.x, self.y-1) \n elif direction == \"down\":\n return (self.x, self.y+1) \n elif direction == \"left\":\n return (self.x-1, self.y) \n elif direction == \"right\":\n return (self.x+1, self.y) \n return None \n\n\nclass Princess(GameElement):\n IMAGE = \"Princess\"\n SOLID = True\n def interact(self, player):\n player.POWER = True \n GAME_BOARD.draw_msg(\"The princess gave you special powers!\")\n\nclass Heart(GameElement):\n IMAGE = \"Heart\"\n SOLID = False\n\nclass Boy(GameElement):\n IMAGE = \"Boy\"\n SOLID = True\n def interact(self, player):\n GAME_BOARD.del_el(PLAYER.x, PLAYER.y)\n GAME_BOARD.set_el(0, 0, PLAYER) \n GAME_BOARD.draw_msg(\"You kissed a boy! Back to the start for you!\")\n heart=Heart() \n GAME_BOARD.register(heart)\n GAME_BOARD.set_el(boy.x-1, boy.y, heart)\n GAME_BOARD.set_el(boy.x+1, boy.y, heart)\n GAME_BOARD.set_el(boy.x, boy.y-1, heart)\n GAME_BOARD.set_el(boy.x, boy.y+1, heart)\n \n\nclass Gem(GameElement):\n IMAGE = \"BlueGem\"\n SOLID = False\n def interact(self, player):\n player.inventory.append(self) \n player.GEM = True\n GAME_BOARD.draw_msg(\"You just acquired a gem! You have %d items!\"%(len(player.inventory)))\n\nclass Key(GameElement):\n IMAGE = \"Key\"\n SOLID = False\n def interact(self, player): \n player.inventory.append(self) \n player.KEY = True \n GAME_BOARD.draw_msg(\"You just picked up a key! You have %d items!\"%(len(player.inventory)))\n\nclass DoorOpen(GameElement):\n IMAGE = \"DoorOpen\"\n SOLID = False \n\n\n\nclass DoorClosed(GameElement):\n IMAGE = \"DoorClosed\"\n SOLID = True \n def interact(self, player):\n if player.POWER and player.KEY: \n GAME_BOARD.draw_msg(\"You opened the door!\")\n \n open_door = DoorOpen() \n GAME_BOARD.register(open_door) \n GAME_BOARD.set_el(self.x, self.y, open_door) \n elif player.POWER:\n GAME_BOARD.draw_msg(\"You have special power, but you still need a key to open the door\")\n elif player.KEY:\n GAME_BOARD.draw_msg(\"You have the key, but you still need the Princess to give you special powers\")\n else:\n GAME_BOARD.draw_msg(\"You need a key and special powers to enter this door\")\n \n\n \n\n#### End class definitions ####\n\ndef initialize():\n \"\"\"Put game initialization code here\"\"\"\n\n rock_positions = [\n (4,6),\n (1,1),\n (3,5),\n (6,2)\n ]\n rocks = []\n\n for pos in rock_positions:\n rock = Rock()\n GAME_BOARD.register(rock)\n GAME_BOARD.set_el(pos[0], pos[1], rock)\n rocks.append(rock)\n\n global PLAYER\n PLAYER = Girl()\n GAME_BOARD.register(PLAYER)\n GAME_BOARD.set_el(2, 1, PLAYER)\n \n tree_positions = [\n (5,0),\n (5,1),\n (7,0),\n (7,1)\n ]\n\n trees =[]\n \n for pos in tree_positions:\n tree = Tree()\n GAME_BOARD.register(tree)\n GAME_BOARD.set_el(pos[0], pos[1], tree)\n trees.append(trees)\n\n global boy\n boy = Boy()\n GAME_BOARD.register(boy)\n GAME_BOARD.set_el(2,4, boy)\n \n\n cindy = Princess()\n GAME_BOARD.register(cindy)\n GAME_BOARD.set_el(5,4, cindy)\n \n gem = Gem()\n GAME_BOARD.register(gem)\n GAME_BOARD.set_el(3, 3, gem)\n\n key = Key()\n GAME_BOARD.register(key)\n GAME_BOARD.set_el(0,5, key)\n\n closed_door = DoorClosed()\n GAME_BOARD.register(closed_door)\n GAME_BOARD.set_el(6,1, closed_door)\n\n GAME_BOARD.draw_msg(\"This game is groovy, man.\")\n\n\ndef second_stage():\n \"\"\"\n create a new game board if the player opens the door and crossed through\n \"\"\"\n GAME_BOARD.draw_msg(\"Congrats! We are going to the second stage.\") \n for x in range(GAME_WIDTH):\n for y in range (GAME_HEIGHT):\n GAME_BOARD.del_el(x, y) \n GAME_BOARD.set_el(0, 0, PLAYER)\n\n\ndef check_bound(next_x,next_y):\n \"\"\"\n check if the position is out of boundary\n \"\"\"\n if next_x >= GAME_WIDTH or next_x<0: \n GAME_BOARD.draw_msg(\"Can't move there!\")\n return False\n \n elif next_y >= GAME_HEIGHT or next_y<0:\n GAME_BOARD.draw_msg(\"Can't move there!\")\n return False\n\n return True\n\n\n\ndef keyboard_handler():\n\n direction=None\n\n # Stage clear check\n if (PLAYER.x, PLAYER.y) == (6,0): \n second_stage()\n\n # Keyboard check\n if KEYBOARD[key.UP]:\n direction = \"up\"\n\n elif KEYBOARD[key.DOWN]:\n direction = \"down\"\n\n elif KEYBOARD[key.LEFT]:\n direction = \"left\"\n \n elif KEYBOARD[key.RIGHT]: \n direction = \"right\"\n\n if direction: \n GAME_BOARD.erase_msg()\n next_location = PLAYER.next_pos(direction)\n PLAYER.NEXT_X = next_location[0]\n PLAYER.NEXT_Y = next_location[1]\n\n\n if check_bound(PLAYER.NEXT_X, PLAYER.NEXT_Y) : \n\n existing_el = GAME_BOARD.get_el(PLAYER.NEXT_X, PLAYER.NEXT_Y) \n \n if existing_el: \n existing_el.interact(PLAYER) \n\n if existing_el is None or not existing_el.SOLID: \n GAME_BOARD.del_el(PLAYER.x, PLAYER.y) \n GAME_BOARD.set_el(PLAYER.NEXT_X, PLAYER.NEXT_Y, PLAYER)\n \n","sub_path":"oop_lesson2/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":6911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"90817919","text":"import cv2\r\nimport numpy as np\r\n\r\n# cap = cv2.VideoCapture('http://192.168.43.156:8080/video')\r\ncap = cv2.VideoCapture(0)\r\n\r\nwhile(True):\r\n ret, frame = cap.read()\r\n cv2.imshow('frame',frame)\r\n frame = cv2.medianBlur(frame,9)\r\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\r\n lower_skin = np.array([0,50,20], dtype=np.uint8)\r\n upper_skin = np.array([255,255,255], dtype=np.uint8)\r\n \r\n #extract skin colur imagw \r\n mask = cv2.inRange(hsv, lower_skin, upper_skin)\r\n\r\n cv2.imshow('mask',mask)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n cv2.destroyAllWindows()\r\n break","sub_path":"blog/ipwebcampy.py","file_name":"ipwebcampy.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"230956570","text":"from tkinter import *\n\n\n\nroot=Tk()\n\nroot.config(background=\"orange\")\n\n\n\nstartMenuLabel = Label(root,text=\"LocoMotive\", fg = \"black\", bg = \"orange\",font = \"Helvetica 30 bold italic\")\nstartMenuLabel.place(relx=.5, rely=.1, anchor=\"c\")\n\n\nstartGame = Button(root,text=\"Start game\",fg=\"black\",bg ='#ff0000',font=\"Helvetica 15 bold\",width=25,height=4,command=())\nstartGame.place(relx=.5, rely=.85, anchor=\"c\")\nstartGame.config(highlightbackground='#e60000',background='#e60000')\n\nrules = Button(root,text=\"Rules\",fg=\"black\",bg = \"dark red\",font=\"Helvetica 15 bold\",width=15,height=3,command=())\nrules.place(relx=.8, rely=.33, anchor=\"c\")\nrules.config(highlightbackground=\"green\",background=\"green\")\n\nsavedGames = Button(root,text=\"Saved games\",fg=\"black\",bg = \"dark red\",font=\"Helvetica 15 bold\",width=15,height=3,command=())\nsavedGames.place(relx=.8, rely=.51, anchor=\"c\")\nsavedGames.config(highlightbackground=\"green\",background=\"green\")\n\nnoOfPlayersLabel= Label(root,text = \"Number of players:\",bg=\"orange\",font = \"Helvetica 15 bold\")\nnoOfPlayersLabel.place(relx=.1,rely=.3)\n\n\nnoOfPlayers = Entry(root,width = 1)\nnoOfPlayers.place(relx=.29,rely=.3)\n\n\nnoOfCPUPlayersLabel= Label(root,text = \"Number of Comp players:\",bg=\"orange\",font = \"Helvetica 15 bold\")\nnoOfCPUPlayersLabel.place(relx=.1,rely=.5)\n\n\nnoOfCPUPlayers = Entry(root,width = 1)\nnoOfCPUPlayers.place(relx=.345,rely=.5)\n\n\n\nroot.geometry(\"800x600+250+250\")\nroot.mainloop()","sub_path":"Start menu.py","file_name":"Start menu.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"285273413","text":"import json\nimport os\nfrom typing import List, Any, Union, Iterator, Tuple\n\nfrom natsort import natsorted\n# noinspection PyTypeChecker\nfrom pandas import DataFrame, Index, Series\nfrom pandas.core.arrays import ExtensionArray\nfrom pandas.core.generic import NDFrame\nfrom pandas.io.json import json_normalize\nimport statistics\n\n\n# noinspection PyTypeChecker\ndef load_json_file(num_file: object, folder_path):\n \"\"\"\n\n :type folder_path: object\n :param folder_path:\n :type num_file: object\n \"\"\"\n print('Loading the json file......please wait it may take some time depending on size of file')\n json_arr = [] # type: List[Any]\n for i in range(num_file):\n try:\n with open(folder_path + str(i) + '.json') as f:\n d = json.load(f)\n json_arr.append(d)\n\n except IOError:\n print('file ' + '' + str(i) + '.json' + '' + ' not' + '' + ' found')\n print('LOaded')\n return json_arr\n\n\ndef sort_json_file(json_path):\n print('sorting the json files in natural way!')\n # This is the path where all the files are stored.\n # Open one of the files,\n lst = [] # type: List[Union[bytes, str]]\n for data_file in os.listdir(json_path): # type: Union[bytes, str]\n lst.append(data_file)\n json_file = natsorted(lst) # type: list\n return [json_file, lst]\n\n\n# noinspection PyTypeChecker\ndef map_json_to_pose(json_file: object, peeps: object) -> object:\n print('mapping the json file and no of pose!')\n # lets connect the number of peeps,json file name and arr[] i.e keypoints\n mapped = zip(json_file, peeps) # type: Iterator[Tuple[Any, Any]] \n # converting values to print as set\n mapped = set(mapped)\n json_to_peeps = list(mapped)\n json_to_peeps = natsorted(json_to_peeps) # type: list\n return json_to_peeps\n\n\n# noinspection PyTypeChecker\ndef get_pose_list(json_arr2: object) -> object:\n \"\"\"\n\n :type json_arr2: object\n \"\"\"\n arr = [] # type: List[Union[Union[Series, ExtensionArray, None, Index, NDFrame, DataFrame], Any]]\n for j in range(0, len(json_arr2)): # type: int\n try:\n keypt = json_normalize(json_arr2[j]['people']) # type: DataFrame\n for i in range(len(keypt['pose_keypoints_2d'])):\n arr.append(keypt['pose_keypoints_2d'][i])\n print(j)\n print(keypt['pose_keypoints_2d'])\n except KeyError as e:\n print('I got a KeyError - reason \"%s\"' % str(e))\n return arr\n\n\n# noinspection PyTypeChecker\ndef remove_confidence_map(arr: object):\n \"\"\"\n\n :type arr: object\n \"\"\"\n point = [] # type: List[Any]\n for j in range(len(arr)):\n for i in range(0, 53):\n if i == 0 or i == 1 or i == 3 or i == 4 or i == 6 or i == 7 or i == 9 or i == 10 or i == 12 or i == 13 or \\\n i == 15 or i == 16 or i == 18 or i == 19 or i == 21 or i == 22 or i == 24 or i == 25 or i == 27 \\\n or i == 28 or i == 30 or i == 31 or i == 33 or i == 34 or i == 36 or i == 37 or i == 39 or i == \\\n 40 or i == 42 or i == 43 or i == 45 or i == 46 or i == 48 or i == 49 or i == 51 or i == 52:\n point.append(arr[j][i])\n return point\n\n\n# noinspection PyTypeChecker\ndef convert(lst: object, var_lst: object) -> object:\n \"\"\"\n\n :type lst: object\n :type var_lst: object\n \"\"\"\n idx = 0 # type: int\n for var_len in var_lst:\n yield lst[idx: idx + var_len]\n idx += var_len\n\n\n# noinspection PyTypeChecker\ndef divide_chunks(l, n: object):\n \"\"\"\n\n :type n: object\n :param l:\n :param n:\n \"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\n\n\ndef remove_zero(n, boolean):\n \"\"\"\n\n :param n: \n \"\"\"\n if boolean == True:\n for j in range(n):\n for i in range(36):\n if points36[j][i] == 0:\n points36[j][i] = statistics.stdev(points36[j])\n\n\ndef file_number(fn):\n num = fn.split('.')[0]\n min_val = sum(ppl[:int(num)])\n max_value = sum(ppl[int(num) + 1:int(num) + 2]) + sum(ppl[:int(num)]) # type: Union[int, Any]\n return min_val, max_value\n\n\ndef makefolder(jsonfile):\n try:\n\n assert isinstance(jsonfile, object)\n os.makedirs(jsonfile)\n except OSError:\n pass\n\n\ndef select_json(j, points36):\n \"\"\"\n\n :param j: \n :return: \n :type points36: object\n \"\"\"\n global x_data\n x_data = []\n y_data = []\n for i in range(36):\n if i % 2 == 0:\n x_data.append(points36[j][i])\n else:\n y_data.append(points36[j][i])\n X = x_data\n Y = y_data # type: List[Any]\n\n return X, Y\n","sub_path":"annotator_tool/modules/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"175236757","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018-2021, earthobservations developers.\n# Distributed under the MIT License. See LICENSE for more info.\nfrom typing import Tuple, Union\n\nimport numpy as np\nfrom scipy.spatial.ckdtree import cKDTree\n\n\nclass Coordinates:\n \"\"\"Class for storing and retrieving coordinates\"\"\"\n\n def __init__(self, latitudes: np.array, longitudes: np.array):\n \"\"\"\n Args:\n latitudes: latitudes in degree\n longitudes: longitudes in degree\n\n \"\"\"\n\n self.latitudes = latitudes\n self.longitudes = longitudes\n\n def get_coordinates(self) -> np.array:\n \"\"\"\n Returns: coordinates in degree where the first column is the latitudes\n and the second column the longitudes\n\n \"\"\"\n return np.array([self.latitudes, self.longitudes]).T\n\n def get_coordinates_in_radians(self):\n \"\"\"\n Returns: coordinates in radians where the first column is the latitudes\n and the second column the longitudes\n\n \"\"\"\n return np.radians(self.get_coordinates())\n\n def __eq__(self, other):\n return np.array_equal(self.latitudes, other.latitudes) and np.array_equal(\n self.longitudes, other.longitudes\n )\n\n\ndef derive_nearest_neighbours(\n latitudes: np.array,\n longitudes: np.array,\n coordinates: Coordinates,\n number_nearby: int = 1,\n) -> Tuple[Union[float, np.ndarray], np.ndarray]:\n \"\"\"\n A function that uses a k-d tree algorithm to obtain the nearest\n neighbours to coordinate pairs\n\n Args:\n latitudes (np.array): latitude values of stations being compared to\n the coordinates\n longitudes (np.array): longitude values of stations being compared to\n the coordinates\n coordinates (Coordinates): the coordinates for which the nearest neighbour\n is searched\n number_nearby: Number of stations that should be nearby\n\n Returns:\n Tuple of distances and ranks of nearest to most distant stations\n \"\"\"\n points = np.c_[np.radians(latitudes), np.radians(longitudes)]\n distance_tree = cKDTree(points)\n return distance_tree.query(\n coordinates.get_coordinates_in_radians(), k=number_nearby\n )\n\n\ndef convert_dm_to_dd(dms: float) -> float:\n \"\"\" Convert degree minutes to decimal degree \"\"\"\n degrees, minutes = divmod(dms, 1)\n\n decimals = round(minutes / 60 * 100, 2)\n\n return degrees + decimals\n","sub_path":"wetterdienst/util/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"53788022","text":"import socket\nimport sys\n\ntest_type = sys.argv[1]\nport = int(sys.argv[2])\nsocket_type = sys.argv[3]\n\ns = socket.socket(socket.AF_INET)\ns.connect((\"127.0.0.1\", port))\ns.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 40000)\n\nif socket_type == 'ssl':\n s2 = socket.ssl(s)\n send = s2.write\n recv = s2.read\nelse:\n send = s.send\n recv = s.recv\n\nprint >> sys.stderr, \">> Making %s request to port %d\" % (socket_type, port)\n\nsend(\"PUT /forbidden HTTP/1.1\\r\\n\")\nsend(\"Host: localhost\\r\\n\")\n\nprint >> sys.stderr, \">> Sending lots of data\"\nsend(\"Content-Length: 100\\r\\n\\r\\n\")\nsend(\"X\" * 100)\n\nsend(\"PUT /forbidden HTTP/1.1\\r\\n\")\nsend(\"Host: localhost\\r\\n\")\n\nprint >> sys.stderr, \">> Sending lots of data\"\nsend(\"Content-Length: 100\\r\\n\\r\\n\")\nsend(\"X\" * 100)\n\n# import time\n# time.sleep(5)\nprint >> sys.stderr, \">> Getting data\"\ndata = ''\nwhile len(data) < 299999:\n try:\n x = recv(10000)\n except:\n break\n if x == '':\n break\n data += x\nsys.stdout.write(data)\n","sub_path":"txweb2/dav/test/tworequest_client.py","file_name":"tworequest_client.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"432350463","text":"import httplib2, json, sys, os, datetime, re, copy, pytz, calendar\r\n\r\nfrom apiclient import discovery\r\nfrom oauth2client import client\r\nfrom sqlalchemy import and_, func\r\n\r\n# add system directory to pull in app & models\r\n\r\nsys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))\r\n\r\nfrom app import db, models\r\n\r\ndef get_calendar_credentials(therapist):\r\n\r\n '''Takes a therapist object refreshes token if needed and returns access to the calendar'''\r\n\r\n credentials = client.OAuth2Credentials.from_json(json.loads(therapist.calendar_credentials))\r\n\r\n if credentials.access_token_expired:\r\n credentials.refresh(httplib2.Http())\r\n therapist.calendar_credentials = json.dumps(credentials.to_json())\r\n db.session.add(therapist)\r\n db.session.commit()\r\n\r\n http_auth = credentials.authorize(httplib2.Http())\r\n service = discovery.build('calendar', 'v3', http=http_auth)\r\n\r\n return service\r\n\r\n\r\ndef enter_appts_to_db(therapist, start_time, end_time):\r\n '''Needs dates use standard datetime.datetime python format, and Therapist Object from the query return of models.Therapist'''\r\n\r\n service = get_calendar_credentials(therapist)\r\n\r\n eventsResults = service.events().list(calendarId='primary', orderBy='startTime', singleEvents=True, q='source: ', timeMin=start_time.isoformat(), timeMax=end_time.isoformat()).execute()\r\n\r\n appts = eventsResults.get('items', [])\r\n \r\n new_appts = []\r\n \r\n for appt in appts:\r\n \r\n appt['description'] = re.sub('<[^<]+?>', ' ', appt['description'])\r\n \r\n appt['description'] = appt['description'].replace(' ',' ').strip()\r\n \r\n rc_from_appt = re.match('source:\\s\\w+', appt['description']).group(0)[8:]\r\n\r\n time_format = '%Y-%m-%dT%H:%M:%S'\r\n\r\n if rc_from_appt == 'MEETING':\r\n start_time = datetime.datetime.strptime(appt['start']['dateTime'][:-6], time_format)\r\n end_time = datetime.datetime.strptime(appt['end']['dateTime'][:-6], time_format)\r\n\r\n meeting = models.CompanyMeeting.query.filter_by(start_datetime = start_time, end_datetime = end_time, company_id = therapist.user.company_id).first()\r\n\r\n if meeting == None:\r\n meeting = models.CompanyMeeting(start_datetime = start_time, end_datetime = end_time, company_id=therapist.user.company_id, description= appt['description'][15:].strip())\r\n\r\n meeting.users.append(therapist.user)\r\n\r\n db.session.add(meeting)\r\n db.session.commit()\r\n\r\n meeting_user = models.MeetingUserLookup.query.filter_by(meeting_id=meeting.id, user_id = therapist.user.id).first()\r\n\r\n meeting_user.attended = 1\r\n\r\n db.session.add(meeting_user)\r\n db.session.commit()\r\n\r\n continue\r\n\r\n client_id_match = re.match('.*\\nclient_id:\\s[0-9]+', appt['description'])\r\n\r\n if client_id_match:\r\n appt_client_id = client_id_match.group(0).split('\\n')[1].split(' ')[1]\r\n\r\n client = models.Client.query.get(appt_client_id)\r\n\r\n else:\r\n client = models.Client.query.filter(func.lower(func.concat(models.Client.first_name, ' ', models.Client.last_name)).like(appt['summary'].strip().lower()), models.Client.regional_center.has(company_id = therapist.user.company_id)).first()\r\n\r\n rc = models.RegionalCenter.query.filter(models.RegionalCenter.appt_reference_name == rc_from_appt, models.RegionalCenter.company_id == therapist.user.company_id).first()\r\n\r\n\r\n if client == None:\r\n client_name = appt['summary'].strip().split()\r\n # parse address for input\r\n new_client = models.Client( first_name=client_name[0], last_name=' '.join(client_name[1:]), therapist=therapist, regional_center=rc)\r\n db.session.add(new_client)\r\n client = new_client\r\n\r\n update_appt = False\r\n\r\n if not client_id_match:\r\n appt_desc = appt['description'].split('\\n')\r\n appt_desc[0] += '\\nclient_id: %s' % client.id\r\n appt['description'] = '\\n'.join(appt_desc)\r\n update_appt = True\r\n\r\n if client_id_match and ' '.join([client.first_name.lower(), client.last_name.lower()]) != appt['summary'].strip().lower():\r\n appt['summary'] = ' '.join([client.first_name, client.last_name])\r\n update_appt = True\r\n\r\n if client.status != 'active':\r\n client.status = 'active'\r\n db.session.add(client)\r\n\r\n if client.therapist != therapist:\r\n client.therapist = therapist\r\n db.session.add(client)\r\n\r\n if client.address:\r\n client_address = client.address + ' ' + client.city + ', ' + client.state + ' ' + client.zipcode\r\n\r\n if appt.get('location', '') != client_address and not rc_from_appt in appt.get('location', ''):\r\n appt['location'] = client_address\r\n update_appt = True\r\n\r\n if update_appt:\r\n service.events().update(calendarId='primary', eventId=appt['id'], body=appt).execute()\r\n\r\n\r\n if appt.get('location', '') == rc_from_appt:\r\n location = rc.address + ' ' + rc.city + ', ' + rc.state + ' ' + rc.zipcode\r\n elif appt.get('location', '').replace(' ', '').lower() == 'lbhrc':\r\n location = '1155 E San Antonio Dr, Long Beach, CA 90807'\r\n else:\r\n location = appt.get('location', None)\r\n\r\n start_time = datetime.datetime.strptime(appt['start']['dateTime'][:-6], time_format)\r\n end_time = datetime.datetime.strptime(appt['end']['dateTime'][:-6], time_format)\r\n\r\n appointment_type='treatment' if ((end_time - start_time).seconds/60) == 60 else 'evaluation'\r\n \r\n appt_type_id = db.session.query(models.ApptType.id)\\\r\n .join(models.RegionalCenter)\\\r\n .filter(models.RegionalCenter.appt_reference_name == rc_from_appt,\\\r\n models.RegionalCenter.company_id == therapist.user.company_id,\\\r\n func.lower(models.ApptType.name) == appointment_type).first()[0]\r\n\r\n\r\n new_appt = models.ClientAppt(\r\n therapist=therapist,\r\n client=client,\r\n start_datetime=start_time,\r\n end_datetime=end_time,\r\n cancelled=1 if 'CNX' in appt['description'] else 0,\r\n appointment_type=appointment_type,\r\n appt_type_id=appt_type_id,\r\n location=location\r\n )\r\n \r\n db.session.add(new_appt)\r\n new_appts.append(new_appt)\r\n if 'CNX' not in appt['description']:\r\n client.needs_appt_scheduled = 0\r\n db.session.add(client)\r\n \r\n if new_appt.appointment_type == 'evaluation':\r\n note = models.ClientApptNote(user=therapist.user,\r\n approved=1,\r\n appt=new_appt,\r\n note = '{} - {} {}'.format(new_appt.appointment_type.capitalize(), therapist.user.first_name, therapist.user.last_name))\r\n db.session.add(note)\r\n # print(client)\r\n db.session.commit()\r\n\r\n return new_appts\r\n\r\n\r\ndef move_appts(from_therapist, to_therapist, client_name, from_date='', to_date=''):\r\n\r\n '''Takes two Therapist Objects, a string client name and to and from Python DateTimes and moves the appointments of a client from one therapist to another.'''\r\n\r\n from_service = get_calendar_credentials(from_therapist)\r\n\r\n to_service = get_calendar_credentials(to_therapist)\r\n\r\n pdt = pytz.timezone(\"America/Los_Angeles\")\r\n\r\n from_date = pdt.localize(from_date)\r\n\r\n from_date_iso = from_date.isoformat()\r\n\r\n if to_date:\r\n to_date = pdt.localize(to_date)\r\n to_date_iso = to_date.isoformat()\r\n eventsResults = from_service.events().list(calendarId='primary', q=client_name, timeMin=from_date_iso, timeMax=to_date_iso).execute()\r\n else:\r\n eventsResults = from_service.events().list(calendarId='primary', q=client_name, timeMin=from_date_iso).execute()\r\n\r\n events = eventsResults['items']\r\n\r\n to_calendar = to_service.calendars().get(calendarId='primary').execute()\r\n from_calendar = from_service.calendars().get(calendarId='primary').execute()\r\n\r\n from_user = from_calendar['id']\r\n write_calendar = to_calendar['id']\r\n\r\n has_acl = False\r\n acl_rules = to_service.acl().list(calendarId='primary').execute()\r\n for acl_rule in acl_rules['items']:\r\n if acl_rule['id'] == 'user:%s' % from_user:\r\n has_acl = True\r\n break\r\n\r\n if not has_acl:\r\n rule = {'scope':{'type': 'user', 'value': from_user}, 'role': 'writer'}\r\n acl_rule = to_service.acl().update(calendarId='primary', ruleId='user:sarah.titlow@gmail.com', body=rule).execute()\r\n\r\n for event in events:\r\n if 'Auth' in event['summary']:\r\n continue\r\n if event.get('recurrence', False):\r\n\r\n time_format = '%Y-%m-%dT%H:%M:%S'\r\n event_start_time = datetime.datetime.strptime(event['start']['dateTime'][:-6], time_format)\r\n event_end_time = datetime.datetime.strptime(event['end']['dateTime'][:-6], time_format)\r\n timezone_info = event['start']['dateTime'][-6:]\r\n\r\n # Create a appointment series with the start date at From and add a recurrence if there is a end date\r\n\r\n event_dow = event_start_time.weekday()\r\n\r\n if from_date > pdt.localize(event_start_time):\r\n to_event_start_time = event_start_time.replace(year=from_date.year, month=from_date.month, day=from_date.day)\r\n to_event_end_time = event_end_time.replace(year=from_date.year, month=from_date.month, day=from_date.day)\r\n else:\r\n to_event_start_time = event_start_time\r\n to_event_end_time = event_end_time\r\n\r\n while to_event_start_time.weekday() != event_dow:\r\n to_event_start_time += datetime.timedelta(1)\r\n to_event_end_time += datetime.timedelta(1)\r\n\r\n to_event = copy.deepcopy(event)\r\n\r\n to_event.pop('id')\r\n to_event.pop('htmlLink')\r\n to_event.pop('etag')\r\n to_event.pop('iCalUID')\r\n to_event['start']['dateTime'] = to_event_start_time.isoformat() + timezone_info\r\n to_event['end']['dateTime'] = to_event_end_time.isoformat() + timezone_info\r\n\r\n if to_date:\r\n for i, recurr in enumerate(to_event['recurrence']):\r\n if recurr[:5] == 'RRULE':\r\n recur_split = recurr.split(';')\r\n has_until = False\r\n for j, recur_filter in enumerate(recur_split):\r\n if recur_filter[:5] == 'UNTIL':\r\n recur_split[j] = 'UNTIL=%s' % to_date.strftime('%Y%m%d')\r\n has_until = True\r\n\r\n to_event['recurrence'][i] = ';'.join(recur_split)\r\n if not has_until:\r\n to_event['recurrence'][i] += ';UNTIL=%s' % to_date.strftime('%Y%m%d')\r\n\r\n # Create a new appointment series after the to date if needed\r\n if to_date:\r\n new_event = copy.deepcopy(event)\r\n\r\n new_event_start_time = event_start_time.replace(year=to_date.year, month=to_date.month, day=to_date.day)\r\n new_event_end_time = event_end_time.replace(year=to_date.year, month=to_date.month, day=to_date.day)\r\n\r\n while new_event_start_time.weekday() != event_dow:\r\n new_event_start_time += datetime.timedelta(1)\r\n new_event_end_time += datetime.timedelta(1)\r\n\r\n new_event.pop('id')\r\n new_event.pop('htmlLink')\r\n new_event.pop('etag')\r\n new_event.pop('iCalUID')\r\n new_event['start']['dateTime'] = new_event_start_time.isoformat() + timezone_info\r\n new_event['end']['dateTime'] = new_event_end_time.isoformat() + timezone_info\r\n\r\n\r\n # Adjust the current event to end on the From change date\r\n has_until = False\r\n for i, recurr in enumerate(event['recurrence']):\r\n if recurr[:5] == 'RRULE':\r\n recur_split = recurr.split(';')\r\n for j, recur_filter in enumerate(recur_split):\r\n if recur_filter[:5] == 'UNTIL':\r\n has_until = True\r\n recur_split[j] = 'UNTIL=%s' % from_date.strftime('%Y%m%d')\r\n event['recurrence'][i] = ';'.join(recur_split)\r\n if not has_until:\r\n event['recurrence'][i] += ';UNTIL=%s' % from_date.strftime('%Y%m%d')\r\n\r\n\r\n # Add all the apointments into the respective calendars\r\n adjust_current_event = from_service.events().update(calendarId='primary', eventId=event['id'], body=event).execute()\r\n insert_to_event = to_service.events().insert(calendarId='primary', body=to_event).execute()\r\n\r\n if to_date:\r\n insert_new_event = from_service.events().insert(calendarId='primary', body=new_event).execute()\r\n else:\r\n # Just move the single appointments Don't have to worry about duplicating and building new ones. Easy!\r\n from_service.events().move(calendarId='primary', eventId=event['id'], destination=write_calendar).execute()\r\n\r\ndef insert_auth_reminder(auth):\r\n\r\n '''Takes a new auth and inserts a recurring note on mondays in the month of expiration'''\r\n if auth.is_eval_only:\r\n return True\r\n\r\n service = get_calendar_credentials(auth.client.therapist)\r\n\r\n client_name = ' '.join([auth.client.first_name, auth.client.last_name])\r\n\r\n auth_event_date = auth.auth_end_date.replace(day=1, hour=00, tzinfo=pytz.timezone('US/Pacific'))\r\n\r\n while auth_event_date.weekday() != 0:\r\n auth_event_date += datetime.timedelta(1)\r\n\r\n eventResults = service.events().list(calendarId='primary',\r\n q=client_name,\r\n timeMin=auth_event_date.isoformat(),\r\n timeMax=(auth_event_date + datetime.timedelta(1)).isoformat()).execute()\r\n\r\n auth_exists = False\r\n\r\n for event in eventResults['items']:\r\n if 'Auth' in event['summary']:\r\n auth_exists = True\r\n\r\n if not auth_exists:\r\n auth_event = {}\r\n\r\n auth_event['start'] = {'date': auth_event_date.strftime('%Y-%m-%d')}\r\n auth_event['end'] = {'date': (auth_event_date + datetime.timedelta(1)).strftime('%Y-%m-%d')}\r\n auth_event['summary'] = 'Auth Expires for %s' % client_name\r\n eom_day = calendar.monthrange(auth_event_date.year, auth_event_date.month)[1]\r\n auth_event['recurrence'] = ['RRULE:FREQ=WEEKLY;UNTIL=%s;BYDAY=MO' % auth_event_date.replace(day=eom_day).strftime('%Y%m%d')]\r\n auth_event['transparency'] = 'transparent'\r\n\r\n insert_auth_event = service.events().insert(calendarId='primary', body=auth_event).execute()\r\n \r\n \r\n # Check to see if auth spans July 1st and set alert to renew authorization.\r\n \r\n date_check = auth.auth_start_date.replace(month=7, day=1)\r\n \r\n auth_start_nums = str(auth.auth_start_date.year)[2:]\r\n \r\n if auth.auth_start_date < date_check and auth.auth_end_date >= date_check and str(auth.auth_id)[:2] == auth_start_nums:\r\n \r\n reminder_date = date_check.replace(hour=00, tzinfo=pytz.timezone('US/Pacific'))\r\n \r\n new_auth_reminder = {}\r\n \r\n new_auth_reminder['start'] = {'date':reminder_date.strftime('%Y-%m-%d')}\r\n new_auth_reminder['end'] = {'date': (reminder_date + datetime.timedelta(1)).strftime('%Y-%m-%d')}\r\n new_auth_reminder['summary'] = 'New Auth ID Needed for %s' % client_name\r\n new_auth_reminder['transparency'] = 'transparent'\r\n new_auth_reminder['colorId'] = 10\r\n \r\n new_auth_reminder['description'] = 'Need new Auth ID for Billing: {}'.format(auth.auth_id)\r\n \r\n if auth.client.case_worker_id:\r\n new_auth_reminder['description'] += '\\n\\nContact CaseWorker: \\n\\n' + auth.client.case_worker.first_name + ' ' + auth.client.case_worker.last_name + ': ' + auth.client.case_worker.phone + '\\nEmail: ' + auth.client.case_worker.email\r\n \r\n insert_new_auth_reminder = service.events().insert(calendarId='primary', body=new_auth_reminder).execute()\r\n \r\n\r\n return True\r\n\r\ndef move_auth_reminder(auth):\r\n '''\r\n Removes old auth reminder for updated authorization.\r\n Inserts new Auth reminder based on new date.\r\n '''\r\n\r\n service = get_calendar_credentials(auth.client.therapist)\r\n\r\n client_name = ' '.join([auth.client.first_name, auth.client.last_name])\r\n\r\n auth_start_date = auth.auth_start_date.replace(day=1, hour=00, tzinfo=pytz.timezone('US/Pacific'))\r\n auth_end_date = auth.auth_end_date.replace(day=20, hour=00, tzinfo=pytz.timezone('US/Pacific'))\r\n\r\n eventResults = service.events().list(calendarId='primary', q='Auth Expires for {}'.format(client_name),\r\n timeMin=auth_start_date.isoformat(),\r\n timeMax=auth_end_date.isoformat()).execute()\r\n\r\n events = eventResults['items']\r\n\r\n for event in events:\r\n service.events().delete(calendarId='primary', eventId=event['id']).execute()\r\n\r\n insert_auth_reminder(auth)\r\n\r\n return True\r\n\r\n\r\n\r\ndef add_new_client_appt(client, appt_datetime, duration, at_regional_center=False, confirmed_appt=True):\r\n\r\n '''Takes a client obj, datetime, duration of appt in minutes and T/F if at regional center pushes appt to calendar for that datetime'''\r\n\r\n service = get_calendar_credentials(client.therapist)\r\n client_name = ' '.join([client.first_name, client.last_name])\r\n\r\n pdt = pytz.timezone(\"America/Los_Angeles\")\r\n\r\n appt_start = pdt.localize(appt_datetime)\r\n\r\n appt_end = appt_start + datetime.timedelta(minutes=duration)\r\n\r\n colors = {'PRIVATE': 3,\r\n 'WRC': 4,\r\n 'HRC': 7}\r\n\r\n rc = client.regional_center\r\n\r\n new_appt= {}\r\n\r\n new_appt['start'] = {'dateTime': appt_start.isoformat()}\r\n new_appt['end'] = {'dateTime': appt_end.isoformat()}\r\n new_appt['summary'] = client_name\r\n new_appt['description'] = 'source: %s\\nclient_id: %s' % (rc.appt_reference_name, client.id)\r\n if client.case_worker_id:\r\n new_appt['description'] += '\\n\\nCaseWorker: ' + client.case_worker.first_name + ' ' + client.case_worker.last_name + ': ' + client.case_worker.phone\r\n if client.additional_info:\r\n new_appt['description'] += '\\n\\n' + client.additional_info\r\n new_appt['colorId'] = colors[rc.appt_reference_name] if confirmed_appt else 8\r\n if at_regional_center:\r\n new_appt['location'] = rc.appt_reference_name\r\n else:\r\n if client.address:\r\n new_appt['location'] = client.address + ', ' + client.city + ', ' + client.state + ' ' + client.zipcode\r\n\r\n service.events().insert(calendarId='primary', body=new_appt).execute()\r\n\r\n\r\ndef add_new_company_meeting(users, start_datetime, duration, additional_info=None):\r\n\r\n '''Takes a list of user ids, datetime, duration of meeting in minutes pushes meeting to calendar for each users at that datetime'''\r\n\r\n for user_id in users:\r\n user = models.User.query.get(user_id)\r\n service = get_calendar_credentials(user.therapist)\r\n\r\n pdt = pytz.timezone(\"America/Los_Angeles\")\r\n\r\n meeting_start = pdt.localize(start_datetime)\r\n\r\n meeting_end = meeting_start + datetime.timedelta(minutes=duration)\r\n\r\n new_meeting = {}\r\n\r\n new_meeting['start'] = {'dateTime': meeting_start.isoformat()}\r\n new_meeting['end'] = {'dateTime': meeting_end.isoformat()}\r\n new_meeting['summary'] = user.company.name + ' Meeting'\r\n new_meeting['description'] = 'source: MEETING'\r\n if additional_info:\r\n new_meeting['description'] += '\\n\\n%s' % additional_info\r\n\r\n service.events().insert(calendarId='primary', body=new_meeting).execute()\r\n","sub_path":"jobs/appts.py","file_name":"appts.py","file_ext":"py","file_size_in_byte":20353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"397746328","text":"#!/usr/bin/env python3\n\nfrom BCScrapper import bcscrapper\nimport argparse\nfrom datetime import datetime\n\n\ndef parse_cli():\n # Process the command line\n parser = argparse.ArgumentParser(\n description='Scrapper de cotação de moedas doBanco Central do Brasil'\n )\n\n parser.add_argument(\n \"-i\", \"--data_inicial\",\n default=\"\",\n help='Defina a data inicial de consulta',\n type=str\n )\n\n parser.add_argument(\n \"-f\", \"--data_final\",\n default=datetime.today().date().isoformat(),\n help='Defina a data inicial de consulta. (default: data atual)',\n type=str\n )\n\n parser.add_argument(\n \"-o\", \"--output\",\n help=\"Saida\",\n default=\"output.csv\",\n type=str\n )\n args = parser.parse_args()\n return(args)\n\nif __name__ == \"__main__\":\n\n args = parse_cli()\n report = bcscrapper.BCReport(args.data_inicial, args.data_final)\n report.report.to_csv(args.output)\n","sub_path":"script/get_currency.py","file_name":"get_currency.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"529917547","text":"import time\nimport unittest, requests\nimport HTMLTestRunner, sys\n\nglobal str\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\ndev = 'https://dev.eor.gosapi.ru/new'\ntest = 'https://test.eor.gosapi.ru/'\ndev1 = 'https://minakov.eor.gosapi.ru/'\ndev2 = 'https://shmyrev.eor.gosapi.ru/'\ntronov = 'https://tronov.eor.gosapi.ru/'\nvragov = 'https://vragov.eor.gosapi.ru/'\nsurin = 'https://surin.eor.gosapi.ru/'\noracle = 'https://task.eor.gosapi.ru/oracle/site/login'\npgs = 'https://task.eor.gosapi.ru/pgs/site/login'\nperm = 'http://dev.perm.gosapi.ru/top/'\n\ndriver = webdriver.Chrome()\ndriver.get(pgs)\ndriver.maximize_window()\nwait = WebDriverWait(driver, 40)\ndriver.implicitly_wait(40)\n\nclass ASeleniumAutoTest_1(unittest.TestCase):\n def test001_CreatedInEORDev(self):\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 1. Нет ошибок при вводе логина')\n except:\n print('ошибка 500!')\n _ = wait.until(EC.element_to_be_clickable((By.ID, 'LoginForm_username')))\n assert \"Login\" in driver.title\n elem = driver.find_element_by_id(\"LoginForm_username\")\n elem.send_keys(\"ipad\")\n elem = driver.find_element_by_id(\"LoginForm_password\")\n elem.send_keys(\"ipad\")\n elem.send_keys(Keys.RETURN)\n\n def test002_Not500or404andLoginIsVisible(self):\n _ = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'hidden-xs')))\n try:\n print('\\n 2. Нет ошибок на рабочем столе')\n assert 'Error' not in driver.title\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"ЭОР - Error\" not in driver.title\n # open desktop\n\n def test003_OpenAllPjct(self):\n _ = wait.until(EC.element_to_be_clickable((By.XPATH, '//i')))\n assert \"ЭОР\" in driver.title\n time.sleep(1)\n driver.find_element_by_xpath('//i').click()\n time.sleep(6)\n allpj = driver.find_element_by_link_text(\"Все проекты\")\n allpj.click()\n print('\\n 3. переходим раздел \"Все проекты\"')\n\n def test004_Not500or404(self):\n title = wait.until(EC.title_is('ЭОР - Checkpoint'))\n # test\n driver.find_element_by_id('search-show').click()\n time.sleep(1)\n #textFild = driver.find_element_by_id('search-text')\n #textFild.send_keys(\"'\")\n #textFild.send_keys(Keys.ENTER)\n #time.sleep(5)\n #r = requests.get('https://task.eor.gosapi.ru/pgs/checkpoint/checkpoint/table')\n #time.sleep(2)\n #if r.status_code == 404 or r.status_code == 500:\n # print(' ERROR! STATUS CODE IS WRONG!',r)\n #else:\n # print(' Ok. Status code is',r)\n # test\n try:\n assert 'Error' not in driver.title\n print('\\n 4. Нет ошибок в разделе \"Все проекты\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Checkpoint\" in driver.title\n\n def test005_Schedule(self):\n schedul = driver.find_element_by_link_text(\"Расписание\")\n schedul.click()\n time.sleep(2)\n _ = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'add-meeting')))\n print('\\n 5. Переходим в раздел \"Расписание\"')\n\n def test006_Not500or404(self):\n title = wait.until(EC.title_is('ЭОР - Default'))\n try:\n assert 'ЭОР - Error' not in driver.title\n driver.find_element_by_xpath('//td/span')\n print('\\n 6. Нет ошибок в разделе \"Расписание\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Default\" in driver.title\n\n def test007_Question(self):\n question = driver.find_element_by_link_text(\"Вопросы/Приоритеты\")\n question.click()\n time.sleep(4)\n _ = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'navbar-header')))\n print('\\n 7. Переходим в раздел \"Вопросы/приоритеты\"')\n\n def test008_Not500or404(self):\n title = wait.until(EC.title_is('ЭОР - Question'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 8. Нет ошибок в разделе \"Вопросы/приоритеты\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Question\" in driver.title\n\n def test009_Material(self):\n material = driver.find_element_by_link_text(\"Материалы\")\n material.click()\n time.sleep(4)\n _ = wait.until(EC.element_to_be_clickable((By.ID, 'search-show')))\n print('\\n 9. Переходим в раздел \"Материалы\"')\n # test\n _ = wait.until(EC.element_to_be_clickable((By.XPATH,\"//nav/div/div[2]/ul/li/a/span\")))\n # filter period\n #driver.find_element_by_xpath('//nav/div/div[2]/ul/li/a/span').click()\n #time.sleep(2)\n #driver.find_element_by_xpath(\"//a[contains(text(),'Не учитывать')]\").click()\n # filter where\n #driver.find_element_by_xpath('//ul[2]/li/a/span').click()\n #time.sleep(2)\n #driver.find_element_by_link_text('Из Совещаний').click()\n # spinner\n #try:\n # driver.find_element_by_xpath('//div[2]/i')\n # print(' Спиннер появился')\n #except:\n # print(' Спиннер не появился/появился на очень короткое время')\n #try:\n # driver.find_element_by_css_selector('div.alert.alert-default')\n # print(\" Появилось сообщение о не найденых материалоах\")\n #except:\n # print(\" Не появилось сообщение о не найденых материалоах\")\n #try:\n # driver.find_element_by_css_selector(\"div.panel-title\")\n # print(' Появился список материалов')\n #except:\n # print(\" Не появился список материалов!\")\n\n def test010_Not500or404(self):\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Material'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 10. Нет ошибок в разделе \"Материалы\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Material\" in driver.title\n\n def test011_Npa(self):\n npa = driver.find_element_by_link_text(\"Нормативно-правовые акты\")\n npa.click()\n time.sleep(4)\n _ = wait.until(EC.element_to_be_clickable((By.ID, 'search-show')))\n print('\\n 11. Переходим в раздел \"Нормативно правовые акты\"')\n\n def test012_Not500or404(self):\n title = wait.until(EC.title_is('ЭОР - Npa'))\n time.sleep(4)\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 12. Нет ошибок в разделе \"Нормативно правовые акты\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Npa\" in driver.title\n\n def test013_Document(self):\n #self.skipTest(self)\n document = driver.find_element_by_link_text(\"Библиотека\")\n document.click()\n time.sleep(4)\n assert 'ЭОР - Error' not in driver.title\n _ = wait.until(EC.element_to_be_clickable((By.ID, 'search-show')))\n print('\\n 13. Переходим в раздел \"Библиотека\"')\n\n def test014_Not500or404(self):\n #self.skipTest(self)\n title = wait.until(EC.title_is('ЭОР - Document'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 14. Нет ошибок в разделе \"Библиотека\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Document\" in driver.title\n\n def test015_Report(self):\n report = driver.find_element_by_link_text(\"Отчёты\")\n report.click()\n time.sleep(1)\n # Отчёт по контрольным точкам\n report1 = driver.find_element_by_link_text(\"Отчет по задачам\")\n report1.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Report'))\n try:\n assert 'ЭОР - Error' not in driver.title\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n _ = wait.until(EC.element_to_be_clickable((By.ID, 'load_table')))\n try:\n assert 'Error' not in driver.title\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n # add\n try: # вкладка \"Блок\"\n wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'div.tree.project > div.head')))\n driver.find_element_by_css_selector('div.tree.project > div.head')\n print('Ошибка 500 при переходе на вкладку \"Блок\" не найдено')\n except:\n self.fail(\n print('Ошибка 500! при переходе на вкладку \"Блок\" в разделе Отчеты -> Отчёты по контрольным точкам')\n )\n driver.find_element_by_xpath('//li/label[2]').click()\n try: # вкладка \"Проект\"\n wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'div.tree.project > div.head')))\n driver.find_element_by_css_selector('div.tree.project > div.head')\n print('Ошибка 500 при переходе на вкладку \"Проект\" не найдено')\n except:\n self.fail(\n print('Ошибка 500! при переходе на вкладку \"Проект\" в разделе Отчеты -> Отчёты по контрольным точкам')\n )\n wait.until(EC.element_to_be_clickable((By.XPATH, '//label[3]')))\n driver.find_element_by_xpath('//label[3]').click()\n try: # вкладка \"Ответственный\"\n wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div.tree.project > div.head')))\n driver.find_element_by_css_selector('div.tree.project > div.head')\n print('Ошибка 500 при переходе на вкладку \"Ответственный\" не найдено')\n except:\n self.fail(\n print('Ошибка 500! при переходе на вкладку \"Ответственный\" в разделе Отчеты -> Отчёты по контрольным точкам')\n )\n wait.until(EC.element_to_be_clickable((By.XPATH, '//label[4]')))\n driver.find_element_by_xpath('//label[4]').click()\n try: # вкладка \"Замы\"\n time.sleep(7)\n driver.find_element_by_id('report-content')\n print('Ошибка 500 при переходе на вкладку \"Замы\" не найдено')\n except:\n self.fail(\n print('Ошибка 500! при переходе на вкладку \"Замы\" в разделе Отчеты -> Отчёты по контрольным точкам')\n )\n # Отчёт Проект Расписания\n schedule = driver.find_element_by_link_text('Отчет по совещаниям')\n schedule.click()\n time.sleep(4)\n _ = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'title_gears')))\n title = wait.until(EC.title_is('ЭОР - Schedule'))\n try:\n assert 'ЭОР - Error' not in driver.title\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Schedule\" in driver.title\n # Отчёт Рейтинги по Проектам\n rating = driver.find_element_by_link_text('Отчёт Рейтинги по Проектам')\n rating.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Projectsrating'))\n try:\n driver.find_element_by_xpath('//div[2]/table/thead/tr/th')\n assert 'ЭОР - Error' not in driver.title\n print('\\n 15. Переходим в раздел \"Отчеты\", во всех отчетах нет ошибок')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n\n # Отчёт по Проектам\n rating = driver.find_element_by_link_text('Отчёт по Проектам')\n rating.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Отчет по проектам'))\n try:\n driver.find_element_by_css_selector('div.project-report-group-title')\n assert 'ЭОР - Error' not in driver.title\n print('\\n 15. Переходим в раздел \"Отчёт по Проектам\", во всех отчетах нет ошибок')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n\n def test016_Admin(self):\n self.skipTest(self)\n admin = driver.find_element_by_link_text(\"Администрирование\")\n admin.click()\n time.sleep(1)\n print('\\n 16. Переходим в раздел \"Администрирование\"')\n # Пользователи\n\n def test017_Users(self):\n self.skipTest(self)\n users = driver.find_element_by_link_text('Пользователи')\n users.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - User'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 17. Нет ошибок в разделе пользователи')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n\n _ = wait.until(EC.element_to_be_clickable((By.ID, 'search-show')))\n try:\n assert 'ЭОР - Error' not in driver.title\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - User\" in driver.title\n\n # Роли\n def test018_Role(self):\n self.skipTest(self)\n users = driver.find_element_by_link_text('Роли')\n users.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Role'))\n try:\n print('\\n 18. Нет ошибок в разделе \"Роли\"')\n assert 'ЭОР - Error' not in driver.title\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n\n _ = wait.until(EC.element_to_be_clickable((By.ID, 'btn_create_user')))\n try:\n print('\\n Нет ошибки на странице пользователи')\n assert 'ЭОР - Error' not in driver.title\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Role\" in driver.title\n # Привилегии\n def test019_Privilege(self):\n self.skipTest(self)\n users = driver.find_element_by_link_text('Права доступа')\n users.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Privilege'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 19. Переходим в раздел \"Права доступа\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n time.sleep(5)\n _ = wait.until(EC.presence_of_element_located((By.ID, 'yw1')))\n try:\n print('\\n Нет ошибки на странице \"Права доступа\"')\n assert 'ЭОР - Error' not in driver.title\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Privilege\" in driver.title\n # Журналы\n def test020_Journal(self):\n self.skipTest(self)\n journ = driver.find_element_by_link_text(\"Журналы\")\n journ.click()\n time.sleep(1)\n print('\\n 20. переходим в раздел \"Журналы\"')\n # Авторизации\n def test021_Logs(self):\n self.skipTest(self)\n autor = driver.find_element_by_link_text(\"Авторизации\")\n autor.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Logs'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 21. Переходим в раздел \"Авторизации\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n\n _ = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'dropdown')))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n нет ошибко в разделе \"Авторизации\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Logs\" in driver.title\n # Обмен данными\n def test022_Data(self):\n self.skipTest(self)\n autor = driver.find_element_by_link_text(\"Обмен данными\")\n autor.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Data'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 22. Переходим в раздел \"Обмен данными\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n _ = wait.until(EC.presence_of_element_located((By.ID, 'resetFilters')))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n нет ошибок в разделе \"Авторизации\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Data\" in driver.title\n # Операции пользователя\n def test023_Operation(self):\n self.skipTest(self)\n autor = driver.find_element_by_link_text(\"Операции пользователя\")\n autor.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Operation'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 23. Переходим в раздел \"Операции пользователя\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n _ = wait.until(EC.presence_of_element_located((By.ID, 'resetFilters')))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n Нет ошибок в разделе \"Операции пользователя\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"ЭОР - Operation\" in driver.title\n # Справочники\n def test024_Dictionary(self):\n self.skipTest(self)\n dictionary = driver.find_element_by_link_text(\"Справочники\")\n dictionary.click()\n time.sleep(4)\n title = wait.until(EC.title_is('ЭОР - Dictionary'))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n 24. Переходим в раздел \"Справочники\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n assert \"Error\" not in driver.title\n _ = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Этапы НПА')))\n try:\n assert 'ЭОР - Error' not in driver.title\n print('\\n нет ошибок в разделе \"Справочники\"')\n except:\n print('ошибка 500!') # проверка на 500/404 ошибку\n assert \"404\" not in driver.title\n\n # Структура данных\n def test027_GoodTone(self):\n print('\\n 27. ТЕСТ ЗАВЕРШЕН ')\n driver.close()\n\n\nif __name__ == '__main__':\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(ASeleniumAutoTest_1))\n # File\n buf = open(\"at_for_500and404.html\", 'wb')\n runner = HTMLTestRunner.HTMLTestRunner(\n stream=buf,\n title='ПРОВЕРКА ВСЕХ РАЗДЕЛОВ ЭОР НА ОШИБКИ 500 И 404',\n description='Отчет по тестированию'\n )\n ret = not runner.run(suite).wasSuccessful()\n sys.exit(ret)\n\n\n\n","sub_path":"Check500404.py","file_name":"Check500404.py","file_ext":"py","file_size_in_byte":22499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"214406449","text":"import sqlite3\n\n\ndef update_transactions(action, username, symbol, last_price, volume):\n conn = sqlite3.connect(\"terminal_trading.db\")\n cur = conn.cursor()\n cur.execute(\"\"\"INSERT INTO transactions(buy_sell, symbol, transact_price, quantity, user) \n VALUES(?,?,?,?,?)\"\"\",\n (action, symbol, last_price, volume, username,))\n conn.commit()\n cur.close()\n conn.close()\n\n\nupdate_transactions('long', 'kapil', 'GOOG', 1000, 10)\n","sub_path":"Week5/gui_trader/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"12466132","text":"#!/usr/bin/env python3\n\ndef criticalConnections(n, edges):\n graph = [[] for _ in range(n)]\n pre = [0] * n\n low = [0] * n\n ans = []\n\n for u, v in edges:\n graph[u-1].append(v-1)\n graph[v-1].append(u-1)\n\n\n def dfs(v, u, clock):\n pre[v] = clock\n low[v] = clock\n clock += 1\n \n for pair in graph[v]:\n if pre[pair] == 0:\n clock = dfs(pair, v, clock)\n\n low[v] = min(low[v], low[pair])\n\n if pre[v] < low[pair]:\n ans.append((v+1, pair+1))\n \n \n elif not pair == u:\n low[v] = min(low[v], low[pair])\n\n\n return clock\n\n\n dfs(0, -1, 0)\n\n\n return ans\n\n\n\n\nif __name__ == '__main__':\n result = criticalConnections(5, [[1, 2], [1, 3], [3, 4], [1, 4], [4, 5]])\n for bridge in result:\n print(bridge)\n print(\"---------------------\")\n\n result = criticalConnections(6, [[1, 2], [1, 3], [2, 3], [2, 4], [2, 5], [4, 6], [5, 6]])\n for bridge in result:\n print(bridge)\n print(\"---------------------\")\n\n result = criticalConnections(9, [[1, 2], [1, 3], [2, 3], [3, 4], [3, 6], [4, 5], [6, 7], [6, 9], [7, 8], [8, 9]])\n for bridge in result:\n print(bridge)\n print(\"---------------------\")\n\n result = criticalConnections(4, [[1,2], [2,3], [2,4]])\n for bridge in result:\n print(bridge)\n print(\"---------------------\")\n\n result = criticalConnections(5, [[1,2], [2,3], [2,4], [2,5] ,[4,5]])\n for bridge in result:\n print(bridge)\n print(\"---------------------\")\n\n\n","sub_path":"LeetCode/critical_connections/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"131414223","text":"import cmd\nimport sys\nimport click\nfrom hyperdns.hapi.client.cli import main\n\n\n@main.command()\n@click.pass_obj\ndef shell(hapi):\n \"\"\"Interactive HAPI shell.\n \n Example:\n (.python)hapi-client-python3 : hapi shell\n Welcome to the HAPI shell! (type help for a list of commands.)\n click on the screen to be able to type\n HAPI> ls\n zone1.com.\n HAPI> in zone1.com.\n HAPI/zone1.com.> ls\n name1\n name2\n HAPI/zone1.com.> exit\n \"\"\"\n class BaseShell(cmd.Cmd):\n def do_out(self,arg):\n \"\"\"Pop up one level\n \"\"\"\n return True\n \n def do_exit(self,arg):\n \"\"\"Exit the command line completely\n \"\"\"\n sys.exit()\n\n def help_general(self):\n print(\"\"\"\nIn general you're probably going to use the following\ncommands the most:\n\n ls list information\n in change your focus\n change update dns\n \n \"\"\")\n \n def help_security(self):\n print(\"Provide informaiton about JWT\")\n \n def emptyline(self):\n pass\n \n def _find_zone(self,arg):\n if not arg.endswith('.'):\n arg=arg+'.'\n z=hapi.zones.get(arg)\n if z==None:\n print(\"Sorry, couldn't find that %s\" % arg)\n return z\n\n def _find_resource(self,arg):\n \"\"\"Take apart arg from right to left, look for a zone\n that matches one of the suffixes\n \"\"\"\n if arg.endswith(\".\"):\n arg=arg[:-1]\n bits=arg.split(\".\")\n sofar=\"\"\n while len(bits)>0:\n POP=bits.pop()\n sofar=\"%s.%s\" % (POP,sofar)\n print(sofar)\n zone=hapi.zones.get(sofar)\n if zone!=None:\n rname=bits.pop()\n while len(bits)>0:\n POP=bits.pop()\n rname=\"%s.%s\" % (POP,rname)\n print(\"Yeah:\",rname)\n sys.exit()\n \n class ResourceShell(BaseShell):\n prompt = ''\n file = None\n resource = None\n zone = None\n \n\n class ZoneShell(BaseShell):\n prompt = ''\n file = None\n zone = None\n \n def complete_ls(self,text,line,begin_index,end_index):\n \"\"\"Returns the completion array for resources\"\"\"\n return [i for i in self.zone.resources if i.startswith(text)]\n\n def do_ls(self,arg):\n \"\"\"This command takes two forms, without an argument it lists the\n resources. With an argument it provides detailed information about\n the resource.\n \"\"\"\n if arg==\"\":\n for r in self.zone.resources:\n print(r)\n else:\n resource=self.zone.resources.get(arg)\n if resource==None:\n print(\"Resource not found\")\n else:\n print(\"RESOURCE\",resource)\n \n def do_download(self,arg):\n \"\"\"Save the zonefile for the current zone.\n \"\"\"\n \n print(\"Save zonefile\")\n \n def do_upload(self,arg):\n \"\"\"Load a zonefile for the current zone\"\"\"\n print(\"Load zonefile\")\n \n def do_change(self,arg):\n \"\"\"\n \"\"\"\n (_rname,_rvalue)=arg.split('=')\n _rname=_rname.strip()\n _rvalue=_rvalue.strip()\n \n r=self.zone.resources.get(_rname)\n if r==None:\n print(\"Need to create %s.%s\" % (_rname,self.zone.fqdn))\n \n\n def emptyline(self):\n pass\n \n def complete_set(self,text,line,begin_index,end_index):\n return [i for i in self.zone.resources if i.startswith(text)]\n \n class MyInteractive (BaseShell):\n intro = 'Welcome to the HAPI shell!' \\\n + ' (type help for a list of commands.)' \\\n + \"\\n click on the screen to be able to type\"\n prompt = 'HAPI> '\n file = None\n \n\n def _recspec_from_line(self,arg):\n argparts=arg.split(\" \")\n if len(argparts)!=4:\n print(\"Malformed record spec\")\n return None\n \n (_fqdn,_rdtype,_rdata,_ttl)=argparts\n return None\n\n def do_addrec(self,arg):\n \"\"\"\n Assert a record - e.g. addrec \n\n This is the 'no frills' version of add. This requires\n that point to a specific resource in an existing zone. The\n resource does not need to exist, but the zone does. If the resource\n does not exist, it will be created. The record will be added to\n the existing pool of records as follows:\n A and AAAA\n These records will have the value added if it is new, but\n if the value already exists only the ttl will be updated.\n singletons\n These records will be overwritten\n other\n The record will be added to the resource record pool.\n \n Example Invocations:\n addrec \n \"\"\"\n recspec=self._recspec_from_line(arg)\n if recspec==None:\n return\n \n \n def do_delrec(self,arg):\n \"\"\"\n Delete a record\n \n This is the 'no frills' version of delete. This requires that you\n specify the record exactly - there is no assistive matching, and if\n you don't get a value right we'll just bork the input.\n \n Example Invocations:\n delrec \n \"\"\"\n recspec=self._recspec_from_line(arg)\n if recspec==None:\n return\n \n\n\n def do_delete(self,arg):\n \"\"\"\n Delete zones, resource, and records\n \n Example Invocations:\n delete \n delete .\n delete from .\n \"\"\"\n if arg==\"\":\n print(\"Summary deletion is a bad idea\")\n return\n \n \n\n def do_change(self,arg):\n \"\"\"Change your DNS\n \n Example Invocations:\n change . to \n change . to ttl \n change . add \n change . ttl \n \"\"\"\n if arg==\"\":\n print(\"Change is good\")\n return\n \n (_rname,_rvalue)=arg.split('=')\n _rname=_rname.strip()\n if not _rname.endswith('.'):\n _rname=_rname+'.' \n _rvalue=_rvalue.strip()\n for z,zone in hapi.zones.items():\n if _rname.endswith(z):\n print(\"OK\")\n return\n print(\"Sorry, can not find a matching zone for %s\" % (_rname))\n\n\n\n\n\n def complete_ls(self,text,line,begin_index,end_index):\n return [\"zones\",\"vendors\"]\n \n def _ls_list_zones(self):\n \"\"\"List the zones\n \"\"\"\n for z in hapi.zones:\n print(z)\n \n def _ls_list_vendors(self):\n \"\"\"List the vendors\n \"\"\"\n for v in hapi.vendors:\n print(v)\n \n def _ls_list_users(self):\n \"\"\"List the user\n \"\"\"\n for z in hapi.admin:\n print(z)\n \n \n def do_ls(self,arg):\n \"\"\"List information about the current environment.\n \n Example Invocations:\n ls\n ls zones\n by itself, ls lists the zones\n ls vendors\n list the configured vendors\n ls \n \"\"\"\n if arg==\"zones\" or arg==\"\":\n self._ls_list_zones()\n elif arg==\"vendors\":\n self._ls_list_vendors()\n else:\n # look for a zone or a resource\n print(\"look for\")\n \n\n\n\n\n\n def complete_in(self,text,line,begin_index,end_index):\n return [i for i in hapi.zones if i.startswith(text)]\n \n def do_in(self,arg):\n \"\"\"\n Spawn a zone or a resource scoped subshell.\n \n Example Invocations\n in zone1.com\n in host.zone1.com\n \"\"\"\n zone=self._find_zone(arg)\n if zone:\n n=ZoneShell()\n n.prompt='HAPI/%s> ' % (zone.fqdn)\n n.zone=zone\n n.cmdloop()\n else:\n (resource,zone)=self._find_resource(arg)\n if resource:\n r=ResourceShell()\n r.zone=zone\n r.resource=resource\n r.prompt='HAPI/%s.%s> ' % (resource.name,zone.fqdn)\n r.cmdloop()\n\n MyInteractive().cmdloop()\n print(\"Have a HAPI day\")\n\n","sub_path":"hyperdns/hapi/client/cli/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":9605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"279308279","text":"\"\"\"\nIn this file we apply GCN on the graph (type simple)\n\"\"\"\n\nimport numpy as np\nimport torch\n\nfrom linkprediction import gcn_stars as gae\nfrom linkprediction import utils_linkprediction as lu\nfrom linkprediction import visualize as vs\n\nprint(\"simple graph\")\nprint(\"-----------------\")\n# build graph (simple)\ngraph, nodes_lookup, review_test,review_train,review_edges_number, test_edges,test_users,test_businesses,business_attributes,business_QC = lu.build_graph()\n\n# attributes\n# input_users = torch.eye(n=917,m=261)\n# input_business = torch.from_numpy(business_attributes.values.astype(np.float32)).float()\n# input_attributes = torch.cat((input_users, input_business), 0)\n\ninput_attributes = torch.eye(len(graph.nodes))\ninput_size = len(graph.nodes)\n\n# scores\naccuracy_scores = []\nprecisions = []\nrecalls = []\nf_measures = []\nsupports = []\nrmse_scores = []\n\n# train model\nfor experiments in range(0, 1):\n print(\"experiment number: \" + str(experiments + 1))\n\n embedding, new_adj,gae = gae.train(\"gcn\", graph, input_attributes, input_size, 16, 16, 300, 30, test_edges,review_edges_number, True)\n\n accuracy_score, precision, recall, f_measure, support, rmse_score = lu.evaluate_stars(gae, embedding, nodes_lookup, review_test)\n\n accuracy_scores.append(accuracy_score)\n precisions.append(precision)\n recalls.append(recall)\n f_measures.append(f_measure)\n supports.append(support)\n rmse_scores.append(rmse_score)\n\n\nedge_embeddings=[]\nedge_stars=[]\n# evaluate model\nfor index, row in review_test.sort_values(by=['user_id']).iterrows():\n node1 = torch.tensor(embedding[nodes_lookup['a_' + row.user_id]])\n node2 = torch.tensor(embedding[nodes_lookup['b_' + row.business_id]]).t()\n business_name = business_QC[business_QC.business_id==row.business_id].name.iloc[0]\n business_stars = business_QC[business_QC.business_id==row.business_id].stars.iloc[0]\n print(gae.dec.forward(0, torch.mul(node1, node2), \"test\") + 1, row.stars, row.user_id, row.business_id,business_name, business_stars)\n edge_embeddings.append(torch.mul(node1, node2).detach().numpy())\n edge_stars.append(row.stars-1)\n\nprint(\"RMSE:\" + str(np.mean(rmse_scores).round(3)))\nprint(\"Accuracy:\" + str(np.mean(accuracy_scores).round(3)))\nprint(\"F_measure:\" + str(np.mean(f_measures).round(3)))\nprint(\"Precision:\" + str(np.mean(precisions).round(3)))\nprint(\"Recall:\" + str(np.mean(recalls).round(3)))\n\nvs.visualize_edge(edge_embeddings,edge_stars)\n","sub_path":"code/test_graph_simple.py","file_name":"test_graph_simple.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"122530975","text":"from matplotlib import pyplot as plt\nimport pandas as pd\nimport csv\n\nacc = [0] * 20\nacc_pure = [0] * 20\nNtime = 500\n\n\nfor time in range(Ntime):\n data1 = pd.read_csv(\"./result/result_%s.csv\" % time, header=0)\n for i in range(len(data1)):\n acc[i] += abs(data1.iloc[i].loc['MSE_mu'])#MSE_mu\tAccuracy\n data2 = pd.read_csv(\"./result_pure/result_pure_%s.csv\" % time, header=0)\n for i in range(len(data2)):\n acc_pure[i] += abs(data2.iloc[i].loc['MSE_mu'])\nfor i in range(20):\n acc[i] = (acc[i] / Ntime)\n acc_pure[i] = (acc_pure[i] / Ntime)\n '''acc[i] = (acc[i] / Ntime)\n acc_pure[i] = (acc_pure[i] / Ntime)'''\n\n\nplt.plot([str(i) for i in range(20)], acc, 's-', label='long-term')\nplt.plot([str(i) for i in range(20)], acc_pure, 'o-', label='pure')\n#plt.ylim(0.0, 1.0)\n\nplt.legend()\nplt.show()","sub_path":"long-term/Dataset/Dataset1/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"347178784","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 20 16:01:29 2017\n\n@author: forrestgump\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nimport sklearn.mixture\n\nfrom scipy import optimize\nfilename = \"gamma_data.txt\"\ndata=[None]*150\n#def gauss(x, *p):\n# A, mu, sigma = p\n# return A*numpy.exp(-(x-mu)**2)/(2.*sigma**2)\n\n#p0 = [1., 0., 1.]\n\n#coeff, var_matrix = curve_fit(gauss, )\nwith open(filename,\"r\") as file:\n b=0\n print(\"File is:\", filename)\n for row in file:\n listobj=row.split()\n #data=row.split()\n #data=map(float,data)\n listobj=[float(i) for i in listobj]\n length=len(listobj)\n data[b] = listobj\n b=b+1\npeak_locations = [None] * length\nfwhm_array = [None]*length\ncurrentdata = [item[1] for item in data]\n\nclass Parameter:\n def __init__(self, value):\n self.value = value\n\n def set(self, value):\n self.value = value\n\n def __call__(self):\n return self.value\n\ndef fit(function, parameters, y, x = None):\n def f(params):\n i = 0\n for p in parameters:\n p.set(params[i])\n i += 1\n return y - function(x)\n\n if x is None: x = np.arange(y.shape[0])\n p = [param() for param in parameters]\n return optimize.leastsq(f, p)\n\n\n\n","sub_path":"protofit.py","file_name":"protofit.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"262979383","text":"# Author: Hanzi Mao \n#\n# License: BSD 3 clause\n\nimport numpy as np\n\nfrom .get_lat_lon import get_lat_lon\n\n\ndef select_area(lat1, lat2, lon1, lon2, reso):\n \"\"\"\n left-up: lat1 lon1 left-down: lat2 lon1 right-up: lat1 lon2 right-down: lat2 lon2\n e.g.\n For Oklahoma\n :param lat1: 38\n :param lat2: 32\n :param lon1: -104\n :param lon2: -92\n \"\"\"\n lats, lons = get_lat_lon(reso)\n\n lat_indices = lats.size - np.searchsorted(lats[::-1], [lat1, lat2], side=\"right\")\n lon_indices = np.searchsorted(lons, [lon1, lon2])\n\n return lat_indices, lon_indices\n\n\n\n","sub_path":"soil_moisture_downscaling/utils/select_area.py","file_name":"select_area.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"206071564","text":"#!/usr/bin/env python3\n\n\nclass Plugin:\n \n _name = 'google'\n\n def __init__(self, bot):\n self.bot = bot\n bot.register_command(self._name, ['google', 'g'], self.search,\n channels=['!##monsterhunter'])\n\n def search(self, server, user, channel, *query):\n \"\"\"Search google for a query.\"\"\"\n query = ' '.join(query)\n results = self.bot.google_search(query)\n if results == []:\n return '[\\x035Google\\x03] \\x02No results\\x02'\n return '[\\x033Google\\x03] {}'.format(results[0])\n","sub_path":"plugins/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"337868538","text":"#To test the greatest neuron model ever\nimport numpy as np\nimport nest\nimport pylab as pl\n\nlabelsize = 14.\nticksize = 14.\ntsim = 100000.\n\ncol_lis = [np.array([63.,25.,255.])/255., np.array([204.,99.,20.])/255.,np.array([178.,120.,76.])/255., np.array([200.,0.,0.])/255.,np.array([153.,88.,61.])/255., np.array([204.,187.,20.])/255.]\namp_arr = np.arange(65000.,80000.,2000.)\nsup_fr_lis =[]\nfig = pl.figure(1,(8,8))\nax1 = fig.add_axes([0.55,0.55,0.37,0.35])\nfor kk,jj in enumerate(np.arange(3.,6.1,1.)):\n fr_lis = []\n for ii in amp_arr:\n nest.ResetKernel()\n dc_gen = nest.Create(\"poisson_generator\",params = {'rate':ii})\n aa = nest.Create(\"ssbn\",params = {'act_state':jj,'max_spb':4.})\n #aa = nest.Create('iaf_neuron')\n sd = nest.Create('spike_detector')\n nest.Connect(aa,sd)\n nest.DivergentConnect(dc_gen,aa,weight = 1., delay = 1.)\n nest.Simulate(tsim)\n spikes = nest.GetStatus(sd,'events')[0]\n num_spikes = len(spikes['senders'])\n f_rate = (num_spikes*1000)/tsim\n fr_lis.append(f_rate)\n ax1.plot(amp_arr, fr_lis,lw = 5., alpha = 0.7, color = col_lis[kk], label = str(jj)) \n \npl.legend(loc = 'best', prop = {'size':10.})\n#pl.xlim(300,500)\nax1.set_ylim(0,40)\nax1.set_ylabel(\"Firing rate (Bq)\",size = labelsize)\nax1.set_xticks(amp_arr[::2])\nax1.set_yticks(np.arange(0,40,10))\nfor tl in ax1.get_xticklabels():\n tl.set_fontsize(ticksize)\n ax1.xaxis.get_major_formatter().set_powerlimits((0,1))\nax1.set_xlabel(\"Poisson rate (Hz)\",fontsize = labelsize)\nax1.text(6.2e4,40,'B',fontsize = labelsize + 3, style = 'normal')\nfor tl in ax1.get_yticklabels():\n tl.set_fontsize(ticksize)\n \nax1.spines['top'].set_visible(False)\nax1.spines['right'].set_visible(False)\nax1.tick_params(axis = 'both', which = 'both',top = 'off', right = 'off')\npl.show() \n","sub_path":"test_ssbn.py","file_name":"test_ssbn.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"497892578","text":"import argparse\n\nimport googleapiclient.discovery\n\n\ndef create_service():\n # Construct the service object for interacting with the Cloud Storage API -\n # the 'storage' service, at version 'v1'.\n # Authentication is provided by application default credentials.\n # When running locally, these are available after running\n # `gcloud auth application-default login`. When running on Compute\n # Engine, these are available from the environment.\n return googleapiclient.discovery.build('storage', 'v1')\n\n\ndef list_buckets(service, project_id):\n buckets = service.buckets().list(project=project_id).execute()\n return buckets\n\n\ndef main(project_id):\n service = create_service()\n buckets = list_buckets(service, project_id)\n print(buckets)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('project_id', help='Your Google Cloud Project ID.')\n\n args = parser.parse_args()\n\n main(args.project_id)\n","sub_path":"GCP/t.py","file_name":"t.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"46542314","text":"\nimport sys\nimport os\n\n#sys.path.append('/Users/asakunotomohiro/Program/sphinx/source/gdscript.py')\n#sys.path.append('/Users/asakunotomohiro/Program/gdscript/gdscript.py')\nsys.path.append('/Users/asakunotomohiro/Program/gdscript')\n#sys.path.append('../../../../gdscript/gdscript.py')\n\n#import sphinx_rtd_theme\n#html_theme = \"sphinx_rtd_theme\"\n#html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\nlanguage = 'ja'\nepub_language = 'ja'\n#html_language = 'ja' ←たぶん、こんな設定は無いと思うが、エラーにはならなかった。\n\n\nsys.path.append(os.path.abspath('extensions'))\n# GDScript を記事内で使うためのモジュール\nextensions = ['gdscript']\n# GDScript 設定ここまで ----------------\n\n\n# TODOリストを使うためのモジュール(インストール不要で使えるようだ)\nextensions += ['sphinx.ext.todo']\n\n[extensions]\ntodo_include_todos=True\n# TODOリスト設定ここまで -----------------------------------------\n\n\n# tabsタグを使うためにモジュールをインストール\nextensions += ['sphinx_tabs.tabs']\ntemplates_path = ['_templates']\n# tabsタグ設定ここまで -----------------------\n\n\n\n\n# Weblate で翻訳された実績や進捗などをreStructuredTextで都合よく表示させることができない。\n# そのため、外部からその情報を引っ張り込むことにした。\n# それが以下の処理になる。\nrst_epilog = \"\"\"\n.. |weblate_widget| image:: https://hosted.weblate.org/widgets/godot-engine/{image_locale}/godot-docs/287x66-white.png\n :alt: Translation status\n :target: https://hosted.weblate.org/engage/godot-engine{target_locale}/?utm_source=widget\n\"\"\".format(\n image_locale='-' if language == 'en' else language,\n target_locale='' if language == 'en' else '/' + language\n)\n\n\n\n\n# 不自然な空白が表示される\n# https://sphinx-users.jp/reverse-dict/html/japanese.html\nsys.path.insert(0, os.path.abspath('.')) # コメントを外します\n#extensions += ['japanesesupport', 'その他の拡張'] # 加えます\nextensions += ['japanesesupport'] # 加えます\n\n\n\n\n# 以下、何をやっているのか全く分からない。\nsource_suffix = '.rst'\nsource_encoding = 'utf-8-sig'\n\nmaster_doc = 'index_jp'\n\nenv_tags = os.getenv('SPHINX_TAGS')\nif env_tags != None:\n for tag in env_tags.split(','):\n print(\"Adding Sphinx tag: %s\" % tag.strip())\n tags.add(tag.strip())\n\nlanguage = os.getenv('READTHEDOCS_LANGUAGE', 'en')\nis_i18n = tags.has('i18n')\n\nexclude_patterns = ['_build']\n\n\nfrom gdscript import GDScriptLexer\nfrom sphinx.highlighting import lexers\nlexers['gdscript'] = GDScriptLexer()\n\npygments_style = 'sphinx'\nhighlight_language = 'gdscript'\n# ここまで、何をやっているのか全く分からない。\n\n\n\n#language = ja\n#language('ja')\ntoday_fmt = '%Y/%m/%d'\n\n\n\ndef setup(app):\n app.add_stylesheet('myStyle.css')\n\n\n\n\n\nhtml_use_smartypants = False\n\n\n\n\nlatex_docclass = {'manual': 'jsbook'}\n\n\n# vim:set ts=4 sw=4 tw=0 fenc=utf-8:\n","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"68657179","text":"__author__ = 'gaa8664'\nimport inventory.connection as connection\nimport inventory.query as query\nimport openpyxl\n\n'''\n A program that will read data from the given query and will copy it to an excel file.\n'''\n\ndata_workbook = None\ndata_sheet = None\n\ndef read_data_from_database(query, parameter_tuple, workbook_name, sheet_title):\n #cursor = connection.get_proddb_connection().cursor(as_dict=True) #Prodigious Connection\n cursor = connection.get_connection().cursor(as_dict=True) # Get prodigious container connection\n cursor.execute(query,parameter_tuple)\n records = cursor.fetchall()\n header_set = False\n for record in records:\n if not header_set:\n header_list = record.keys()\n create_excel(workbook_name,sheet_title, header_list)\n header_set = True\n row = record.values()\n add_data_to_excel(workbook_name,sheet_title,list(row) )\n\n\n cursor.close()\n #connection.close_proddb_connection() # Close Prodigious connection\n connection.close_connection() # Close ProdigiousContainer connection\n return header_list\n\n\ndef create_excel(workbook_name, sheet_title, header_list):\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n sheet.title = sheet_title\n sheet.append(list(header_list))\n workbook.save(workbook_name)\n\n\ndef add_data_to_excel(workbook_name, sheet, data_row):\n global data_workbook\n global data_sheet\n if not data_workbook :\n data_workbook = openpyxl.load_workbook(workbook_name)\n data_sheet = data_workbook[sheet]\n print(data_row)\n data_sheet.append(data_row)\n\n\n\ndef populate_excel():\n pass\n\nif __name__ == '__main__':\n global data_workbook\n workbook_name = 'E://title.xlsx'\n list_x = read_data_from_database(query.PO,('2017-01-01','2017-12-31'),'E://title.xlsx','test')\n data_workbook.save(workbook_name)\n\n\n\n\n","sub_path":"LearningPython/inventory/read_copy.py","file_name":"read_copy.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"432569576","text":"from __future__ import absolute_import\nimport modules.runas\nimport modules.ssh\nimport modules.cmake\n\ndef emit(writer, **kwargs):\n if \"cmakeVersionFull\" not in kwargs:\n raise Exception(\"'cmakeVersionFull' is mandatory!\")\n cmakeVersionFull = kwargs[\"cmakeVersionFull\"]\n modules.runas.emit(writer)\n modules.ssh.emit(writer)\n modules.cmake.emit(writer, cmakeVersionFull)\n writer.packages([\"ca-certificates\", \"doxygen\", \"clang-format-8\"])\n writer.emit(\"\"\"\n RUN update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-8 100\n ENV CUDA_ROOT /usr/local/cuda\n \"\"\")\n\ndef images():\n return {\n \"cuda-dev-dt:10.2\": {\n \"base\": \"gitlab-master.nvidia.com:5005/dt-compute-public/container/cuda-released/10.2-ubuntu18.04-gnu8:20200602\",\n \"needsContext\": True,\n \"cmakeVersionFull\": \"3.18.0-rc2\"\n },\n \"cuda-dev-dt:11.0\": {\n \"base\": \"gitlab-master.nvidia.com:5005/dt-compute-public/container/cuda-nightly/11.0-ubuntu18.04-gnu8:20200602\",\n \"needsContext\": True,\n \"cmakeVersionFull\": \"3.18.0-rc2\"\n }\n }\n","sub_path":"images/cuda_dev_dt.py","file_name":"cuda_dev_dt.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"136744744","text":"import re\nimport os\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n# ----------------------------------------------- Abre archivo HTML\nprint(\"=======================================================================================================================================\")\nload_sessions = open('sessions.txt', \"r\")\nfor line in open('sessions.txt', \"r\"):\n line = str(load_sessions.readline().split('\\n')[0])\n print(line)\nload_sessions.close()\nprint(\"=======================================================================================================================================\")\nsession = input(\"Number of session: \")\nrootDir = str(os.getcwd())+\"/\"+str(session)\nfor dirName, subdirList, fileList in os.walk(rootDir):\n for fname in fileList:\n part1 = fname.split('_')[1]\n part2 = fname.split('_')[0]\ndir_root = \"file://\"+os.getcwd()+\"/\"+str(session)+\"/\"+part2+'_'+part1\nprint(\"================================================================ INFO =================================================================\")\ndriver = webdriver.Chrome(executable_path=\"/usr/bin/chromedriver\")\ntry:\n driver.get(dir_root+\"_info.html\") \nexcept:\n print(\"[!] Module 'info' not found.\")\n# ----------------------------------------------- Extraer texto del html(info).\nfor letter in \"abcdefghijklmnopqrstuvwxyz\":\n try:\n label_inf = driver.find_element_by_xpath('//*[@id=\"u_0_2'+letter+'\"]/div[1]/ul').text\n except Exception as err:\n continue\n try:\n label_inf2 = driver.find_element_by_xpath('//*[@id=\"u_0_2'+letter+'\"]/div[2]/ul').text # Obtine informacion del HTML en texto plano.\n except Exception as err:\n continue\npatterns_delete = [\"No hay lugares de trabajo para mostrar\",\"No hay escuelas para mostrar\",\"No hay lugares para mostrar\",\"No hay información de situación sentimental para mostrar\"]\nfor pattern in patterns_delete:\n label_inf = label_inf.replace(pattern, \"\")\n# ------------------------------------------------ Regular Expressions --------------------------------------------------------\nmodules = ['regx_email','regx_bdate','regx_insta','regx_face','regx_instalink','regx_cellphone','regx_work','regx_studies','regx_living_in','regx_from','regx_lived','regx_love']\ncodes = [r\"([\\w\\.-]+)@([\\w\\.-]+)(\\.[\\w\\.]+)\",r\"([\\d]+\\sde\\s[\\w\\.-]+\\sde\\s\\d\\d\\d\\d)\",r\"[^Enlaces sociales][\\w\\W\\.\\d-]+(Instagram)[\\)$]\",\nr\"(https://www.facebook)[\\w\\.]+(/)([\\W\\w\\.\\_-]+)(\\?)(ref=tn_tnmn)\",r\"(https://www.instagram)[\\w\\.]+(/)([\\W\\w\\.\\_-]+)(/)\",\nr\"(Teléfonos)(\\n[0-9]{4,5}\\s[0-9]{2}-[0-9]{4})\",r\"((Encargad[oa]|Trabaja)\\sen\\s[\\W\\w\\d\\.-]+[\\n$])\",r\"(Estudió\\sen\\s[\\W\\w\\d\\.-]+[\\n$])\",\nr\"(Vive\\sen\\s[\\W\\w\\d\\.-]+[\\n$])\",r\"(De\\s[\\W\\w\\d\\.-]+[\\n$])\",r\"(Vivió\\sen\\s[\\W\\w\\d\\.-]+[\\n$])\",r\"((En\\suna\\srelación|Comprometid[oa]|Casad[oa])\\scon\\s[\\W\\w\\.-]+[\\n$]?)\"]\nvariation = ['','',\".split('\\n')[1]\",\".split('\\n')[0]\",\".split('\\n')[0]\",\".split('\\n')[1]\",\".split('\\n')[0]\",\n\".split('\\n')[0]\",\".split('\\n')[0]\",\".split('\\n')[0]\",\".split('\\n')[0]\",\".split('\\n')[0]\"]\ncounter = 0\nfor code in codes:\n modules[counter] = code\n if counter <= 5:\n matcher = re.search(modules[counter], label_inf2)\n else:\n matcher = re.search(modules[counter], label_inf)\n if matcher:\n if counter <= 1:\n print(matcher.group())\n elif counter == 2:\n print(matcher.group().split('\\n')[1])\n elif counter == 3 or 4: \n print(matcher.group().split('\\n')[0])\n elif counter == 5:\n print(matcher.group().split('\\n')[1])\n elif counter > 5:\n print(matcher.group().split('\\n')[0])\n counter += 1\n# ============================================== LOOP PARA INFO GENERAL ============================================= #\ndef acssi_transform(inputString): # Funcion para quitar emojis.\n return inputString.encode('ascii', 'ignore').decode('ascii')\nmodules = [\"events\",\"app_instapp\",\"music\",\"sports\",\"movies\",\"tv\",\"likes\",\"map\",\"books\",\"games\",\"reviews\",\"notes\",\"did_you_know\"]\ncodes = ['//*[@id=\"collection_wrapper_2344061033\"]','//*[@id=\"collection_wrapper_124024574287414\"]','//*[@id=\"collection_wrapper_221226937919712\"]',\n'//*[@id=\"collection_wrapper_330076653784935\"]','//*[@id=\"collection_wrapper_177822289030932\"]','//*[@id=\"collection_wrapper_309918815775486\"]',\n'//*[@id=\"collection_wrapper_2409997254\"]','//*[@id=\"collection_wrapper_302324425790\"]','//*[@id=\"collection_wrapper_332953846789204\"]',\n'//*[@id=\"collection_wrapper_249944898349166\"]','//*[@id=\"collection_wrapper_254984101287276\"]','//*[@id=\"collection_wrapper_2347471856\"]',\n'//*[@id=\"collection_wrapper_1773166999589123\"]']\ncounter = 0\nfor module in modules:\n try:\n driver.get(dir_root+\"_\"+module+\".html\")\n except:\n print(\"[!] Module \"+\"'\"+module+\"'\"+\" not found.\")\n print(\"================================================================ \"+module.upper()+\" ===============================================================\")\n try:\n label_inf = driver.find_element_by_xpath(codes[counter]).text\n if counter == 1 or 12: # Filtros para modulos especiales.\n label_inf_t = acssi_transform(label_inf)\n if counter == 1:\n regx_hashtag = r\"(#[\\w-]+[\\s])+[\\n]*\"\n matcher = re.search(regx_hashtag, label_inf_t)\n if matcher:\n matcher = acssi_transform(matcher.group())\n print('Hashtags de instagram: ',matcher)\n else:\n print(label_inf_t.replace('Comentarios',\"\"))\n else:\n print(label_inf.replace('Músico/banda',\"\")) # Se puede aplicar filtros generales\n except Exception as err:\n pass\n counter += 1\n \npost_modules = [\"friends\",\"group\",\"photos\",\"react\",\"videos\"]","sub_path":"script_izanagi.py","file_name":"script_izanagi.py","file_ext":"py","file_size_in_byte":5772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"295956035","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Generator(nn.Module):\n def __init__(self, input_dim, output_shape):\n \"\"\"\n Args:\n input_dim: the dimension of the input space\n output_shape: the shape of the image to be generated\n grayscale only!\n\n \"\"\"\n super(Generator, self).__init__()\n self.input_dim = input_dim\n self.output_shape = output_shape\n\n self.fc = nn.Sequential(\n nn.Linear(self.input_dim, 1024),\n nn.BatchNorm1d(1024), nn.ReLU(),\n nn.Linear(1024, 128*(self.output_shape[0]//2)*(self.output_shape[1]//2)),\n nn.BatchNorm1d(128*(self.output_shape[0]//2)*(self.output_shape[1]//2)), nn.ReLU()\n )\n\n self.upconv = nn.Sequential(\n nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(64), nn.ReLU(),\n nn.ConvTranspose2d(64, 1, kernel_size=3, padding=1)\n )\n\n def forward(self, X):\n X = self.fc(X)\n X = X.view(-1, 128, self.output_shape[0]//2, self.output_shape[1]//2)\n X = self.upconv(X)\n return X\n\n\nclass Discriminator(nn.Module):\n def __init__(self, input_shape):\n super(Discriminator, self).__init__()\n self.input_shape = input_shape\n\n self.conv = nn.Sequential(\n nn.Conv2d(1, 64, kernel_size=4, stride=2, padding=1),\n nn.LeakyReLU(),\n nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1),\n nn.BatchNorm2d(128), nn.LeakyReLU()\n )\n\n self.fc = nn.Sequential(\n nn.Linear(128*(self.input_shape[0]//4)*(self.input_shape[1]//4), 1024),\n nn.BatchNorm1d(1024),\n nn.Linear(1024, 2),\n nn.Sigmoid()\n )\n\n def forward(self, X):\n X = self.conv(X)\n X = X.view(-1, 128*(self.input_shape[0]//4)*(self.input_shape[1]//4))\n X = self.fc(X)\n return X\n\n\nif __name__ == '__main__':\n pass","sub_path":"torchkit/models/vision/GAN/gan.py","file_name":"gan.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"361499480","text":"#Alba Reinders y Alejandro Valverde\nimport sys\nimport time\nfrom itertools import combinations\nimport itertools\n\nfile = \"\"\n\n#Pedir el archvo a analizar\ntry:\n file_name = sys.argv[1]\n contenido = open(file_name).readlines()\nexcept Exception as e:\n print(\"Se necesita un archivo\")\n quit()\n\nmuseums_distances = []\n\n\n#leer el txt\nn = 0\n\nwhile n < len(contenido):\n museums_distances.append([])\n for i in contenido[n].split():\n museums_distances[n].append(int(i))\n n += 1\n\nstart_time = time.time()\n\n#CODIGO\n#Diccionario que guarda las distancias\ninformation_dict = {}\n#Diccionario que guarda el orden\norder_dict = {}\n\n#Array con todos los museos menos el primero\nall_museums = []\n\n#Caso inicial\n#Guardar las distancias de todos los museos al de origen\nfor i in range(1, len(museums_distances)):\n all_museums.append(i)\n information_dict[str(i) + '-0'] = museums_distances[i][0]\n\n#Casos intermedios\n#Guardar las distancias de todos los museos en base al caso anterior\n#Bucle pasos\nfor i in range(2, len(museums_distances)+1):\n #print(i)\n\n #Bucle iteraciones de cada paso\n for j in range(1, len(museums_distances)):\n\n #Copia del array de todos los museos menos el primero\n combination_museums = all_museums[:]\n\n #Menos en el caso final, evita que haya rutas de un museo a si mismo\n #En el caso final, si mismo es 0 y este ya no forma parte del lista por\n #ello no hace falta quitarlo, y si se quita produce que se vacie la\n #lista entera\n if i != len(museums_distances):\n combination_museums.remove(j)\n\n #Todas las combinaciones de tamano i-1 del array copiado\n combination_set = combinations(combination_museums, i-1)\n\n #Bucle combinaciones\n for k in combination_set:\n #Nombre de la posicion que se utiliza para guardar en el diccionario\n #information_dict\n str_position = \"\"\n #Numero que se inicializa muy grande para encontrar el minimo\n minimun = float(\"inf\")\n #Orden de la posicion que se utiliza para guardar en el diccionario\n #order_dict\n order_of_position = \"\"\n\n #Cada elemento de la combinacion\n for l in k:\n #Transformacion a un array del resultado de cada combinacion\n aux_list = list(itertools.chain.from_iterable([k]))\n\n #Distancia de cada posicion para guardar despues en el\n #diccionario\n distance_position = 0\n\n #Caso que siempre sigue al inicial\n #Primer caso de los casos intermedios\n if i-1 == 1:\n #Calculamos la distancia de j a l + la distancia de l a 0\n distance_position = museums_distances[j][l] + information_dict[str(l) + '-0']\n #Indicar donde se va a guardar la distancia\n #Es el nombre de la key en el diccionario\n str_position = str(j) + '-' + str(aux_list[0])\n #Guardar la distancia en el minimo, porque es el que se\n #anade al final al diccionario\n minimun = distance_position\n #Guardar el orden en el que se recorren los museos\n order_of_position = str(j) + '-' + str(l) + '-0'\n\n #Caso final\n elif i == len(museums_distances):\n #Array identico a aux_list, que se ultiliza para determinar\n #el nombre con el formato correcto\n copy_array = aux_list[:]\n copy_array = '-'.join(map(str, copy_array))\n\n #Eliminar el museo en el que estas\n aux_list.remove(l)\n aux_list = '-'.join(map(str, aux_list))\n\n #Calculamos la distancia del primer museo a l + la distancia de l al resto\n distance_position = museums_distances[0][l] + information_dict[str(l) + '-' + aux_list]\n #Esta distancia se compara con el minimo para ver si es mejor\n if distance_position < minimun:\n #Establece el minimo con esta distancia\n minimun = distance_position\n #Indicar donde se va a guardar la distancia\n #Es el nombre de la key en el diccionario\n str_position = str(0) + '-' + copy_array\n #Guardar el orden en el que se recorren los museos\n order_of_position = str(0) + '-' + order_dict['order ' + str(l) + '-' + aux_list]\n\n #Resto de casos\n else:\n\n #Array identico a aux_list, que se ultiliza para determinar\n #el nombre con el formato correcto\n copy_array = aux_list[:]\n copy_array = '-'.join(map(str, copy_array))\n\n #Eliminar el museo en el que estas\n aux_list.remove(l)\n aux_list = '-'.join(map(str, aux_list))\n\n #Calculamos la distancia de j a l + la distancia de l al resto\n distance_position = museums_distances[j][l] + information_dict[str(l) + '-' + aux_list]\n #Esta distancia se compara con el minimo para ver si es mejor\n if distance_position < minimun:\n #Establece el minimo con esta distancia\n minimun = distance_position\n #Indicar donde se va a guardar la distancia\n #Es el nombre de la key en el diccionario\n str_position = str(j) + '-' + copy_array\n #Guardar el orden en el que se recorren los museos\n order_of_position = str(j) + '-' + order_dict['order ' + str(l) + '-' + aux_list]\n\n #Crear entradas nuevas para los diccionarios\n information_dict[str_position] = minimun\n order_dict['order ' + str_position] = order_of_position\n\n\n\n#Camino ordenado de 0-1-...-n\nobjective = \"0-\" + '-'.join(map(str, all_museums))\n\n#Guardar la distancia y el orden de la ruta final\ndistance = information_dict[objective]\norder = order_dict['order ' + objective].split('-')\n\n\n#El tiempo hay que comentarlo\n#totalTime = time.time() - start_time\n\nauxOrder = \"\"\nfor i in range(len(order)-1):\n if order[i] != \"-\":\n auxOrder += \"M\"+ str(order[i]) + \", \"\n\nauxOrder += \"M0\"\n\n\nprint(\"Distancia total: \" + str(distance))\nprint(\"Itinerario: \" + auxOrder)\n#print(\"Tiempo: %s segundos\" % totalTime)\n","sub_path":"p1-383444-383383/parte-3/part-3.py","file_name":"part-3.py","file_ext":"py","file_size_in_byte":6669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"620202352","text":"# coding=utf-8\nimport sys\nimport os\nimport shutil\nfrom enCount.config import data_root, genomes_root, results_root\nimport enCount.externals.rnastar as rnastar\nfrom enCount.integration.config import sync_test_data\n\n\nclass IntRNASTAR:\n\n genome_lengths = {\n \"chM\": 16571,\n \"ch21ch22\": 99434461,\n \"initial\": 3101804739,\n }\n\n genome_refs = {\n \"chM\": 1,\n \"ch21ch22\": 2,\n \"initial\": 84,\n }\n\n counts = {\n \"SAMP_CHM\": 1000,\n \"SAMP_CH21CH22\": 5000,\n }\n\n def __init__(self, genome_name=\"chM\", sample_name=\"SAMP_CHM\"):\n sync_test_data()\n\n self.genome_name = genome_name\n self.sample_name = sample_name\n self.in_genome_fasta_dir = os.path.join(genomes_root, \"fasta\", self.genome_name)\n self.out_genome_dir = os.path.join(genomes_root, \"index\", self.genome_name)\n\n self.in_gtf = os.path.join(genomes_root, \"gtf\", \"%s.gtf\" % self.genome_name)\n if self.genome_name == \"chM\": self.in_gtf = None # contains no junctions, gtf must not be included\n\n self.in_fastq_1 = os.path.join(data_root, \"fastq\", self.sample_name, \"ENCFF624OCC.fastq.gz\")\n self.in_fastq_2 = os.path.join(data_root, \"fastq\", self.sample_name, \"ENCFF604UQO.fastq.gz\")\n\n self.out_mapping_dir = os.path.join(results_root, \"mappings\", self.sample_name)\n\n for d in [self.out_genome_dir, self.out_mapping_dir]:\n if os.path.exists(d):\n print(\"Removing %s\" % d)\n shutil.rmtree(d)\n os.makedirs(d)\n\n def test_rnastar_generate_align(self):\n \"\"\"\n Testing the STAR aligner pipeline inside a container.\n :return:\n \"\"\"\n\n # STEP 1: Generate genome\n print(\"Working directory\", os.getcwd())\n\n # Check input files\n for f_in in [self.in_genome_fasta_dir]:\n print(\"\\tChecking %s\" % f_in)\n assert os.path.exists(f_in)\n\n # Generate genome ; skip gtf for th chM example with no junctions;\n r = rnastar.run_star_generate_genome(in_gtf=self.in_gtf,\n in_genome_fasta_dir=self.in_genome_fasta_dir,\n out_genome_dir=self.out_genome_dir)\n assert r == 0\n\n\n # STEP 2: Align reads\n for f_in in [self.in_fastq_1, self.in_fastq_2, self.out_genome_dir, self.out_mapping_dir]:\n print(\"\\tChecking %s\" % f_in)\n assert os.path.exists(f_in)\n\n # Run alignment\n r = rnastar.run_star(in_fastq_pair=[self.in_fastq_1, self.in_fastq_2],\n out_dir=self.out_mapping_dir, in_genome_dir=self.out_genome_dir)\n assert r == 0\n\n count = rnastar.get_read_count(self.out_mapping_dir)\n print(\"Number of counted reads: %d\" % count)\n assert count == self.counts[self.sample_name]\n\n\nif __name__ == \"__main__\":\n try:\n genome_name = sys.argv[1]\n sample_name = sys.argv[2]\n test = IntRNASTAR(sample_name=sample_name, genome_name=genome_name)\n except IndexError:\n print(\"Genome and sample names not provided, defaulting to chM.\")\n test = IntRNASTAR()\n\n test.test_rnastar_generate_align()","sub_path":"enCount/integration/rnastar.py","file_name":"rnastar.py","file_ext":"py","file_size_in_byte":3207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"131935010","text":"import pandas as pd\nfrom lifetimes.utils import summary_data_from_transaction_data\nfrom lifetimes.utils import calibration_and_holdout_data\n\ndef reformat(data):\n data['Timestamp'] = pd.to_datetime(data['Timestamp'], \n format='%Y/%m/%d %H:%M').dt.date\n \n summary = summary_data_from_transaction_data(\n transactions=data,\n customer_id_col='CustomerID', \n datetime_col='Timestamp', \n monetary_value_col='PurchaseValue',\n observation_period_end='2017-12-06',\n freq='D').reset_index()\n \n summary_cal_holdout = calibration_and_holdout_data(\n transactions=data,\n customer_id_col='CustomerID', \n datetime_col='Timestamp',\n calibration_period_end='2017-07-12',\n observation_period_end='2017-12-06',\n freq='D',\n monetary_value_col='PurchaseValue').reset_index()\n \n return summary, summary_cal_holdout\n ","sub_path":"reformat.py","file_name":"reformat.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"617671585","text":"## BORROWED FROM https://github.com/moontails/NLP/blob/master/pmi.py\n##\n## Part 2:\n## Use pointwise mutual information to compare words in the movie corpora\n##\nimport os.path\nimport sys\nimport heapq\nfrom operator import itemgetter\nfrom collections import defaultdict\n#----------------------------------------\n# Data input \n#----------------------------------------\n\n# Read a text file into a corpus (list of sentences (which in turn are lists of words))\n# (taken from nested section of HW0)\ndef readFileToCorpus(f):\n \"\"\" Reads in the text file f which contains one sentence per line.\n \"\"\"\n if os.path.isfile(f):\n file = open(f, \"r\") # open the input file in read-only mode\n i = 0 # this is just a counter to keep track of the sentence numbers\n corpus = [] # this will become a list of sentences\n print (\"Reading file \", f)\n for line in file:\n i += 1\n sentence = line.split() # split the line into a list of words\n corpus.append(sentence) # append this list as an element to the list of sentences\n if i % 1000 == 0:\n sys.stderr.write(\"Reading sentence \" + str(i) + \"\\n\") # just a status message: str(i) turns the integer i into a string, so that we can concatenate it\n return corpus\n else:\n print (\"Error: corpus file \", f, \" does not exist\") # We should really be throwing an exception here, but for simplicity's sake, this will suffice.\n sys.exit() # exit the script\n\n#--------------------------------------------------------------\n# PMI data structure\n#--------------------------------------------------------------\nclass PMI:\n # Given a corpus of sentences, store observations so that PMI can be calculated efficiently\n def __init__(self, corpus):\n self.Px = defaultdict(int)\n self.Pxy = defaultdict(int)\n self.N = len(corpus)\n self.train(corpus)\n\n def train(self,corpus):\n for i in range(len(corpus)):\n sent = list(set(corpus[i]))\n for j in range(len(sent)):\n self.Px[sent[j]] += 1\n for k in range(j+1,len(sent)):\n self.Pxy[self.pair(sent[j],sent[k])] += 1\n \n # Return the pointwise mutual information (based on sentence (co-)occurrence frequency) for w1 and w2\n def getPMI(self, w1, w2):\n return float(self.Pxy[self.pair(w1,w2)]*self.N) / (self.Px[w1] * self.Px[w2])\n\n # Given a frequency cutoff k, return the list of observed words that appear in at least k sentences\n def getVocabulary(self, k):\n wordlist = []\n for word,count in self.Px.iteritems():\n if count >= k:\n wordlist.append(word)\n return wordlist\n\n # Returns a list of word pairs (2-tuples)\n # Given a list of words, return the pairs of words that have the highest PMI (without repeated pairs, and without duplicate pairs (wi, wj) and (wj, wi))\n def getPairsWithMaximumPMI(self, words, n):\n h = []\n words = set(words)\n for (word1,word2),count in self.Pxy.iteritems():\n if word1 in words and word2 in words:\n heapq.heappush(h, (self.getPMI(word1,word2),(word1,word2)) )\n if len(h) >= 5000: \n h = heapq.nlargest(n, h)\n \n h = heapq.nlargest(n, h) \n topwordlist = []\n\n for pmi,words in h:\n topwordlist.append(words)\n return topwordlist\n\n #-------------------------------------------\n # Provided PMI methods\n #-------------------------------------------\n # Writes the list of wordPairs to a file, along with each pair's PMI\n def writePairsToFile(self, wordPairs, filename): \n file=open(filename, 'w+')\n for (wi, wj) in wordPairs:\n print >>file, str(self.getPMI(wi, wj))+\" \"+wi+\" \"+wj\n\n # Helper method: given two words w1 and w2, returns the pair of words in sorted order\n # That is: pair(w1, w2) == pair(w2, w1)\n def pair(self, w1, w2):\n return (min(w1, w2), max(w1, w2))\n\n#-------------------------------------------\n# The main routine\n#-------------------------------------------\nif __name__ == \"__main__\":\n corpus = readFileToCorpus('train.txt')\n pmi = PMI(corpus)\n lv_pmi = pmi.getPMI(\"luke\", \"vader\")\n print (\"PMI of \\\"luke\\\" and \\\"vader\\\": \", lv_pmi)\n numPairs = 100\n k = 200\n for k in 2, 5, 10, 50, 100, 200:\n print (\"\\nRunning for k: \" + str(k))\n commonWords = pmi.getVocabulary(k) # words must appear in least k sentences\n wordPairsWithGreatestPMI = pmi.getPairsWithMaximumPMI(commonWords, numPairs)\n pmi.writePairsToFile(wordPairsWithGreatestPMI, \"pairs_minFreq=\"+str(k)+\".txt\")","sub_path":"project/pmi.py","file_name":"pmi.py","file_ext":"py","file_size_in_byte":4743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"652809489","text":"import numpy as np\nimport pickle\n\ndef loadfile(mean, var, zmean, zvar, tau, temp, mixtures, model, data_size = \"full\", scaling = False, model_save_dir = \"\", fn=\"\", file = \"res\", dset=\"mnist\"):\n s = \"s\" if scaling else \"f\" \n exp_name = \"{}_m{}_zm{}_r{}_t{}_m{}_kdT{}_{}_{}\".format(model, mean, zmean, 50, tau, int(mixtures), int(temp), s, data_size) + fn\n if (file=='res'):\n with open(model_save_dir + '/{}_retrain_res_{}.p'.format(dset, exp_name),'rb') as f:\n file = pickle.load(f)\n if (file=='gmp'):\n with open(model_save_dir + '/{}_retrain_gmp_{}.p'.format(dset, exp_name),'rb') as f:\n file = pickle.load(f)\n if (file=='model'):\n file = torch.load(model_save_dir + '/{}_retrain_model_{}.m'.format(dset, exp_name))\n return file\n\ndef stack_weights(weight_dict):\n weights = np.array([], dtype=np.float32)\n for layer in weight_dict:\n weights = np.hstack( (weights, weight_dict[layer] ) )\n return weights\n\n#Codebook\n#Create Indexbook\ndef create_index(bpi, nz_list, weight_p):\n max_skip = 2**bpi\n if (nz_list[0] != 0):\n ridx_list = [0]\n w_list = [0]\n else:\n ridx_list = []\n w_list = []\n\n cidx = 0\n for nz in nz_list:\n\n nzc = nz - cidx\n ins_0 = int(np.floor(nzc/max_skip))\n nidx = int(nzc - (max_skip * ins_0))\n for i in range (ins_0):\n w_list.append(0)\n ridx_list.append(max_skip)\n w_list.append(1)\n ridx_list.append(nidx)\n #print (nz, cidx, nzc)\n cidx = nz\n lri = len(weight_p) - sum(ridx_list)\n if (lri>0):\n ridx_list.append(lri-1)\n w_list.append(0)\n return ridx_list, w_list\n\ndef recover_index(ridx_list, w_list, sz):\n rec = np.zeros(sz)\n for r,w in zip (list(np.array(ridx_list).cumsum()), w_list):\n rec[r] = w\n return rec\n\ndef cr_calc(res):\n mixtures = res['mixtures']\n weight_p = stack_weights(res['prune_weights'])\n weight_s = (weight_p != 0)\n nz_list = list(np.where(weight_s == True)[0])\n cb = 32.0 * mixtures\n sb = 32.0 * (len(res['scale'][-1]) - 1)\n orig_net = len(weight_p) * 32.0\n \n res_dict = {}\n \n for bpi in range(2,10):\n rl, wl = create_index (bpi, nz_list, weight_p)\n #rec = recover_index(rl, wl, len(weight_p))\n ib = bpi * len(rl)\n bpw = np.ceil(np.log2(res['mixtures']))\n wb = bpw * len(wl)\n cr = orig_net / (cb + wb + ib + sb)\n res2_dict = {}\n res2_dict['cr'] = cr\n res2_dict['on'] = orig_net\n res2_dict['wb'] = wb\n res2_dict['ib'] = ib\n res2_dict['sb'] = sb\n res2_dict['cb'] = cb\n res_dict[bpi] = res2_dict\n return res_dict","sub_path":"src/utils_write.py","file_name":"utils_write.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"536030876","text":"import matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n\ndef plot_adsorbed_masses(ads_data, gas, figname=None):\n\n comps = ads_data[gas+'_comp']\n mass = ads_data[gas+'_mass']\n error = ads_data[gas+'_error']\n air_mass = ads_data['O2_mass']+ads_data['N2_mass']\n air_error = ads_data['O2_error']+ads_data['N2_error']\n total_mass = ads_data['total_mass']\n total_error = ads_data['total_mass_error']\n\n plt.clf()\n plt.figure(figsize=(4.5,4.5), dpi=100)\n plt.errorbar(comps, mass, error, marker='o', markersize=5, alpha=0.5, linewidth=0, elinewidth=1)\n plt.errorbar(comps, air_mass, yerr=air_error, marker='o', markersize=5, alpha=0.5, linewidth=0, elinewidth=1)\n plt.errorbar(comps, total_mass, yerr=total_error, marker='o', markersize=5, alpha=0.1, linewidth=0, elinewidth=1)\n plt.xlabel(gas+' Mole Fractions')\n plt.ylabel('Adsorbed Mass')\n plt.legend([gas, 'Air', 'Total'])\n plt.tight_layout()\n\n if figname != None:\n plt.savefig(figname)\n plt.close()\n\n\ndef plot_kH(ads_data, gas, p, figname=None):\n\n comps = ads_data[gas+'_comp']\n mass = ads_data[gas+'_mass']\n error = ads_data[gas+'_error']\n air_mass = ads_data['O2_mass']+ads_data['N2_mass']\n air_error = ads_data['O2_error']+ads_data['N2_error']\n total_mass = ads_data['total_mass']\n total_error = ads_data['total_mass_error']\n\n # Initialize Figure\n plt.clf()\n plt.figure(figsize=(4.5, 4.5), dpi=100)\n\n fit = np.poly1d(p)\n plt.plot(comps, fit(comps), 'r-')\n plt.errorbar(comps, mass, error, marker='o', markersize=3, elinewidth=1, linewidth=0)\n\n plt.xlabel(gas+' Mole Fractions')\n plt.xticks(np.linspace(0,0.05,6), fontsize=8)\n plt.ylabel('Adsorbed Mass\\n[mg/g Framework]')\n plt.yticks(fontsize=8)\n\n textstr='K_H = '+str(np.round(p[0], 2))\n props = dict(boxstyle='round', facecolor='white', alpha=1)\n plt.text(0.3*max(comps), 1.08*max(mass)+max(error), textstr, fontsize=10, bbox=props)\n\n plt.tight_layout()\n if figname != None:\n plt.savefig(figname)\n plt.close()\n\n\ndef plot_all_kH(gas, data, figname):\n colors = mpl.cm.get_cmap('RdBu')\n color0 = colors(0.80)\n color1 = colors(0.20)\n\n comps = []\n khs = []\n for row in data:\n comps.extend([row['Maximum Composition']])\n khs.extend([row['k_H']])\n\n if gas != 'None':\n if gas == 'CO2':\n gas_for_title = '$CO_2$'\n else:\n gas_for_title = '$' + gas[0].upper() + gas[1::] +'$'\n\n plt.clf()\n plt.figure(figsize=(4.5,4.5), dpi=600)\n plt.semilogy(comps,khs,'o', alpha=0.7, color=color0)\n plt.ylim([1e-2,1e8])\n plt.xlim([-0.001,0.051])\n plt.title(gas_for_title+' in Air', fontsize=16)\n plt.xlabel('Maximum Mole Fraction\\n(End of Henry\\'s Regime)', fontsize=16)\n plt.ylabel('Henry\\'s Coefficient\\n[mg/g/mole fraction]',fontsize=16)\n plt.xticks(fontsize=12)\n plt.yticks(fontsize=12)\n plt.tight_layout()\n plt.savefig(figname)\n plt.close()\n","sub_path":"sensor_array/helper/plotting_functions.py","file_name":"plotting_functions.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"352324197","text":"from django.shortcuts import render\nfrom .models import BoardModel\nfrom django.shortcuts import redirect\nfrom django.views.generic import CreateView\nfrom django.urls import reverse_lazy\n\n# Create your views here.\ndef listfunction(request):\n object_list = BoardModel.objects.all()\n\n return render(request, 'list.html',{'object_list':object_list})\n\ndef showfunction(request, pk):\n object_id = BoardModel.objects.get(pk=pk)\n return render(request,'show.html',{'object_id':object_id})\n\n\ndef likefunction(request,pk):\n article = BoardModel.objects.get(pk=pk)\n article.like = article.like + 1\n article.save()\n return redirect('list')\n\n\nclass PostCreate(CreateView):\n template_name='create.html'\n model = BoardModel\n fields = ('title', 'content', 'images')\n success_url = reverse_lazy('list')\n\n","sub_path":"dietapp/boardapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"256488272","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def pathSum(self, root: TreeNode, sum: int) -> int:\n \n def dfs(node,cumsum,maP):\n nonlocal ans\n if not node:\n return\n \n cumsum+=node.val\n if cumsum-sum in maP:\n ans+=maP[cumsum-sum]\n \n if cumsum not in maP:\n maP[cumsum]=0\n maP[cumsum]+=1\n \n dfs(node.left,cumsum,maP)\n dfs(node.right,cumsum,maP)\n \n maP[cumsum]-=1\n \n \n \n maP = {0:1}\n ans = 0\n dfs(root,0,maP)\n return ans","sub_path":"Python/Medium/437. Path Sum III.py","file_name":"437. Path Sum III.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"230627789","text":"import multiprocessing\nimport time\nimport random\nfrom ipython_genutils.py3compat import xrange\nfrom math import pi\nimport json\nimport os\nclass Consumer(multiprocessing.Process):\n def __init__(self, task_queue, result_queue):\n multiprocessing.Process.__init__(self)\n self.task_queue = task_queue\n self.result_queue = result_queue\n\n def run(self):\n \"\"\"\n Handles task from queue.\n \"\"\"\n proc_name = self.name # from Process\n while True:\n next_task = self.task_queue.get() # multiprocessing.JoinableQueue() init from Consumer, get task obj\n if next_task is None: # poision pill\n print(f'Exiting {proc_name}')\n\n self.task_queue.task_done()\n break\n #print(proc_name, next_task)\n answer = next_task()\n self.task_queue.task_done()\n self.result_queue.put(answer)\n\nclass Task():\n def __init__(self, a, b):\n self.a = a\n self.b = b\n\n def __call__(self):\n time.sleep(0.1) # pretend to take some time to do the work\n\n print(\"Hello from a worker\", os.getpid())\n print()\n s = 0\n random.seed(self.b)\n #random.seed()\n for i in range(self.a): #args ?\n x = random.random()\n y = random.random()\n #print(f'x {x}, y {y}')\n if x ** 2 + y ** 2 <= 1.0:\n s += 1\n\n return s\n\n\ndef run_jobs(num_consumers, accuracy, num_of_predictions):\n # Establish communication queues\n tasks = multiprocessing.JoinableQueue()\n results = multiprocessing.Queue() # like a list\n\n # Start consumers\n\n\n # multiprocessing.cpu_count()\n\n print('Creating %d consumers' % num_consumers)\n consumers = [Consumer(tasks, results)\n for i in range(num_consumers)]\n\n list(worker.start() for worker in consumers)\n # start() Start the process’s activity.\n # This must be called at most once per process object.\n # It arranges for the object’s run() method to be invoked in a separate process.\n\n\n # Enqueue jobs\n pi_est = 0\n #accuracy = 0.01 # format ok 99% = 0.01 99.9 0.001\n\n\n # 0.001\n\n n = 0\n print(f' abs val {abs(pi - pi_est)}')\n total_result = 0\n count_tasks = 0\n inc_rnd = 0\n while abs(pi - pi_est) > accuracy:\n inc_rnd += 1\n\n tasks.put(Task(a=num_of_predictions, b=inc_rnd)) # we put task for the consumers 12 + 12 + 12 +12 8 +8+ 8+ 8)\n #tasks.join()\n count_tasks += num_consumers\n result = results.get()\n total_result += result\n #print('Result:', total_result)\n n += num_of_predictions\n pi_est = (4.0 * total_result) / n\n\n #print(f'pi estimate = {pi_est}')\n print(f'steps {n}')\n print(\" Steps\\tSuccess\\tPi est.\\tError\")\n print(\"%6d\\t%7d\\t%1.5f\\t%1.5f\" % (n, total_result, pi_est, pi - pi_est))\n\n #n = 1000 # comp per task/\n\n for i in range(num_consumers):\n tasks.put(None) # Terminate\n tasks.join()\n\n print(f'number of tasks {n/count_tasks}')\n return n/count_tasks\n\nif __name__ == '__main__':\n accuracy = 0.00001\n num_of_predictions = 10000000\n\n timer = {}\n for i in range(1,13):\n start_time = time.time()\n tasks_taken = run_jobs(num_consumers=i, accuracy=accuracy, num_of_predictions=num_of_predictions)\n time_taken = (time.time() - start_time)\n print('Time', time_taken)\n timer[str(i)] = (tasks_taken, time_taken)\n\n print(f'time {timer}')\n # with open('pi_acc'+str(accuracy)+'.json', 'w') as outfile:\n f_name = 'pi_acc_pred'+str(num_of_predictions)+'_accs'+str(accuracy)\n with open(f_name+'.json', 'w') as outfile:\n json.dump(timer, outfile)\n\n","sub_path":"lab2/poison_pill_motecarlo_final2.py","file_name":"poison_pill_motecarlo_final2.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"341547222","text":"def valid_substring(dp, i, s):\n if i == len(dp):\n return True\n for k in range(i, len(dp)):\n if dp[i][k] and valid_substring(dp, k + 1, s):\n return True\n return False\n\n\ndef is_concat(s, d):\n dp = [[False for _ in range(len(s))] for _ in range(len(s))]\n for i in range(len(s)):\n for j in range(i, len(s)):\n if s[i:j + 1] in d:\n dp[i][j] = True\n return valid_substring(dp, 0, s)\n\n\nassert is_concat(\n 'catworld',\n set(['hello', 'world', 'cat'])\n)\n\nassert is_concat(\n 'caterdog',\n set(['cat', 'dog', 'cater'])\n)\n\nassert not is_concat(\n 'caterdo',\n set(['cat', 'dog', 'cater'])\n)\n","sub_path":"challenges/dynamic_programming/is_concat/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"578428045","text":"##RAMBO Momentum Generator\nfrom __future__ import division\nimport numpy as np\nimport matrix2py\nfrom tqdm import tqdm\nimport pandas as pd\nimport sys\n\ndef minkowski_product(p1, p2):\n #Minkowski product of two 4-vectors\n return np.sum(p1[0]*p2[0] - p1[1]*p2[1] - p1[2]*p2[2] - p1[3]*p2[3])\n\ndef dot_product(v1, v2):\n #Dot product of two vectors\n return np.sum(np.multiply(v1, v2), axis=0)\n\ndef rambo(n = 5):\n #Random phase space generator RAMBO.\n rho_1, rho_2, rho_3, rho_4 = np.random.rand(4, n)\n\n c = 2*rho_1 - 1\n phi = 2*np.pi*rho_2\n\n q_0 = - np.log(np.multiply(rho_3,rho_4))\n q_1 = q_0*np.sqrt(1-c**2)*np.cos(phi)\n q_2 = q_0*np.sqrt(1-c**2)*np.sin(phi)\n q_3 = q_0*c\n\n q = np.array([q_0, q_1, q_2, q_3])\n Q = np.sum(q, axis=1)\n M = np.sqrt(minkowski_product(Q, Q))\n b = - Q[1:]/M\n x = 1/M\n gamma = np.sqrt(1 + dot_product(b,b))\n a = 1/(1+gamma)\n\n p_0 = x*(gamma*q_0 + dot_product(q[1:],b[:,None]))\n p_123 = x*np.add(q[1:], np.outer(b, q[0] + a*dot_product(q[1:],b[:,None])))\n \n p = np.transpose(np.array([p_0, p_123[0], p_123[1], p_123[2]]))\n return p\n\ndef sing_event(mom, CM, n):\n #Generate one full set of momenta and matrix element\n p_a = np.array([CM, 0, 0, CM])/2\n p_b = np.array([CM, 0, 0, -CM])/2\n \n me = matrix2py.get_me(np.transpose(np.concatenate(([p_a, p_b], mom))), alphas, renormalisation_scale, nhel)[0] #Matrix element calculation\n \n return np.array(me)\n\n##Initital variables:\nCM = 1000 #Center of mass energy\nn_jet = 2 #Number of jets\nmatrix2py.initialise('../../Cards/param_card.dat')\nalphas = 0.08703536379467461\nrenormalisation_scale = CM\nnhel = -1 # means sum over all helicity \n \ndef genDataNPY(n_processes):\n me = np.zeros((n_processes,4))\n mom = np.zeros((n_processes, n_jet, 4))\n for i in tqdm(range(n_processes)):\n mom[i] = rambo(n_jet)*CM\n \n for i in tqdm(range(n_processes)):\n me[i] = sing_event(mom[i], CM, n_jet)\n np.save('NLO_mom_{}jet_{}'.format(n_jet, n_processes), mom)\n np.save('NLO_me_{}jet_{}'.format(n_jet, n_processes), me)\n\n \n##IMPORTANT\n#me[0] : Born Matrix Element\n#me[1] : Finite Part of NLO Matrix Element\n#me[2] : Single Pole Residue\n#me[3] : Double Pole Residue \n \n \ngenDataNPY(int(sys.argv[1])) ##Enter number of datapoints when calling code (ie python GenDataLO.py 100000)\n","sub_path":"TimerNLO.py","file_name":"TimerNLO.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"313807062","text":"import numpy as np\n\n\nclass ReplayBuffer:\n\n def __init__(self, config):\n\n self.max_batch = config.max_batch\n self.size = 0\n assert self.size <= self.max_batch\n\n self.storage = []\n self.result = []\n self.step = []\n self.blackjack = []\n self.double = []\n self.surrender = []\n\n def store(self, trajectory, step, result, blackjack):\n\n if self.size >= self.max_batch:\n self.storage = self.storage[1:]\n self.result = self.result[1:]\n self.step = self.step[1:]\n self.blackjack = self.blackjack[1:]\n # self.double = self.double[1:]\n # self.surrender = self.surrender[1:]\n self.size -= 1\n\n self.storage.append(trajectory)\n self.result.append(result)\n self.step.append(step)\n self.blackjack.append(blackjack)\n # self.double.append(double)\n # self.surrender.append(surrender)\n self.size += 1\n\n def get_data(self, ind):\n\n return self.storage[ind]\n\n def get_step(self, ind):\n\n return self.step[ind]\n\n def get_performance(self):\n success_count = 0\n fail_count = 0\n tie_count = 0\n for i in range(self.size):\n if self.result[i] == 1:\n success_count += 1\n elif self.result[i] == -1:\n fail_count += 1\n elif self.result[i] == 0:\n tie_count += 1\n success_rate = success_count / self.size\n fail_rate = fail_count / self.size\n tie_rate = tie_count / self.size\n return success_rate, fail_rate, tie_rate, np.mean(self.step), np.mean(self.blackjack) #, np.mean(self.double), np.mean(self.surrender)\n","sub_path":"Code/DQN+BN/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"225549810","text":"\"\"\"\n* Performand metrics reporting for clients using Artifactory\n\"\"\"\n\n###############################################################################\n# I M P O R T S\n###############################################################################\n\nfrom threading import Semaphore\nimport time\nimport sys\n\n###############################################################################\n# C L A S S\n###############################################################################\nclass ArtifactoryPerformance(object):\n \"\"\"\n \"\"\"\n\n def __init__(self, logger = None, debug = False):\n \"\"\"\n * Store the credentials, artifact, retrieve the host, and setup the logging\n \"\"\"\n\n self.debug = debug\n self.LOG = logger\n\n self.startTime = time.time()\n self.endTime = 0\n\n self.numberOfFiles = 0\n self.totalSize = 0\n \n def __enter__(self):\n \"\"\"\n \"\"\"\n return self\n\n def __exit__(self, exception_type, exception_val, trace):\n \"\"\"\n \"\"\"\n if sys.version_info >= (2, 5):\n return\n\n self.endTime = time.time()\n elapsedTime = self.endTime - self.startTime\n mbPerSecond = (self.totalSize / elapsedTime) / 1048576\n sizeInMB = self.totalSize / 1048576\n\n # print summary here\n print(\"\\nThe operation took {:.2f} seconds to complete. {} files totaling {:.2f} MB averaging {:.2f} MB/s\"\n .format((elapsedTime, self.numberOfFiles, sizeInMB, mbPerSecond)))\n\n def addFile(self, size):\n \"\"\"\n * add 1 to the number of files and add a size\n \"\"\"\n Semaphore().acquire()\n\n self.numberOfFiles += 1\n self.totalSize += size\n\n Semaphore().release()\n","sub_path":"devenable/projects/artifactory/re-tools/artifactory_tools/artifactory_performance.py","file_name":"artifactory_performance.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"233021316","text":"from flask import render_template, request, redirect\r\nfrom app import app, models\r\nimport json\r\n\r\nactive_week = \"active\"\r\n\r\n@app.route('/')\r\n@app.route('/home')\r\ndef home():\r\n return render_template('index.html',\r\n title=\"Home\")\r\n\r\n@app.route('/games')\r\ndef games():\r\n week = 'All'\r\n games = models.Games.query.all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week=active_week,\r\n games=games)\r\n\r\n@app.route('/games/week1')\r\ndef week1():\r\n week = 1\r\n games = models.Games.query.filter_by(week=week).all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week1=active_week,\r\n games=games)\r\n\r\n@app.route('/games/week2')\r\ndef week2():\r\n week = 2\r\n games = models.Games.query.filter_by(week=week).all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week2=active_week,\r\n games=games)\r\n\r\n@app.route('/games/week3')\r\ndef week3():\r\n week = 3\r\n games = models.Games.query.filter_by(week=week).all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week3=active_week,\r\n games=games)\r\n\r\n@app.route('/games/week4')\r\ndef week4():\r\n week = 4\r\n games = models.Games.query.filter_by(week=week).all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week4=active_week,\r\n games=games)\r\n\r\n@app.route('/games/week5')\r\ndef week5():\r\n week = 5\r\n games = models.Games.query.filter_by(week=week).all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week5=active_week,\r\n games=games)\r\n\r\n@app.route('/games/week6')\r\ndef week6():\r\n week = 6\r\n games = models.Games.query.filter_by(week=week).all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week6=active_week,\r\n games=games)\r\n\r\n@app.route('/games/week7')\r\ndef week7():\r\n week = 7\r\n games = models.Games.query.filter_by(week=week).all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week7=active_week,\r\n games=games)\r\n\r\n@app.route('/games/week8')\r\ndef week8():\r\n week = 8\r\n games = models.Games.query.filter_by(week=week).all()\r\n return render_template('games.html',\r\n title=\"Games\",\r\n week=week,\r\n active_week8=active_week,\r\n games=games)\r\n\r\n@app.route('/raw/standings')\r\ndef standings_json():\r\n teams = models.Teams.query.all()\r\n\r\n dataSet = []\r\n\r\n for team in teams:\r\n team_data = {'owner': team.team_owner, 'team': team.team_name, 'division': team.division, 'wins': team.team_wins, 'losses': team.team_losses}\r\n dataSet.append(team_data)\r\n\r\n return json.dumps(dataSet)\r\n\r\n@app.route('/raw/standings/')\r\ndef standings_navy_json(division):\r\n teams = models.Teams.query.filter_by(division=division).all()\r\n\r\n dataSet = []\r\n\r\n for team in teams:\r\n team_data = {'owner': team.team_owner, 'team': team.team_name, 'wins': team.team_wins, 'losses': team.team_losses}\r\n dataSet.append(team_data)\r\n\r\n return json.dumps(dataSet)\r\n\r\n@app.route('/raw/stats/offense')\r\ndef offense_stats_json():\r\n offense_stats = models.OffenseTeamStats.query.all()\r\n\r\n offenseDataSet = []\r\n\r\n for team in offense_stats:\r\n team_stats = {'team': team.team_name, 'games': team.games_played, 'totalyards': team.total_yards,\r\n 'passingyards': team.passing_yards, 'rushingyards': team.rushing_yards, 'turnovers': team.turnovers,\r\n 'qbr': team.qbr, 'pointsfor': team.points_scored}\r\n offenseDataSet.append(team_stats)\r\n\r\n return json.dumps(offenseDataSet)\r\n\r\n@app.route('/raw/stats/defense')\r\ndef defense_stats_json():\r\n defense_stats = models.DefenseTeamStats.query.all()\r\n\r\n defenseDataSet = []\r\n\r\n for team in defense_stats:\r\n team_stats = {'team': team.team_name, 'games': team.games_played, 'totalyards': team.total_yards_against,\r\n 'passingyards': team.passing_yards_against, 'rushingyards': team.rushing_yards_against, 'turnovers': team.turnovers_forced,\r\n 'qbr': team.opposing_qbr, 'pointsagaisnt': team.points_allowed}\r\n defenseDataSet.append(team_stats)\r\n\r\n return json.dumps(defenseDataSet)\r\n\r\n\r\n@app.route('/stats')\r\ndef stats():\r\n #per_game = (models.OffenseTeamStats.games_played.query.all() - models.OffenseTeamStats.query.\r\n\r\n total_yards = models.OffenseTeamStats.query.with_entities(models.OffenseTeamStats.team_name, models.OffenseTeamStats.total_yards).order_by((models.OffenseTeamStats.total_yards).desc()).limit(3).all()\r\n passing_yards = models.OffenseTeamStats.query.with_entities(models.OffenseTeamStats.team_name, models.OffenseTeamStats.passing_yards).order_by(models.OffenseTeamStats.passing_yards.desc()).limit(3).all()\r\n rushing_yards = models.OffenseTeamStats.query.with_entities(models.OffenseTeamStats.team_name, models.OffenseTeamStats.rushing_yards).order_by(models.OffenseTeamStats.rushing_yards.desc()).limit(3).all()\r\n turnovers = models.OffenseTeamStats.query.with_entities(models.OffenseTeamStats.team_name, models.OffenseTeamStats.turnovers).order_by(models.OffenseTeamStats.turnovers.asc()).limit(3).all()\r\n qbr = models.OffenseTeamStats.query.with_entities(models.OffenseTeamStats.team_name, models.OffenseTeamStats.qbr).order_by(models.OffenseTeamStats.qbr.desc()).limit(3).all()\r\n\r\n total_yards_allowed = models.OffenseTeamStats.query.with_entities(models.DefenseTeamStats.team_name, models.DefenseTeamStats.total_yards_against).order_by(models.DefenseTeamStats.total_yards_against.asc()).limit(3).all()\r\n passing_yards_allowed = models.OffenseTeamStats.query.with_entities(models.DefenseTeamStats.team_name, models.DefenseTeamStats.passing_yards_against).order_by(models.DefenseTeamStats.passing_yards_against.asc()).limit(3).all()\r\n rushing_yards_allowed = models.OffenseTeamStats.query.with_entities(models.DefenseTeamStats.team_name, models.DefenseTeamStats.rushing_yards_against).order_by(models.DefenseTeamStats.rushing_yards_against.asc()).limit(3).all()\r\n turnovers_forced = models.OffenseTeamStats.query.with_entities(models.DefenseTeamStats.team_name, models.DefenseTeamStats.turnovers_forced).order_by(models.DefenseTeamStats.turnovers_forced.desc()).limit(3).all()\r\n opposing_qbr = models.OffenseTeamStats.query.with_entities(models.DefenseTeamStats.team_name, models.DefenseTeamStats.opposing_qbr).order_by(models.DefenseTeamStats.opposing_qbr.asc()).limit(3).all()\r\n\r\n return render_template('stats.html',\r\n title='Stats',\r\n total_yards=total_yards,\r\n passing_yards=passing_yards,\r\n rushing_yards=rushing_yards,\r\n turnovers=turnovers,\r\n qbr=qbr,\r\n total_yards_allowed=total_yards_allowed,\r\n passing_yards_allowed=passing_yards_allowed,\r\n rushing_yards_allowed=rushing_yards_allowed,\r\n turnovers_forced=turnovers_forced,\r\n opposing_qbr=opposing_qbr)\r\n\r\n\r\n@app.route('/stats/offense')\r\ndef offense_stats():\r\n return render_template('offensestats.html',\r\n title=\"Stats\")\r\n\r\n@app.route('/stats/defense')\r\ndef defense_stats():\r\n return render_template('defensestats.html',\r\n title=\"Stats\")\r\n\r\n@app.route('/standings')\r\ndef standings():\r\n return render_template('standings.html',\r\n title=\"Standings\")\r\n\r\n@app.route('/standings/navy')\r\ndef navy_standings():\r\n return render_template('navystandings.html',\r\n title=\"Navy Standings\")\r\n\r\n@app.route('/standings/gold')\r\ndef gold_standings():\r\n return render_template('goldstandings.html',\r\n title=\"Gold Standings\")\r\n\r\n\r\n@app.route('/team/')\r\ndef team(teamname):\r\n team = models.Teams.query.filter_by(team_name=teamname).all()\r\n\r\n for t in team:\r\n offense = models.OffenseTeamStats.query.filter_by(team_id=t.id).first()\r\n defense = models.DefenseTeamStats.query.filter_by(team_id=t.id).first()\r\n\r\n return render_template('teams.html',\r\n team=team,\r\n active=teamname,\r\n offense=offense,\r\n defense=defense)\r\n\r\n@app.errorhandler(404)\r\ndef not_found_error(error):\r\n return render_template('404.html'), 404\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(port=port)\r\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"486107303","text":"#!/usr/bin/env python3\n#\n# slosepa.py\n# SLOw hash SEcure Password Author\n# ver 0.31 - 20191122\n# -minor fix to seeds' init's\n# ver 0.3 - 20191121\n# random-randomization\n# -unique, randomer seeds to each hash function\n# -randomly bounded seeds' lengths\n# -randomlier randomized selection of digest nibble\n# -triple conversion dict's\n# -random conversion dict selection\n# -randomer final char (to meet user requirement)\n# -(not so random) import optimizations\n#\n# **************\n# * escollapse *\n# * CISSP, PT+ *\n# * 20191008 *\n# **************\n#\n# usage:\n# 1 - specify desired password length\n# 2 - specify number of hashing rounds\n# 3 - press play\n#\n# future operations:\n# 1 - argument inputs\n# 2 - gui\n# 3 - browser plugin?\n\nimport itertools\nfrom string import ascii_letters, digits, punctuation\nfrom secrets import choice as ch\nfrom secrets import randbelow as randb\nfrom hashlib import blake2b, sha3_512, sha512\n\n# future args\npwLength = 30\nrounds = 500000\n\n# initializations\nconversionDict1 = {}\nconversionDict2 = {}\nconversionDict3 = {}\ndictList = []\nallChar = ascii_letters + digits + punctuation\nallChar1 = list(allChar)\nfor i in range(len(allChar1)):\n temp = ch(allChar1)\n allChar1.remove(temp)\n conversionDict1[hex(i)] = temp\nallChar2 = list(allChar)\nfor i in range(len(allChar2)):\n temp = ch(allChar2)\n allChar2.remove(temp)\n conversionDict2[hex(i)] = temp\nallChar3 = list(allChar)\nfor i in range(len(allChar3)):\n temp = ch(allChar3)\n allChar3.remove(temp)\n conversionDict3[hex(i)] = temp\n\n# idea here, create a list of the initialized dicts\n# then we can reference the index later, instead\n# of an if loop matching a number.\ndictList.append(conversionDict1)\ndictList.append(conversionDict2)\ndictList.append(conversionDict3)\n\n\ndef generate_seed():\n seed = ''\n for _ in itertools.repeat(None, pwLength * randb(1337) + 1):\n j = randb(len(dictList))\n seed += ch(list(dictList[j].values()))\n return seed\n\n\n# generate seeds to hashing functions\nfuncSeed1 = generate_seed()\nfuncSeed2 = generate_seed()\nfuncSeed3 = generate_seed()\n# print('function seed1 = {0}'.format(funcSeed1))\n# print('function seed2 = {0}'.format(funcSeed2))\n# print('function seed3 = {0}'.format(funcSeed3))\n\n\nblaked = blake2b()\nsha3d = sha3_512()\nsha2d = sha512()\n\nblaked.update(bytearray(funcSeed1, 'utf-8'))\nsha3d.update(bytearray(funcSeed2, 'utf-8'))\nsha2d.update(bytearray(funcSeed3, 'utf-8'))\n\nfor i in range(rounds):\n blaked.update(bytearray(blaked.hexdigest(), 'utf-8'))\n sha3d.update(bytearray(sha3d.hexdigest(), 'utf-8'))\n sha2d.update(bytearray(sha2d.hexdigest(), 'utf-8'))\n\npreprefinal = ''\nfor i in range(pwLength):\n j = randb(3)\n if j == 0:\n preprefinal += blaked.hexdigest()[randb(128)]\n elif j == 1:\n preprefinal += sha3d.hexdigest()[randb(128)]\n elif j == 2:\n preprefinal += sha2d.hexdigest()[randb(128)]\nprefinal = [i+j for i, j in zip(preprefinal[::2], preprefinal[1::2])]\n\nrblaked = blaked.hexdigest()[::-1]\nrsha3d = sha3d.hexdigest()[::-1]\nrsha2d = sha2d.hexdigest()[::-1]\n\npreprefinal2 = ''\nfor i in range(pwLength):\n j = randb(3)\n if j == 0:\n preprefinal2 += rblaked[randb(128)]\n elif j == 1:\n preprefinal2 += rsha3d[randb(128)]\n elif j == 2:\n preprefinal2 += rsha2d[randb(128)]\nprefinal2 = [i+j for i, j in zip(preprefinal2[::2], preprefinal2[1::2])]\n\n# first half\nfor i in range(pwLength // 2):\n j = randb(3)\n if j == 0:\n if hex(int(prefinal[i], 16)) in conversionDict1.keys():\n prefinal[i] = conversionDict1[hex(int(prefinal[i], 16))]\n elif hex(int(prefinal[i], 16) % 94) in conversionDict1.keys():\n prefinal[i] = conversionDict1[hex(int(prefinal[i], 16) % 94)]\n elif j == 1:\n if hex(int(prefinal[i], 16)) in conversionDict2.keys():\n prefinal[i] = conversionDict2[hex(int(prefinal[i], 16))]\n elif hex(int(prefinal[i], 16) % 94) in conversionDict2.keys():\n prefinal[i] = conversionDict2[hex(int(prefinal[i], 16) % 94)]\n elif j == 2:\n if hex(int(prefinal[i], 16)) in conversionDict3.keys():\n prefinal[i] = conversionDict3[hex(int(prefinal[i], 16))]\n elif hex(int(prefinal[i], 16) % 94) in conversionDict3.keys():\n prefinal[i] = conversionDict3[hex(int(prefinal[i], 16) % 94)]\nfinal = ''.join(prefinal)\n\n# second half\nfor i in range(pwLength // 2):\n j = randb(3)\n if j == 0:\n if hex(int(prefinal2[i], 16)) in conversionDict1.keys():\n prefinal2[i] = conversionDict1[hex(int(prefinal2[i], 16))]\n elif hex(int(prefinal2[i], 16) % 94) in conversionDict1.keys():\n prefinal2[i] = conversionDict1[hex(int(prefinal2[i], 16) % 94)]\n elif j == 1:\n if hex(int(prefinal2[i], 16)) in conversionDict2.keys():\n prefinal2[i] = conversionDict2[hex(int(prefinal2[i], 16))]\n elif hex(int(prefinal2[i], 16) % 94) in conversionDict2.keys():\n prefinal2[i] = conversionDict2[hex(int(prefinal2[i], 16) % 94)]\n elif j == 2:\n if hex(int(prefinal2[i], 16)) in conversionDict3.keys():\n prefinal2[i] = conversionDict3[hex(int(prefinal2[i], 16))]\n elif hex(int(prefinal2[i], 16) % 94) in conversionDict3.keys():\n prefinal2[i] = conversionDict3[hex(int(prefinal2[i], 16) % 94)]\nfinal += ''.join(prefinal2)\n\n# ensure user requirement is met\n# ...seriously, one char that is less outrageously random is okay\nif len(final) != pwLength:\n idx = str(randb(len(allChar)))\n addToFinal = conversionDict3[hex(int(idx))]\n final += ''.join(addToFinal)\n print(\"\\n'final' = \" + final)\nelse:\n print(\"\\n'final' = \" + final)\n","sub_path":"slosepa.py","file_name":"slosepa.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"457618950","text":"import json\nfrom pandas import DataFrame\nimport pandas as pd\n\n\ndef make_simple_match_info(matchjsonfile):\n '''\n output : time | total_gold | position\n '''\n with open(matchjsonfile, mode='r', encoding='utf-8') as f:\n jsontext = f.read()\n\n data = json.loads(jsontext)\n\n frames = data['timeline']['frames']\n record = []\n for frame in frames:\n data_per_min = {'time': 0, 'total_gold': 0, 'pos_x': -1, 'pos_y': -1}\n\n time_m = frame['timestamp']//60000\n mydata = frame['participantFrames']['6']\n position = mydata.get('position', dict())\n\n data_per_min['time'] = time_m\n data_per_min['total_gold'] = mydata['totalGold']\n\n if position:\n data_per_min['pos_x'] = position['x']\n data_per_min['pos_y'] = position['y']\n\n record.append(data_per_min)\n\n df = DataFrame(record)\n\n order = ['time', 'total_gold', 'pos_x', 'pos_y']\n df = df[order]\n\n outputname = 'matchinfo.csv'\n df.to_csv(outputname, sep='\\t')\n print('Complete to create match info : ', outputname)","sub_path":"makematchinfo.py","file_name":"makematchinfo.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"191414978","text":"from setuptools import find_packages, setup\n\nimport re\nVERSION_FILE = \"cheval/_version.py\"\nversion_line = open(VERSION_FILE, \"rt\").read()\nregex = r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"\nmo = re.search(regex, version_line, re.M)\nif mo:\n version_string = mo.group(1)\nelse:\n raise RuntimeError(\"Unable to find version string in %s.\" % (VERSION_FILE,))\n\nsetup(\n name='wsp-cheval',\n author='wsp',\n maintatiner='Peter Kucirek',\n maintainer_email='peter.kucirek@wsp.com',\n version=version_string,\n packages=find_packages(),\n python_requires='>=3.6',\n install_requires=[\n 'pandas>= 0.22, <0.24',\n 'numpy>=1.14',\n 'astor',\n 'numba==0.45',\n 'numexpr',\n 'deprecated',\n 'attrs>=19.3'\n ]\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"319695839","text":"# 테이블 조회\n\nimport sqlite3\n\n# DB파일 조회(없으면 새로 생성)\nconn = sqlite3.connect(\n \"/Users/ki/project/fa_python/python-basic/resource/database.db\"\n)\n\n# 커서 바인딩\nc = conn.cursor()\n\n# 데이터 조회(전체)\nc.execute(\"SELECT * FROM users\")\n\n# 커서 위치가 변경\n# 1 row 선택\n# print(\"One -> \\n\", c.fetchone())\n\n# 지정 row 선택\n# print(\"Three -> \\n\", c.fetchmany(size=3))\n\n# 전체 row 선택\n# print(\"All -> \\n\", c.fetchall())\n\n# 순회1\n# rows = c.fetchall()\n# for row in rows:\n# print(\"retrieve1 >\", row)\n\n# 순회2\n# for row in c.fetchall():\n# print(\"retrieve2 >\", row)\n\n# 순회3\n# for row in c.execute(\"SELECT * FROM users ORDER BY id desc\"):\n# print(\"retrieve3 >\", row)\n\nprint()\n\n# WHERE Retieve1\nparam1 = (3,)\nc.execute(\"SELECT * FROM users WHERE id=?\", param1)\nprint(\"param1 >\", c.fetchone())\nprint(\"param1 >\", c.fetchall()) # 데이터 없음\n\n# WHERE Retieve2\nparam2 = 4\nc.execute(\"SELECT * FROM users WHERE id='%s'\" % param2)\nprint(\"param2 >\", c.fetchone())\nprint(\"param2 >\", c.fetchall()) # 데이터 없음\n\n# WHERE Retieve3\nc.execute(\"SELECT * FROM users WHERE id=:Id\", {\"Id\": 5})\nprint(\"param3 >\", c.fetchone())\nprint(\"param3 >\", c.fetchall()) # 데이터 없음\n\n# WHERE Retieve4\nparam4 = (3, 5)\nc.execute(\"SELECT * FROM users WHERE id IN(?,?)\", param4)\nprint(\"param4 >\", c.fetchall())\n\n# WHERE Retieve5\nc.execute(\"SELECT * FROM users WHERE id IN('%d','%d')\" % (3, 4))\nprint(\"param5 >\", c.fetchall())\n\n# WHERE Retieve6\nc.execute(\"SELECT * FROM users WHERE id=:Id1 OR id=:Id2\", {\"Id1\": 1, \"Id2\": 3})\nprint(\"param6 >\", c.fetchall())\n\n# Dump 출력\nwith conn:\n with open(\n \"/Users/ki/project/fa_python/python-basic/resource/dump.sql\", \"w\"\n ) as f:\n for line in conn.iterdump():\n f.write(\"%s\\n\" % line)\n print(\"Dump Print Complete\")\n\n# f.close(), conn.close()\n","sub_path":"python_basic/section12-2.py","file_name":"section12-2.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"67353058","text":"from PIL import Image\n\t\nif __name__ == '__main__':\n\tim_A = Image.open('PictureA.png')\n\tim_B = Image.open('PictureB.png')\n\twidth, height = im_A.size\n\tim_ans = Image.new(\"RGB\", (width, height), \"white\") \n\tfor i in range(0,width):\n\t\tfor j in range(0,height):\n\t\t\trgb_A = im_A.getpixel((i,j))\n\t\t\trgb_B = im_B.getpixel((i,j))\n\t\t\tif rgb_A == rgb_B:\n\t\t\t\tim_ans.putpixel((i,j), (255,255,255))\n\t\t\telse:\n\t\t\t\tim_ans.putpixel((i,j), rgb_B)\n\tim_ans.save(\"PictureAns.png\")\n","sub_path":"HW0/Q2.py","file_name":"Q2.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"253256334","text":"# Copyright 2020. ThingsBoard\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\"\"\"Import libraries\"\"\"\n\nimport serial\nimport time\nimport traceback\nimport Pyro4\nfrom threading import Thread\nfrom random import choice\nfrom string import ascii_lowercase\nfrom thingsboard_gateway.connectors.connector import Connector, log # Import base class for connector and logger\nfrom thingsboard_gateway.tb_utility.tb_utility import TBUtility\nimport thingsboard_gateway.extensions.opcda.OpenOPC as OpenOPC\nfrom thingsboard_gateway.extensions.opcda.opcda_converter import CustomOpcdaUplinkConverter\n\n\nclass CustomOpcdaConnector(Thread, Connector): # Define a connector class, it should inherit from \"Connector\" class.\n def __init__(self, gateway, config, connector_type):\n super().__init__() # Initialize parents classes\n self.statistics = {'MessagesReceived': 0,\n 'MessagesSent': 0} # Dictionary, will save information about count received and sent messages.\n self.__config = config # Save configuration from the configuration file.\n self.__gateway = gateway # Save gateway object, we will use some gateway methods for adding devices and saving data from them.\n self.__connector_type = connector_type # Saving type for connector, need for loading converter\n self.setName(self.__config.get(\"name\",\n \"Custom %s connector \" % self.get_name() + ''.join(choice(ascii_lowercase) for _ in range(5)))) # get from the configuration or create name for logs.\n log.info(\"Starting Custom %s connector\", self.get_name()) # Send message to logger\n self.daemon = True # Set self thread as daemon\n self.stopped = True # Service variable for check state\n self.connected = False # Service variable for check connection to device\n self.devices = {} # Dictionary with devices, will contain devices configurations, converters for devices and serial port objects\n self.load_converters() # Call function to load converters and save it into devices dictionary\n self.opc_servers = {}\n self.__connect_to_devices() # Call function for connect to devices\n log.info('Custom connector %s initialization success.', self.get_name()) # Message to logger\n log.info(\"Devices in configuration file found: %s \", '\\n'.join(device for device in self.devices)) # Message to logger\n\n def __connect_to_devices(self): # Function for opening connection and connecting to devices\n print(\"__connect_to_devices=\", self.devices)\n try:\n for opc_server in self.__config[\"opcServerList\"]:\n opc = OpenOPC.open_client(host=opc_server[\"opcProxyIp\"], port=opc_server[\"opcProxyPort\"])\n opc.connect(opc_server[\"opcServer\"])\n self.opc_servers[opc_server[\"serverId\"]] = {\"opc\": opc, \"collectInterval\": opc_server[\"collectInterval\"]}\n except OpenOPC.OPCError:\n print(\"OpenOPC.OPCError\")\n traceback.print_exc()\n except Pyro4.errors.CommunicationError:\n # [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。 地址错误\n # [WinError 10061] 由于目标计算机积极拒绝,无法连接。 端口错误\n print(\"Pyro4.errors.CommunicationError\")\n traceback.print_exc()\n else: # if no exception handled - add device and change connection state\n self.connected = True\n\n def open(self): # Function called by gateway on start\n self.stopped = False\n self.start()\n\n def get_name(self): # Function used for logging, sending data and statistic\n return self.name\n\n def is_connected(self): # Function for checking connection state\n return self.connected\n\n def load_converters(self): # Function for search a converter and save it.\n devices_config = self.__config.get('devices')\n try:\n if devices_config:\n for device_config in devices_config:\n if device_config.get('converter') is not None:\n converter = TBUtility.check_and_import(self.__connector_type, device_config['converter'])\n self.devices[device_config['name']] = {'converter': converter(device_config),\n 'device_config': device_config}\n else:\n converter = CustomOpcdaUplinkConverter(device_config)\n self.devices[device_config['name']] = {'converter': converter, 'device_config': device_config}\n else:\n log.error('Section \"devices\" in the configuration not found. A custom connector %s has being stopped.', self.get_name())\n self.close()\n except Exception as e:\n log.exception(e)\n\n def run(self): # Main loop of thread\n try:\n while True:\n for server_id in self.opc_servers:\n tag_list = []\n for device in self.devices:\n if server_id == self.devices[device][\"device_config\"][\"serverId\"]:\n for attribute in self.devices[device][\"device_config\"][\"attributes\"]:\n tag_list.append(device+\".\"+attribute[\"path\"])\n for timeserie in self.devices[device][\"device_config\"][\"telemetry\"]:\n tag_list.append(device+\".\"+timeserie[\"path\"])\n data_from_device = self.opc_servers[server_id][\"opc\"].read(tag_list)\n converted_data = self.devices[device]['converter'].convert(self.devices[device]['device_config'], data_from_device)\n self.__gateway.send_to_storage(self.get_name(), converted_data)\n time.sleep(5)\n if not self.connected:\n break\n except Exception as e:\n log.exception(e)\n self.close()\n\n def close(self): # Close connect function, usually used if exception handled in gateway main loop or in connector main loop\n self.stopped = True\n for opc_server in self.opc_servers:\n try:\n if self.devices[opc_server]['opc'].ping():\n self.devices[opc_server]['opc'].close()\n except Pyro4.errors.DaemonError:\n traceback.print_exc()\n\n\n def on_attributes_update(self, content): # Function used for processing attribute update requests from ThingsBoard\n log.debug(content)\n # if self.devices.get(content[\"device\"]) is not None:\n # device_config = self.devices[content[\"device\"]].get(\"device_config\")\n # if device_config is not None:\n # log.debug(device_config)\n # if device_config.get(\"attributeUpdates\") is not None:\n # requests = device_config[\"attributeUpdates\"]\n # for request in requests:\n # attribute = request.get(\"attributeOnThingsBoard\")\n # log.debug(attribute)\n # if attribute is not None and attribute in content[\"data\"]:\n # try:\n # value = content[\"data\"][attribute]\n # str_to_send = str(request[\"stringToDevice\"].replace(\"${\" + attribute + \"}\", str(value))).encode(\"UTF-8\")\n # self.devices[content[\"device\"]][\"serial\"].write(str_to_send)\n # log.debug(\"Attribute update request to device %s : %s\", content[\"device\"], str_to_send)\n # time.sleep(.01)\n # except Exception as e:\n # log.exception(e)\n # try:\n # # 写入方式一\n # # opc.write(('Bucket Brigade.Int4', 100.0))\n # # 写入方式二\n # opc.write([('Bucket Brigade.Int4', 10.0), ('Bucket Brigade.Int2', 20.0)])\n # print(opc.servers())\n # print(opc.list())\n # print(opc.list('Simulation Items'))\n # print(opc.list('Configured Aliases'))\n # print(opc.list('Simulation Items.Random.*Real*'))\n # print(opc.info())\n # # while True:\n # # v = opc.read(taglist)\n # # for i in range(len(v)):\n # # (name, val, qual, time) = v[i]\n # # print('% -15s % -15s % -15s % -15s'% (name, val, qual, time))\n # except Exception as e:\n # print(e)\n # finally:\n # opc.close()\n\n def server_side_rpc_handler(self, content):\n pass\n","sub_path":"thingsboard_gateway/extensions/opcda/opcda_connector.py","file_name":"opcda_connector.py","file_ext":"py","file_size_in_byte":9375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"174499059","text":"from forex_python.converter import CurrencyRates\nfrom tkinter import *\nfrom tkinter import ttk\n\nc = CurrencyRates()\nselectmoney = ['THB','USD','GBP','HKD','IDR','ILS','DKK','INR','CHF','EUR','CNY','SGD','MYR']\n\ndef leftClickButton(event):\n c = CurrencyRates()\n convertrate = float(input_money.get()) * c.get_rate(selectmoney1.get(),selectmoney2.get())\n labelResult.configure(text=str(round(convertrate, 3)))\n\nmainWindow = Tk(className=' ')\nlabelText = Label(mainWindow,bg='gray',text=\"หาค่าเงินต่างประเทศ\",font=(\"Hight\",15))\nlabelText.place(x=200, y=15, anchor=CENTER)\n\n#Selectmoney\nlabelMoney1 = Label(mainWindow,text='เลือกค่าเงิน',bg='gray',font=(\"Hight\",10))\nlabelMoney1.place(x=100, y=55, anchor=CENTER)\nselectmoney1 = ttk.Combobox(mainWindow,value=selectmoney,width=10)\nselectmoney1.place(x=100, y=75, anchor=CENTER)\nlabelMoney2 = Label(mainWindow,text='เลือกค่าเงิน',bg='gray',font=(\"Hight\",10))\nlabelMoney2.place(x=280, y=55, anchor=CENTER)\nselectmoney2 = ttk.Combobox(mainWindow,value=selectmoney,width=10)\nselectmoney2.place(x=280, y=75, anchor=CENTER)\nlabelMoney = Label(mainWindow,text='จำนวนเงิน',bg='gray',font=(\"Hight\",10))\nlabelMoney.place(x=190, y=100, anchor=CENTER)\ninput_money = Entry(mainWindow,width=15)\ninput_money.place(x=190, y=120, anchor=CENTER)\n#Selectmoney\n\n#Button\nButton = Button(mainWindow,text=\"แปลงค่าเงิน\")\nButton.bind('',leftClickButton)\nButton.place(x=190, y=150, anchor=CENTER)\n#Button\n\n#Result\nlabelResult = Label(mainWindow,text=\"รอผล\",font=(\"Hight\",14))\nlabelResult.place(x=190, y=200, anchor=CENTER)\n#Result\n\nmainWindow.geometry(\"400x250\")\nmainWindow.configure(bg='gray')\nmainWindow.mainloop()\n\n\n","sub_path":"Lecture114_Naphat_T.py","file_name":"Lecture114_Naphat_T.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"361664581","text":"def format_response(weather):\n try:\n name = weather['name']\n country = weather['sys']['country']\n desc = weather['weather'][0]['description']\n temp = weather['main']['temp']\n tempmin = weather['main']['temp_min']\n tempmax = weather['main']['temp_max']\n feelslike = weather['main']['feels_like']\n humidity = weather['main']['humidity']\n pressure = weather['main']['pressure']\n windspeed = weather['wind']['speed']\n winddeg = weather['wind']['deg']\n visibility = weather['visibility']\n\n final_str = 'City: %s \\nCountry: %s \\nConditions: %s \\nTemperature (°C): %s \\nMin Temperature (°C): %s \\nMax ' \\\n 'Temperature (°C): %s \\nFeels Like (°C): %s \\nHumidity : %s%% \\nPressure: %s mb \\nWind Speed: %s ' \\\n 'meter/sec \\nWind Degree: %s° \\nVisibility: %s meters' % (\n name, country, desc, temp, tempmin, tempmax, feelslike, humidity, pressure, windspeed, winddeg,\n visibility)\n except:\n final_str = 'There was a problem retrieving that\\ninfo.\\n\\nPlease enter city name again or zip\\ncode again.'\n\n return final_str","sub_path":"FormatResponse.py","file_name":"FormatResponse.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"149039673","text":"def set_parameters(numKids, yearly_cons, dist):\n\n with open('alpg/configs/example_external_inputs.py', 'r') as file:\n data = file.readlines()\n\n data[143] = 'numKids = ' + str(numKids) + '\\n'\n data[144] = 'yearlyConsumption = ' + str(yearly_cons) + '\\n'\n data[145] = 'distancetoWork = ' + str(dist) + '\\n'\n\n\n with open('alpg/configs/example_external_inputs.py', 'w') as file:\n file.writelines(data)","sub_path":"alpg/set_parameters.py","file_name":"set_parameters.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"60953528","text":"import numpy as np\n\nimport torch\n\n# abs\ndata = [-1, -2, -3, 2]\ntensor = torch.FloatTensor(data) # 32bit\n# 更多操作:https://pytorch.org/docs/stable/torch.html#math-operations\n\n\nprint(np.abs(data))\nprint(tensor)\nprint(torch.abs(tensor)) # 等价与下面\nprint(tensor.abs())\n\n# 矩阵乘法\ndata = [[1, 2], [3, 4]]\ntensor = torch.FloatTensor(data) # 32bit\ndata = np.array(data)\nprint(\n '\\nnumpy:', np.matmul(data, data),\n '\\ntorch:', torch.matmul(tensor, tensor)\n)\nprint(\n '\\nnumpy:', data.dot(data),\n '\\ntorch:', torch.mm(tensor, tensor)\n)\n","sub_path":"mf_00_basis/base_ops.py","file_name":"base_ops.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"443736968","text":"\n\n\n\"\"\"\nThe module provides access to several different types of clocks, each useful for different purposes.\n\"\"\"\n\n\n\n# Comparing Clocks\n\nimport textwrap\nimport time\n\n\navailable_clocks = [\n (\"monotonic\", time.monotonic),\n (\"perf_counter\", time.perf_counter),\n (\"process_time\", time.process_time),\n (\"time\", time.time),\n]\n\n\nfor clock_name, func in available_clocks:\n print(textwrap.dedent('''\\\n {name}:\n adjustable : {info.adjustable}\n implementation: {info.implementation}\n monotonic : {info.monotonic}\n resolution : {info.resolution}\n current : {current}\n ''').format(\n name=clock_name,\n info=time.get_clock_info(clock_name),\n current=func())\n )\n\n\n\n# Wall Clock Time\n\n\"\"\"\nPrints number of seconds since the start of epoch.\nFor Unix systems, epoch starts 0:00, January 1, 1970.\n\"\"\"\n\nprint()\nprint(\"+\" * 40)\n\nprint('The time is :', time.time())\n\n\n\n# Processor Clock Time\n\n\n\"\"\"\nThe value returned by \"process_time()\" reflect the actual time\nused by the program as it runs.\n\"\"\"\n\nprint()\nprint(\"+\" * 40)\n\n\nfor i in range(5):\n print(\"Process time is :\", time.process_time())\n time.sleep(2)\n print(\"Process time after delay :\", time.process_time())\n","sub_path":"Dates and Times/time — Clock Time.py","file_name":"time — Clock Time.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"484468148","text":"# Copyright (C) 2018 Google Inc.\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n\n\"\"\"\nAdd ACR for background tasks\n\nCreate Date: 2018-06-27 10:44:24.975681\n\"\"\"\n# disable Invalid constant name pylint warning for mandatory Alembic variables.\n# pylint: disable=invalid-name\n\nimport datetime\nimport sqlalchemy as sa\n\nfrom alembic import op\nfrom ggrc.migrations.utils import acr_propagation\n\n\n# revision identifiers, used by Alembic.\nrevision = '385ee48cd6b9'\ndown_revision = '6bc56d6072a2' # Last migration from ggrc workflows\n\nROLE_NAME = \"Admin\"\nOBJECT_TYPE = \"BackgroundTask\"\n\n\ndef upgrade():\n \"\"\"Upgrade database schema and/or data, creating a new revision.\"\"\"\n op.execute(\n acr_propagation.ACR_TABLE.insert().values(\n name=ROLE_NAME,\n object_type=OBJECT_TYPE,\n parent_id=None,\n created_at=datetime.datetime.now(),\n updated_at=datetime.datetime.now(),\n internal=False,\n non_editable=True,\n read=True,\n update=True,\n delete=True,\n my_work=False,\n )\n )\n\n\ndef downgrade():\n \"\"\"Downgrade database schema and/or data back to the previous revision.\"\"\"\n condition = sa.and_(\n acr_propagation.ACR_TABLE.c.name == ROLE_NAME,\n acr_propagation.ACR_TABLE.c.object_type == OBJECT_TYPE,\n )\n op.execute(\n acr_propagation.ACL_TABLE.delete().where(\n acr_propagation.ACL_TABLE.c.ac_role_id.in_(\n sa.select([acr_propagation.ACR_TABLE.c.id]).where(condition)\n )\n )\n )\n op.execute(acr_propagation.ACR_TABLE.delete().where(condition))\n","sub_path":"src/ggrc/migrations/versions/20180627104424_385ee48cd6b9_add_acr_for_background_tasks.py","file_name":"20180627104424_385ee48cd6b9_add_acr_for_background_tasks.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"247588112","text":"from typing import List\nfrom functools import reduce\n\ndef parse_input(filename: str) -> List[int]:\n with open(filename, 'r') as f:\n lines = list(map(lambda x: int(x), f.readlines()))\n return lines\n\ndef number_transform(num: int, sub_num:int) -> int:\n value = num * sub_num\n return value % 20201227\n\ndef find_loop_count(num: int, sub_num:int) -> int:\n loop_counter = 0\n accum = 1\n while accum != num:\n accum = number_transform(accum, sub_num)\n loop_counter += 1\n return loop_counter\n\nsub_num = 7\nkeys = parse_input(\"input.txt\")\nloop_count = find_loop_count(keys[0], sub_num)\nsub_num = keys[1]\naccum = 1\nfor i in range(loop_count):\n accum = number_transform(accum, sub_num)\nprint(f\"Part 1: {accum}\")\n\n","sub_path":"Chris/Day25/hodges_day25.py","file_name":"hodges_day25.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"97442100","text":"#coding:utf-8\nimport glob\nimport os\nimport sys\nfrom Streaming import StreamManager\nfrom . import Account\nfrom twitter import OAuth\nfrom collections import OrderedDict\nfrom RException import RaijinException\nfrom config import config as cfg\n\nclass AccountInfo(object):\n __instance = None\n\n def __new__(cls):\n if cls.__instance is None:\n cls.__instance = object.__new__(cls)\n return cls.__instance\n\n def __init__(self):\n self.__AccountDictionary = OrderedDict()\n self.__DefaultAccount = None\n self.__stream = StreamManager.StreamManager()\n self.load_accounts()\n\n def load_accounts(self):\n oauth = OAuth.OAuth()\n files = [os.path.relpath(x, cfg.ACCOUNT) for x in glob.glob(\n os.path.join(cfg.ACCOUNT, '*.conf'))]\n\n for config in files:\n account = Account.Account(oauth.load_token(os.path.join(cfg.ACCOUNT , config)))\n self.add_account(account)\n if(len(self.__AccountDictionary) == 1):\n self.default_account = account.screen_name\n self.__stream.add_account(account)\n\n def add_account(self, account_instance):\n # 引数:認証済みTwythonのインスタンス\n self.__AccountDictionary.update(\n {account_instance.screen_name: account_instance})\n self.__stream.add_account(account_instance)\n\n def get_account(self, account_name):\n if account_name in self.__AccountDictionary:\n return self.__AccountDictionary[account_name]\n else:\n raise RaijinException.NoneAccountException()\n\n @property\n def debug_ac(self):\n print(self.__AccountDictionary)\n\n @property\n def account_dict(self):\n return self.__AccountDictionary\n\n def clearAccount(self):\n \"\"\" 終了時に絶対に実行する \"\"\"\n self.__AccountDictionary = {}\n\n @property\n def default_account(self):\n return self.__DefaultAccount\n\n @default_account.setter\n def default_account(self, account_name):\n if account_name in self.__AccountDictionary:\n self.__DefaultAccount = account_name\n else:\n raise RaijinException.NoneAccountException()\n\n @property\n def stream(self):\n return self.__stream\n\nif __name__ == '__main__':\n AccountInfo.load_account()\n AccountInfo.get_account('h1manoa').account.update_status(status='おはようなぎ')\n","sub_path":"Raijin/account/AccountInfo.py","file_name":"AccountInfo.py","file_ext":"py","file_size_in_byte":2429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"95765087","text":"from product.models import *\nfrom post.models import *\nfrom django.db.models import Avg\nimport random\n\nfrom django.views import View\nfrom django.http import JsonResponse\n\nclass ProductRankingView(View):\n def get(self, request):\n category = random.randrange(1, SecondCategory.objects.count())\n products = Product.objects.filter(secondcategory_id=category).order_by('-like_nums')\n\n product_ranking = [\n {'id': product.id,\n 'category': product.secondcategory.name,\n 'brand': product.brand_name,\n 'productName': product.name,\n 'productImage': product.product_image,\n 'rate': [UserScore.objects.filter(product_id=product.id).aggregate(Avg('score'))['score__avg'],\n len(UserScore.objects.filter(product_id=product.id))]\n } for product in products[:4]]\n\n return JsonResponse({'ProductData1' : product_ranking}, status = 200)\n\nclass BrandRankingView(View):\n def get(self, request):\n brand_rand = random.randrange(1, Product.objects.count())\n brand_get = Product.objects.get(id = brand_rand)\n brands = Product.objects.filter(brand_name = brand_get.brand_name).order_by('-like_nums')\n brand_ranking = [\n {'id' : brand.id,\n 'brand' : brand.brand_name,\n 'productName' : brand.name,\n 'productImage' : brand.product_image,\n 'rate' : [UserScore.objects.filter(product_id = brand.id).aggregate(Avg('score'))['score__avg'],\n len(UserScore.objects.filter(product_id = brand.id))]\n } for brand in brands[:4]]\n\n return JsonResponse({'BrandData2' : brand_ranking}, status = 200)\n\nclass NewpickView(View):\n def get(self, request):\n new_picks = Product.objects.order_by('?')[:7]\n new_pick = [\n {'id': new_pick.id,\n 'brand': new_pick.brand_name,\n 'productName': new_pick.name,\n 'productImage': new_pick.product_image\n } for new_pick in new_picks]\n\n return JsonResponse({'PickData3': new_pick}, status=200)\n\nclass ProductView(View):\n def get(self, request):\n firstcategory = request.GET.get('category', None)\n offset = int(request.GET.get('offset'))\n limit = int(request.GET.get('limit'))\n\n category_dict = {}\n if firstcategory:\n category_dict['firstcategory'] = firstcategory\n products = Product.objects.filter(**category_dict).order_by('-like_nums')\n product_ranking = [\n {'id' : product.id,\n 'brand' : product.brand_name,\n 'productName' : product.name,\n 'productImage' : product.product_image,\n 'rate' : [UserScore.objects.filter(product_id = product.id).aggregate(Avg('score'))['score__avg'],\n len(UserScore.objects.filter(product_id = product.id))]\n } for product in products[offset : offset + limit]]\n\n return JsonResponse({'products': product_ranking}, status = 200)\n\nclass ProductDetailView(View):\n def get(self, request, product_id):\n product = Product.objects.get(id = product_id)\n product_scores = UserScore.objects.filter(product_id = product_id)\n\n score = []\n score_dict = {0.0 : 0, 0.5 : 0, 1.0 : 0, 1.5 : 0, 2.0 : 0, 2.5 : 0, 3.0 : 0, 3.5 : 0, 4.0 : 0, 4.5 : 0, 5.0 : 0}\n\n for product_score in product_scores:\n score.append(product_score.score)\n\n for key in score_dict:\n score_dict[key] = score.count(key)\n\n product_details = [\n {'brand' : product.brand_name,\n 'productName' : product.name,\n 'productImage' : product.product_image,\n 'likes' : product.like_nums,\n 'powerReview' : product.review_nums,\n 'miniReview' : product.mini_nums,\n 'count' : product.capacity,\n 'price' : product.price,\n 'rateData' : list(score_dict.values())\n }]\n\n power_reviews = Post.objects.order_by('?')[:7]\n review = [\n {'id' : power_review.id,\n 'title' : power_review.title,\n 'image' : power_review.first_image,\n 'likes' : power_review.like_number,\n 'views' : power_review.view_number\n } for power_review in power_reviews]\n\n return JsonResponse({'product_data': product_details, 'review_data' : review}, status = 200)\n\n\nclass ReviewProductView(View):\n def get(self, request, product_id):\n if Product.objects.filter(id=product_id).exists():\n product = Product.objects.get(id=product_id)\n product_elements = {\n 'image': product.product_image,\n 'name': product.name,\n 'brand': product.brand_name,\n }\n return JsonResponse({'product_elements': product_elements}, status=200)\n return JsonResponse({'message': 'Product_does_not_exist'}, status=404)","sub_path":"product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"557624496","text":"from calculator.Addition import addition\nfrom calculator.Division import division\n\n\ndef median(numbers):\n n = len(numbers)\n numbers.sort()\n if n % 2 == 0:\n first_median = numbers[int(division(2, n))]\n second_median = numbers[len(numbers) // 2 - 1]\n med = division(2, addition(first_median, second_median))\n else:\n med = numbers[division(2, n)]\n return med","sub_path":"Statistics/Median.py","file_name":"Median.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"652028756","text":"import re\nimport urlnorm\nimport parsedatetime\nimport countrynames\nimport phonenumbers\nfrom normality import stringify\nfrom urlparse import urlparse\nfrom datetime import date, datetime\nfrom urlparse import urldefrag\nfrom phonenumbers.phonenumberutil import NumberParseException\nfrom flanker.addresslib import address\n\nfrom aleph.data.validate import is_country_code, is_domain, is_partial_date\n\nPHONE_FORMAT = phonenumbers.PhoneNumberFormat.INTERNATIONAL\nCUT_ZEROES = re.compile(r'(\\-00?)?\\-00?$')\n\n\ndef parse_phone(number, country=None):\n \"\"\"Parse a phone number and return in international format.\n\n If no valid phone number can be detected, None is returned. If\n a country code is supplied, this will be used to infer the\n prefix.\n\n https://github.com/daviddrysdale/python-phonenumbers\n \"\"\"\n number = stringify(number)\n if number is None:\n return\n if country is not None:\n country = country.upper()\n try:\n num = phonenumbers.parse(number, country)\n if phonenumbers.is_possible_number(num):\n if phonenumbers.is_valid_number(num):\n num = phonenumbers.format_number(num, PHONE_FORMAT)\n return num.replace(' ', '')\n return\n except NumberParseException:\n return\n\n\ndef parse_country(country, guess=True):\n \"\"\"Determine a two-letter country code based on an input.\n\n The input may be a country code, a country name, etc.\n \"\"\"\n if guess:\n country = countrynames.to_code(country)\n if country is not None:\n country = country.lower()\n if is_country_code(country):\n return country\n\n\ndef parse_email(email):\n \"\"\"Parse and normalize an email address.\n\n Returns None if this is not an email address.\n \"\"\"\n if email is not None:\n parsed = address.parse(email)\n if parsed is not None:\n email = parsed.address.lower()\n email = email.strip(\"'\").strip('\"')\n return email\n\n\ndef parse_url(text):\n \"\"\"Clean and verify a URL.\"\"\"\n # TODO: learn from https://github.com/hypothesis/h/blob/master/h/api/uri.py\n url = stringify(text)\n if url is not None:\n if url.startswith('//'):\n url = 'http:' + url\n elif '://' not in url:\n url = 'http://' + url\n try:\n norm = urlnorm.norm(url)\n norm, _ = urldefrag(norm)\n return norm\n except:\n return None\n return None\n\n\ndef parse_domain(text):\n \"\"\"Extract a domain name from a piece of text.\"\"\"\n domain = stringify(text)\n if domain is not None:\n try:\n domain = urlparse(domain).hostname or domain\n except ValueError:\n pass\n if '@' in domain:\n _, domain = domain.rsplit('@', 1)\n domain = domain.lower()\n if domain.startswith('www.'):\n domain = domain[len('www.'):]\n domain = domain.strip('.')\n if is_domain(domain):\n return domain\n\n\ndef parse_date(text, guess=True, date_format=None):\n \"\"\"The classic: date parsing, every which way.\"\"\"\n # handle date/datetime before converting to text.\n if isinstance(text, datetime):\n text = text.date()\n if isinstance(text, date):\n return text.isoformat()\n\n text = stringify(text)\n if text is None:\n return\n elif date_format is not None:\n # parse with a specified format\n try:\n obj = datetime.strptime(text, date_format)\n return obj.date().isoformat()\n except:\n pass\n elif guess and not is_partial_date(text):\n # use dateparser to guess the format\n try:\n obj = fuzzy_date_parser(text)\n return obj.date().isoformat()\n except Exception:\n pass\n else:\n # limit to the date part of a presumed date string\n text = text[:10]\n\n # strip -00-00 from dates because it makes ES barf.\n text = CUT_ZEROES.sub('', text)\n\n if is_partial_date(text):\n return text\n\n\ndef fuzzy_date_parser(text):\n \"\"\"Thin wrapper around ``parsedatetime`` module.\n\n Since there's no upstream suppport for multiple locales, this wrapper\n exists.\n\n :param str text: Text to parse.\n :returns: A parsed date/time object. Raises exception on failure.\n :rtype: datetime\n \"\"\"\n locales = parsedatetime._locales[:]\n\n # Loop through all the locales and try to parse successfully our string\n for locale in locales:\n const = parsedatetime.Constants(locale)\n const.re_option += re.UNICODE\n parser = parsedatetime.Calendar(const)\n try:\n parsed, ok = parser.parse(text)\n except:\n continue\n\n if ok:\n return datetime(*parsed[:6])\n\n raise Exception('Failed to parse the string.')\n","sub_path":"aleph/data/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":4809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"508257259","text":"#\n# @lc app=leetcode.cn id=557 lang=python3\n#\n# [557] 反转字符串中的单词 III\n#\n\n# @lc code=start\nclass Solution:\n def reverseWords(self, s: str) -> str:\n s = s.split()\n res= [''.join(reversed(item)) for item in s]\n return ' '.join(res)\n \n# @lc code=end\n\n","sub_path":"Week_09/557.反转字符串中的单词-iii.py","file_name":"557.反转字符串中的单词-iii.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"362765849","text":"\"\"\"The Game of Hog.\"\"\"\n\nfrom dice import four_sided, six_sided, make_test_dice\nfrom ucb import main, trace, log_current_line, interact\n\nGOAL_SCORE = 100 # The goal of Hog is to score 100 points.\n\n######################\n# Phase 1: Simulator #\n######################\n\ndef roll_dice(num_rolls, dice=six_sided):\n \"\"\"Roll DICE for NUM_ROLLS times. Return either the sum of the outcomes,\n or 1 if a 1 is rolled (Pig out). This calls DICE exactly NUM_ROLLS times.\n\n num_rolls: The number of dice rolls that will be made; at least 1.\n dice: A zero-argument function that returns an integer outcome.\n \"\"\"\n # These assert statements ensure that num_rolls is a positive integer.\n assert type(num_rolls) == int, 'num_rolls must be an integer.'\n assert num_rolls > 0, 'Must roll at least once.'\n \n counter = 1 # We begin the counter of how many rolls at one\n total = 0 # This is the sum of all rolls that don't give a one.\n one_indicator = 0 # This increments by one each time a one is rolled.\n while counter<=num_rolls: # This will give us exactly num_rolls amount of rolls. \n a = dice()\n if a == 1:\n one_indicator = one_indicator + 1\n else:\n total = total + a # If the roll is not one, it is summed into the total.\n counter = counter + 1 # we increment to get to the next roll. \n \n if one_indicator>0:\n return 1 # If we rolled at least one one then we Pig Out.\n else:\n return total # If no ones were rolled then we return the sum of the outcomes.\n\n \ndef take_turn(num_rolls, opponent_score, dice=six_sided):\n \"\"\"Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free bacon).\n\n num_rolls: The number of dice rolls that will be made.\n opponent_score: The total score of the opponent.\n dice: A function of no args that returns an integer outcome.\n \"\"\"\n assert type(num_rolls) == int, 'num_rolls must be an integer.'\n assert num_rolls >= 0, 'Cannot roll a negative number of dice.'\n assert num_rolls <= 10, 'Cannot roll more than 10 dice.'\n assert opponent_score < 100, 'The game should be over.'\n if num_rolls == 0: # if zero dice are chosen to be rolled we implement Free Bacon.\n if opponent_score<10: # opponent_score is a single digit and equals abs of diff of its digit with zero.\n return opponent_score + 1\n else: #This means opponent_score is in the double digits. We need mod arithmetic to find the place values.\n return abs(opponent_score//10-opponent_score%10) + 1\n else: # num_rolls is from 1 to 10 and we call on roll_dice()\n return roll_dice(num_rolls,dice)\n\n\ndef select_dice(score, opponent_score):\n \"\"\"Select six-sided dice unless the sum of SCORE and OPPONENT_SCORE is a\n multiple of 7, in which case select four-sided dice (Hog wild).\n \"\"\"\n if (score + opponent_score) % 7 == 0: # When the sum of both players' score is a multiple of 7, the current player is assigned a four sided dice.\n return four_sided\n else: # If the sum is not a multiple of 7, the current player is assigned a six sided dice.\n return six_sided\n\ndef bid_for_start(bid0, bid1, goal=GOAL_SCORE):\n \"\"\"Given the bids BID0 and BID1 of each player, returns three values:\n\n - the starting score of player 0\n - the starting score of player 1\n - the number of the player who rolls first (0 or 1)\n \"\"\"\n assert bid0 >= 0 and bid1 >= 0, \"Bids should be non-negative!\"\n assert type(bid0) == int and type(bid1) == int, \"Bids should be integers!\"\n\n # The buggy code is below:\n if bid0 == bid1: # This is the case when both players' bid is the same.\n return goal, goal, 0\n if bid0 == bid1 - 5: # This is the case when first player's bid is 5 more than the second player's bid.\n return 0, 10, 1\n if bid0 == bid1 + 5: # This is the case when first player's bid is 5 less than the second player's bid. \n return 10, 0, 0\n if bid1 > bid0: # This is the case when second player's bid is greater than the first player's bid. \n return bid1, bid0, 1\n else: # This is the case when first player's bid is greater than the second player's bid.\n return bid1, bid0, 0\n\ndef swine_swap(score,opponent_score): # This is a function I wrote that will switch players' scores at the end of a turn if either score is double the other.\n if score == 2*opponent_score or opponent_score == 2*score: # When one of the players' score is half the other players' score, we switch both scores.\n return opponent_score, score\n else:\n return score, opponent_score\n\ndef other(who):\n \"\"\"Return the other player, for a player WHO numbered 0 or 1.\n\n >>> other(0)\n 1\n >>> other(1)\n 0\n \"\"\"\n return 1 - who\n\ndef play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE):\n \"\"\"Simulate a game and return the final scores of both players, with\n Player 0's score first, and Player 1's score second.\n\n A strategy is a function that takes two total scores as arguments\n (the current player's score, and the opponent's score), and returns a\n number of dice that the current player will roll this turn.\n\n strategy0: The strategy function for Player 0, who plays first\n strategy1: The strategy function for Player 1, who plays second\n score0 : The starting score for Player 0\n score1 : The starting score for Player 1\n \"\"\"\n who = 0 # Which player is about to take a turn, 0 (first) or 1 (second)\n while score0 >> strategy = always_roll(5)\n >>> strategy(0, 0)\n 5\n >>> strategy(99, 99)\n 5\n \"\"\"\n def strategy(score, opponent_score):\n return n\n return strategy\n\n# Experiments\n\ndef make_averaged(fn, num_samples=1000):\n \"\"\"Return a function that returns the average_value of FN when called.\n\n To implement this function, you will have to use *args syntax, a new Python\n feature introduced in this project. See the project description.\n\n >>> dice = make_test_dice(3, 1, 5, 6)\n >>> averaged_dice = make_averaged(dice, 1000)\n >>> averaged_dice()\n 3.75\n >>> make_averaged(roll_dice, 1000)(2, dice)\n 6.0\n\n In this last example, two different turn scenarios are averaged.\n - In the first, the player rolls a 3 then a 1, receiving a score of 1.\n - In the other, the player rolls a 5 and 6, scoring 11.\n Thus, the average value is 6.0.\n \"\"\"\n def fn_num_samps(*args): # This is the nested function that will be returned\n counter = 1 # This is our counter to run through num_samples\n sum = 0 # This creates the sum that we will update through each loop.\n while counter<=num_samples: # We loop through num_samples amount of times.\n sum = sum + fn(*args) # Adds one more application of fb on the arguments to the sum.\n counter = counter + 1 # We increment our counter by one to move on to the next sample.\n return sum/num_samples # Returns the average of summing of fn on the arguments an num_samples amount of times.\n return fn_num_samps\n\ndef max_scoring_num_rolls(dice=six_sided):\n \"\"\"Return the number of dice (1 to 10) that gives the highest average turn\n score by calling roll_dice with the provided DICE. Assume that dice always\n return positive outcomes.\n\n >>> dice = make_test_dice(3)\n >>> max_scoring_num_rolls(dice)\n 10\n \"\"\"\n current_dice = 10 # We start with ten rolls and work down to one roll.\n highest_outcome = 0 # We will never be able to roll this low, so this is a great start place.\n while current_dice>=1: # We start with 10 dice loop through each amouunt of dice up through rolling only one dice.\n a = make_averaged(roll_dice)(current_dice,dice) # This finds the average outcome of rolling current_dice number of dice.\n if a>=highest_outcome: # If the average is greater than or equal to the previous current_dice number's average, then it becomes the new average.\n ideal_dice = current_dice # Sets the ideal_dice to current_dice if the number of dice rolled gives the lowest \n highest_outcome = a # Sets highest_outcome to a if a is now the greatest outcome calculated thus far.\n current_dice = current_dice-1 # Decrements our dice count so we can loop through 10 dice to 1 dice. \n return ideal_dice # Returns the number of dice that gives the highest average outcome. In the case of a tie, it will return the lowest number of dice. \n\ndef winner(strategy0, strategy1):\n \"\"\"Return 0 if strategy0 wins against strategy1, and 1 otherwise.\"\"\"\n score0, score1 = play(strategy0, strategy1)\n if score0 > score1:\n return 0\n else:\n return 1\n\ndef average_win_rate(strategy, baseline=always_roll(5)):\n \"\"\"Return the average win rate (0 to 1) of STRATEGY against BASELINE.\"\"\"\n win_rate_as_player_0 = 1 - make_averaged(winner,10000)(strategy, baseline)\n win_rate_as_player_1 = make_averaged(winner,10000)(baseline, strategy)\n return (win_rate_as_player_0 + win_rate_as_player_1) / 2 # Average results\n\ndef run_experiments():\n \"\"\"Run a series of strategy experiments and report results.\"\"\"\n if False: # Change to False when done finding max_scoring_num_rolls\n six_sided_max = max_scoring_num_rolls(six_sided)\n print('Max scoring num rolls for six-sided dice:', six_sided_max)\n four_sided_max = max_scoring_num_rolls(four_sided)\n print('Max scoring num rolls for four-sided dice:', four_sided_max)\n\n if False: # Change to True to test always_roll(8)\n print('always_roll(8) win rate:', average_win_rate(always_roll(8)))\n\n if False: # Change to True to test bacon_strategy\n print('bacon_strategy win rate:', average_win_rate(bacon_strategy))\n\n if False: # Change to True to test swap_strategy\n print('swap_strategy win rate:', average_win_rate(swap_strategy))\n\n if True: # Change to True to test final_strategy\n print('final_strategy win rate:', average_win_rate(final_strategy))\n\n \"*** You may add additional experiments as you wish ***\"\n\n# Strategies\n\ndef bacon_strategy(score, opponent_score, margin=8, num_rolls=5):\n \"\"\"This strategy rolls 0 dice if that gives at least MARGIN points,\n and rolls NUM_ROLLS otherwise.\n \"\"\"\n a = abs(opponent_score%10 - opponent_score//10) + 1 # This is the absolute value of the difference of the digts of the opponent's score.\n if a >= margin: # Checks if rolling zero dice gives at least margin amount of points.\n return 0 \n else: # If rolling 0 does not give at least marginal amount of points, then we roll num_rolls.\n return num_rolls\n \n\n\ndef swap_strategy(score, opponent_score, margin=8, num_rolls=5):\n \"\"\"This strategy rolls 0 dice when it would result in a beneficial swap and\n rolls NUM_ROLLS if it would result in a harmful swap. It also rolls\n 0 dice if that gives at least MARGIN points and rolls\n NUM_ROLLS otherwise.\n \"\"\"\n a = abs(opponent_score%10 - opponent_score//10) + 1 # This is the absolute value of the difference of the digts of the opponent's score.\n if 2*(score+a) == opponent_score: # Your score will be half your opponent's score\n return 0\n elif (score + a) == 2*opponent_score: # Your score will be double your opponent's score\n return num_rolls\n elif a>=margin: # Your score will not be half or double your opponent's score, but is equal to or greater than the margin.\n return 0\n else: # If none of the three cases above are satisifed.\n return num_rolls\n\n\ndef final_strategy(score, opponent_score):\n \"\"\"Write a brief description of your final strategy.\n\n The first thing this strategy checks for is if we are close to winning. If we are close, then we play very conservatively and defensively to avoid getting swine swapped.\n Next thing is, if we are some what close to winning, then we play a little less conservatively yet still defensively to get into the 'end game' phase of our strategy.\n After that, we check to get a beneficial Swine Swap if we are signinficantly behind or prevent a harmful Swine Swap if we are signinficantly ahead. If we are not too\n behind or not too ahead, then we simply roll the max_scoring_num_rolls amount of dice. (max_scoring_num_rolls is 4 for four sided dice, and 6 for six sided dice.)\n Next thing we check is if an outcome of 1 will let us Hog Wild our opponent. We do so only if we are signinficantly ahead. If we are not too ahead or are behind at all,\n then we roll the max_scoring_num_rolls amount of dice.\n Next thing is if we are really ahead, and we can Hog Wild our opponent with an outcome of Free Bacon, then we do so. Afterwards, we check if we can Hog Wild them with\n just an outcome of 1, in which case we roll 10 dice.\n Lastly, we have our default case where we roll 4 dice if we have a four sided dice, and we roll 6 dice if we have a six sided dice.\n\n \"\"\"\n\n\n a = opponent_score*2 - score # This is the score that when added to your score, will make your new score double your opponent's score. In other words, adding 'a' to your score will cause a harmful swine swap.\n dice = select_dice(score,opponent_score) # This calls on the select_dice function to tell you if you are rolling a four sided dice or a six sided dice.\n hog_wild_remainder = (score+opponent_score)%7 # This is the remainder when 7 is divided into the sum of both players' score. It's used to check if we want to Hog Wild our opponent.\n bacon_value = abs(opponent_score%10 - opponent_score//10)+1 # This is how many points you will score if you apply Free Bacon.\n diff_scores = score - opponent_score # This is the difference between your score and the opponent's score.\n \n \n if score>=90 and dice == six_sided: # First off, is your score is at least 90, your only concern is to finish the game while avoiding getting harmfully swine swapped.\n if bacon_value+score == 2* opponent_score: # This is the case when Free Bacon will make your score become double the opponent's and cause a harmful swine swap.\n return swap_strategy(score,opponent_score,8,2) # Calling swap_strategy will avoid getting a harmful swine swap and will roll a conservative number of dice.\n else: # This is the case when Free Bacon will not lead to a harmful swine swap.\n return bacon_strategy(score,opponent_score,8,2) # We call on bacon_strategy to see if Free Bacon will get us very close to 100, or if we call on a conservative number of dice.\n return bacon_strategy(score,opponent_score,8,2)\n elif score>=90 and dice == four_sided: # The same logic applies here and for the next four lines below as above for the six sided dice case.\n if bacon_value+score == 2* opponent_score:\n return swap_strategy(score,opponent_score,8,2) \n else:\n return bacon_strategy(score,opponent_score,8,2)\n \n \n elif score>=80 and dice == six_sided: # If your score is at least 80, but not at least 90, then you want to play with a few more dice to get to the 'at least 90' range.\n return bacon_strategy(score,opponent_score,8,6) # We apply Bacon Strategy if Free Bacon gives us at least 8 points. Otherwise, we roll six dice.\n elif score>=80 and dice == four_sided: # Same as above, we're trying to get into the 'at least 90' range. \n return bacon_strategy(score,opponent_score,8,4) # We apply Bacon Strategy if Free Bacon gives us at least 8 points. Otherwise, we roll four dice. \n \n \n elif 1<=a and a<=10 and diff_scores>=15 and dice == six_sided: # If a harmful swine swap is possibly given by Free Bacon and your score is signficantly greater than your opponent's score, then we use swap_strategy to avoid getting swine swapped.\n return swap_strategy(score,opponent_score,11,6)\n elif 1<=a and a<=10 and diff_scores>=15 and dice == four_sided: # This is the same as above except for a four sided dice.\n return swap_strategy(score,opponent_score,11,4)\n elif 1<=a and a<=10 and diff_scores<15 and dice == six_sided: # If a swine swap is possible, but your score is close to your opponent's score, then it is more beneficial to just roll the max_num_rolls amount of dice.\n return 6\n elif 1<=a and a<=10 and diff_scores<15 and dice == four_sided: # This is teh same as above except for a four sided dice.\n return 4 \n \n \n elif score == opponent_score/2-1 and diff_scores>-15 and dice == six_sided: # If an outcome of 1 will get you a beneficial swine swap, but you are not significantly behind, then we just roll the max_num_rolls amount of dice.\n return 6\n elif score == opponent_score/2-1 and diff_scores>-15 and dice == four_sided: # This is the same as above excepet for a four sided dice.\n return 4\n elif score == opponent_score/2-1 and diff_scores<=-15 and dice == six_sided: # If an outcome of 1 will get you a beneficial swine swap, and you are significantly behind, then we apply swap_strategy to see if Free Bacon works or if we should roll 10 dice.\n return swap_strategy(score,opponent_score,11,10) \n elif score == opponent_score/2-1 and diff_scores<=-15 and dice == four_sided: # This is the same as above except for a four sided dice.\n return swap_strategy(score,opponent_score,11,10)\n \n\n elif diff_scores>=40 and hog_wild_remainder == bacon_value: # If you are significantly ahead, and there's a chance to Hog Wild your opponent with Free Bacon, then roll 0.\n return 0\n elif diff_scores>=40 and hog_wild_remainder == 1: # If you are significantly ahead, and you need a 1 to Hog Wld your opponent, but Free Bacon will not give you a 1, then roll 10 dice.\n return 10\n \n\n elif dice == four_sided: # If none of the cases above are satisifed and you have a four sided dice, then roll 4 dice by default. \n return 4\n else: # If none of the cases above are satisified and you have a six sided dice, then roll 6 dice by default.\n return 6\n\n\n##########################\n# Command Line Interface #\n##########################\n\n# Note: Functions in this section do not need to be changed. They use features\n# of Python not yet covered in the course.\n\n\n@main\ndef run(*args):\n \"\"\"Read in the command-line argument and calls corresponding functions.\n\n This function uses Python syntax/techniques not yet covered in this course.\n \"\"\"\n import argparse\n parser = argparse.ArgumentParser(description=\"Play Hog\")\n parser.add_argument('--run_experiments', '-r', action='store_true',\n help='Runs strategy experiments')\n args = parser.parse_args()\n\n if args.run_experiments:\n run_experiments()\n","sub_path":"hog.py","file_name":"hog.py","file_ext":"py","file_size_in_byte":20295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"426261194","text":"from KernelNN import Layer\nfrom kernel_functions import RBF\nfrom sklearn.datasets import fetch_mldata\n\nimport matplotlib.pyplot as plt\n\nrbf_kernel = RBF(theta=1)\n\nmnist = fetch_mldata('MNIST original')\ndata = mnist.data.reshape(-1, 28, 28, 1) / 255\ninputs = dict()\nfor i in range(10):\n inputs[i] = data[mnist.target == i]\n\nimg = inputs[5][100]\n\nL1 = Layer(input_shape=[28, 28, 1], kernel_shape=[3, 3], kernel_func=rbf_kernel,\n node_thr=0.5, name=\"l1\")\n\nL1.init_kernel(img)\nfor j in range(10):\n for i in range(11):\n L1.train(inputs[j][i])\n if i % 5 == 0:\n L1.remove_node()\n L1.remove_edge()\n L1.plot_kernels()\n L1.add_node()\n\n\nfor i in range(10):\n L1.run(inputs[i][0])\n L1.plot_output()\n\ndef plot(img):\n plt.imshow(img[:, :, 0], interpolation='nearest', cmap=plt.cm.gray)\n plt.tick_params(axis=\"both\", which=\"both\",\n top=\"off\", bottom=\"off\", left=\"off\", right=\"off\",\n labelbottom=\"off\", labelleft=\"off\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"293835565","text":"#coding=utf-8\nfrom numpy import *\nfrom sklearn import svm\n\ndef svm_clas(train,test,label):\n classifier = svm.SVC(kernel='linear', C=0.01)\n classifier.fit(train, label)\n data_out=classifier.predict(test)\n return data_out\n\n","sub_path":"SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"540655075","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 23 15:15:59 2017\nProblem 3_7:\nWrite a function that would read a CSV file that looks like this, flowers.csv:\n\npetunia,5.95\nalyssum,3.95\nbegonia,5.95\nsunflower,5.95\ncoelius,4.95\n\nand look up the price of a flower and print out that price. Remember to import\nthe necessary library.\n\nHere is my run on the above CSV file:\nproblem3_7(\"flowers.csv\",\"alyssum\")\n3.95\n@author: DouglasHartman\n\"\"\"\n\n\ndef problem3_7(csv_pricefile, flower):\n import csv\n fin = open(csv_pricefile)\n# print(\"\\n\", csv_pricefile, \"\\n\")\n for row in csv.reader(fin):\n # print(row)\n if row[0] == flower:\n # print(\"Found Flower {} {}\".format(flower, row[1]))\n print(\"{}\".format(row[1]))\n fin.close()\n","sub_path":"All/problem3_7.py","file_name":"problem3_7.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"500853939","text":"import matplotlib.pylab as plt\nimport matplotlib.pyplot\nfrom matplotlib.font_manager import FontProperties\nfrom matplotlib.ticker import ScalarFormatter\nfrom matplotlib.ticker import FixedFormatter\nimport pylab as pl\nimport numpy as np\nimport math, os\nimport glob, pickle\n\nformatter = ScalarFormatter(useMathText=True)\n#formatter.set_scientific(True)\n#formatter.set_powerlimits((-3,3))\n\nfig_width_pt = 246.0*2 # Get this from LaTex using \\the\\columnwidth\ninches_per_pt = 1.0/72.27\ngolden_mean = (np.sqrt(5)-1.0)/2.0\nfig_width = fig_width_pt*inches_per_pt # width in inches\nfig_height = fig_width*golden_mean # height in inches\nfig_size = [fig_width, fig_height]\nparams = {'axes.labelsize':10,\n 'text.fontsize':8,\n 'legend.fontsize':8,\n 'xtick.labelsize':8.5,\n 'ytick.labelsize':5.5,\n 'figure.figsize':fig_size,\n 'font.family': 'serif'}\n\npl.rcParams.update(params)\npl.clf()\npl.figure()\nfig = pl.figure()\naxes = pl.Axes(fig, [.2, .2, .7, .7])\nfig.add_axes(axes)\naxes.yaxis.set_major_formatter(formatter)\n\nfor i in xrange(1, 10, 1):\n data = np.loadtxt('/disk1/mjw/HOD_MockRun/Data/Multipoles/Multipoles_zCube_xvel_clipThreshold_1.0e+03_fullCube_BootStrap_kbin_0.010_00'+str(i)+'.dat')\n pl.loglog(data[:,0], data[:,1])\n\nfor i in xrange(10, 40, 1):\n data = np.loadtxt('/disk1/mjw/HOD_MockRun/Data/Multipoles/Multipoles_zCube_xvel_clipThreshold_1.0e+03_fullCube_BootStrap_kbin_0.010_0'+str(i)+'.dat')\n pl.loglog(data[:,0], data[:,1])\n \nfor i in xrange(1, 10, 1):\n data = np.loadtxt('/disk1/mjw/HOD_MockRun/Data/Multipoles/Multipoles_zCube_xvel_clipThreshold_1.0e+03_fullCube_BootStrap_kbin_0.010_00'+str(i)+'.dat')\n pl.loglog(data[:,0], data[:,2], '--')\n\nfor i in xrange(10, 40, 1):\n data = np.loadtxt('/disk1/mjw/HOD_MockRun/Data/Multipoles/Multipoles_zCube_xvel_clipThreshold_1.0e+03_fullCube_BootStrap_kbin_0.010_0'+str(i)+'.dat')\n pl.loglog(data[:,0], data[:,2], '--')\n\npl.xlabel(r'$k [h^{-1} Mpc]$')\npl.ylabel('P(k)')\n\npl.yscale('log')\npl.xscale('log')\n\npl.xlim(10**-2, 1.0)\npl.ylim(100, 5*10**4)\n\n#pl.clf()\n\npl.savefig('/disk1/mjw/HOD_MockRun/Plots/Pk_BootStrap.pdf')\n","sub_path":"Other/Plotting/VIPERS_PkBootStrap.py","file_name":"VIPERS_PkBootStrap.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"642754256","text":"# https://news.naver.com\n# data/naver_most_news.html\n#가장 많이 본 뉴스 추출\n#정치, 경제 ...\n\nimport sys\nimport re\n\nfrom urllib.request import urlopen\nfrom html import unescape\n\n# url = 'https://news.naver.com/'\n# f = urlopen(url)\n# encode = f.info().get_content_charset()\n# text = f.read().decode(encode)\n\n# with open('data/naver_most_news.html', 'w', encoding=encode) as f:\n# f.write(text)\n\nwith open('data/naver_most_news.html', 'r', encoding='euc-kr') as f:\n html = f.read()\n\n# #뉴스 제목\nfor part_html in re.findall(\n r'', html, re.DOTALL):\n\n title = re.sub(r'<.*?>', '', part_html)\n title = re.sub(r'"', '\"', title)\n title = re.sub(r'·', '·', title)\n title = re.sub(r'\\s{2}', ' ', title)\n title = re.sub(r'\\s{3,}', '\\r\\n', title)\n\n print(title)\n\n","sub_path":"py1809/hello_urllib/hello_urllib09.py","file_name":"hello_urllib09.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"42784621","text":"\"\"\"\nbioBakery Workflows: utilities module\nUtility functions for workflows and tasks\n\nCopyright (c) 2016 Harvard School of Public Health\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\nall copies 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\nTHE SOFTWARE.\n\"\"\"\n\nimport os\nimport sys\nimport math\nimport functools\nimport time\nimport collections\n\nfrom anadama2.tracked import TrackedDirectory\n\n# try to import urllib.request.urlretrieve for python3\ntry:\n from urllib.request import urlretrieve\nexcept ImportError:\n from urllib import urlretrieve\n\ndef get_package_file(basename, type=\"template\"):\n \"\"\" Get the full path to a file included in the installed python package.\n\n Args:\n basename (string) : The basename of the file\n type (string) : The type of file to find (template or Rscript)\n\n Returns: \n string : The full path to the file\n\n \"\"\"\n\n if type == \"template\":\n subfolder = \"document_templates\"\n extension = \".template.py\"\n else:\n subfolder = \"Rscripts\"\n extension = \".R\"\n\n # get all of the templates in this folder\n package_install_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), subfolder)\n found_files=filter(lambda file: file.endswith(extension),os.listdir(package_install_folder))\n\n # return the template with the name\n matching_file=list(filter(lambda file: file.startswith(basename+extension), found_files))\n\n if matching_file:\n matching_file=os.path.join(package_install_folder,matching_file[0])\n else:\n matching_file=\"\"\n\n return matching_file\n \n\n\ndef change_pweave_figure_size_heatmap(pdf_format):\n \"\"\" Change the figure size for heatmaps based on the output format\"\"\"\n fig_size = (4,4) if pdf_format else (2.5,2.5)\n change_pweave_figure_size(fig_size)\n \ndef reset_pweave_figure_size():\n \"\"\" Set the pweave figure size back to the default \"\"\"\n change_pweave_figure_size((8,6))\n \ndef change_pweave_figure_size(fig_size):\n \"\"\" Change the pweave default figure size \"\"\"\n import pweave\n pweave.rcParams[\"chunk\"][\"defaultoptions\"].update({'f_size': fig_size})\n\ndef byte_to_megabyte(byte):\n \"\"\"\n Convert byte value to megabyte\n \"\"\"\n \n return byte / (1024.0**2)\n\nclass ReportHook():\n def __init__(self):\n self.start_time=time.time()\n \n def report(self, blocknum, block_size, total_size):\n \"\"\"\n Print download progress message\n \"\"\"\n \n if blocknum == 0:\n self.start_time=time.time()\n if total_size > 0:\n print(\"Downloading file of size: \" + \"{:.2f}\".format(byte_to_megabyte(total_size)) + \" MB\\n\")\n else:\n total_downloaded=blocknum*block_size\n status = \"{:3.2f} MB \".format(byte_to_megabyte(total_downloaded))\n \n if total_size > 0:\n percent_downloaded=total_downloaded * 100.0 / total_size\n # use carriage return plus sys.stdout to overwrite stdout\n try:\n download_rate=total_downloaded/(time.time()-self.start_time)\n estimated_time=(total_size-total_downloaded)/download_rate\n except ZeroDivisionError:\n download_rate=0\n estimated_time=0\n estimated_minutes=int(estimated_time/60.0)\n estimated_seconds=estimated_time-estimated_minutes*60.0\n status +=\"{:3.2f}\".format(percent_downloaded) + \" % \" + \\\n \"{:5.2f}\".format(byte_to_megabyte(download_rate)) + \" MB/sec \" + \\\n \"{:2.0f}\".format(estimated_minutes) + \" min \" + \\\n \"{:2.0f}\".format(estimated_seconds) + \" sec \"\n status+=\" \\r\"\n sys.stdout.write(status)\n\ndef read_file_n_lines(file,n):\n \"\"\" Read a file n lines at a time \"\"\"\n\n line_set=[]\n with open(file) as file_handle:\n for line in file_handle:\n if len(line_set) == n:\n yield line_set\n line_set=[]\n line_set.append(line)\n\n # yield the last set\n if len(line_set) == n:\n yield line_set\n \ndef read_file_catch(file, delimiter=\"\\t\"):\n \"\"\" Try to read the file, catch on error. Split data by delimiter. \"\"\"\n \n try:\n handle=open(file)\n lines=handle.readlines()\n handle.close()\n except EnvironmentError:\n sys.exit(\"Error: Unable to read file: \"+file)\n \n # split rows by delimiter\n new_lines=[line.rstrip().split(delimiter) for line in lines] \n \n return new_lines\n \ndef read_metadata(metadata_file, taxonomy_file, name_addition=\"\", ignore_features=[], otu_table=False):\n \"\"\" Read in the metadata file. Samples can be rows or columns.\n Ignore features if set. \n \n Args:\n metadata_file (string): The path to the metadata file.\n taxonomy_file (string): The path to a taxonomy file (or any file with\n the sample names as the column names).\n name_addition (string): Any strings that should be removed from the\n names in the taxonomy files to get the sample names.\n ignore_features (list): A list of strings of features to ignore\n when reading the metadata file.\n otu_table (bool): Set if otu table is used for taxonomy to allow for different\n header format.\n \n Returns:\n (list): A list of lists of the metadata (samples as columns)\n \"\"\"\n \n # read in a taxonomy file to get the sample names from the columns\n if otu_table:\n samples=set([name.replace(name_addition,\"\") for name in read_file_catch(taxonomy_file)[0][1:-1]])\n else:\n samples=set([name.replace(name_addition,\"\") for name in read_file_catch(taxonomy_file)[0][1:]])\n \n # read in the metadata file\n data=read_file_catch(metadata_file)\n # check if the columns or rows are samples\n possible_samples=data[0][1:]\n overlap=samples.intersection(possible_samples)\n if len(list(overlap)) == 0:\n # the samples must be the rows so invert the data\n data=[list(a) for a in zip(*data)]\n possible_samples=data[0][1:]\n overlap=samples.intersection(possible_samples)\n \n # check for samples not included in metadata\n if len(list(overlap)) < len(list(samples)):\n sys.exit(\"ERROR: Not all of the samples in the data set have\"+\n \" metadata. Please review the metadata file. The following samples\"+\n \" were not found: \"+\",\".join(list(samples.difference(possible_samples))))\n\n # remove any features that should be ignored\n new_data=[]\n for row in data:\n if not row[0] in ignore_features:\n new_data.append(row)\n else:\n ignore_features.remove(row[0])\n\n # check for any features that do not vary\n check_diff = {}\n for row in new_data[1:]:\n for value in row[1:]:\n if not row[0] in check_diff:\n check_diff[row[0]]=[]\n check_diff[row[0]]=check_diff[row[0]]+[value]\n\n for feature_name, feature_types in check_diff.items():\n if len(list(set(feature_types))) == 1:\n sys.exit(\"ERROR: Please remove feature '\"+feature_name+\"' as it\"+\n \" only includes a single type of '\"+feature_types[0]+\"'.\")\n\n # check for any features that were not found\n if ignore_features:\n sys.exit(\"ERROR: Unable to find features that should be ignored: \"+\n \",\".join(ignore_features))\n \n return new_data\n\ndef label_metadata(data, categorical=[], continuous=[]):\n \"\"\" Label the metadata type. All numerical is continous.\n \n Args:\n data (lists of lists): A list of metadata \n categorical (list): A list of categorical features.\n continuous (list): A list of continuous features.\n \n Returns:\n (dict): A dictionary of metadata labels\n (list): A list of lists of the metadata (converted to floats if continuous)\n \"\"\"\n \n # add labels to the metadata, ignore sample names, convert to nan misisng values if continuous\n missing = [\"Unknown\", \"unknown\", \"NA\", \"na\", \"nan\", \"NaN\", \"NAN\", \" \"]\n labeled_data=[data[0]]\n labels={}\n for row in data[1:]:\n # check if there are missing values in row, convert to nan\n for index, item in enumerate(row):\n if item in missing or item == \"\":\n row[index] = \"nan\"\n # apply specific labels if set\n label=None\n if row[0] in continuous:\n try:\n row[1:] = map(float, row[1:])\n label=\"con\"\n except ValueError:\n label=\"cat\"\n continuous.remove(row[0])\n if row[0] in categorical:\n label=\"cat\"\n categorical.remove(row[0])\n if not label:\n try:\n row[1:] = map(float, row[1:])\n label=\"con\"\n except ValueError:\n label=\"cat\"\n if label == \"cat\":\n # if label is categorical convert misisng values to Unknown\n for index, item in enumerate(row):\n if item == \"nan\":\n row[index] = \"NA\"\n labeled_data.append(row)\n labels[row[0]]=label\n \n # check for remaining labels\n if categorical:\n sys.exit(\"ERROR: Unable to find and label categorical feature in metadata: \"+\n \",\".join(categorical))\n if continuous:\n sys.exit(\"ERROR: Unable to find and label continuous feature in metadata: \"+\n \",\".join(continuous))\n \n return labels, labeled_data\n\ndef filter_metadata_categorical(metadata, metadata_labels):\n \"\"\" Return only the metadata that is categorical \n \n Args:\n metadata (lists of lists): A list of metadata.\n metadata_labels (dict): The labels for the metadata.\n \n Returns:\n metadata (lists of lists): Only the categorical metadata.\n \"\"\"\n \n new_metadata=[]\n for row in metadata:\n if metadata_labels.get(row[0],\"con\") == \"cat\":\n new_metadata.append(row)\n \n return new_metadata\n\ndef group_samples_by_metadata(metadata, data, samples):\n \"\"\" Return the samples grouped by the metadata. The data and metadata\n should have the same ordering of sample columns.\n \n Args:\n metadata (list): A single metadata list.\n data (list): A single data set.\n samples (list): The samples (corresponding to the columns in the \n data/metadata).\n \n Return:\n data (list of lists): The data organized by the metadata groups.\n \"\"\"\n \n # get the samples for each metadata type\n sorted_samples_grouped={}\n for name, type in zip(samples,metadata[1:]):\n sorted_samples_grouped[type]=sorted_samples_grouped.get(type,[])+[name]\n \n sorted_data_grouped={}\n for row in data:\n sorted_temp={}\n for data_point, type in zip(row, metadata[1:]):\n sorted_temp[type]=sorted_temp.get(type,[])+[data_point]\n \n for key, value in sorted_temp.items():\n if not key in sorted_data_grouped:\n sorted_data_grouped[key]=[]\n sorted_data_grouped[key].append(value)\n \n return sorted_data_grouped, sorted_samples_grouped\n \ndef merge_metadata(metadata, samples, values, values_without_names=None):\n \"\"\" Merge the metadata and values into a single set. Samples are columns. \n\n Args:\n metadata (lists of lists): A list of metadata. \n samples (list): A list of samples that correspond with value columns.\n values (lists of lists): A list of values to merge with the metadata.\n values_without_names (bool): Set if the values do not have row names.\n Returns:\n (list): A list of lists of the merged data.\n (list): A list of the samples (might be a subset based on metadata available).\n \"\"\"\n \n # get the indexes for the samples in the data that match with the metadata\n sample_index=[]\n metadata_index=[]\n samples_found=[]\n for index, name in enumerate(metadata[0][1:]):\n if name in samples:\n samples_found.append(name)\n sample_index.append(samples.index(name))\n metadata_index.append(index)\n \n # warn if no metadata samples match the values samples\n if len(sample_index) == 0:\n print(\"Warning: Metadata does not match samples.\")\n return values, samples\n \n if len(samples) > len(metadata[0][1:]):\n print(\"Warning: Metadata only provided for a subset of samples.\")\n \n # add metadata to the new data\n new_data=[]\n for row in metadata[1:]:\n # add only matching samples\n new_data.append([row[0]]+[row[i+1] for i in metadata_index])\n \n # add abundance values to the new data\n for row in values:\n if values_without_names:\n new_data.append([row[i] for i in sample_index])\n else:\n new_data.append([row[0]]+[row[i+1] for i in sample_index])\n \n return new_data, samples_found\n\ndef download_file(url, download_file):\n \"\"\"\n Download a file from a url\n Create folder for downloaded file if it does not exist\n \"\"\"\n\n create_folders(os.path.dirname(download_file))\n\n try:\n print(\"Downloading \"+url)\n file, headers = urlretrieve(url,download_file,reporthook=ReportHook().report)\n # print final return to start new line of stdout\n print(\"\\n\")\n except EnvironmentError:\n print(\"WARNING: Unable to download \"+url)\n\ndef try_log10(value):\n \"\"\" Try to convert value to log10 \"\"\"\n \n try:\n new_value = math.log10(value)\n except ValueError:\n new_value = 0\n \n return new_value\n\ndef name_task(sample,software):\n \"\"\" Name the task based on the sample name and software \"\"\"\n \n return software+\"____\"+os.path.basename(sample)\n\ndef add_to_list(items,new_item):\n \"\"\" Add the value to the list/tuple. If the item is not a list, create a new\n list from the item and the value \n \n Args:\n items (list, string or tuple): Single or multiple items\n new_item (string): The new value\n \n Returns:\n (list): A list of all values\n \"\"\"\n \n if isinstance(items,tuple):\n items=[i for i in items]\n \n if not isinstance(items,list):\n items=[items]\n \n return items+[new_item]\n\ndef metacyc_url(pathway):\n \"\"\" Return the url for the pathway on the MetaCyc website \n \n Args:\n pathway (string): The MetaCyc pathway\n \n Returns\n (string): The url to the website for the pathway\n \n \"\"\"\n \n return \"http://metacyc.org/META/NEW-IMAGE?type=NIL&object=\"+pathway\n\ndef run_task(command, **keywords):\n \"\"\" Run the task command, formatting command with keywords. The command stdout\n and stderr are written to the workflow log.\n \n Args:\n command (string): A string to execute on the command line. It can be\n formatted the same as a task command.\n \n Returns:\n (int): Return code from command. \n \"\"\"\n\n from anadama2.helpers import format_command\n from anadama2.helpers import sh\n \n # format the command to include the items for this task\n command=format_command(command, **keywords)\n \n # run the command\n return_code = sh(command)()\n \n return return_code\n\ndef partial_function(function, **keywords):\n \"\"\" Return a partial function, setting function name attribute\n \n Args:\n function (function): A function\n keywords: One or more keywords to be applied to the function\n \n Returns:\n (function): A partial function\n \n \"\"\"\n \n partial = functools.partial(function, **keywords)\n partial.__name__ = function.__name__\n \n return partial\n \n\ndef paired_files(files, extension, pair_identifier=None):\n \"\"\" Find sets of paired-end reads\n \n This function will find sets of paired end reads from a list of files.\n \n Args:\n files (list): A list of files (with or without the full paths)\n extension (string): The extension for all files.\n pair_identifier (string): The string in the file basename to identify\n the first pair in the set (optional).\n \n Requires:\n None\n \n Returns:\n list: A list of paired files.\n \n Example:\n paired_set = paired_reads([\"1.R1.fq\", \"1.R2.fq\"],\".fq\")\n \n \"\"\"\n \n # add period to extension if not included\n if not extension.startswith(\".\"):\n extension=\".\"+extension\n \n if pair_identifier is None:\n pair_identifier=\".R1\"\n \n # check for the one in the pair identifier\n if not \"1\" in pair_identifier:\n sys.exit(\"Please provide the identifier for the first pair set (ie R1).\")\n \n pair_identifier2=pair_identifier.replace(\"1\",\"2\",1)\n\n input_pair1 = list(filter(lambda file: os.path.basename(file).replace(extension,\"\").endswith(pair_identifier), files))\n input_pair2 = list(filter(lambda file: os.path.basename(file).replace(extension,\"\").endswith(pair_identifier2), files))\n \n # only return matching pairs of files in the same order\n paired_file_set = [[],[]]\n for file1 in sorted(input_pair1):\n # find the matching file in the second set\n name1=sample_names(file1, extension, pair_identifier)\n for file2 in input_pair2:\n name2=sample_names(file2, extension, pair_identifier2)\n if name1 and name1 == name2:\n paired_file_set[0].append(file1)\n paired_file_set[1].append(file2)\n input_pair2.remove(file2)\n break\n \n return paired_file_set\n\ndef sample_names(files,extension,pair_identifier=None):\n \"\"\" Return the basenames of the files, without any extensions, as the sample names\n \n Args:\n files (list): A list of files (with or without the full paths)\n extension (string): The extension for all files.\n pair_identifier (string): The string in the file basename to identify\n the first pair in the set (optional).\n \n Requires:\n None\n \n Returns:\n list: A list of sample names (file basenames)\n\n Example:\n names = sample_names([\"1.R1.fq\", \"1.R2.fq\"],\".fq\")\n \n \"\"\"\n \n # add period to extension if not included\n if not extension.startswith(\".\"):\n extension=\".\"+extension\n \n # if files is a string, convert to a list\n convert=False\n if isinstance(files,str):\n files=[files]\n convert=True\n \n samples=[os.path.basename(file).replace(extension,\"\") for file in files]\n \n # remove the pair_idenifier from the sample name, if provided\n if pair_identifier:\n # only remove the last instance of the pair identifier\n samples=[pair_identifier.join(sample.split(pair_identifier)[:-1]) if pair_identifier in sample else sample for sample in samples]\n \n if convert:\n samples=samples[0]\n \n return samples\n\ndef find_files(folder, extension=None, exit_if_not_found=None):\n \"\"\" Return the files in the given folder with the extension if provided\n \n Args:\n folder (string): A path to a folder\n extension (string): The file extension to search for (optional)\n exit_if_not_found (bool): Indicator to check if files exist (optional) \n \n Requires:\n None\n \n Returns:\n list: A list of files in the folder\n\n Example:\n files = find_files(\"examples\",\"fastq\")\n \"\"\"\n \n # get all of the files in the folder\n files=[os.path.join(folder,file) for file in os.listdir(folder)]\n files=list(filter(lambda file: os.path.isfile(file),files))\n \n # filter to only files with extension\n if extension:\n files=list(filter(lambda file: file.endswith(extension), files))\n \n if exit_if_not_found:\n if not files:\n message=\"ERROR: No files were found in the folder \" + folder\n if extension:\n message+=\" with extension \"+extension\n sys.exit(message+\" .\\n\")\n \n return files\n\ndef name_files(names, folder, subfolder=None, tag=None, extension=None, create_folder=None):\n \"\"\" Return a list of file names based on the names and folders provided\n \n Args:\n names (list or string): A list of basenames or files.\n folder (string): The path to the folder.\n subfolder (string): The subfolder to use with the files (optional).\n tag (string): The tag to add to the file basenames (optional).\n extension (string): The extension to use for the files (optional).\n create_folder (bool): Create the folder and subfolder if they do not exist (optional).\n\n Requires:\n None\n \n Returns:\n list: A list of file names (or string if input is string).\n \n Example:\n files = name_files([\"file1\",\"file2\"], \"output\")\n \"\"\"\n \n # if names is a list, convert to string\n was_string=False\n if isinstance(names, str):\n was_string=True\n names=[names]\n \n # get the basenames from the files\n names=[os.path.basename(name) for name in names]\n \n # use the full path to the folder\n folder=os.path.abspath(folder)\n \n # get the name of the full folder plus subfolder if provided\n if subfolder:\n folder=os.path.join(folder,subfolder)\n\n # add the extension if provided, and replace existing\n if extension:\n names=[os.path.splitext(name)[0]+\".\"+extension for name in names]\n\n # add the tag to the names, if provided\n if tag:\n names=[os.path.splitext(name)[0]+\"_\"+tag+os.path.splitext(name)[1] for name in names]\n \n files=[os.path.join(folder,name) for name in names]\n \n if create_folder:\n create_folders(os.path.dirname(files[0]))\n \n # if the input was originally a string, convert from list\n if was_string:\n files=files[0]\n \n return files\n\ndef create_folders(folder):\n \"\"\" Create folder if it does not exist\n \n Args:\n folder (string): The full path to the folder.\n \n Requires:\n None\n \n Returns:\n None\n \n Example:\n create_folders(\"new_folder\")\n \"\"\"\n \n try:\n if not os.path.exists(folder):\n os.makedirs(folder)\n except EnvironmentError:\n print(\"Warning: Unable to create folder: \"+ folder)\n \ndef match_files(files1,files2,mapping):\n \"\"\" Match files from two sets using the mapping provided\n \n Args:\n files1 (list): A list of files for set1\n files2 (list): A list of files for set2\n mapping (string): The file with the mapping information. This file\n should be tab delimited. It can have headers starting with \"#\". \n It should have the basenames for the files for set1 and set2 with\n each line as \"fileA\\tfileB\" with fileA in set files1 and fileB in\n set files2.\n \n Requires:\n None\n \n Returns:\n (list): An ordered list of the first set of files\n (list): An ordered list of the second set of files\n The two lists will be the same length with pairs having the same index\n in each list.\n \n Example:\n match_files([\"wts_1.fastq\",\"wts_2.fastq\"],[\"wms_1.tsv\",\"wms_2.tsv\"],\"mapping.tsv\")\n \n mapping.tsv contains:\n # wts wms\n wts_1 wms_1\n wts_2 wms_2\n\n \"\"\"\n \n # read in the mapping file\n set_mappings={}\n try:\n file_handle=open(mapping,\"r\")\n lines=file_handle.readlines()\n file_handle.close() \n except EnvironmentError:\n sys.exit(\"ERROR: Unable to read mapping file: \" + mapping)\n \n for line in lines:\n if not line.startswith(\"#\"):\n data=line.rstrip().split(\"\\t\")\n if len(data) > 1:\n item1=data[0]\n item2=data[1]\n if \".\" in item1 or \".\" in item2:\n sys.exit(\"ERROR: Sample names should not contain file extensions ('.fastq'),\"+\n \"pair identifiers ('.R1.'), or periods ('.') as part of the name.\")\n # check for duplicate mappings\n if item1 in set_mappings:\n print(\"Warning: Duplicate mapping in file: \" + item1)\n set_mappings[item1]=item2\n \n pair1=[]\n pair2=[]\n for item1,item2 in set_mappings.items():\n file1=list(filter(lambda file: os.path.basename(file).startswith(item1),files1))\n file2=list(filter(lambda file: os.path.basename(file).startswith(item2), files2))\n if len(file1) == 1 and len(file2) == 1:\n # check for the pair\n pair1.append(file1[0])\n pair2.append(file2[0])\n elif len(file1) == 0:\n print(\"Warning: Unable to find file with key, \" + item1 + \" in folder \" + os.path.dirname(files1))\n elif len(file2) == 0:\n print(\"Warning: Unable to find file with key, \" + item2 + \" in folder \" + os.path.dirname(files2))\n else:\n print(\"Warning: Duplicate files found for mapping keys: \" + item1 + \" \" + item2)\n\n if len(pair1) != len(files1):\n print(\"Warning: Unable to find matches for all of the files in the set.\")\n \n return pair1, pair2\n\ndef row_average(data):\n \"\"\" Compute the average of each row in a data set\n \n Args:\n data (list of lists): Each list in data represents a row of data. \n \n Requires:\n None\n \n Returns:\n (list): A list of averages, one for each row in the original data.\n \n Example:\n row_average([[1,2,3],[4,5,6]])\n \"\"\" \n \n return [sum(row)/(len(row)*1.0) for row in data]\n\ndef row_variance(data):\n \"\"\" Compute the variance of each row in a data set\n \n Args:\n data (list of lists): Each list in data represents a row of data. \n \n Requires:\n None\n \n Returns:\n (list): A list of variances, one for each row in the original data.\n \n Example:\n row_variance([[1,2,3],[4,5,6]])\n \"\"\"\n \n data_averages=row_average(data)\n data_variances=[]\n for average, row in zip(data_averages,data):\n data_variances.append(sum((i-average)**2 for i in row)/(len(row)*1.0))\n \n return data_variances\n\ndef relative_abundance(data, percent=False):\n \"\"\" Compute the relative abundance values for a set of data \n \n Args:\n data (list of lists): Each list in data represents a row of data. \n percent (bool): Abundance is a percent of 100 (30 for 30% instead of 0.3)\n \n Requires:\n None\n \n Returns:\n (list of lists): Each list in data represents a row of data with relative abundance values.\n \n Example:\n relative_abundance([[1,2,3],[4,5,6]]) \n \"\"\" \n\n # compute the sum for each column\n sums=[0.0]*len(data[0])\n for i in range(len(data[0])):\n for row in data:\n sums[i]+=float(row[i])\n \n relab=[]\n for row in data:\n new_row=[]\n for i, value in enumerate(row):\n try:\n new_value=value/sums[i]\n except ZeroDivisionError:\n new_value=0\n new_row.append(new_value)\n if percent:\n new_row = map(lambda x: x * 100.0, new_row)\n relab.append(new_row)\n \n return relab\n\ndef filter_zero_rows(taxa, data, ignore_index=None):\n \"\"\" Remove any taxa and data rows from the lists if the data sum for a row is zero.\n \n Args:\n taxa (list): The list of taxa.\n data (list of lists): Each list in data represents a row of data.\n ignore_index (int): An index to ignore in each row in computing the sum.\n \n Requires:\n None\n \n Returns:\n (list): A list of labels for the non-zero rows.\n (list of lists): Each list in data represents a row of data that is non-zero. \n \"\"\" \n new_taxa=[]\n new_data=[]\n for taxon, row in zip(taxa, data):\n if ignore_index is not None:\n temp_row = row\n del temp_row[ignore_index]\n row_sum = sum(temp_row)\n else:\n row_sum = sum(row)\n if row_sum != 0:\n new_taxa.append(taxon)\n new_data.append(row)\n \n return new_taxa, new_data\n\ndef taxa_shorten_name(taxa, level, remove_identifier=None):\n \"\"\" Shorten the taxa name by removing the levels indicated (useful for plotting)\n \n Args:\n taxa (list): The list of taxa.\n level (int): The level to filter.\n remove_identifier (bool): If set remove the [k|p|c|r|f|g|s|t__]) from the name. \n \n Requires:\n None\n \n Returns:\n (list): The list of taxa after removing the unclassified names. \n \"\"\" \n\n new_names=[]\n for taxon in taxa:\n name=taxon.split(\";\")[level]\n if remove_identifier:\n name=name.split(\"__\")[-1]\n new_names.append(name)\n \n return new_names\n\ndef top_rows(row_labels, data, max_sets, function):\n \"\"\" Get the top rows in the data based on the metric provided \n \n Args:\n row_labels (list): A list of labels for each row.\n data (list of lists): Each list in data represents a row of data. \n max_sets (int): Total number of top rows to return.\n function (string): The function to run to get the top values (average or variance)\n \n Requires:\n None\n \n Returns:\n (list): A list of labels for the top rows.\n (list of lists): Each list in data represents a row of data for the top data.\n \n Example:\n top_rows([\"row1\",\"row2\"],[[1,2,3],[4,5,6]],1)\n \"\"\"\n \n # get the data after applying the metric function\n if function == \"variance\":\n stats_data=row_variance(data)\n else:\n stats_data=row_average(data)\n \n # sort the numbers by decreasing order\n sorted_indexes=sorted(range(len(stats_data)),key=lambda i: stats_data[i],reverse=True)\n \n # reduce max sets if the number of rows is less than max sets\n if len(row_labels) < max_sets:\n max_sets = len(row_labels)\n \n top_labels=[]\n top_data=[]\n for i in range(max_sets):\n top_labels.append(row_labels[sorted_indexes[i]])\n top_data.append(data[sorted_indexes[i]])\n \n return top_labels, top_data\n\ndef remove_stratified_pathways(pathways, data, remove_description=None):\n \"\"\" Remove the stratified pathways from the data set.\n Also remove the unintegrated and unmapped values. Remove the descriptions\n from the pathway names if set.\n \n Args:\n pathways (list): A list of pathway names for each row.\n data (list of lists): Each list in data represents a row of data. \n remove_description (bool): If set, remove the pathway description\n from the names returned.\n \n Requires:\n None\n \n Returns:\n (list): A list of pathway names.\n (list): A list of lists of the data.\n \n Example:\n remove_stratified_pathways([\"pwy1\",\"pwy1|bug1\"],[[1,2,3],[4,5,6]])\n \"\"\"\n \n new_pathways=[]\n new_data=[]\n \n for path, row in zip(pathways, data):\n if not \"|\" in path and not \"UNINTEGRATED\" in path and not \"UNMAPPED\" in path:\n if remove_description:\n path=path.split(\":\")[0]\n new_pathways.append(path)\n new_data.append(row)\n \n return new_pathways, new_data \n\ndef pathway_names(pathways):\n \"\"\" Split the pathway names and descriptions\n \n Args:\n pathways (list): A list of pathway names and descriptions \n (from a pathway abundance or coverage file) \n \n Requires:\n None\n \n Returns:\n (dict): A dictionary of pathway names to descriptions\n \n \"\"\"\n \n path_names = {}\n for path in pathways:\n # ignore stratified pathways\n if not \"|\" in path:\n try:\n description = path.split(\":\")\n name = description.pop(0)\n description=\":\".join(description)\n except ValueError:\n continue\n \n path_names[name]=description\n \n return path_names\n \n\ndef filter_taxa_abundance(taxonomy, data, min_abundance, min_samples):\n \"\"\" Remove the taxons by min abundance and min samples.\n \n Args:\n taxonomy (list): A list of taxonomy strings for each row.\n data (list of lists): Each list in data represents a row of data. \n min_abundance (float): Remove data without min abundance. \n min_samples (float): Remove data not in min samples.\n \n Requires:\n None\n \n Returns:\n (list): A list of species names.\n (list): A list of lists of the data.\n \n Example:\n filter_taxa_abundance([\"g__ABC\",\"s__DEF\"],[[1,2,3],[4,5,6]],10,2)\n \"\"\" \n\n filtered_data=[]\n filtered_taxonomy=[]\n # compute the min samples required for this data set\n min_samples_required=math.ceil(len(data[0])*(min_samples/100.0))\n for taxon, data_row in zip(taxonomy, data):\n # filter the species to only include those with min abundance in min of samples\n total_samples_pass_filter=len(list(filter(lambda x: x>min_abundance, data_row)))\n if total_samples_pass_filter >= min_samples_required: \n filtered_taxonomy.append(taxon)\n filtered_data.append(data_row)\n \n return filtered_taxonomy, filtered_data\n\ndef filter_taxa_level_metaphlan2_format(taxonomy, data, min_abundance=None, min_samples=None, level=6):\n \"\"\" Remove the taxons that are not a species level (or set a different level with keyword) from the data set.\n Also filter the species if filters are provided. Metaphlan2 format with \"|\" delimiters and tiered\n abundances (so genus level is split and repeated stratified by species).\n \n Args:\n taxonomy (list): A list of taxonomy strings for each row.\n data (list of lists): Each list in data represents a row of data. \n min_abundance (float): If set, remove data without min abundance. To\n be used with min_samples.\n min_samples (float): If set, remove data not in min samples.\n level (int): Taxonomic level (default set to species)\n \n Requires:\n None\n \n Returns:\n (list): A list of species names.\n (list): A list of lists of the data.\n \n Example:\n filter_taxa_level_metaphlan2_format([\"g__ABC\",\"s__DEF\"],[[1,2,3],[4,5,6]])\n \"\"\"\n\n taxonomic_levels=[\"|k__\",\"|p__\",\"|c__\",\"|o__\",\"|f__\",\"|g__\",\"|s__\",\"|t__\"]\n\n # get the level indicator to search for and the next level to filter\n search_taxa = taxonomic_levels[level]\n remove_taxa = taxonomic_levels[level+1] if level+1 < len(taxonomic_levels) else \"\\n\"\n\n species_data=[]\n species_taxonomy=[]\n # identify the species data in the data set\n # filter out those with species and strain information\n for taxon, data_row in zip(taxonomy, data):\n if search_taxa in taxon and not remove_taxa in taxon:\n species_taxonomy.append(taxon.split(\"|\")[-1].replace(search_taxa[1:],\"\").replace(\"_\",\" \"))\n species_data.append(data_row)\n\n # if filters are provided, then filter the data by both min abundance\n # and min samples\n if min_abundance is not None and min_samples is not None:\n species_taxonomy, species_data = filter_taxa_abundance(species_taxonomy, species_data, min_abundance, min_samples)\n\n return species_taxonomy, species_data\n\ndef read_otu_table(file):\n \"\"\" Read in an otu table. Remove extra brackets from taxonomy names if present.\n \n Args:\n file (string): A file containing the otu table (tsv format).\n \n Requires:\n None\n \n Returns:\n (list): A list of samples.\n (list): A list of otu ids.\n (list): A list of taxons.\n (list): A list of lists of data.\n \n Example:\n samples, ids, taxonomy, data = read_otu_table(\"otu_table.tsv\")\n \"\"\"\n \n data=[]\n samples=[]\n taxonomy=[]\n ids=[]\n with open(file) as file_handle:\n samples = file_handle.readline().rstrip().split(\"\\t\")[1:-1]\n for line in file_handle:\n data_points=line.rstrip().split(\"\\t\")\n ids.append(data_points.pop(0))\n taxonomy.append(data_points.pop().replace(\"[\",\"\").replace(\"]\",\"\"))\n data.append([float(i) for i in data_points])\n \n return samples, ids, taxonomy, data\n \n\ndef sort_data(data, samples, sort_by_name=False, sort_by_name_inverse=False):\n \"\"\" Sort the data with those with the largest values first or by sample name\n\n Args:\n data (list): The data points for each sample.\n samples (list): The sample names that correspond to each data point. \n sort_by_name (bool): If true, sort by sample name\n sort_by_name_inverse (bool): If true, sort by the inverse of the name (so the reverse of the string)\n this is useful for samples with sample name plus features\n\n Requires:\n None\n \n Returns:\n (list): The data points for each sample sorted.\n (list): The sample names that correspond to each data point sorted.\n \n \"\"\"\n import numpy\n \n # if the data is a list of lists of single values, then convert to a list of values\n if isinstance(data[0], list) and max([len(row) for row in data]) == 1:\n data=[row[0] for row in data]\n \n # if set, sort by sample name (samples as columns in the data)\n if sort_by_name or sort_by_name_inverse:\n data_by_sample={sample:data_point for sample,data_point in zip(samples,numpy.transpose(data))}\n sorted_samples=sorted(samples)\n if sort_by_name_inverse:\n # use the reverse of the sample names to sort\n sorted_samples=sorted(samples, key=lambda x: x[::-1])\n sorted_data_transpose=[data_by_sample[sample] for sample in sorted_samples]\n sorted_data = numpy.transpose(sorted_data_transpose)\n else:\n data_by_sample={sample:data_point for sample,data_point in zip(samples,data)}\n sorted_samples=sorted(data_by_sample,key=data_by_sample.get, reverse=True)\n sorted_data=[data_by_sample[sample] for sample in sorted_samples]\n \n return sorted_samples, sorted_data\n\ndef is_paired_table(file):\n \"\"\" Check if a file contains paired read counts using the header information.\n \n Args:\n file (string): A file of read counts.\n \n Requires:\n None\n \n Returns:\n (bool): True if the file contains paired read counts\n \n \"\"\"\n \n # read in the first line in the file\n try:\n with open(file) as file_handle:\n header=file_handle.readline()\n except EnvironmentError:\n sys.exit(\"Unable to read file: \" + file)\n \n paired = True if \"pair\" in header.lower() else False\n \n return paired\n\ndef microbial_read_proportion_multiple_databases(data, columns, orphan_data=None, rna=None):\n \"\"\" Compute microbial read proportions from the KneadData read counts for \n multiple databases \n \n Args:\n data (list of lists): The single or paired data read counts for each sample.\n columns (list): The names of the columns corresponding to the paired data. These\n columns include the reference database names.\n orphan_data (list of lists): The orphan data (if paired end reads)\n rna (bool): If set, this data set is RNA so compute additional ratio.\n \n Requires:\n None\n \n Returns:\n (list of lists): A list of ratios for each sample.\n (list): A list of strings with labels for the ratios.\n \"\"\"\n \n # compute ratios for each database used for qc\n dna_microbial_reads=[]\n dna_microbial_labels=[]\n for index, qc_database in enumerate(columns[2:]):\n # get a subset of the data for this ratio\n data_subset=[row[:2]+[row[index+2]] for row in data]\n\n # create subset of orphan data if provided\n orphan_subset=None\n if orphan_data and len(orphan_data[0]) > 2:\n orphan_subset=[row[:2]+[row[index+2]] for row in orphan_data]\n else:\n orphan_subset=orphan_data\n \n reads_ratio, ratio_labels = microbial_read_proportion(data_subset, \n orphan_data=orphan_subset, database_name=qc_database, rna=rna)\n dna_microbial_labels+=ratio_labels\n if not dna_microbial_reads:\n dna_microbial_reads=reads_ratio\n else:\n dna_microbial_reads=[row1+row2 for row1, row2 in zip(dna_microbial_reads,reads_ratio)]\n \n return dna_microbial_reads, dna_microbial_labels\n\ndef microbial_read_proportion(paired_data, orphan_data=None, rna=None, database_name=None):\n \"\"\" Compute microbial read proporations from the KneadData read counts.\n \n Args:\n paired_data (list of lists): The paired data read counts for each sample.\n orphan_data (list of lists): The orphan data read counts for each sample. \n rna (bool): If set, this data set is RNA so compute additional ratio.\n database_name (string): The name of the contaminate database.\n \n Requires:\n None\n \n Returns:\n (list of lists): A list of ratios for each sample.\n (list): A list of strings with labels for the ratios.\n \n \"\"\"\n \n # if the database name is not set, use the default\n if database_name is None:\n database_name=\"hg38\"\n \n # if the orphan reads are not provided, create an empty set of data\n if orphan_data is None:\n orphan_data=[]\n for i in range(len(paired_data)):\n orphan_data.append([0,0,0,0])\n \n proportion_decontaminated = []\n for paired_row, orphan_row in zip(paired_data, orphan_data):\n decontaminated_sum = 2.0 * paired_row[-1] + orphan_row[-1] + orphan_row[-2]\n decon_trim = decontaminated_sum / (2.0 * paired_row[1] + orphan_row[0] + orphan_row[1])\n decon_raw = decontaminated_sum / (2.0 * paired_row[0])\n if rna:\n decon_ratio = decontaminated_sum / (2.0 * paired_row[-2] + orphan_row[-3] + orphan_row[-4])\n proportion_decontaminated.append([\"{0:.5f}\".format(i) for i in [decon_trim, decon_ratio, decon_raw]])\n else:\n proportion_decontaminated.append([\"{0:.5f}\".format(i) for i in [decon_trim, decon_raw]])\n\n if rna:\n labels=[database_name+\" mRNA / Trim\",database_name+\" mRNA / \"+database_name,database_name+\" mRNA / Raw\"]\n else:\n labels=[database_name+\" / Trim\",database_name+\" / Raw\"]\n \n return proportion_decontaminated, labels\n\n\ndef taxa_remove_unclassified(taxa, delimiter=\";\"):\n \"\"\" Rename the taxa to remove the unclassified levels\n \n Args:\n taxa (list): The list of taxa.\n delimiter (str): The string delimiter (usually pipe or semi-colon).\n \n Requires:\n None\n \n Returns:\n (list): The list of taxa after removing the unclassified names.\n \"\"\"\n \n # remove any levels where the name is unknown (ie empty)\n for taxon in taxa:\n new_name=[]\n for level in taxon.replace(\" \",\"\").split(delimiter):\n try:\n rank, name = level.split(\"__\")\n except ValueError:\n # ignore identities like \"unclassified\" if present\n continue\n if name:\n new_name.append(level)\n else:\n break\n yield delimiter.join(new_name)\n \ndef taxonomy_trim(taxa):\n \"\"\" Trim the taxonomy name to include the most specific known name followed by unclassified\n \n Args:\n taxa (list): The list of taxa.\n \n Requires:\n None\n \n Returns:\n (list): The list of taxa after trimming.\n \"\"\"\n \n # remove any spaces from the taxonomy\n taxa = [taxon.replace(\" \",\"\") for taxon in taxa]\n\n # determine the delimiter (pipe or semi-colon)\n delimiter=\"|\" if \"|\" in taxa[0] else \";\"\n \n # get the taxa with unclassified levels removed\n taxa_unclassified_removed = taxa_remove_unclassified(taxa,delimiter)\n \n trimmed_taxa=[]\n for taxon_full, taxon_reduced in zip(taxa, taxa_unclassified_removed):\n # if the taxon is specific to species level, then \n # return the genus and species level\n if taxon_full == taxon_reduced:\n data = taxon_full.split(delimiter)\n trimmed_taxa.append(data[-2]+\".\"+data[-1])\n \n else:\n most_specific_clade = taxon_reduced.split(delimiter)[-1]\n if not most_specific_clade:\n trimmed_taxa.append(taxon_reduced.replace(delimiter,\".\")) \n else:\n data = taxon_full.split(most_specific_clade)\n trimmed_taxa.append(most_specific_clade+data[-1].replace(delimiter,\".\"))\n \n return trimmed_taxa\n \ndef terminal_taxa(taxa, data):\n \"\"\" Reduce the list of taxa to just those that represent the terminal nodes. If there\n are duplicate terminal nodes, then sum the duplicates.\n \n Args:\n taxa (list): The list of taxa (in the same order as the data).\n data (list of lists): The data points for all samples for each taxa.\n \n Requires:\n None\n \n Returns:\n (list): The list of taxa (terminal node only)\n (list of lists): The data after reducing to terminal node taxa.\n \"\"\" \n \n terminal_node_taxa=[]\n # check the taxa by level, starting with the most specific level of strain\n # use a full match with strain instead of just startswith to allow for unclassified\n # strains to not match with classified strains\n # if strains are not present, then run at a species level instead\n \n # check for the most specific taxonomy level (ie strain or species)\n max_taxonomy_level=max([len(taxon.split(\";\")) for taxon in taxa])\n \n taxa_for_level, data_level=taxa_by_level(taxa, data, level=max_taxonomy_level-1, keep_unclassified=True)\n for taxon in taxa_for_level:\n matching_taxa=list(filter(lambda x: x.replace(\" \",\"\") == taxon.replace(\" \",\"\"), terminal_node_taxa))\n if len(matching_taxa) == 0:\n terminal_node_taxa.append(taxon)\n \n for level in reversed(range(max_taxonomy_level-1)):\n taxa_for_level, data_level=taxa_by_level(taxa, data, level, keep_unclassified=True)\n for taxon in taxa_for_level:\n # check if part of this taxon is already included\n matching_taxa=list(filter(lambda x: x.replace(\" \",\"\").startswith(taxon.replace(\" \",\"\")), terminal_node_taxa))\n if len(matching_taxa) == 0:\n terminal_node_taxa.append(taxon)\n \n # create a set of terminal node taxa and data\n new_taxa={}\n for taxon, row in zip(taxa, data):\n if taxon in terminal_node_taxa:\n if taxon in new_taxa:\n new_taxa[taxon]=[a+b for a,b in zip(new_taxa[taxon],row)]\n else:\n new_taxa[taxon]=row\n \n new_taxa_list=sorted(new_taxa.keys())\n new_data_list=[new_taxa[i] for i in new_taxa_list] \n \n return new_taxa_list, new_data_list\n \ndef taxa_by_level(taxa, data, level, keep_unclassified=None):\n \"\"\" Combine the data to represent the taxa by a specific level\n \n Args:\n taxa (list): The list of taxa (in the same order as the data).\n data (list of lists): The data points for all samples for each taxa.\n level (int): The level to sum the taxa (zero is kingdom level).\n keep_unclassified (bool): If set, keep unclassified taxa.\n \n Requires:\n None\n \n Returns:\n (list): The list of taxa (all to the level specified)\n (list of lists): The data after summing to the taxa level specified.\n \"\"\" \n\n # first remove any unclassified levels\n if not keep_unclassified:\n taxa=taxa_remove_unclassified(taxa)\n \n # sum the taxa by the level provided\n data_sum={}\n for taxon, taxon_data in zip(taxa, data):\n split_taxon=taxon.split(\";\")\n if len(split_taxon) < (level+1):\n # do not include those taxa that are not specified to the level requested\n continue\n new_taxon_level=\";\".join(split_taxon[:(level+1)])\n if new_taxon_level in data_sum:\n data_sum[new_taxon_level]=[a+b for a,b in zip(data_sum[new_taxon_level],taxon_data)]\n else:\n data_sum[new_taxon_level]=taxon_data\n \n new_taxa=[]\n new_data=[] \n for taxon, taxon_data in data_sum.items():\n new_taxa.append(taxon)\n new_data.append(taxon_data)\n \n return new_taxa, new_data\n\ndef format_data_comma(data):\n \"\"\" Format the numbers in the string to include commas.\n \n Args:\n data (string or list): A text string.\n \n Requires:\n None\n \n Returns:\n (string): A text string.\n \n \"\"\"\n \n if not isinstance(data,list):\n data=data.split()\n\n new_string=[]\n for token in data:\n try:\n new_token=\"{:,}\".format(int(token))\n except ValueError:\n new_token=token\n new_string.append(new_token)\n \n return \" \".join(new_string)\n\ndef read_eestats2(file):\n \"\"\" Read the eestats2 file which is an ascii table.\n \n Args:\n file (string): The path to the eestats file.\n \n Requires:\n None\n \n Returns:\n (list): The table rows.\n (list): The table columns.\n (list): The table data.\n (string): The summary.\n \n \"\"\"\n \n with open(file) as file_handle:\n eestats_lines = file_handle.readlines()\n \n # read in the overall stats line\n overall_stats = format_data_comma(eestats_lines[1].rstrip())\n # read in the maxee values from the columns\n columns = list(filter(lambda x: x.strip() and not x in [\"Length\",\"MaxEE\"],eestats_lines[3].rstrip().split()))\n columns = [column+\" maxee\" for column in columns]\n rows = []\n data = []\n # read through the data table\n for line in eestats_lines[5:]:\n stats = list(filter(lambda x: x.strip(),line.strip().split(\" \")))\n # move spaces in data values and percents\n stats = [stat.replace(\"( \",\"(\").replace(\"( \",\"(\").replace(\"(\",\" (\") for stat in stats]\n rows.append(stats.pop(0)+\" nt\")\n data.append([format_data_comma(stat) for stat in stats])\n \n return rows, columns, data, overall_stats\n\ndef get_files(folder, extension):\n \"\"\" Return paths to all files in a folder with a given extension \"\"\"\n \n for file in os.listdir(folder):\n file=os.path.join(folder, file)\n if os.path.isfile(file) and file.endswith(extension):\n yield file\n\ndef read_picard(file, threshold=20):\n \"\"\" Read the picard file which is an ascii table of quality scores per base.\n \n Args:\n file (string): The path to the picard file.\n \n Requires:\n None\n \n Returns:\n (list): A list of tuples of base / quality score. \n (bool): True if any quality score in the set does not meet the threshold.\n \"\"\"\n \n with open(file) as file_handle:\n picard_lines = file_handle.readlines()\n \n # read through file to get quality scores ignoring all lines with comments/headers\n data=[]\n below_threshold=False\n for line in picard_lines:\n if not (line.startswith(\"#\") or line.startswith(\"CYCLE\")):\n new_data=line.rstrip().split(\"\\t\")\n # check if the quality score passes the threshold\n try:\n new_data=(int(new_data[0]),float(new_data[1]))\n if new_data[1] < threshold:\n below_threshold=True\n data.append(new_data)\n except ValueError:\n pass\n \n return data, below_threshold\n\ndef rank_species_average_abundance(file):\n \"\"\" Read in a taxonomy file, and sort species by average abundance \n \n Args:\n file (string): The path to the merged taxonomy file generated by MetaPhlAn2\n \n Requires:\n None\n \n Returns:\n (list): A list of species ordered by decreasing average abundance\n \"\"\"\n \n def try_format_data(value):\n \"\"\" Try to format the data in a file \"\"\"\n try:\n value = float(value)\n except ValueError:\n value= 0\n \n return value\n \n species=collections.OrderedDict()\n with open(file) as file_handle:\n try:\n column_names = file_handle.readline().rstrip().split(\"\\t\")[1:]\n except IndexError:\n column_names = []\n for line in file_handle:\n line=line.rstrip().split(\"\\t\")\n taxonomy=line.pop(0).split(\"|\")[-1]\n data=[try_format_data(i) for i in line]\n try:\n average=sum(data)/(len(data)*1.0)\n except ZeroDivisionError:\n average=0\n # only store values for species\n if taxonomy.startswith(\"s__\"):\n species[taxonomy]=average\n \n # sort the species from highest to lowest average abundance\n sorted_species = sorted(species, key=species.get, reverse=True)\n # if abundances are not provided then use original ordering\n if sum(species.values()) == 0:\n sorted_species = species.keys()\n \n return sorted_species\n\ndef order_clade_list(task,clade_list,abundance_file,output_file):\n \"\"\" Using the average abundances order the clade list from strainphlan \n \n Args:\n task (anadama2.task): An instance of the task class.\n clade_list (string): The path to the file containing the strainphlan list of clades.\n abundance_file (string): The path to the merged abundance file from metaphlan2.\n output_file (string): The file to write the ordered clade list.\n \n Requires:\n none\n \n Returns:\n none\n \"\"\"\n \n # get the species listed by average abundance\n species_ranked = rank_species_average_abundance(abundance_file)\n \n # read in the clade list\n clades=set()\n with open(clade_list) as file_handle:\n for line in file_handle:\n if line.startswith(\"s__\"):\n clades.add(line.rstrip().split(\" \")[0])\n \n # write out ordered species also included in clade list\n with open(output_file,\"w\") as file_handle:\n for taxon in species_ranked:\n if taxon in clades:\n file_handle.write(taxon+\"\\n\")\n \n\ndef sort_fastq_file(task):\n \"\"\"Sorts a FASTQ file by name (sequence identifier contents).\n\n Args:\n task (anadama2.task): An instance of the task class.\n\n Requires:\n None\n\n Returns:\n None\n \"\"\"\n sample_name = os.path.basename(task.depends[0].name)\n output_dir = os.path.dirname(task.targets[0].name)\n temp_dir = os.path.join(output_dir, \"%s.tmp\" % sample_name)\n\n if task.depends[0].name.endswith('.gz'):\n sort_command = \"zcat \"\n else:\n sort_command = \"cat \" \n \n sort_command += (\"[depends[0]] | paste - - - - | sort -T [depends[1]] -k1,1 | \"\n \"tr '\\t' '\\n' > [targets[0]]\")\n\n run_task('mkdir -p [targets[0]]',\n depends=[TrackedDirectory(output_dir)],\n targets=[TrackedDirectory(temp_dir)])\n\n run_task(sort_command,\n depends=task.depends + [TrackedDirectory(temp_dir), TrackedDirectory(output_dir)],\n targets=task.targets)\n\n run_task(\"rm -rf [depends[0]]\",\n depends=[TrackedDirectory(temp_dir)] + task.targets)\n\n\ndef extract_orphan_reads(task):\n \"\"\"Extracts orphan reads from the provided input files. Orphan reads are saved into a separate file \n for further downstream analysis.\n\n Args:\n task (anadama2.task): An instance of the task class.\n\n Requires:\n seqtk v1.2+: A fast and lightweight tool for processing sequences in the FASTA\n or FASTQ format\n\n Returns:\n None\n \"\"\"\n sample_name = os.path.basename(os.path.dirname(task.depends[0].name))\n orphans_dir = os.path.dirname(task.targets[0].name)\n\n run_task(\"seqtk dropse [depends[0]] > [targets[0]]\",\n depends=task.depends,\n targets=task.targets[0])\n\n run_task(\"extract_orphan_reads.py -r [depends[0]] -b [depends[1]] -o [depends[2]]\",\n depends=[task.depends[0], task.targets[0], TrackedDirectory(orphans_dir)],\n targets=[task.targets[1]],\n args=[\".fastq\"])\n\n\ndef is_paired_end(input_files, extension, pair_identifier):\n \"\"\"Returns true if the provided set of input files are paired-end.\n\n Args:\n input_files (list): A list of files to verify if paired-end data.\n extension (string): The extension for all files.\n pair_identifier (string): The string in the file basename to identify\n the first pair in the set.\n\n Requires:\n None\n\n Returns:\n bool: True if paired-end datasets; False otherwise.\n \"\"\"\n input_pair1, input_pair2 = paired_files(input_files, extension, pair_identifier)\n \n return True if input_pair1 else False\n","sub_path":"biobakery_workflows/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":59479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"567143607","text":"from pyModbusTCP.server import ModbusServer, DataBank\nfrom time import sleep\nfrom random import uniform\nfrom pyModbusTCP import utils\nfrom OPC_Client import OPC_client\nimport statistics as stats\n\n\n\n##############Funcion de lectura y escritura modbus###################\ndef read_float(address, number=1):\n reg_l = DataBank.get_words(address, number*2)\n if reg_l:\n return[utils.decode_ieee(f)for f in utils.word_list_to_long(reg_l)]\n else:\n return None\n \ndef write_float(address, floats_list):\n b32_l = [utils.encode_ieee(f) for f in floats_list]\n b16_l = utils.long_list_to_word(b32_l)\n return DataBank.set_words(address, b16_l)\n\n##############Servidor Modbus###################\nservidor = ModbusServer(host=\"localhost\", port=12346, no_block=True)\n#servidor_inputs = ModbusServer(host=\"localhost\", port=12346, no_block=True)\n\nservidor.start()\n#servidor_inputs.start()\n##############Cliente OPC###################\nclient = OPC_client(\"opc.tcp://localhost:4080\")\n\nclient.conect()\nflag =1 \n####Creacion de lista de variables para reducción de tiempo de envio de 1 a 5 sseg##########\nflocculant1_list = []\noutput_flow1_list = []\ninput_flow_list = []\ninput_solidC_list = []\nbed_list = []\npressure_list = []\ntorque_list = []\nsolidC_list = []\n\n###############################Proceso de envio y recepción de datos######################################\n\nwhile True:\n \n sleep(1)\n #Lectura variables desde cliente modbus\n Variables = read_float(0,8)\n print(Variables)\n \n #inputs\n flocculant1 = Variables[0]\n output_flow1 = Variables[1]\n\n #Perturbaciones\n input_flow = Variables[2]\n input_solidC = Variables[3]\n\n #Salidas\n bed = Variables[4]\n pressure = Variables[5]\n torque = Variables[6]\n solidC = Variables[7]\n\n if len(flocculant1_list) < 5:\n \n if input_solidC !=0:\n\n flocculant1_list.append(flocculant1)\n output_flow1_list.append(output_flow1)\n input_flow_list.append(input_flow)\n input_solidC_list.append(input_solidC)\n bed_list.append(bed)\n pressure_list.append(pressure)\n torque_list.append(torque)\n solidC_list.append(solidC)\n \n else:\n flocculant1_list = flocculant1_list\n output_flow1_list = output_flow1_list\n input_flow_list = input_flow_list\n input_solidC_list = input_solidC_list\n bed_list = bed_list\n pressure_list = pressure_list\n torque_list = torque_list\n solidC_list = solidC_list \n\n else:\n flocculant1_mean = stats.mean(flocculant1_list)\n flocculant1_list = [flocculant1] \n output_flow1_mean = stats.mean(output_flow1_list)\n output_flow1_list = [output_flow1] \n input_flow_mean = stats.mean(input_flow_list)\n input_flow_list = [input_flow] \n input_solidC_mean = stats.mean(input_solidC_list)\n input_solidC_list = [input_solidC] \n bed_mean = stats.mean(bed_list)\n bed_list = [bed] \n pressure_mean = stats.mean(pressure_list)\n pressure_list = [pressure] \n torque_mean = stats.mean(torque_list)\n torque_list = [torque] \n solidC_mean = stats.mean(solidC_list)\n solidC_list = [solidC] \n\n # intentar conectar al servidor UA\n try:\n if flag == 0:\n client.connect()\n flag = 1\n\n ##########Envio MODBUS-OPC##########\n #Entradas a OPC\n #client.inputs['flocculant'].set_value(float(flocculant1_mean) + uniform(0.000001, 0.00011))\n #client.inputs['output_flow'].set_value(float(output_flow1_mean) +uniform(0.000001, 0.00011))\n #Perturbarciones a OPC\n client.perturbations['input_flow'].set_value(float(input_flow_mean))\n client.perturbations['solid_concentration'].set_value(float(input_solidC_mean))\n # #Salidas a OPC\n client.outputs['bed'].set_value(float(bed_mean))\n client.outputs['pressure'].set_value(float(pressure_mean))\n client.outputs['torque'].set_value(float(torque_mean))\n client.outputs['solidC'].set_value(float(solidC_mean))\n \n ##########Envio OPC-MODBUS##########\n #Recepcion desde cliente OPC\n flocculant = client.inputs['flocculant'].get_value()\n output_flow = client.inputs['output_flow'].get_value()\n\n print(flocculant)\n\n #envio a cliente modbus\n write_float(0,[flocculant,output_flow]) \n\n\n # De fallar la conexión opcua, intentar nuevamente\n except Exception as e:\n print(e)\n flag = 0\n sleep(2)\n\n \nservidor.close()","sub_path":"anillo_2021_01_25/modbus_to_opc_pc2/server_modbus_to_opc_pc2.py","file_name":"server_modbus_to_opc_pc2.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"26217921","text":"# encoding: utf-8\nimport requests\nimport lxml\nimport js2xml\nfrom lxml import etree\nheaders ={\n#这边cookie替换成你的cookie \n'Cookie':'_s_tentry=-; Apache=8649092955591.762.1486540352135; SINAGLOBAL=8649092955591.762.1486540352135; ULV=1486540352143:1:1:1:8649092955591.762.1486540352135:; ALF=1489135502; SUB=_2A251nqreDeRxGedG6FcR-CfNzzmIHXVXYDaWrDV8PUJbkNBeLWfGkW13xFR3uIfuOrPptYaXHQkIv9r-Ow..; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WWgKPExsGMru6YkIv0yiZii5JpX5oz75NHD95Qp1hefehn4eKBfWs4Dqcj.i--ci-zXiKnXi--ci-2Ei-2ci--Xi-iFiK.4i--4iKnfiK.E', \n'User-Agent':'Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19',\n }\n#获取红包列表\ndef getuid():\n\turl = 'http://chunjie.hongbao.weibo.com/hongbao2017/h5index'\n\t# 带上request headers\n\tz = requests.get(url,headers=headers)\n\tif z.status_code == 200:\n\t# 这边是查找所有的ouid\n\t\talluid = etree.HTML(z.content).xpath('//div[@class=\"m-auto-box\"]/@action-data')\n\treturn alluid\n#获取st的值 \ndef getst(url):\n#带上request headers\n\tz = requests.get(url,headers=headers)\n\t# 获取第一段JavaScript,并去掉 ,防止中文报错 \n\tjscode = etree.HTML(z.content).xpath(\"//script[contains(., 'weibo')]/text()\")[0].replace(u'','') \n\t#使用js2xml 把JavaScript代码替换成xml \n\tparsed_js = js2xml.parse(jscode) \n\t#打印下 xml \n\t#print(js2xml.pretty_print(parsed_js)) \n\t#从上面可以看到st在哪,然后用xpath写出来 \n\tst = parsed_js.xpath('//property[@name=\"st\"]/string/text()')[0] \n\treturn st \n# 抢红包 \ndef tj(url,uid,st,tjheaders):\n#生成需要发送的data\n\tdata = { 'groupid':'1000110', 'uid':uid, 'share':'1', 'st':st } \n\t# 这里使用了post,headers增加了Referer \n\tz = requests.post(url,data=data,headers=tjheaders) \n\t#把得到的结果以json形式展示 \n\t_ = z.json() \n\t#如果json中有“ok”,表示提交成功了,否则返回报错信息 \n\tif _.has_key('ok'): \n\t\tprint(_['data']['error_msg'])\n\t\tprint('chengong')\n\telse:\n\t\tprint(_['errMsg'])\n\t\tprint('shibai')\n\nif __name__ == '__main__': \n# 得到所有的uid \n\tuids = getuid() \n\tfor uid in uids:\n\t\t#生成红包页面的url \n\t\turl = 'http://hongbao.weibo.com/h5/aboutyou?groupid=1000110&ouid=%s&ref=redbag17' %uid \n\t\t#print('url', url)\n\t\t#获取st \n\t\tst = getst(url) \n\t\t#print('st', st)\n\t\t#生成点击“抢红包”页面的url \n\t\ttjurl = 'http://hongbao.weibo.com/aj_h5/lottery?uid=%s&groupid=1000110&wm=' %uid \n\t\t#print('tjurl', tjurl)\n\t\t# 添加Referer,如果不添加会报错 \n\t\theaders['Referer'] = url \n\t\ttjheaders = headers \n\t\ttry:\n\t\t# 点击“抢红包” \n\t\t\ttj(tjurl,uid,st,tjheaders)\n\t\texcept:\n\t\t\tpass","sub_path":"pachong/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"327347062","text":"import essentia\nimport sys\nimport essentia.standard as es\nimport pika\nimport json\nimport os\n\nmqhost = os.environ.get(\"HOST\")\nmquser = os.environ.get(\"USER\")\nmqpass = os.environ.get(\"PASS\")\nmqport = os.environ.get(\"PORT\")\n\ncredentials = pika.PlainCredentials(mquser, mqpass)\nconnection = pika.BlockingConnection(pika.ConnectionParameters(mqhost, mqport,'/',credentials))\nchannel = connection.channel()\n\nchannel.queue_declare(queue='musicFeatures')\nchannel.queue_declare(queue='classifyMusic')\n\nprint(' [*] Waiting for messages. To exit press CTRL+C')\n\ndef callback(ch, method, properties, body):\n ch.basic_ack(delivery_tag = method.delivery_tag)\n print(\" [x] Received %r\" % body)# See all feature names in the pool in a sorted order\n id = body\n # Compute all features, aggregate only 'mean' (media) and 'stdev' (desvio padrao) statistics for all low-level, rhythm and tonal frame features - https://essentia.upf.edu/documentation/essentia_python_examples.html\n features, features_frames = es.MusicExtractor(lowlevelStats=['mean', 'stdev'],\n rhythmStats=['mean', 'stdev'],\n tonalStats=['mean', 'stdev'])('/Audios/'+id+'.wav')\n print(\"Filename:\", features['metadata.tags.file_name'])\n print(\" Pitch Salience:\")\n print(\" Mean:\", features['lowlevel.pitch_salience.mean'])\n print(\" StDev:\", features['lowlevel.pitch_salience.stdev'])\n print(\"Loudness:\",features['lowlevel.average_loudness'])\n print(\"BPM:\", features['rhythm.bpm'])\n print(\"Beat positions (sec.)\", features['rhythm.beats_position'])\n toSend = [\n features['metadata.tags.file_name'],\n features['lowlevel.pitch_salience.mean'],\n features['lowlevel.average_loudness'],\n features['rhythm.bpm']\n ]\n channel.queue_declare(queue='classifyMusic')\n channel.basic_publish(exchange='',\n routing_key='classifyMusic',\n body=json.dumps(toSend))\n print(\" [x] Sent \",features['metadata.tags.file_name'],\" to classify!!\")\n print(' [*] Waiting for messages. To exit press CTRL+C')\n\n\n\nchannel.basic_consume(queue='musicFeatures',\n auto_ack=False,\n on_message_callback=callback)\n\nchannel.start_consuming()","sub_path":"src/featuresExtraction.py","file_name":"featuresExtraction.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"281483640","text":"from __future__ import division, print_function, absolute_import\nfrom datetime import datetime\nimport time\nimport os\n#import logging\n#logging.getLogger('tensorflow').disabled = True\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\nimport numpy as np\nfrom cloud_cnnbag.trainer import input_generator as i_gen\nfrom cloud_cnnbag.trainer import simple_cnnbag_cloud as scnn\nfrom sklearn import metrics as skmetrics\nimport matplotlib.pyplot as plt\nimport argparse\ntf.logging.set_verbosity(tf.logging.INFO)\n\n\nclass Model_Trainer:\n def __init__(self):\n self.config=dict()\n\n def init_embeddings(self, sess, embedding_weights, random_label, random_distance):\n with tf.device('/cpu:0'):\n saver = tf.train.Saver([embedding_weights])\n vizpath = self.config['word_embd_dir']\n saver.restore(sess, os.path.join(vizpath, 'embedding_weights.ckpt'))\n saver = tf.train.Saver([random_distance, random_label])\n vizpath2 = self.config['pos_label_embd_dir']\n saver.restore(sess, os.path.join(vizpath2, 'random_distance_labels.ckpt'))\n\n def get_outdir(self, outdir_path):\n timestamp = str(int(time.time()))\n out_dir = os.path.abspath(os.path.join(outdir_path, timestamp))\n if not os.path.exists(out_dir):\n os.mkdir(out_dir)\n return out_dir\n\n def set_config(self, arguments):\n self.config['trainpath'] = arguments.trainpath\n self.config['evalpath'] = arguments.evalpath\n self.config['jobdir'] = self.get_outdir(arguments.job_dir)\n #self.config['jobdir'] = arguments.job_dir\n self.config['word_embd_dir'] = arguments.embdworddir\n self.config['pos_label_embd_dir'] = arguments.embdposlabeldir\n self.config['embd_size'] = arguments.embdsize\n self.config['num_classes'] = arguments.numclasses\n self.config['train_batch_size'] = arguments.trainbatchsize\n self.config['eval_batch_size'] = arguments.evalbatchsize\n self.config['num_shuffle'] = arguments.numshuffle\n self.config['numepochs'] = arguments.numepochs\n self.config['optimizer'] = arguments.optimizer\n self.config['init_lr'] = arguments.lr\n self.config['l2_reg'] = arguments.l2reg\n self.config['dropout'] = arguments.dropout\n self.config['num_kernel'] = arguments.numfilters\n self.config['min_window'] = arguments.minwin\n self.config['max_window'] = arguments.maxwin\n self.config['summary_step'] = arguments.summaryfreq\n self.config['checkpoint_step'] = arguments.checkpointfreq\n self.config['log_step'] = 10\n\n def dev_step(self, mtest, iterator, num_valid_batch, valid_features, valid_labels, global_step, sess):\n dev_loss = []\n dev_auc = []\n dev_f1_score = []\n sess.run(iterator.initializer)\n for i in range(num_valid_batch):\n try:\n valid_input_vals, valid_label_vals = sess.run([valid_features['input'], valid_labels])\n feed_dict = {mtest._inputs: valid_input_vals,\n mtest._labels: valid_label_vals,\n mtest.batch_size: self.config['eval_batch_size'],\n mtest.dropout_keep: 1.0}\n loss_value, predictions, curlabels = sess.run([mtest._total_loss, mtest._predictions, mtest._labels_class1], feed_dict)\n dev_loss.append(loss_value)\n prec, rec, thresholds = skmetrics.precision_recall_curve(curlabels,predictions['scores_class1'])\n #self.plot_pr(rec, prec, 'SkLearn Validation Set Precision-Recall Curve')\n try:\n auc = skmetrics.auc(rec, prec)\n except:\n auc = 0.0\n if np.isnan(auc):\n auc=0.0\n dev_auc.append(auc)\n try:\n f1score = skmetrics.f1_score(curlabels, predictions['classes'])\n except:\n f1score=0\n dev_f1_score.append(f1score)\n if global_step == self.max_train_steps and i==(num_valid_batch-1):\n self.plot_pr(rec, prec, 'SkLearn Validation Set Precision-Recall Curve', 'pr_valid.png')\n except tf.errors.OutOfRangeError:\n break\n return np.mean(dev_loss), np.mean(dev_auc), np.mean(dev_f1_score)\n\n def get_num_examples(self, paths):\n sizes=[]\n with tf.Session() as sess:\n for path in paths:\n size = sess.run(i_gen.get_len(path))\n sizes.append(size)\n return sizes\n\n def plot_pr(self, recall, precision, title,name):\n #plt.draw()\n fig = plt.figure()\n plt.xlim(0, 1)\n plt.ylim(0, 1)\n plt.gca().set_aspect('equal', adjustable='box')\n plt.plot(recall, precision, 'b', label='Precision-Recall curve', linestyle='-', marker='o', color='b')\n plt.title(title)\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n savepath = os.path.join(self.config['jobdir'], name)\n plt.savefig(savepath, dpi=fig.dpi)\n\n def get_embeddings(self):\n with tf.device('/cpu:0'):\n embedding_weights = tf.get_variable('embedding_weights', (71608, 500), trainable=False,\n initializer=tf.zeros_initializer)\n random_label = tf.get_variable('random_label', (9, 100), trainable=False, initializer=tf.zeros_initializer)\n random_distance = tf.get_variable('random_distance', (201, 100), trainable=False,\n initializer=tf.zeros_initializer)\n return (embedding_weights, random_label, random_distance)\n\n def test_skmetrics(self, curlabels, predictions, global_step):\n skprec, skrec, skthresholds = skmetrics.precision_recall_curve(curlabels, predictions['scores_class1'])\n auc = skmetrics.auc(skrec, skprec)\n f1score = skmetrics.f1_score(curlabels, predictions['classes'])\n self.plot_pr(skrec, skprec,'SkLearn Train Step %d Precision-Recall Curve'%global_step)\n return f1score\n\n\n def train(self):\n train_size, valid_size = self.get_num_examples((self.config['trainpath'], self.config['evalpath']))\n #graph\n with tf.Graph().as_default():\n embeddings = self.get_embeddings()\n self.max_train_steps = int(np.ceil(train_size/self.config['train_batch_size'])*self.config['numepochs'])\n self.num_valid_batch = int(np.ceil(valid_size/self.config['eval_batch_size']))\n num_train_batch = int(np.ceil(train_size/self.config['train_batch_size']))\n with tf.variable_scope('inputs'):\n train_iterator, train_features, train_labels, train_names = i_gen.create_input(embeddings, self.config['trainpath'],\n self.config['train_batch_size'],\n self.config['num_shuffle'])\n valid_iterator, valid_features, valid_labels, valid_names = i_gen.create_input(embeddings, self.config['evalpath'],\n self.config['eval_batch_size'],\n self.config['num_shuffle'])\n with tf.variable_scope('cnn'):\n m = scnn.Model(self.config, num_train_batch)\n\n\n # checkpoint\n saver = tf.train.Saver(tf.global_variables())\n save_path = os.path.join(self.config['jobdir'], 'cnnmodel.ckpt')\n summary_op = tf.summary.merge_all()\n\n # session\n with tf.Session().as_default() as sess:\n train_summary_writer = tf.summary.FileWriter(os.path.join(self.config['jobdir'], \"train\"), graph=sess.graph)\n dev_summary_writer = tf.summary.FileWriter(os.path.join(self.config['jobdir'], \"dev\"), graph=sess.graph)\n sess.run([\n tf.local_variables_initializer(),\n tf.global_variables_initializer(),\n ])\n self.init_embeddings(sess, embeddings[0], embeddings[1], embeddings[2])\n global_step=0\n print(\"\\nStart training (save checkpoints in %s)\\n\" % self.config['jobdir'])\n for _ in range(self.config['numepochs']):\n sess.run(train_iterator.initializer)\n while True:\n try:\n start_time = time.time()\n train_input_vals, train_label_vals = sess.run([train_features['input'], train_labels])\n feed_dict = {m._inputs:train_input_vals,\n m._labels:train_label_vals,\n m.batch_size:self.config['train_batch_size'],\n m.dropout_keep:self.config['dropout']}\n _, loss_value, eval_ops, predictions, current_lr, curlabels= sess.run([m._train_op, m._total_loss,\n m._eval_op, m._predictions,\n m._learning_rate,\n m._labels_class1],\n feed_dict)\n global_step += 1\n proc_duration = time.time() - start_time\n assert not np.isnan(loss_value), \"Model loss is NaN.\"\n f1, auc_tf = self.calc_eval_values(eval_ops)\n #self.plot_pr(eval_ops['recalls_op'], eval_ops['precisions_op'], 'Tensorflow Train Step %d Precision-Recall Curve' % global_step)\n #self.test_skmetrics(curlabels,predictions,global_step)\n if global_step==1 or global_step % self.config['log_step'] == 0:\n self.print_log(global_step, self.config, proc_duration, current_lr,loss_value, f1, auc_tf)\n if global_step==1 or global_step % self.config['summary_step']==0 or global_step==self.max_train_steps:\n summary_str = sess.run(summary_op)\n print(\"\\n===== write summary =====\")\n self.write_summaries(train_summary_writer, summary_str, global_step,\n loss_value, auc_tf, f1)\n if global_step == 1 or global_step % (100*self.config['summary_step']) == 0 or global_step == self.max_train_steps:\n dev_loss, dev_auc, dev_f1 = self.dev_step(m, valid_iterator, self.num_valid_batch,\n valid_features, valid_labels, global_step,sess)\n self.write_summaries(dev_summary_writer, summary_str, global_step, dev_loss,\n dev_auc, dev_f1, is_train=False)\n if global_step==self.max_train_steps:\n self.plot_pr(eval_ops['recalls_op'], eval_ops['precisions_op'],\n 'Tensorflow Train Step %d Precision-Recall Curve' % global_step,\n 'pr_train.png')\n print()\n\n # stop learning if learning rate is too low\n if current_lr < 1e-5:\n print('Learning rate too low %.8f. Stop training.'%current_lr)\n break\n\n if global_step % self.config['checkpoint_step'] == 0:\n saver.save(sess, save_path, global_step=global_step)\n saver.save(sess, save_path, global_step=global_step)\n except tf.errors.OutOfRangeError:\n break\n\n saver.save(sess, save_path, global_step=global_step)\n\n def calc_eval_values(self, eval_ops):\n pre_tf, rec_tf, auc_tf = eval_ops['precisions_op'], eval_ops['recalls_op'], eval_ops['auc_op']\n index = len(pre_tf)//2\n if(pre_tf[index]==0.0 and rec_tf[index]==0.0):\n f1=0.0\n else:\n f1 = (2.0 * pre_tf[index] * rec_tf[index]) / (pre_tf[index] + rec_tf[index]) # threshold = 0.5\n return f1, auc_tf\n\n\n def print_log(self, global_step, config, proc_duration, current_lr, loss_value, f1, auc):\n examples_per_sec = config['train_batch_size'] / proc_duration\n format_str = '%s: step %d/%d, f1 = %.4f, auc = %.4f, loss = %.4f ' + \\\n '(%.1f examples/sec; %.3f sec/batch), lr: %.6f'\n print(format_str % (datetime.now(), global_step, self.max_train_steps, f1, auc, loss_value,\n examples_per_sec, proc_duration, current_lr))\n\n\n def write_summaries(self, summary_writer, summary_str, global_step, curloss, curauc, curf1, is_train=True):\n summary_writer.add_summary(summary_str, global_step)\n if(is_train==True):\n #curloss = np.mean(curloss)\n #curauc = np.mean(curauc)\n #curf1 = np.mean(curf1)\n print(\"%s: step %d/%d: train_loss = %.6f, train_auc = %.4f, train_f1 = %.4f\" \\\n % (datetime.now(), global_step, self.max_train_steps,\n curloss, curauc, curf1))\n else:\n print(\"%s: step %d/%d: valid_loss = %.6f, valid_auc = %.4f, valid_f1 = %.4f\" \\\n % (datetime.now(), global_step, self.max_train_steps,\n curloss, curauc, curf1))\n summary_writer.add_summary(\n self._summary_for_scalar('loss', curloss), global_step=global_step)\n summary_writer.add_summary(\n self._summary_for_scalar('auc', curauc), global_step=global_step)\n summary_writer.add_summary(\n self._summary_for_scalar('f1', curf1), global_step=global_step)\n\n\n def _summary_for_scalar(self, name, value):\n return tf.Summary(value=[tf.Summary.Value(tag=name, simple_value=float(value))])\n\ndef main():\n model_trainer = Model_Trainer()\n parser = argparse.ArgumentParser()\n parser.add_argument('--trainpath',\n default='C:/Users/ttasn/Documents/ASU/Research/PhD/deeplearning/dataset_creation/data/model_type_1/tfrecords/sample/train_all2.tfrecords',\n type=str,\n help='Training files GCS')\n parser.add_argument('--evalpath',\n default='C:/Users/ttasn/Documents/ASU/Research/PhD/deeplearning/dataset_creation/data/model_type_1/tfrecords/sample/valid_all3.tfrecords',\n type=str,\n help='Evaluation files GCS')\n parser.add_argument('--job-dir',\n default='C:/Users/ttasn/Documents/ASU/Research/PhD/deeplearning/phd/cloud_cnnbag/trainer/outputs',\n type=str,\n help=\"\"\"\\\n GCS or local dir for checkpoints, exports, and\n summaries. Use an existing directory to load a\n trained model, or a new directory to retrain\"\"\")\n parser.add_argument('--embdworddir',\n type=str,\n default='C:/Users/ttasn/Documents/ASU/Research/PhD/deeplearning/dataset_creation/data/embd_all2/', #'gs://zodophd/embd',\n help='Word embedding directory')\n parser.add_argument('--embdposlabeldir',\n type=str,\n default='C:/Users/ttasn/Documents/ASU/Research/PhD/deeplearning/dataset_creation/data/embd_pos_label/', #'gs://zodophd/embd_pos_label',\n help='Position and label embedding directory')\n parser.add_argument('--embdsize',\n type=int,\n default=700,\n help='Word embedding size')\n parser.add_argument('--numclasses',\n type=int,\n default=2,\n help='Number of classes')\n parser.add_argument('--trainbatchsize',\n type=int,\n default=50,\n help='Batch size for training steps')\n parser.add_argument('--evalbatchsize',\n type=int,\n default=100,\n help='Batch size for evaluation steps')\n parser.add_argument('--numshuffle',\n type=int,\n default=1000,\n help='Batch size for evaluation steps')\n parser.add_argument('--numepochs',\n type=int,\n default=2,\n help='Maximum number of epochs on which to train')\n parser.add_argument('--optimizer',\n choices=[\n 'adam',\n 'sgd',\n 'adagrad',\n 'adadelta',\n ],\n default='adam',\n help='Set optimizer')\n parser.add_argument('--lr',\n type=float,\n default=1e-3,\n help='Learning rate')\n parser.add_argument('--l2reg',\n type=float,\n default=0.001,\n help='L2reg')\n parser.add_argument('--dropout',\n type=float,\n default=0.5,\n help='Dropout')\n parser.add_argument('--numfilters',\n type=int,\n default=125,\n help='Number of filters for each filter size')\n parser.add_argument('--minwin',\n type=int,\n default=5,\n help='Min window for filter')\n parser.add_argument('--maxwin',\n type=int,\n default=10,\n help='Max window for filter')\n parser.add_argument('--summaryfreq',\n type=int,\n default=10,\n help='Write summary and evaluate model per n steps')\n parser.add_argument('--checkpointfreq',\n type=int,\n default=1000,\n help='Save model per n steps')\n\n\n parser.add_argument('--verbosity',\n choices=[\n 'DEBUG',\n 'ERROR',\n 'FATAL',\n 'INFO',\n 'WARN'\n ],\n default='INFO',\n help='Set logging verbosity')\n parse_args, unknown = parser.parse_known_args()\n # Set python level verbosity\n tf.logging.set_verbosity(parse_args.verbosity)\n # Set C++ Graph Execution level verbosity\n os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(\n tf.logging.__dict__[parse_args.verbosity] / 10)\n del parse_args.verbosity\n\n if unknown:\n tf.logging.warn('Unknown arguments: {}'.format(unknown))\n\n model_trainer.set_config(parse_args)\n model_trainer.train()\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"trainer/train_cnnbag_local.py","file_name":"train_cnnbag_local.py","file_ext":"py","file_size_in_byte":19953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"150101426","text":"import os\nimport glob\nfrom pathlib import Path\nimport pandas as pd\nimport numpy as np\nfrom collections import OrderedDict\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\ndata = {}\nnormHysteresis_all = {}\nnormHysteresis_average = {}\ntimeHysteresis = {}\nMOKE_Data = {}\nAveraged_Data = {}\nAllData = {}\nPumpProbeData = {}\nInformation = {}\nTeslaDict = {}\n\n\nclass DataAnalysisMOKE:\n\n def __init__(self, path, timeStamp):\n self.root = path\n self.filename = timeStamp\n self.textfilename = \"AllData_Reduced\"\n self.saveFilePath = str(self.root)+\"//\"+str(self.filename)+\"//Analysis//\"\n self.makeFolder(self.saveFilePath)\n self.makeFolder(self.saveFilePath+str(\"CompareLoops\"))\n\n def readData(self):\n\n \"\"\"\n read all the data files from one measurement series\n (saved as one timestamp)\n finds all files with the name (self.textfilename = \"AllData_Reduced\")\n and reads fluence as well as Voltage for the measurement.\n finds all hysteresis measurements (if they exist): static and\n time resolved\n saves all of the data in dictionaries\n :return: data in dictionaries\n \"\"\"\n\n readFromPath = str(self.root) + \"\\\\\" + str(self.filename)\n rootdir = Path(readFromPath)\n AllData_List = [\n f for f in rootdir.resolve().glob('**/**/**/' +\n str(self.textfilename) +\n '.txt') if f.is_file()\n ]\n Filelist = [0] * len(AllData_List)\n for idx, val in enumerate(AllData_List):\n Information[idx] = {}\n index = str(AllData_List[idx])\n head, tail = os.path.split(index)\n Filelist[idx] = head\n head, tailnew = head.split(str(self.filename) + str(\"\\\\\"))\n\n InfoList = tailnew.split(\"\\\\\")\n Information[idx]['Fluence'] = InfoList[1]\n Information[idx]['Voltage'] = InfoList[2]\n\n for idx, val in enumerate(AllData_List):\n os.chdir(str(Filelist[idx]))\n data[idx] = \\\n pd.read_table(str(self.textfilename) + '.txt', delimiter='\\t',\n comment='%', header=0, skiprows=0,\n error_bad_lines=False)\n\n # if no Hysteresis was measured (e.g. no Hysteresis folder exists):\n # stop reading data at this point\n try:\n os.chdir(\"../Hysteresis\")\n except FileNotFoundError:\n return\n\n # read the static Hysteresis for each fluence measurement\n '''\n try:\n staticHyst = glob.glob('*_Staticps.txt')\n normHysteresis[idx] = \\\n pd.read_table(staticHyst[0], delimiter='\\t', comment='%',\n header=0, skiprows=0, error_bad_lines=False)\n except FileNotFoundError:\n normHysteresis[idx] = 0\n '''\n try:\n staticHyst = glob.glob('*_6.666666666666686ps.txt')\n normHysteresis_all[idx] = \\\n pd.read_table(staticHyst[0], delimiter='\\t', comment='%',\n header=0, skiprows=0, error_bad_lines=False)\n except FileNotFoundError:\n normHysteresis[idx] = 0\n\n # read the time resolved hysteresis for this measurement\n try:\n timeHyst = glob.glob('*ps.txt')\n timeHysteresis[idx] = {}\n for idx2, val2 in enumerate(timeHyst):\n timeHysteresis[idx][idx2] = \\\n pd.read_table(timeHyst[idx2], delimiter='\\t',\n comment='%', header=0, skiprows=0,\n error_bad_lines=False)\n except FileNotFoundError:\n timeHysteresis[idx] = 0\n\n\n def readLastTimeZero():\n \"\"\"\n read t0 from the MeasurementParameterList\n if empty: return -1\n :return: t0\n \"\"\"\n filename = \"D:\\\\Data\\\\TRMOKE_MeasurementParameterList.dat\"\n if os.path.isfile(filename):\n fileHandle = open(filename, \"r\")\n lineList = fileHandle.readlines()\n fileHandle.close()\n try:\n lastline = np.fromstring(lineList[-1], dtype=float, sep=' \\t')\n return lastline[5]\n except IndexError:\n return -1\n else:\n return -1\n\n def findNormValue():\n col = get_color_list(len(data.keys()), 'plasma')\n for key, value in data.items():\n frame = normHysteresis[key]\n frame['average'] = frame.iloc[:, 1:3].mean(axis=1)\n firstmax = frame['# #Voltage (V)'].idxmax()\n firstmin = frame['# #Voltage (V)'].idxmin()\n secondmax = frame['# #Voltage (V)'].loc[firstmin:].idxmax()\n\n branchStart = pd.DataFrame(\n {\"Voltage\": frame['# #Voltage (V)'].loc[0:firstmax],\n \"Hyst\": \"\"})\n branchdown = pd.DataFrame(\n {\"Voltage\": frame['# #Voltage (V)'].loc[firstmax:firstmin],\n \"Hyst\": \"\"})\n branchUp = pd.DataFrame(\n {\"Voltage\": frame['# #Voltage (V)'].loc[firstmin:secondmax],\n \"Hyst\": \"\"})\n\n for i in range(0, firstmax + 1):\n branchStart['Hyst'].iloc[i] = frame['average'].iloc[i]\n\n newidx = 0\n\n for i in range(firstmax, firstmin + 1):\n branchdown['Hyst'].iloc[newidx] = frame['average'].iloc[i]\n newidx = newidx + 1\n\n newidx = 0\n for i in range(firstmin, secondmax + 1):\n branchUp['Hyst'].iloc[newidx] = frame['average'].iloc[i]\n newidx = newidx + 1\n\n newidx = 0\n for i in range(secondmax, len(frame['# #Voltage (V)'])):\n branchdown['Hyst'].iloc[newidx] = (branchdown['Hyst'].iloc[\n newidx] +\n frame['average'].iloc[i]) / 2\n newidx = newidx + 1\n\n AvgHyst = pd.concat([branchStart, branchUp[::-1], branchdown[::-1]])\n AvgHyst.set_index('Voltage', inplace=True)\n\n plotNormHysteresis(AvgHyst, firstmax, firstmin, key, col)\n plotAllNormHysteresis(AvgHyst, firstmax, firstmin, key, col)\n\n def averageHysteresis(self):\n\n for key, value in normHysteresis_all.items():\n data = value.values\n data[:, 0] = np.round(data[:, 0], 6)\n data1 = data[50:, :]\n\n selectIncreasing = np.diff(data1[:, 0]) > 0\n selectDecreasing = np.diff(data1[:, 0]) < 0\n data1 = data1[1:, :]\n currents = np.unique(data1[:, 0])\n results = np.zeros((np.size(currents), 6))\n\n counter = 0\n for c in currents:\n results[counter, 0] = c\n selectCurrent = data1[:, 0] == c\n select1 = selectCurrent & selectIncreasing\n select2 = selectCurrent & selectDecreasing\n results[counter, 1] = np.mean(data1[select1, 1])\n results[counter, 2] = np.mean(data1[select2, 1])\n results[counter, 3] = np.mean(data1[select1, 2])\n results[counter, 4] = np.mean(data1[select2, 2])\n #results[counter, 5] = TeslaDict[c] if c in TeslaDict else TeslaDict[\n # min(TeslaDict.keys(), key=lambda k: abs(float(k) - float(c)))]\n results[counter, 5] = np.copy(results[counter, 1])\n\n counter += 1\n\n offset = np.mean(np.append(results[np.invert(np.isnan(\n results[:, 1])), 1],\n results[\n np.invert(np.isnan(results[:, 2])), 2]))\n\n t0 = 183\n results[:, 1] = results[:, 1]-offset\n results[:, 2] = results[:, 2]-offset\n results[:, 3] = results[:, 3]-offset\n results[:, 4] = results[:, 4]-offset\n def MOKE(self, dataframe, t0=readLastTimeZero(), deleteLoop=[]):\n\n for key, value in dataframe.items():\n print(key)\n # set timeZero\n if t0 == -1:\n Information[key]['t0'] = 0\n else:\n Information[key]['t0'] = t0\n\n # remove index column\n del value['Unnamed: 0']\n\n # calculate a time axis with coorected Zero and insert column\n # in dataframe\n StagePos = (value['StagePosition']).convert_objects(\n convert_numeric=True)\n StagePos = StagePos - float(Information[key]['t0'])\n value.insert(0, 'StagePos', StagePos)\n\n # round original column of magnetic field to either\n # positiv or negativ\n value['MagneticField'] = np.where(value['MagneticField'] > 0,\n 1 *\n np.round(value['MagneticField'][0]),\n (-1 *\n np.round(value['MagneticField'][0]))\n )\n\n # Sort the values for Chopped and Unchopped as well as\n # positive and negative field\n ChopMPlus = value.loc[(value.loc[:, 'Chopper'] > 0) & (\n value.loc[:, 'MagneticField'] > 0)]\n UnChopMPlus = value.loc[(value.loc[:, 'Chopper'] <= 0) & (\n value.loc[:, 'MagneticField'] > 0)]\n ChopMMinus = value.loc[(value.loc[:, 'Chopper'] > 0) & (\n value.loc[:, 'MagneticField'] < 0)]\n UnChopMMinus = value.loc[(value.loc[:, 'Chopper'] <= 0) & (\n value.loc[:, 'MagneticField'] < 0)]\n\n # set loop and stage position as index\n\n ChopMPlus.set_index(['Loops', 'StagePos'], inplace=True)\n UnChopMPlus.set_index(['Loops', 'StagePos'], inplace=True)\n ChopMMinus.set_index(['Loops', 'StagePos'], inplace=True)\n UnChopMMinus.set_index(['Loops', 'StagePos'], inplace=True)\n\n PumpProbe = ChopMPlus.copy(deep=True)\n\n del PumpProbe['Diodesignal']\n #del PumpProbe['MinusDiode']\n #del PumpProbe['PlusDiode']\n #del PumpProbe['ReferenzDiode']\n del PumpProbe['Background']\n del PumpProbe['Chopper']\n del PumpProbe['MagneticField']\n\n AllData = PumpProbe.copy(deep=True)\n PumpProbe['Diodesignal_Plus'] = (ChopMPlus['Diodesignal'].values -\n UnChopMPlus['Diodesignal'].values)\n\n PumpProbe['Diodesignal_Minus'] = (ChopMMinus['Diodesignal'].values -\n UnChopMMinus['Diodesignal'].values)\n\n PumpProbe['Diodesignal_Minus'] = \\\n PumpProbe['Diodesignal_Minus'].values[::-1]\n\n '''\n PumpProbe['Diode_Minus_Minus'] = (ChopMMinus['MinusDiode'].values -\n UnChopMMinus['MinusDiode'].values)\n\n PumpProbe['Diode_Minus_Plus'] = (ChopMPlus['MinusDiode'].values -\n UnChopMPlus['MinusDiode'].values)\n\n PumpProbe['Diode_Plus_Minus'] = (ChopMMinus['PlusDiode'].values -\n UnChopMMinus['PlusDiode'].values)\n\n PumpProbe['Diode_Plus_Plus'] = (ChopMPlus['PlusDiode'].values -\n UnChopMPlus['PlusDiode'].values)\n\n PumpProbe['ReferenceDiode_Plus_Minus'] = (ChopMMinus['ReferenzDiode'].values -\n UnChopMMinus['ReferenzDiode'].values)\n\n PumpProbe['ReferenceDiode_Plus_Minus'] = (ChopMPlus['ReferenzDiode'].values -\n UnChopMPlus['ReferenzDiode'].values)\n '''\n\n\n\n # drop specified loops\n for entry in deleteLoop:\n\n ChopMPlus = self.dropLoops(ChopMPlus, entry)\n UnChopMPlus = self.dropLoops(UnChopMPlus, entry)\n ChopMMinus = self.dropLoops(ChopMMinus, entry)\n UnChopMMinus = self.dropLoops(UnChopMMinus, entry)\n\n # Average All Loops\n ChopMPlus_AverageOverLoop = ChopMPlus.groupby(level=[1]).mean()\n ChopMMinus_AverageOverLoop = ChopMMinus.groupby(level=[1]).mean()\n UnChopMPlus_AverageOverLoop = UnChopMPlus.groupby(level=[1]).mean()\n UnChopMMinus_AverageOverLoop = UnChopMMinus.groupby(level=[1]).mean()\n\n # create MOKE dataframe\n MOKE_Average = ChopMPlus_AverageOverLoop.copy(deep=True)\n del MOKE_Average['Chopper']\n del MOKE_Average['MagneticField']\n\n Data_Average = pd.DataFrame(index=MOKE_Average.index,\n columns=['MOKESignal',\n 'ElectronicSignal',\n 'MinusDiode', 'PlusDiode',\n 'ReferenzDiode'])\n\n MOKE_Average['Diodesignal'] = (ChopMPlus_AverageOverLoop[\n 'Diodesignal'].values -\n UnChopMPlus_AverageOverLoop[\n 'Diodesignal'].values) - (\n ChopMMinus_AverageOverLoop[\n 'Diodesignal'].values -\n UnChopMMinus_AverageOverLoop[\n 'Diodesignal'].values)\n\n Data_Average['MOKESignal'] = MOKE_Average['Diodesignal']\n #Data_Average.set_index(['StagePos'], inplace=True)\n Data_Average['ElectronicSignal'] = (ChopMPlus_AverageOverLoop[\n 'Diodesignal'].values -\n UnChopMPlus_AverageOverLoop[\n 'Diodesignal'].values) + (\n ChopMMinus_AverageOverLoop[\n 'Diodesignal'].values -\n UnChopMMinus_AverageOverLoop[\n 'Diodesignal'].values)\n '''Data_Average['MinusDiode'] = (ChopMPlus_AverageOverLoop[\n 'MinusDiode'].values +\n ChopMMinus_AverageOverLoop[\n 'MinusDiode'].values) - (\n UnChopMPlus_AverageOverLoop[\n 'MinusDiode'].values +\n UnChopMMinus_AverageOverLoop[\n 'MinusDiode'].values) /\\\n (UnChopMPlus_AverageOverLoop[\n 'MinusDiode'].values +\n UnChopMMinus_AverageOverLoop[\n 'MinusDiode'].values)\n Data_Average['PlusDiode'] = (ChopMPlus_AverageOverLoop[\n 'PlusDiode'].values +\n ChopMMinus_AverageOverLoop[\n 'PlusDiode'].values) - (\n UnChopMPlus_AverageOverLoop[\n 'PlusDiode'].values +\n UnChopMMinus_AverageOverLoop[\n 'PlusDiode'].values) /\\\n (UnChopMPlus_AverageOverLoop[\n 'PlusDiode'].values +\n UnChopMMinus_AverageOverLoop[\n 'PlusDiode'].values)\n '''\n MOKE_Data[key] = MOKE_Average\n PumpProbeData[key]= PumpProbe\n Averaged_Data[key] = Data_Average\n\n return MOKE_Data, Data_Average\n\n def dropLoops(self, frame, loop):\n return frame.drop([loop], level='Loops')\n\n def plotCompareLoops_PumpProbe(self, PlotFrame, name= 'noName', xmin=np.inf,\n xmax=np.inf, ymin=np.inf, ymax=np.inf):\n for key, value in PlotFrame.items():\n if PlotFrame[key].empty == False:\n fig = plt.figure()\n fig.set_size_inches(18.5, 10.5)\n for loop in range(value.index.get_level_values(0).nunique()):\n col = self.get_color_list(value.index.get_level_values(0).nunique(), 'viridis')\n plt.plot(value.xs(loop+1, level='Loops').index.values, value.xs(loop+1, level='Loops')['Diodesignal_Plus'],\n label=str(\n Information[key][\n 'Fluence']) + \"mJcm2 Loop:\" + str(loop),\n color=col[loop], alpha=0.75)\n plt.plot(value.xs(loop + 1, level='Loops').index.values, value.xs(loop + 1, level='Loops')['Diodesignal_Minus'],\n label=str(\n Information[key]['Fluence']) + \"mJcm2 Loop:\" + str(loop),\n color=col[loop], alpha=0.75)\n if (xmin and xmax !=np.inf):\n plt.xlim(xmin, xmax)\n if (ymin and ymax != np.inf):\n plt.ylim(ymin, ymax)\n plt.legend()\n handles, labels = plt.gca().get_legend_handles_labels()\n by_label = OrderedDict(zip(labels, handles))\n plt.legend(by_label.values(), by_label.keys())\n plt.savefig(str(self.saveFilePath)+str(\"CompareLoops\\\\\")+'MOKE_CompareLoops_' + str(Information[key]['Fluence']) + 'mJcm2_.png', dpi=300,\n transparent=False)\n plt.close()\n\n def get_color_list(self, N, cmap):\n # returns a list of N rgb values extracted from the cmap\n cmap = cm.get_cmap(cmap, N)\n return cmap(np.arange(N))\n\n def makeFolder(self, Name):\n if not os.path.exists(Name):\n os.makedirs(Name)\n \"\"\"\n This procedure creates an empty folder if the target Folder does not already exist. \n Parameters\n ----------\n PathToFolder : string\n Path to the newly created folder\n\n Example\n -------\n >>> makeFolder(\"SubFolder/NewFolderName\")\n Creates a new folder with the name \"NewFolder\" in the directory \"SubFolder\" \n relative to the working path but only if this folder does not already exist.\n \"\"\"\n\n def plotDataframeUnit(self, PlotFrame, unit, name ='', xmin=np.inf,\n xmax=np.inf, ymin=np.inf, ymax=np.inf):\n plt.figure()\n plt.clf()\n col = self.get_color_list(len(PlotFrame.keys()), 'plasma')\n for key, value in PlotFrame.items():\n if not PlotFrame[key].empty:\n y = pd.to_numeric(value[unit].values.tolist())\n x = pd.to_numeric(value.index.values.tolist())\n plt.plot(x, y, label=str(Information[key]['Fluence']),\n color=col[key])\n if (xmin and xmax != np.inf):\n plt.xlim(xmin, xmax)\n if (ymin and ymax != np.inf):\n plt.ylim(ymin, ymax)\n handles, labels = plt.gca().get_legend_handles_labels()\n by_label = OrderedDict(zip(labels, handles))\n plt.legend(by_label.values(), by_label.keys())\n plt.savefig(str(self.saveFilePath)+str(unit)+str(name)+'.png', dpi=300)\n plt.show()\n plt.close()\n\n def readMagenticFieldFromLastFile(self):\n list_of_files = glob.glob('D:\\\\PythonSkripts\\\\MagnetfieldCalibration\\\\*.dat')\n latest_file = max(list_of_files, key=os.path.getctime)\n magRef = np.genfromtxt(latest_file)\n TeslaDict = dict(magRef)\n return TeslaDict\n\ndef main():\n analysis = DataAnalysisMOKE(\"D:\\\\Data\\\\MOKE_PumpProbe\", \"20180812_171227\")\n analysis.readData()\n TeslaDict = analysis.readMagenticFieldFromLastFile()\n analysis.MOKE(data)\n analysis.averageHysteresis()\n #analysis.plotCompareLoops_PumpProbe(PumpProbeData)\n #analysis.plotDataframeUnit(Averaged_Data, 'MOKESignal')\n #analysis.plotDataframeUnit(Averaged_Data, 'ElectronicSignal')\n #analysis.plotDataframeUnit(Averaged_Data, 'ElectronicSignal',\n # name='_zoomed', xmin=-10, xmax=50)\n #analysis.plotDataframeUnit(Averaged_Data, 'ElectronicSignal',\n # name='_zoomed2', xmin=-10, xmax=200)\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/AnalysisMOKE20.py","file_name":"AnalysisMOKE20.py","file_ext":"py","file_size_in_byte":21369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"144134329","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\nn_params = 21\n\n#file = open('GaussElimData/206005460_2146.47_2.18_3.53_ltf.lc')\n#file = open('GaussElimData/206059064_2179.16_15.62_3.44_ltf.lc')\nfile = open('GaussElimData/206067215_2146.62_27.89_2.50_ltf.lc')\n#file = open('/home/marko/Desktop/MIT Research/KIC012557548.dat', 'r')\n#file = open('/home/marko/Desktop/MIT Research/KIC008153499.dat', 'r')\nfile.next()\nfile.next()\n\ntime = []\nflux = []\n\ndata_period = 10. #in days\nshortest_period = 0.5 #in days\nf_max = 1./shortest_period\ndelta_f = 1./data_period\n\nfreqrange = np.linspace(delta_f, f_max, f_max/delta_f)\n\nfor line in file:\n\tparts = line.split()\n\ttime.append(float(parts[0]))\n\tflux.append(float(parts[1]))\n\t#flux.append(float(parts[2]))\n\nmaxtime = int(data_period*round(float(time[-2])/data_period))\n\ntimesplit = np.linspace(data_period, maxtime, maxtime/data_period)\n\n#timefull = np.zeros_like(time)\n#fitfull = np.zeros_like(flux)\n#datafull = np.zeros_like(flux)\n\ntimefull = []\nfitfull = []\ndatafull = []\n\nfor val in xrange(len(timesplit)):\n#for val in range(0, len(timesplit)):\n\tif timesplit[val]==maxtime: continue\n\ttime50 = [t for t in time if timesplit[val] <= t <= timesplit[val+1]]\n\tdata50 = [flux[time.index(t)] for t in time50]\n\n\tfmatrix = np.array([[0.]*n_params for _ in range(n_params)])\n\tfmatrix.shape = (n_params,n_params)\n\tdmatrix = np.array([0.]*n_params)\n\tdmatrix.shape = (n_params,1)\n\n\tif time50==[]:continue\n\t\n\tfor x in xrange(len(time50)-1):\n\t#\td = (19.2 + 16.5*(t/100.) - 134*((t/100.)**2) + 449*((t/100.)**3))\n\t\tt = time50[x]\n\t\td = data50[x]\n\t\t#f1 = math.sin(2*math.pi*freqrange[0]*t)\n\t\t#f2 = math.sin(2*math.pi*freqrange[1]*t)\n\t\t#f3 = math.sin(2*math.pi*freqrange[2]*t)\n\t\t#f4 = math.sin(2*math.pi*freqrange[3]*t)\n\t\t#f5 = math.sin(2*math.pi*freqrange[4]*t)\n\t\t#f6 = math.sin(2*math.pi*freqrange[5]*t)\n\t\t#f7 = math.sin(2*math.pi*freqrange[6]*t)\n\t\t#f8 = math.sin(2*math.pi*freqrange[7]*t)\n\t\t#f9 = math.sin(2*math.pi*freqrange[8]*t)\n\t\t#f10 = math.sin(2*math.pi*freqrange[9]*t)\n\t\t#f11 = math.cos(2*math.pi*freqrange[0]*t)\n\t\t#f12 = math.cos(2*math.pi*freqrange[1]*t)\n\t\t#f13 = math.cos(2*math.pi*freqrange[2]*t)\n\t\t#f14 = math.cos(2*math.pi*freqrange[3]*t)\n\t\t#f15 = math.cos(2*math.pi*freqrange[4]*t)\n\t\t#f16 = math.cos(2*math.pi*freqrange[5]*t)\n\t\t#f17 = math.cos(2*math.pi*freqrange[6]*t)\n\t\t#f18 = math.cos(2*math.pi*freqrange[7]*t)\n\t\t#f19 = math.cos(2*math.pi*freqrange[8]*t)\n\t\t#f20 = math.cos(2*math.pi*freqrange[9]*t)\n\t\t#f21 = 1.\n\n\t\tfsinvector = [math.sin(2*math.pi*freqrange[i]*t) for i in range(len(freqrange)/2)]\n\t\tfcosvector = [math.cos(2*math.pi*freqrange[i]*t) for i in range(len(freqrange)/2)]\n\t\t\n\t\tfvector = fsinvector\n\t\tfvector.extend(fcosvector)\n\t\tfvector.append(1)\n\n\t\n\t\t#fvector = [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20, f21]\n\t\n\t\tfor row in range(n_params):\n\t\t\tfor column in range(n_params):\n\t\t\t\tfmatrix[row, column] += (fvector[row]*fvector[column])\n\t\t\tdmatrix[row] += d*fvector[row]\n\t\n\t\n\tinvfmatrix = np.linalg.inv(fmatrix)\n\t\n\tsolmatrix = np.dot(invfmatrix, dmatrix)\n\t\n\t#print solmatrix\n\t\n\tfit50 = []\n\t\n\tfor x in xrange(len(time50)):\n\t\tt = time50[x]\n\t\t#fit1 = solmatrix[0]*math.sin(2*math.pi*freqrange[0]*t)\n\t\t#fit2 = solmatrix[1]*math.sin(2*math.pi*freqrange[1]*t)\n\t\t#fit3 = solmatrix[2]*math.sin(2*math.pi*freqrange[2]*t)\n\t\t#fit4 = solmatrix[3]*math.sin(2*math.pi*freqrange[3]*t)\n\t\t#fit5 = solmatrix[4]*math.sin(2*math.pi*freqrange[4]*t)\n\t\t#fit6 = solmatrix[5]*math.sin(2*math.pi*freqrange[5]*t)\n\t\t#fit7 = solmatrix[6]*math.sin(2*math.pi*freqrange[6]*t)\n\t\t#fit8 = solmatrix[7]*math.sin(2*math.pi*freqrange[7]*t)\n\t\t#fit9 = solmatrix[8]*math.sin(2*math.pi*freqrange[8]*t)\n\t\t#fit10 = solmatrix[9]*math.sin(2*math.pi*freqrange[9]*t)\n\t\t#fit11 = solmatrix[10]*math.cos(2*math.pi*freqrange[0]*t)\n\t\t#fit12 = solmatrix[11]*math.cos(2*math.pi*freqrange[1]*t)\n\t\t#fit13 = solmatrix[12]*math.cos(2*math.pi*freqrange[2]*t)\n\t\t#fit14 = solmatrix[13]*math.cos(2*math.pi*freqrange[3]*t)\n\t\t#fit15 = solmatrix[14]*math.cos(2*math.pi*freqrange[4]*t)\n\t\t#fit16 = solmatrix[15]*math.cos(2*math.pi*freqrange[5]*t)\n\t\t#fit17 = solmatrix[16]*math.cos(2*math.pi*freqrange[6]*t)\n\t\t#fit18 = solmatrix[17]*math.cos(2*math.pi*freqrange[7]*t)\n\t\t#fit19 = solmatrix[18]*math.cos(2*math.pi*freqrange[8]*t)\n\t\t#fit20 = solmatrix[19]*math.cos(2*math.pi*freqrange[9]*t)\n\t\t#fit21 = solmatrix[20]*1.\n\n\t\tfitsinvector = [solmatrix[i]*math.sin(2*math.pi*freqrange[i]*t) for i in range(len(freqrange)/2)]\n\t\tfitcosvector = [solmatrix[i+10]*math.cos(2*math.pi*freqrange[i]*t) for i in range(len(freqrange)/2)]\n\t\t\n\t\tfitvector = fitsinvector\n\t\tfitvector.extend(fitcosvector)\n\t\tfitvector.append(solmatrix[20]*1)\n\t\n\t\tfit50.extend(data50[x]-sum(fitvector))\n\n\ttimefull.extend(time50)\n\tdatafull.extend(data50)\n\tfitfull.extend(fit50)\n\t#for x in xrange(len(time50)):\n\t#\tfitfull[((val-1)*len(time50))+x] = fit50[x]\n\t#\ttimefull[((val-1)*len(time50))+x] = time50[x]\n\t#\tdatafull[((val-1)*len(time50))+x] = data50[x]\n\tfig = plt.figure()\n\tsp1 = fig.add_subplot(211)\n\tsp1.step(time50, data50, 'k')\n\t\n\tsp2 = fig.add_subplot(212)\n\tsp2.step(time50, fit50, 'k')\n#\n\tfigname = 'GaussElimData/fig' + str(val)\n\tplt.savefig(figname)\n#\n\tplt.close()\n\n\t#del time50, fit50, fvector, data50, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20, fit1, fit2, fit3, fit4, fit5, fit6, fit7, fit8, fit9, fit10, fit11, fit12, fit13, fit14, fit15, fit16, fit17, fit18, fit19, fit20\n\nfig2 = plt.figure()\n\nfor value in range(len(flux)):\n\tflux[value] -= 1\n\nsplt1 = fig2.add_subplot(211)\nsplt1.step(time[:-2], flux[:-2], 'k')\n\nsplt2 = fig2.add_subplot(212, sharex=splt1, sharey=splt1)\nsplt2.step(timefull, fitfull, 'k')\n\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n#timevector = []\n#datavector = []\n\n#f11vector = []\n#f12vector = []\n#f13vector = []\n#f14vector = []\n#f21vector = []\n#f22vector = []\n#f23vector = []\n#f24vector = []\n#f31vector = []\n#f32vector = []\n#f33vector = []\n#f34vector = []\n#f41vector = []\n#f42vector = []\n#f43vector = []\n#f44vector = []\n\n#d1vector = []\n#d2vector = []\n#d3vector = []\n#d4vector = []\n\n#for t in xrange(100):\n#\td = (19.2 + 16.5*(t/100.) - 134*((t/100.)**2) + 449*((t/100.)**3))\t\n\t#f11vector.append(1*1)\n\t#f12vector.append(1*(t/100.))\n\t#f13vector.append(1*((t/100.)**2))\n\t#f14vector.append(1*((t/100.)**3))\n\t#f21vector.append(1*(t/100.))\n\t#f22vector.append((t/100.)*(t/100.))\n\t#f23vector.append((t/100.)*((t/100.)**2))\n\t#f24vector.append((t/100.)*((t/100.)**3))\n\t#f31vector.append(1*((t/100.)**2))\n\t#f32vector.append((t/100.)*((t/100.)**2))\n\t#f33vector.append(((t/100.)**2)*((t/100.)**2))\n\t#f34vector.append(((t/100.)**2)*((t/100.)**3))\n\t#f41vector.append(1*((t/100.)**3))\n\t#f42vector.append((t/100.)*((t/100.)**3))\n\t#f43vector.append(((t/100.)**2)*((t/100.)**3))\n\t#f44vector.append(((t/100.)**3)*((t/100.)**3))\n\t#d1vector.append(d*1)\n\t#d2vectoar.append(d*(t/100.))\n\t#d3vector.append(d*((t/100.)**2))\n\t#d4vector.append(d*((t/100.)**3))\n\n\n##\ttimevector.append(t)\n##\tdatavector.append(d)\n\n#f11 = sum(f11vector)\n#f12 = sum(f12vector)\n#f13 = sum(f13vector)\n#f14 = sum(f14vector)\n#f21 = sum(f21vector)\n#f22 = sum(f22vector)\n#f23 = sum(f23vector)\n#f24 = sum(f24vector)\n#f31 = sum(f31vector)\n#f32 = sum(f32vector)\n#f33 = sum(f33vector)\n#f34 = sum(f34vector)\n#f41 = sum(f41vector)\n#f42 = sum(f42vector)\n#f43 = sum(f43vector)\n#f44 = sum(f44vector)\n#d1 = sum(d1vector)\n#d2 = sum(d2vector)\n#d3 = sum(d3vector)\n#d4 = sum(d4vector)\n#\n\n#dmatrix = np.matrix([[d1], [d2], [d3], [d4]])\n#fmatrix = np.matrix([[f11, f12, f13, f14], [f21, f22, f23, f24], [f31, f32, f33, f34], [f41, f42, f43, f44]])\n#invfmatrix = np.linalg.inv(fmatrix)\n\n#solmatrix = np.dot(invfmatrix, dmatrix)\n\n#print solmatrix","sub_path":"gaussianelimination.py","file_name":"gaussianelimination.py","file_ext":"py","file_size_in_byte":7653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"616474354","text":"import ffmpeg\nimport numpy as np\n\nimport os\nimport sys\nsys.argv=['']\nsys.path.append('/nethome/jbang36/eva_jaeho')\n\nfrom loaders.seattle_loader import SeattleLoader\n\n\n\n\n\n\nif __name__ == \"__main__\":\n ###dummy_video = np.ndarray(shape = (10, 100, 200, 3)) -- let's try loading a normal video\n original_video = '/nethome/jbang36/eva_jaeho/data/seattle/seattle2_10min.mp4'\n\n seattle_loader = SeattleLoader()\n dummy_video = seattle_loader.load_images(original_video)\n ## we will see if we can load and save the dummy video\n\n\n framerate = 25\n _, height, width, _ = dummy_video.shape\n fn = '/nethome/jbang36/eva_jaeho/data/seattle/test2.mp4'\n\n vcodec = 'libx264'\n\n process = (\n ffmpeg\n .input('pipe:', format='rawvideo', r=framerate, pix_fmt='rgb24', s='{}x{}'.format(width, height))\n .output(fn, pix_fmt='yuv420p', vcodec=vcodec)\n .overwrite_output()\n .run_async(pipe_stdin=True, pipe_stdout=True)\n )\n\n for frame in dummy_video:\n process.stdin.write(\n frame\n .astype(np.uint8)\n .tobytes()\n )\n process.stdin.close()\n process.wait()\n\n\n\n","sub_path":"examples/encoder_prototyping.py","file_name":"encoder_prototyping.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"182540847","text":"\n\n#calss header\nclass _GRID():\n\tdef __init__(self,): \n\t\tself.name = \"GRID\"\n\t\tself.definitions = [u'a pattern or structure made from horizontal and vertical lines crossing each other to form squares: ', u'a system of wires through which electricity is connected to different power stations across a region: ', u'a pattern of squares with numbers or letters used to find places on a map']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_grid.py","file_name":"_grid.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"18449629","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.azclierror import InvalidArgumentValueError\nfrom azure.cli.core.commands.client_factory import get_subscription_id\nfrom msrestazure.tools import is_valid_resource_id, resource_id\nfrom azext_scvmm.scvmm_constants import (\n EXTENDED_LOCATION_TYPE,\n)\nfrom .vendored_sdks.models import (\n ExtendedLocation,\n)\n\n\ndef get_resource_id(\n cmd,\n resource_group_name: str,\n provider_name_space: str,\n resource_type: str,\n resource: str,\n):\n \"\"\"\n Gets the resource id for the resource if name is given.\n \"\"\"\n\n if resource is None or is_valid_resource_id(resource):\n return resource\n return resource_id(\n subscription=get_subscription_id(cmd.cli_ctx),\n resource_group=resource_group_name,\n namespace=provider_name_space,\n type=resource_type,\n name=resource,\n )\n\n\ndef create_dictionary_from_arg_string(values, option_string=None):\n \"\"\"\n Creates and returns dictionary from a string containing params in KEY=VALUE format.\n \"\"\"\n params_dict = {}\n for item in values:\n try:\n key, value = item.split('=', 1)\n params_dict[key.lower()] = value\n except ValueError as err:\n raise InvalidArgumentValueError(\n f'usage error: {option_string} KEY=VALUE [KEY=VALUE ...]'\n ) from err\n return params_dict\n\n\ndef get_extended_location(custom_location):\n return ExtendedLocation(\n type=EXTENDED_LOCATION_TYPE,\n name=custom_location,\n )\n","sub_path":"src/scvmm/azext_scvmm/scvmm_utils.py","file_name":"scvmm_utils.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"534964538","text":"import pandas as pd\r\nimport googlemaps\r\nimport json\r\nfrom pymongo import MongoClient\r\nclient = MongoClient()\r\ndb = client.Saarthi\r\nnis= db.nis\r\n\r\ndf = pd.read_excel(\"Average noise pollution statistics for the year 2016.xlsx\", \"Yearly Average\")\r\nfp = open(\"db_nis.txt\",\"a\",encoding=\"utf8\")\r\nfp1 = open(\"dbn_nis1.txt\",\"a\",encoding=\"utf8\")\r\ngmaps = googlemaps.Client(key='AIzaSyBNbSHpD55qfU-m2WbrhoPEEIAHFEIIKVE')\r\nprint(df.iloc[38,2])\r\nprint(df.iloc[38,15])\r\nloc = []\r\nfor i in range(3,39):\r\n loc.append([df.iloc[i,2],df.iloc[i,15]])\r\nprint(gmaps.geocode(loc[0][0]+' Pune'))\r\nfor i in loc:\r\n #print(i)\r\n result = gmaps.geocode(i[0] + ' Pune')\r\n if (len(result)!=0) :\r\n lat = result[0][\"geometry\"][\"location\"][\"lat\"]\r\n lon = result[0][\"geometry\"][\"location\"][\"lng\"]\r\n fp.write(str(lat) + \" \" + str(lon) + \" \" + str(i[1]) + \"\\n\")\r\n fp1.write(str(lat) + \" \" + str(lon) + \" \" + str(i[1]) + \"\\n\" + \" [\" + i[0] +\"]\" + \"\\n\")\r\n nis.insert_one({\"lat\":lat, \"lng\": lon, \"attr\": i[1]})\r\nfp.close()\r\nfp1.close()\r\n","sub_path":"Data_analysis/db_nis_analysis.py","file_name":"db_nis_analysis.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"215923178","text":"import numpy as np\nimport tensorflow as tf\nfrom scipy.signal import convolve2d\nfrom matplotlib import pyplot as plt\nimport matplotlib.animation as animation\n\n\nclass Conway(object):\n\n def __init__(self):\n self.shape = (50, 50)\n self.session = tf.Session()\n \n\n def run(self):\n initial_board = self.init_board()\n\n board = tf.placeholder(tf.int32, shape=self.shape, name='board')\n board_update = tf.py_func(self.update_board, [board], [tf.int32])\n\n initial_board_values = self.session.run(initial_board)\n X = self.session.run(board_update, feed_dict={board: initial_board_values})[0]\n\n ani = animation.FuncAnimation(self.plot(X), self.game_of_life, interval=200, blit=True)\n plt.show()\n\n return X\n\n\n def init_board(self):\n initial_board = tf.random_uniform(self.shape, minval=0, maxval=2, dtype=tf.int32)\n return initial_board\n\n\n def update_board(self, X):\n N = convolve2d(X, np.ones((3,3)), mode='same', boundary='wrap') - X\n X = (N == 3) | (X & (N == 2))\n return X\n\n\n def game_of_life(self, *args):\n X = self.session.run(board_update, feed_dict={board: X})[0]\n plot.set_array(X)\n return plot,\n\n\n def plot(self, X):\n fig = plt.figure()\n plot = plt.imshow(X, cmap='Greys', interpolation='nearest')\n plt.show()\n return fig\n\n\nif __name__ == '__main__':\n\n conway = Conway()\n X = conway.run()\n","sub_path":"python/tensorflow/demos/tensorflow/concepts/conway.py","file_name":"conway.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"229480111","text":"import os\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.tensorboard import SummaryWriter\nfrom torchvision import transforms\n\nimport params\nimport utils\nfrom dataloader import CIFAR10\n\nfrom models.softmax import Softmax\n\n\nclass ModelTrainer:\n \"\"\"Class for training and testing of model\"\"\"\n\n def __init__(self, args):\n self.args = args\n\n if self.args.eval:\n if self.args.eval_checkpoint == \"\":\n raise ValueError(\n \"Eval mode is set, but no checkpoint path is provided!\"\n )\n self.loader = torch.load(self.args.eval_checkpoint)\n\n # Data Augmentation\n transformations_img_train = [\n transforms.ToTensor(),\n transforms.Normalize(\n self.args.cifar10_mean_color, self.args.cifar10_std_color\n ),\n ]\n transformations_img_test = [\n transforms.ToTensor(),\n transforms.Normalize(\n self.args.cifar10_mean_color, self.args.cifar10_std_color\n ),\n ]\n if self.args.data_aug:\n data_aug_transform = [\n transforms.RandomCrop(\n self.args.random_crop_size, padding=self.args.random_crop_pad\n ),\n transforms.RandomHorizontalFlip(),\n ]\n transformations_img_train = data_aug_transform + transformations_img_train\n transform_train = transforms.Compose(transformations_img_train)\n transform_test = transforms.Compose(transformations_img_test)\n\n # Datasets\n if self.args.eval is False:\n self.train_dataset = CIFAR10(\n self.args.cifar10_dir,\n split=\"train\",\n download=True,\n transform=transform_train,\n )\n self.val_dataset = CIFAR10(\n self.args.cifar10_dir,\n split=\"val\",\n download=True,\n transform=transform_test,\n )\n self.test_dataset = CIFAR10(\n self.args.cifar10_dir, split=\"test\", download=True, transform=transform_test\n )\n\n # Data Loaders\n if self.args.eval is False:\n self.train_loader = torch.utils.data.DataLoader(\n self.train_dataset, batch_size=self.args.batch_size, shuffle=True\n )\n self.val_loader = torch.utils.data.DataLoader(\n self.val_dataset, batch_size=self.args.test_batch_size, shuffle=True\n )\n self.test_loader = torch.utils.data.DataLoader(\n self.test_dataset, batch_size=self.args.test_batch_size, shuffle=True\n )\n\n # Load the model\n if self.args.model == \"softmax\":\n self.model = Softmax(self.args.image_size, self.args.no_of_classes)\n else:\n raise Exception(\"Unknown model {}\".format(self.args.model))\n\n if self.args.eval:\n self.model.load_state_dict(self.loader)\n\n if self.args.cuda:\n self.model.cuda()\n\n self.best_test_accuracy = 0.0\n self.best_test_epoch = 0\n\n if self.args.eval is False:\n\n if self.args.optimiser == \"sgd\":\n self.opt = optim.SGD(\n self.model.parameters(),\n lr=self.args.learning_rate,\n momentum=self.args.momentum,\n weight_decay=self.args.weight_decay,\n )\n else:\n raise Exception(\"Unknown optimiser {}\".format(self.args.optim))\n\n if self.args.lr_scheduler:\n self.lr_scheduler = optim.lr_scheduler.MultiStepLR(\n self.opt,\n milestones=self.args.lr_schedule,\n gamma=self.args.lr_decay_factor,\n )\n\n # Loss function\n self.criterion = nn.CrossEntropyLoss()\n\n self.args.logdir = os.path.join(\"checkpoints\", self.args.exp_name)\n utils.create_dir(self.args.logdir)\n\n if self.args.filelogger:\n self.logger_path = os.path.join(\"checkpoints\", self.args.exp_name, \"%s_values.log\" % self.args.exp_name)\n self.logger = {\n \"train_loss_per_iter\": [],\n \"train_loss_per_epoch\": [],\n \"val_loss_per_iter\": [],\n \"val_loss_per_epoch\": [],\n \"val_accuracy_per_iter\": [],\n \"val_accuracy_per_epoch\": [],\n \"test_loss\": [],\n \"test_accuracy\": [],\n \"best_epoch\": 0,\n \"best_test_accuracy\": 0.0\n }\n if self.args.tensorboard:\n self.writer = SummaryWriter(log_dir=self.args.logdir, flush_secs=30)\n self.writer.add_text(\"Arguments\", params.print_args(self.args))\n\n def train_val(self, epoch):\n \"\"\"Train the model for one epoch and evaluate on val split if log_intervals have passed\"\"\"\n\n for batch_idx, batch in enumerate(self.train_loader):\n self.model.train()\n self.opt.zero_grad()\n\n self.iter += 1\n\n images, targets = batch\n if self.args.cuda:\n images, targets = images.cuda(), targets.cuda()\n\n logits, unnormalised_scores = self.model(images)\n loss = self.criterion(unnormalised_scores, targets)\n loss.backward()\n self.opt.step()\n\n if batch_idx % self.args.log_interval == 0:\n val_loss, val_acc = self.evaluate(\"Val\", n_batches=4)\n\n train_loss, val_loss, val_acc = utils.convert_for_print(\n loss, val_loss, val_acc\n )\n\n if self.args.filelogger:\n self.logger[\"train_loss_per_iter\"].append([self.iter, train_loss])\n self.logger[\"val_loss_per_iter\"].append([self.iter, val_loss])\n self.logger[\"val_accuracy_per_iter\"].append([self.iter, val_acc])\n\n if self.args.tensorboard:\n self.writer.add_scalar(\"Loss_at_Iter/Train\", train_loss, self.iter)\n self.writer.add_scalar(\"Loss_at_Iter/Val\", val_loss, self.iter)\n self.writer.add_scalar(\"Accuracy_at_Iter/Val\", val_acc, self.iter)\n\n examples_this_epoch = batch_idx * len(images)\n epoch_progress = 100.0 * batch_idx / len(self.train_loader)\n print(\n \"Train Epoch: %3d [%5d/%5d (%5.1f%%)]\\t \"\n \"Train Loss: %0.6f\\t Val Loss: %0.6f\\t Val Acc: %0.1f\"\n % (\n epoch,\n examples_this_epoch,\n len(self.train_loader.dataset),\n epoch_progress,\n train_loss,\n val_loss,\n val_acc,\n )\n )\n\n if self.args.filelogger:\n self.logger[\"train_loss_per_epoch\"].append([epoch, train_loss])\n self.logger[\"val_loss_per_epoch\"].append([epoch, val_loss])\n self.logger[\"val_accuracy_per_epoch\"].append([epoch, val_acc])\n\n if self.args.tensorboard:\n self.writer.add_scalar(\"Loss_at_Epoch/Train\", train_loss, epoch)\n self.writer.add_scalar(\"Loss_at_Epoch/Val\", val_loss, epoch)\n self.writer.add_scalar(\"Accuracy_at_Epoch/Val\", val_acc, epoch)\n\n def evaluate(self, split, epoch=None, verbose=False, n_batches=None):\n \"\"\"Evaluate model on val or test data\"\"\"\n\n self.model.eval()\n with torch.no_grad():\n loss = 0\n correct = 0\n n_examples = 0\n\n if split == \"Val\":\n loader = self.val_loader\n elif split == \"Test\":\n loader = self.test_loader\n\n for batch_idx, batch in enumerate(loader):\n images, targets = batch\n if args.cuda:\n images, targets = images.cuda(), targets.cuda()\n\n logits, unnormalised_scores = self.model(images)\n loss += F.cross_entropy(unnormalised_scores, targets, reduction=\"sum\")\n pred = logits.max(1, keepdim=False)[1]\n correct += pred.eq(targets).sum()\n n_examples += pred.shape[0]\n if n_batches and (batch_idx >= n_batches):\n break\n\n loss /= n_examples\n acc = 100.0 * correct / n_examples\n\n if split == \"Test\" and acc >= self.best_test_accuracy:\n self.best_test_accuracy = utils.convert_for_print(acc)\n self.best_test_epoch = epoch\n if self.args.filelogger:\n self.logger[\"best_epoch\"] = self.best_test_epoch\n self.logger[\"best_test_accuracy\"] = self.best_test_accuracy\n if verbose:\n if epoch is None:\n epoch = 0\n self.best_test_epoch = 0\n loss, acc = utils.convert_for_print(loss, acc)\n print(\n \"\\n%s set Epoch: %2d \\t Average loss: %0.4f, Accuracy: %d/%d (%0.1f%%)\"\n % (split, epoch, loss, correct, n_examples, acc)\n )\n print(\n \"Best %s split Performance: Epoch %d - Accuracy: %0.1f%%\"\n % (split, self.best_test_epoch, self.best_test_accuracy)\n )\n\n if self.args.filelogger:\n self.logger[\"test_loss\"].append([epoch, loss])\n self.logger[\"test_accuracy\"].append([epoch, acc])\n if self.args.tensorboard:\n self.writer.add_scalar(\"Loss_at_Epoch/Test\", loss, epoch)\n self.writer.add_scalar(\"Accuracy_at_Epoch/Test\", acc, epoch)\n self.writer.add_scalar(\n \"Accuracy_at_Epoch/Best_Test_Accuracy\",\n self.best_test_accuracy,\n self.best_test_epoch,\n )\n\n return loss, acc\n\n def train_val_test(self):\n \"\"\" Function to train, validate and evaluate the model\"\"\"\n self.iter = 0\n for epoch in range(1, self.args.epochs + 1):\n self.train_val(epoch)\n self.evaluate(\"Test\", epoch, verbose=True)\n if self.args.lr_scheduler:\n self.lr_scheduler.step()\n if epoch % self.args.checkpoint_save_interval == 0:\n print(\n \"Saved %s/%s_epoch%d.pt\\n\"\n % (self.args.logdir, self.args.exp_name, epoch)\n )\n torch.save(\n self.model.state_dict(),\n \"%s/%s_epoch%d.pt\" % (self.args.logdir, self.args.exp_name, epoch),\n )\n self.writer.close()\n if self.args.filelogger:\n utils.write_log_to_json(self.logger_path, self.logger)\n\n\nif __name__ == \"__main__\":\n args = params.parse_args()\n utils.set_random_seed(args.seed, args.cuda)\n trainer = ModelTrainer(args=args)\n if args.eval is False:\n trainer.train_val_test()\n if args.eval is True:\n trainer.evaluate(\"Test\", verbose=True)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"465995938","text":"import numpy as np\nimport cv2\n\nim=cv2.imread(\"/home/nam/VndMoneyRec_Nam/img_test/IMG_20181201_170631.jpg\",4)\n\nim=cv2.imread(\"/home/nam/Tiền/abcd.jpg\",4)\n\n\nimgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n\nret, thresh = cv2.threshold(imgray, 127, 255, 0)\n\nim2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\nhull = []\n\nfor i in range(len(contours)):\n hull.append(cv2.convexHull(contours[i], False))\n\ndrawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)\n\nmax_idx = 0\nmax_contour = contours[0]\nfor idx, each_contour in enumerate(contours):\n if cv2.contourArea(each_contour) > cv2.contourArea(max_contour):\n max_contour = each_contour\n max_idx = idx\n\n\ncolor_contours = (0, 255, 0)\ncolor = (255, 0, 0)\n# draw ith contour\ncv2.drawContours(im, contours, max_idx, color_contours, 3, 8, hierarchy)\n# draw ith convex hull object point\ncv2.drawContours(im, hull, i, max_idx, 1, 100)\n\n# cv2.imwrite( \"/home/nam/VndMoneyRec_Nam/output/Countour_convexHull.jpg\", im)\nrect = cv2.boundingRect(max_contour)\nx, y, w, h = rect\ncv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)\n\ncv2.imshow('dst',im)\nif cv2.waitKey(0) & 0xff == 27:\n cv2.destroyAllWindows()\nprint(max_idx)\nprint(len(contours))\n","sub_path":"convexhull.py","file_name":"convexhull.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"570993320","text":"import os\r\nimport sys\r\n\r\n\r\n# 初始化\r\ndef setup():\r\n BASEDIR = os.path.dirname(os.path.abspath(__file__))\r\n # print(BASEDIR)\r\n # print(os.path.abspath(os.path.join(BASEDIR, '..')))\r\n sys.path.insert(0, BASEDIR)\r\n sys.path.insert(0, os.path.abspath(os.path.join(BASEDIR, '..')))\r\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"devops10.settings\")\r\n\r\n import django\r\n django.setup()\r\n\r\n\r\n# 业务逻辑\r\ndef logic():\r\n m2m_query()\r\n\r\ndef m2m_query():\r\n from book.models import Publisher, Book\r\n from user.models import UserProfile\r\n\r\n b = Book.objects.get(name='从卓越到优秀')\r\n authors = b.authors.all() # QuerySet\r\n for a in authors:\r\n print(a.username, a.phone, a.staff_id, a.email)\r\n\r\n u = UserProfile.objects.get(username='pc3')\r\n books = u.book_set.all()\r\n print(books)\r\n print('pc3发行', [ b.name for b in books])\r\n\r\n\r\ndef base_object_query():\r\n from book.models import Publisher, Book\r\n\r\n # Foreignkey 基于对象的查询\r\n b = Book.objects.get(name='从卓越到优秀')\r\n # 正向查询\r\n print(\"----正向查询----\")\r\n print(b.name, b.desc, b.publisher_state, b.get_publisher_state_display())\r\n print(b.publisher_id)\r\n print(b.publisher.name, b.publisher.address)\r\n\r\n # 反向查询\r\n print(\"----反向查询----\")\r\n p = Publisher.objects.get(name='人民出版社')\r\n print(p.book_set.all()) # QuerySet\r\n print([p.name for p in p.book_set.all()])\r\n book_info = []\r\n for b in p.book_set.all():\r\n book_info.append({\r\n 'name': b.name,\r\n 'desc': b.desc,\r\n 'publisher_state': b.get_publisher_state_display(),\r\n })\r\n # print(b.name, b.desc, b.get_publisher_state_display())\r\n print(book_info)\r\n\r\ndef base_field_query():\r\n # Foreignkey 基于字段的查询\r\n from book.models import Publisher, Book\r\n\r\n # bs = Book.objects.filter(publisher__name='人民出版社')\r\n # print(bs)\r\n\r\n ps = Publisher.objects.filter(book__desc='非常好的书籍')\r\n print(ps)\r\n\r\n # # 正向查询\r\n # print(\"----正向查询----\")\r\n # b = Book.objects.filter(publisher__name='人民出版社')\r\n # print(b.query)\r\n # for x in b.all():\r\n # print(x.name, x.publisher.name, x.get_publisher_state_display())\r\n #\r\n # # 反向向查询\r\n # print(\"----反向查询----\")\r\n # p = Publisher.objects.filter(book__name='Go源码分析')\r\n # print(p.query)\r\n # for x in p.all():\r\n # print(x.name, x.address, x.book_set.all())\r\n\r\n\r\n# 入口函数\r\ndef main():\r\n setup()\r\n\r\n logic()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"lesson04/devops10/scripts/m2m_fk_01.py","file_name":"m2m_fk_01.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"57352771","text":"from decimal import Decimal\nfrom django.conf import settings\nfrom .models import Product\n\n\nclass Cart(object):\n\n def __init__(self, request):\n self.session = request.session\n cart = self.session.get(settings.CART_SESSION_ID)\n if not cart:\n cart = self.session[settings.CART_SESSION_ID] = {}\n self.cart = cart\n\n def __iter__(self):\n ids = self.cart.keys()\n # products = Product.objects.filter(id__in=ids)\n\n def add(self, product, quantity=1):\n id = product.id\n if str(id) not in self.cart.keys():\n self.cart[id] = {\n \"id\": id,\n \"name\": product.name,\n \"quantity\": 1,\n \"price\": product.price,\n }\n print(\"no\" + str(id))\n else:\n # print(\"yes\" + str(id))\n for key, value in self.cart.items():\n if key == str(id):\n value['quantity'] = value['quantity'] + 1\n # print(value['quantity'])\n self.save()\n # print(self.cart)\n\n def decrement(self, product):\n id = product.id\n needProducts = self.cart.values()\n for item in needProducts:\n if item['id'] == id:\n item['quantity'] = item['quantity'] - 1\n # print(item['quantity'])\n if item['quantity'] == 0:\n return\n self.save()\n\n def remove(self, product):\n id = product.id\n for x, y in self.cart.items():\n if id == y['id']:\n key = x\n if key in self.cart:\n del self.cart[key]\n self.save()\n\n def clear(self):\n del self.session[settings.CART_SESSION_ID]\n self.save()\n\n def save(self):\n # self.session[settings.CART_SESSION_ID] = self.cart\n self.session.modified = True\n\n def items(self):\n cart = self.cart.values()\n return cart\n\n def get_total_items(self):\n keys = self.cart.keys()\n count = len(keys)\n return count\n\n def get_total_price(self):\n a = []\n for item in self.cart.values():\n total_sum = item['quantity'] * Decimal(item['price'])\n a.append(total_sum)\n return sum(a)\n\n\n\n\n\n","sub_path":"shopapp/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"513891947","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponseNotFound\nfrom django.contrib import messages\nfrom django.contrib.auth import logout, login, authenticate\nfrom clubbing.forms import SignUpForm, AddPurchase, FormOrder\nfrom clubbing.models import *\n\n\ndef index(request):\n list_item = Item.objects.all()\n return render(request, 'index.html', context={'items': list_item})\n\n\ndef logout_page(request):\n if request.user.is_authenticated:\n logout(request)\n return render(request, 'logout.html')\n else:\n return render(request, 'error.html', context={'error_title': 'Выход',\n 'error_content': 'Авторизованные пользователи могут только выйти!'})\n\n\ndef login_page(request):\n # user = authenticate(request)\n # login(request, user)\n if request.method == 'GET':\n return render(request, 'login.html')\n elif request.method == 'POST':\n login_str = request.POST[\"login\"]\n password_str = request.POST[\"password\"]\n user = authenticate(username=login_str, password=password_str)\n if user is not None:\n login(request, user)\n else:\n return render(request, 'login.html', context={'error_m': 'Не верный логин или пароль'})\n return redirect('index')\n\n# ASd123fkasd123\ndef register_page(request):\n if request.method == 'GET':\n return render(request, 'register.html', context={'form': SignUpForm()})\n elif request.method == 'POST':\n form = SignUpForm(request.POST, request.FILES)\n # print(form.errors)\n if form.is_valid():\n form.save()\n else:\n return render(request, 'register.html', context={'form': SignUpForm(), 'error_m': 'Ошибка при заполнении формы регистрации'})\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password1')\n user = authenticate(username=username, password=password)\n if user is None:\n return redirect('register')\n login(request, user)\n return redirect('index')\n\n\ndef purchases(request):\n if request.user.is_authenticated and request.user.group == User.ORGANIZER:\n if request.method == 'GET':\n listPurchases = Purchase.objects.all().filter(user=request.user).order_by('-id')\n return render(request, 'purchases.html', context={'purchases': listPurchases})\n else:\n purch = Purchase.objects.get(pk=request.POST['purch'])\n purch.status = request.POST['status']\n purch.save()\n msg = f'Продажа началась для тоавара: {purch.item}' if request.POST['status'] == 'SL' else f'Продажа закрыта: {purch.item}'\n messages.info(request, msg)\n return redirect('purchases')\n\n\ndef detail_item(request, pk):\n d_item = Item.objects.get(pk=pk)\n return render(request, 'detail_item.html', context={'detail': d_item})\n\n\ndef add_purchase(request):\n if request.user.is_authenticated and request.user.group == User.ORGANIZER:\n if request.method == 'GET':\n item_list = Item.objects.all()\n return render(request, 'add_purchase.html', context={'form': AddPurchase(initial={'user': request.user}), 'items': item_list})\n else:\n purch_form = AddPurchase(request.POST, initial={'user': request.user})\n d_item = Item.objects.get(pk=request.POST['item'])\n max_cost_purch = int(request.POST['max_cost'])\n if purch_form.is_valid():\n if d_item.price > max_cost_purch:\n messages.error(request, 'Максимальная стоимость должна быть не меньше цены за товар')\n return render(request, 'add_purchase.html', context={'form': AddPurchase(initial={'user': request.user})})\n\n purch_form.save()\n messages.info(request, 'Товар успешно добавлен')\n return redirect('purchases')\n else:\n messages.error(request, 'Ошибка при заполнении формы добавления товара')\n return render(request, 'add_purchase.html', context={'form': AddPurchase(initial={'user': request.user})})\n\ndef clubbings(request):\n if request.user.is_authenticated and request.user.group == 'BR':\n if request.method == 'GET':\n all_purch = Purchase.objects.reverse().all().filter(status=Purchase.OPEN)\n orders = [el['purchase'] for el in Order.objects.all().filter(buyer=request.user).values('purchase')]\n\n return render(request, 'clubbings.html', context={'orders': orders,\n 'purchases': all_purch})\n else:\n form_order = FormOrder(request.POST)\n if form_order.is_valid():\n form_order.save()\n all_purchases = Purchase.objects.all()\n # Назначаем старт продажи\n for purch in all_purchases:\n count_members = len(purch.members.all())\n if count_members * purch.item.price >= purch.max_cost:\n purch.status = Purchase.SELL\n purch.save()\n messages.info(request, 'Вы встали в очередь на заказ!')\n return redirect('clubbings')\n\ndef profile(request):\n return render(request, 'profile.html')","sub_path":"clubbing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"606772583","text":"import sys\nimport pytesseract\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport re\n\n\ndef is_allowed_specific_char(string):\n charRe = re.compile(r'[^a-zA-Z.]')\n string = charRe.search(string)\n return not bool(string)\n\ndef maincalculation(im):\n text = pytesseract.image_to_string(im)\n arraystring = text.split()\n Button_number = 0\n Cardview_number = 0\n button_heights = []\n button_widths = []\n for x in range(len(arraystring)):\n if arraystring[x] == 'Button':\n Button_number= Button_number+1\n buttonstr = arraystring[x + 1]\n button = list(buttonstr)\n print(button)\n for a in range(len(button)):\n if button[a] == '/':\n button_height = button[:a]\n button_width = button[a:]\n button_width.remove('/')\n button_height_int = 0\n for a in range(len(button_height)):\n button_height_int = 10 * button_height_int + int(button_height[a])\n print(button_height_int)\n button_width_int = 0\n for a in range(len(button_width)):\n button_width_int = 10 * button_width_int + int(button_width[a])\n print(button_width_int)\n button_heights.append(button_height_int)\n button_widths.append(button_width_int)\n if arraystring[x] == 'CardView':\n Cardview_number = Cardview_number + 1\n cardviewstr = arraystring[x + 1]\n cardview = list(cardviewstr)\n print(cardview)\n for a in range(len(cardview)):\n if cardview[a] == '/':\n cardview_height = cardview[:a]\n cardview_width = cardview[a:]\n cardview_width.remove('/')\n return button_heights, button_widths\n\ndef imagedata(image):\n axisdata = []\n axis = pytesseract.image_to_boxes(image)\n for x in range(len(axis)):\n if is_allowed_specific_char(axis[x]):\n axisdata.append(axis[x])\n while axis[x+2] != ' ':\n axisdata.append(axis[x+2])\n x = x+1\n return axisdata\n\n\ndef imagedata2(image):\n axisdatay = []\n axis = pytesseract.image_to_boxes(image)\n for x in range(len(axis)):\n if is_allowed_specific_char(axis[x]):\n axisdatay.append(axis[x])\n count = 0\n for a in range(x, len(axis)):\n if axis[a] == ' ':\n count = count + 1\n if count == 2:\n a = a+1\n axisdatay.append(axis[a])\n a = a + 1\n x = x+1\n for x in axisdatay:\n if x == ' ':\n axisdatay.remove(x)\n return axisdatay\n\n\ndef buttonletter(image):\n text = pytesseract.image_to_string(image)\n arraystring = text.split()\n buttonstring = []\n print(arraystring)\n for x in range(len(arraystring)):\n if arraystring[x] == 'Button':\n buttonstring.append( arraystring[x+3])\n return buttonstring\n\n\ndef buttonpixel(image):\n x = imagedata(image)\n y = imagedata2(image)\n buttonx = []\n buttony = []\n for i in range(len(x)):\n if is_allowed_specific_char(x[i]):\n buttonx.append(x[i])\n arrayvalue = 0\n array = []\n i = i+1\n for a in range(i, len(x)):\n if not is_allowed_specific_char(x[a]):\n array.append(x[i])\n i = i+1\n else:\n break\n for a in range(len(array)):\n arrayvalue = 10 * arrayvalue + int(array[a])\n buttonx.append(arrayvalue)\n for i in range(len(y)):\n if is_allowed_specific_char(y[i]):\n buttony.append(y[i])\n arrayvalue = 0\n array = []\n i = i+1\n for a in range(i, len(y)):\n if not is_allowed_specific_char(y[a]):\n array.append(y[i])\n i = i+1\n else:\n break\n for a in range(len(array)):\n arrayvalue = 10 * arrayvalue + int(array[a])\n buttony.append(arrayvalue)\n return buttonx, buttony\n\n\ndef precise(image):\n x, y = buttonpixel(image)\n buttoninx = []\n buttoniny = []\n for i in range(len(x)):\n if x[i] == \"B\" and x[i+2] == \"u\" and x[i+4] == \"t\" and x[i+6] == \"t\" and x[i+8] == \"o\" and x[i+10] == \"n\":\n buttoninx.append(x[i+1])\n for i in range(len(y)):\n if y[i] == \"B\" and y[i+2] == \"u\" and y[i+4] == \"t\" and y[i+6] == \"t\" and y[i+8] == \"o\" and y[i+10] == \"n\":\n buttoniny.append(y[i+1])\n return buttoninx, buttoniny\n\n","sub_path":"webtoapp/imageana.py","file_name":"imageana.py","file_ext":"py","file_size_in_byte":4750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"637076575","text":"#!/usr/local/bin/python3\n#coding=utf-8\n\nfrom db_utils.db_function import get_process_data\n\n\ndef get_param_value(param = ''):\n sql = \"show global variables like '{:s}'\".format(param)\n results = get_process_data(sql)\n if results:\n res = '{} : {}'.format(results[0], results[1])\n print(res)\n\ndef get_status_value(param = '',only_get_val = 1):\n sql = \"show global status like '{:s}'\".format(param)\n results = get_process_data(sql)\n if results:\n if only_get_val == 1:\n res = '{} : {}'.format(results[0], results[1])\n print(res)\n else:\n res = results[1]\n return res\n","sub_path":"module/db_utils/polling_param_status.py","file_name":"polling_param_status.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"231908181","text":"import random\nimport math\nfrom tower_configuration import g_BADDIE_WIGGLE,g_BADDIE_MAX_WIGGLE\n\nEPSILON = 0.00001\n\nclass Baddie:\n\n def __init__(self, x, y, speed, hp, radius):\n self.x = x\n self.y = y\n self.speed = speed\n self.hp = hp\n self.radius = radius\n self.alive = True\n self.distance = 0.\n self.dx = 0.\n self.dy = 0.\n self.pdx = 0.\n self.pdy = 0.\n return\n\n def getPosition(self):\n return self.x, self.y\n\n def getDirection(self):\n return self.dx, self.dy\n\n def getAlive(self):\n return self.alive\n\n def getRadius(self):\n return self.radius\n\n def setDead(self):\n self.alive = False\n return\n\n def takeDamage(self, damage):\n self.hp -= damage\n if self.hp <= EPSILON:\n self.setDead()\n\n return\n\n def getDistance(self):\n return self.distance\n\n #\n # moves the baddie a little along the path\n #\n def evolve(self, dt, maps, width, height):\n \n # get map direction\n i, j = int(self.x), int(self.y)\n if maps[j][i]:\n dx, dy = maps[j][i].getDirection()\n else:\n dx, dy = 0, 0\n\n # modify personal direction with minor wiggle\n self.pdx += random.uniform(-g_BADDIE_WIGGLE, g_BADDIE_WIGGLE)\n self.pdy += random.uniform(-g_BADDIE_WIGGLE, g_BADDIE_WIGGLE)\n if self.pdx < -g_BADDIE_MAX_WIGGLE: self.pdx = -g_BADDIE_MAX_WIGGLE\n if self.pdx > g_BADDIE_MAX_WIGGLE: self.pdx = g_BADDIE_MAX_WIGGLE\n if self.pdy < -g_BADDIE_MAX_WIGGLE: self.pdy = -g_BADDIE_MAX_WIGGLE\n if self.pdy > g_BADDIE_MAX_WIGGLE: self.pdy = g_BADDIE_MAX_WIGGLE\n \n # modify direction by personal direction\n dx += self.pdx\n dy += self.pdy\n\n # update personal velocity\n self.dx = dx * self.speed\n self.dy = dy * self.speed\n\n # update personal position\n ddx = dt * self.dx\n ddy = dt * self.dy\n self.x += ddx\n self.y += ddy\n\n # update distance traveled by baddie\n self.distance += math.sqrt(ddx*ddx + ddy*ddy)\n \n # off the map border\n if self.x < 0 or self.x > width or self.y < 0 or self.y > height:\n self.alive = False\n \n return","sub_path":"RookieKit-2012/tower_baddie.py","file_name":"tower_baddie.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"418641524","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreated on 28 Feb 2017\n\n@author: Bruno Beloff (bruno.beloff@southcoastscience.com)\n\nDESCRIPTION\nThe modem_power utility is used to apply or remove power to the South Coast Science 2G modem board for BeagleBone.\n\nNote: in some operating system configurations, the modem board is under control of the Debian modem manager. In these\ncases, the modem manager may override the operation of this utility. The modem_power utility is not available on\nRaspberry Pi systems.\n\nSYNOPSIS\nmodem_power.py { 0 | 1 } [-v]\n\nEXAMPLES\n./modem_power.py 1\n\"\"\"\n\nimport sys\n\nfrom scs_core.sys.signalled_exit import SignalledExit\n\nfrom scs_dev.cmd.cmd_power import CmdPower\n\nfrom scs_dfe.interface.interface_conf import InterfaceConf\n\nfrom scs_host.bus.i2c import I2C\nfrom scs_host.sys.host import Host\n\n\n# --------------------------------------------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n I2C.Utilities.open()\n\n # ----------------------------------------------------------------------------------------------------------------\n # cmd...\n\n cmd = CmdPower()\n\n if not cmd.is_valid():\n cmd.print_help(sys.stderr)\n exit(2)\n\n if cmd.verbose:\n print(\"modem_power: %s\" % cmd, file=sys.stderr)\n\n try:\n # ------------------------------------------------------------------------------------------------------------\n # resources...\n\n # Interface...\n interface_conf = InterfaceConf.load(Host)\n\n if interface_conf is None:\n print(\"modem_power: InterfaceConf not available.\", file=sys.stderr)\n exit(1)\n\n interface = interface_conf.interface()\n\n if cmd.verbose:\n print(\"modem_power: %s\" % interface, file=sys.stderr)\n sys.stderr.flush()\n\n\n # ------------------------------------------------------------------------------------------------------------\n # run...\n\n # signal handler...\n SignalledExit.construct(\"modem_power\", cmd.verbose)\n\n if cmd.all is not None:\n interface.power_modem(cmd.all)\n\n\n # ----------------------------------------------------------------------------------------------------------------\n # end...\n\n except ConnectionError as ex:\n print(\"modem_power: %s\" % ex, file=sys.stderr)\n\n except (KeyboardInterrupt, SystemExit):\n pass\n\n finally:\n if cmd and cmd.verbose:\n print(\"modem_power: finishing\", file=sys.stderr)\n\n I2C.Utilities.close()\n","sub_path":"src/scs_dev/modem_power.py","file_name":"modem_power.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"224017671","text":"import PathFinding\nimport re\nimport numpy\n\ndef read_pgm(filename, byteorder='>'):\n \"\"\"Return image data from a raw PGM file as numpy array.\n\n Format specification: http://netpbm.sourceforge.net/doc/pgm.html\n\n \"\"\"\n with open(filename, 'rb') as f:\n buffer = f.read()\n try:\n header, width, height, maxval = re.search(\n b\"(^P5\\s(?:\\s*#.*[\\r\\n])*\"\n b\"(\\d+)\\s(?:\\s*#.*[\\r\\n])*\"\n b\"(\\d+)\\s(?:\\s*#.*[\\r\\n])*\"\n b\"(\\d+)\\s(?:\\s*#.*[\\r\\n]\\s)*)\", buffer).groups()\n except AttributeError:\n raise ValueError(\"Not a raw PGM file: '%s'\" % filename)\n return numpy.frombuffer(buffer,\n dtype='u1' if int(maxval) < 256 else byteorder+'u2',\n count=int(width)*int(height),\n offset=len(header)\n ).reshape((int(height), int(width)))\n\n\ndef convertToMap(fileName):\n map = [[]]\n image = read_pgm(fileName, byteorder='<')\n for y, line in enumerate(image):\n map.append([])\n for x, item in enumerate(line):\n if item == 255:\n map[y].append(True)\n elif item == 205:\n map[y].append(False)\n else:\n map[y].append(None)\n return map\n\ndef readBFTxt(filename):\n bfarr = []\n with open(filename) as f:\n for line in f:\n bfarr.append([int(x) for x in line.strip().split(',')[:-1]])\n\n return bfarr\n\ndef writeBFTxt(filename, bfmap):\n with open(filename, 'w') as f:\n for row in bfmap:\n for col in row:\n f.write(str(col))\n f.write(',')\n f.write('\\n')\n\ndef convertToImg(map):\n image = [[]]\n for y, line in enumerate(image):\n image.append([])\n for x, item in enumerate(line):\n if item == True:\n image[y].append(255)\n elif item == False:\n image[y].append(205)\n else:\n image[y].append(0)\n\nif __name__ == '__main__':\n from matplotlib import pyplot\n\n env = read_pgm('tfmCropTouchUp.pgm', byteorder='<')\n #print('Converting to image')\n # pyplot.imshow(env, pyplot.cm.gray)\n # print('Done converting to image')\n # pyplot.show()\n # colors = []\n # for row in map:\n # for item in row:\n # if item not in colors:\n # colors.append(item)\n # print(colors)\n coordStart = (617, 188)\n coordGoal = (2687, 1776)\n #coordGoal = (801, 168)\n\n coordFlipStart = (621, 962)\n coordFlipGoal = (561, 1133)\n\n# print(map[coordStart[1]][coordStart[0]])\n# print(map[coordGoal[1]][coordGoal[0]])\n\n # bfmap = PathFinding.brushfire(map)\n bfmap = readBFTxt('tfmbf')\n #wfmap = PathFinding.wavefront(env, coordGoal)\n #writeBFTxt('tfmwf', wfmap)\n wfmap = readBFTxt('tfmwf')\n\n\n #print(PathFinding.gradientDescent(map, (3, 2), (7, 6), bfmap))\n print(PathFinding.gradientDescent(env, coordStart, coordGoal, bfmap, wfmap))\n\n #print(PathFinding.gradientDescent(map2, coordStart, coordGoal))\n\n\n\n\n\n# if __name__ == '__main__':\n# with open('thirdFloorMap.pgm') as mapImg:\n# for line in mapImg.readlines():\n# print(line)","sub_path":"TestMain.py","file_name":"TestMain.py","file_ext":"py","file_size_in_byte":3235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"75873833","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# EMLEK - Efficient Machine LEarning toolKit #\n# #\n# This file contains a class that defines an efficient scikit-learn like #\n# pipeline that caches already done processing to disk to accelerate running #\n# time for further executions. #\n# #\n# Developped using Python 3.6. #\n# #\n# Author: Thomas SELECK #\n# e-mail: thomas.seleck@outlook.fr #\n# Date: 2018-05-11 #\n# Version: 1.0.0 #\n# #\n###############################################################################\n\nimport os\nimport numpy as np\nimport pandas as pd\npd.options.mode.chained_assignment = None # default='warn'\nimport time\nfrom sklearn.base import BaseEstimator, clone\nfrom sklearn.pipeline import Pipeline\nfrom joblib import Memory\nfrom inspect import signature\nfrom sklearn.utils.metaestimators import if_delegate_has_method\nfrom scipy.sparse import csr_matrix\nimport pickle\nimport shutil\n\n__all__ = [\"EfficientPipeline\"\n ]\n \ndef _fit_transform_helper(transformer, X, y, name, step_index, to_pandas, additional_data, **fit_params):\n if hasattr(transformer, \"fit_transform\"):\n if \"additional_data\" in list(dict(signature(transformer.transform).parameters).keys()):\n X = transformer.fit_transform(X, y, additional_data, **fit_params)\n else:\n X = transformer.fit_transform(X, y, **fit_params)\n else:\n if \"y\" in list(dict(signature(transformer.transform).parameters).keys()) and \"additional_data\" in list(dict(signature(transformer.transform).parameters).keys()):\n X = transformer.fit(X, y, additional_data, **fit_params).transform(X, y, additional_data)\n elif \"y\" in list(dict(signature(transformer.transform).parameters).keys()): # If the transformer needs 'y' for training set\n X = transformer.fit(X, y, **fit_params).transform(X, y)\n else:\n X = transformer.fit(X, y, **fit_params).transform(X)\n \n # If we want to keep Pandas format\n if to_pandas and not isinstance(X, pd.DataFrame) and not isinstance(X, pd.SparseDataFrame):\n if isinstance(X, np.ndarray): # If X is a regular numpy array, convert it to standard DataFrame\n X = pd.DataFrame(X, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(X.shape[1])])\n elif isinstance(X, csr_matrix): # If X is a sparse matrix, convert it to a SparseDataFrame\n X = pd.SparseDataFrame(X, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(X.shape[1])])\n\n return X, transformer\n\nclass EfficientPipeline(Pipeline):\n \"\"\"\n The purpose of this class is to provide an efficient scikit-learn like pipeline \n that caches already done processing to disk to accelerate running time for further \n executions. This class is based on the original Scikit-Learn Pipeline:\n http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html\n \"\"\"\n\n def __init__(self, steps, cache_dir = None, to_pandas = True):\n \"\"\"\n This is the class' constructor.\n\n Parameters\n ----------\n steps : list\n List of (name, transform) tuples that are chained, in the order in which they \n are chained, with the last object an estimator.\n\n cache_dir : string (default = None)\n This is the path of the directory where cached transformers will be stored. If\n set to None, no caching is done.\n\n to_pandas : bool (default = True)\n This flag indicates whether or not the output of each transformer must be a Pandas\n DataFrame.\n \n Returns\n -------\n None\n \"\"\"\n\n # Class' attributes\n self.steps = steps\n self.cache_dir = cache_dir\n self.to_pandas = to_pandas\n\n # Create cache\n self._memory = Memory(cachedir = self.cache_dir, verbose = 0)\n\n # Create history of steps\n self._steps_history_fit = []\n self._steps_history_fit_transform = []\n self._steps_history_transform = []\n\n def _fit(self, X, y = None, additional_data = None, **fit_params):\n \"\"\"\n This method is a helper for fit method.\n\n Parameters\n ----------\n X : pd.DataFrame\n This is a data frame containing the data used to fit the transformer.\n\n y : pd.Series (default = None)\n This is the target associated with the X data.\n\n Returns\n -------\n Xt : pd.DataFrame\n This is a data frame containing the data transformed by transformers.\n\n final_estimator_params : dict\n Params needd for final estimator.\n \"\"\"\n\n # Check that every step is a transformer\n self._validate_steps()\n\n # Get params for each transformer\n fit_params_steps = dict((name, {}) for name, step in self.steps if step is not None)\n\n for pname, pval in fit_params.items():\n step, param = pname.split(\"__\", 1)\n fit_params_steps[step][param] = pval\n \n # Enable caching\n fit_transform_helper_cached = self._memory.cache(_fit_transform_helper)\n\n # Create steps history\n if self.cache_dir is not None:\n for name, step in self.steps:\n if hasattr(self.named_steps[name], \"fit\"):\n self._steps_history_fit.append((name, self.named_steps[name].fit.__func__.__code__.co_code))\n else:\n self._steps_history_fit.append((name, None))\n\n if hasattr(self.named_steps[name], \"fit_transform\"):\n self._steps_history_fit_transform.append((name, self.named_steps[name].fit_transform.__func__.__code__.co_code))\n else:\n self._steps_history_fit_transform.append((name, None))\n\n if hasattr(self.named_steps[name], \"transform\"):\n self._steps_history_transform.append((name, self.named_steps[name].transform.__func__.__code__.co_code))\n else:\n self._steps_history_transform.append((name, None))\n\n # If a steps history already exists, load it\n if os.path.exists(self.cache_dir + \"steps_history_fit.pkl\") and os.path.exists(self.cache_dir + \"steps_history_fit_transform.pkl\") and os.path.exists(self.cache_dir + \"steps_history_transform.pkl\"):\n with open(self.cache_dir + \"steps_history_fit.pkl\", \"rb\") as f:\n last_steps_history_fit = pickle.load(f)\n\n with open(self.cache_dir + \"steps_history_fit_transform.pkl\", \"rb\") as f:\n last_steps_history_fit_transform = pickle.load(f)\n\n with open(self.cache_dir + \"steps_history_transform.pkl\", \"rb\") as f:\n last_steps_history_transform = pickle.load(f)\n\n valid_fit_steps_lst = []\n for (current_name, current_bytecode), (last_name, last_bytecode) in zip(self._steps_history_fit, last_steps_history_fit):\n if current_name != last_name or current_bytecode != last_bytecode:\n break\n else:\n valid_fit_steps_lst.append(last_name)\n\n valid_fit_transform_steps_lst = []\n for (current_name, current_bytecode), (last_name, last_bytecode) in zip(self._steps_history_fit_transform, last_steps_history_fit_transform):\n if current_name != last_name or current_bytecode != last_bytecode:\n break\n else:\n valid_fit_transform_steps_lst.append(last_name)\n\n valid_transform_steps_lst = []\n for (current_name, current_bytecode), (last_name, last_bytecode) in zip(self._steps_history_transform, last_steps_history_transform):\n if current_name != last_name or current_bytecode != last_bytecode:\n break\n else:\n valid_transform_steps_lst.append(last_name)\n\n self._valid_steps_lst = []\n for valid_fit_step, valid_fit_transform_step, valid_transform_step in zip(valid_fit_steps_lst, valid_fit_transform_steps_lst, valid_transform_steps_lst):\n if valid_fit_step == valid_fit_transform_step and valid_fit_step == valid_transform_step:\n self._valid_steps_lst.append(valid_fit_step)\n else:\n self._valid_steps_lst = []\n\n # Remove invalid steps\n if os.path.exists(self.cache_dir + \"cached_steps_paths_dict.pkl\"):\n with open(self.cache_dir + \"cached_steps_paths_dict.pkl\", \"rb\") as f:\n cached_steps_paths_dict = pickle.load(f)\n\n invalid_steps_lst = list(set(cached_steps_paths_dict.keys()) - set(self._valid_steps_lst))\n for invalid_step in invalid_steps_lst:\n shutil.rmtree(cached_steps_paths_dict[invalid_step])\n\n # Fit transformers and apply their transformations\n Xt = X\n cached_steps_paths_dict = {}\n for step_idx, (name, transformer) in enumerate(self.steps[:-1]):\n if transformer is None:\n pass\n else:\n if self.to_pandas:\n step_index = Xt.index\n else:\n step_index = None\n\n if hasattr(self._memory, \"cachedir\") and self._memory.cachedir is None:\n # we do not clone when caching is disabled to preserve backward compatibility\n cloned_transformer = transformer\n else:\n cloned_transformer = clone(transformer)\n\n # Fit or load from cache the current transfomer\n if self.cache_dir is not None:\n cached_steps_paths_dict[name] = fit_transform_helper_cached.get_output_dir(cloned_transformer, Xt, y, name, step_index, self.to_pandas, additional_data, **fit_params_steps[name])[0]\n\n Xt, fitted_transformer = fit_transform_helper_cached(cloned_transformer, Xt, y, name, step_index, self.to_pandas, additional_data, **fit_params_steps[name])\n \n # Replace the transformer of the step with the fitted transformer. This is necessary when loading the transformer from the cache.\n self.steps[step_idx] = (name, fitted_transformer)\n\n # Save steps history to disk\n if self.cache_dir is not None:\n with open(self.cache_dir + \"steps_history_fit.pkl\", \"wb\") as f:\n pickle.dump(self._steps_history_fit, f)\n\n with open(self.cache_dir + \"steps_history_fit_transform.pkl\", \"wb\") as f:\n pickle.dump(self._steps_history_fit_transform, f)\n\n with open(self.cache_dir + \"steps_history_transform.pkl\", \"wb\") as f:\n pickle.dump(self._steps_history_transform, f)\n\n with open(self.cache_dir + \"cached_steps_paths_dict.pkl\", \"wb\") as f:\n pickle.dump(cached_steps_paths_dict, f)\n\n if self._final_estimator is None:\n return Xt, {}\n \n return Xt, fit_params_steps[self.steps[-1][0]]\n\n def fit(self, X, y = None, additional_data = None, **fit_params):\n \"\"\"\n This method is called to fit the transformer on the training data.\n\n Parameters\n ----------\n X : pd.DataFrame\n This is a data frame containing the data used to fit the transformer.\n\n y : pd.Series (default = None)\n This is the target associated with the X data.\n\n Returns\n -------\n None\n \"\"\"\n\n Xt, fit_params_steps = self._fit(X, y, additional_data, **fit_params)\n \n # Fit the final estimator\n if self._final_estimator is not None:\n self._final_estimator.fit(Xt, y, **fit_params_steps)\n \n return self\n\n @if_delegate_has_method(delegate = \"_final_estimator\")\n def predict(self, X, additional_data = None):\n \"\"\"\n Apply transforms to the data, and predict with the final estimator.\n\n Parameters\n ----------\n X : pd.DataFrame\n Data to predict on. Must fulfill input requirements of first step of the pipeline.\n \n Returns\n -------\n y_pred : numpy array\n Series containing the transformed data.\n \"\"\"\n\n Xt = X\n\n for name, transform in self.steps[:-1]:\n if transform is not None:\n if self.to_pandas:\n step_index = Xt.index\n\n if \"additional_data\" in list(dict(signature(transformer.transform).parameters).keys()):\n Xt = transform.transform(Xt, additional_data)\n else:\n Xt = transform.transform(Xt)\n\n # If we want to keep Pandas format\n if self.to_pandas and not isinstance(Xt, pd.DataFrame) and not isinstance(Xt, pd.SparseDataFrame):\n if isinstance(Xt, np.ndarray): # If Xt is a regular numpy array, convert it to standard DataFrame\n Xt = pd.DataFrame(Xt, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(Xt.shape[1])])\n elif isinstance(Xt, csr_matrix): # If Xt is a sparse matrix, convert it to a SparseDataFrame\n Xt = pd.SparseDataFrame(Xt, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(Xt.shape[1])])\n\n return self.steps[-1][-1].predict(Xt)\n\n def fit_transform(self, X, y, additional_data = None, **fit_params):\n \"\"\"\n Fit the model and transform with the final estimator.\n\n Parameters\n ----------\n X : pd.DataFrame\n This is a data frame containing the data used to fit the transformer.\n\n y : pd.Series (default = None)\n This is the target associated with the X data.\n\n Returns\n -------\n None\n \"\"\"\n\n last_step = self._final_estimator\n Xt, fit_params = self._fit(X, y, additional_data, **fit_params)\n\n if hasattr(last_step, \"fit_transform\"):\n return last_step.fit_transform(Xt, y, **fit_params)\n elif last_step is None:\n return Xt\n else:\n if \"y\" in list(dict(signature(last_step.transform).parameters).keys()) and \"additional_data\" in list(dict(signature(last_step.transform).parameters).keys()):\n return last_step.fit(X, y, additional_data, **fit_params).transform(Xt, y, additional_data)\n elif \"y\" in list(dict(signature(last_step.transform).parameters).keys()): # If the transformer needs 'y' for training set\n return last_step.fit(X, y, **fit_params).transform(Xt, y)\n else:\n return last_step.fit(X, y, **fit_params).transform(Xt)\n\n @if_delegate_has_method(delegate = \"_final_estimator\")\n def fit_predict(self, X, y, additional_data = None, **fit_params):\n \"\"\"\n Applies fit_predict of last step in pipeline after transforms.\n\n Parameters\n ----------\n X : pd.DataFrame\n This is a data frame containing the data used to fit the transformer.\n\n y : pd.Series (default = None)\n This is the target associated with the X data.\n\n Returns\n -------\n None\n \"\"\"\n\n Xt, fit_params = self._fit(X, y, additional_data, **fit_params)\n\n return self.steps[-1][-1].fit_predict(Xt, y, **fit_params)\n\n @if_delegate_has_method(delegate = \"_final_estimator\")\n def predict_proba(self, X, additional_data = None):\n \"\"\"\n Apply transforms, and predict_proba of the final estimator.\n\n Parameters\n ----------\n X : pd.DataFrame\n Data to predict on. Must fulfill input requirements of first step of the pipeline.\n \n Returns\n -------\n y_pred : numpy array\n Series containing the transformed data.\n \"\"\"\n\n Xt = X\n\n for name, transform in self.steps[:-1]:\n if transform is not None:\n if self.to_pandas:\n step_index = Xt.index\n\n if \"additional_data\" in list(dict(signature(transform.transform).parameters).keys()):\n Xt = transform.transform(Xt, additional_data)\n else:\n Xt = transform.transform(Xt)\n\n # If we want to keep Pandas format\n if self.to_pandas and not isinstance(Xt, pd.DataFrame) and not isinstance(Xt, pd.SparseDataFrame):\n if isinstance(Xt, np.ndarray): # If Xt is a regular numpy array, convert it to standard DataFrame\n Xt = pd.DataFrame(Xt, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(Xt.shape[1])])\n elif isinstance(Xt, csr_matrix): # If Xt is a sparse matrix, convert it to a SparseDataFrame\n Xt = pd.SparseDataFrame(Xt, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(Xt.shape[1])])\n\n return self.steps[-1][-1].predict_proba(Xt)\n\n @if_delegate_has_method(delegate = \"_final_estimator\")\n def predict_log_proba(self, X, additional_data = None):\n \"\"\"\n Apply transforms, and predict_log_proba of the final estimator.\n\n Parameters\n ----------\n X : pd.DataFrame\n Data to predict on. Must fulfill input requirements of first step of the pipeline.\n \n Returns\n -------\n y_pred : numpy array\n Series containing the transformed data.\n \"\"\"\n\n Xt = X\n\n for name, transform in self.steps[:-1]:\n if transform is not None:\n if self.to_pandas:\n step_index = Xt.index\n\n if \"additional_data\" in list(dict(signature(transformer.transform).parameters).keys()):\n Xt = transform.transform(Xt, additional_data)\n else:\n Xt = transform.transform(Xt)\n\n # If we want to keep Pandas format\n if self.to_pandas and not isinstance(Xt, pd.DataFrame) and not isinstance(Xt, pd.SparseDataFrame):\n if isinstance(Xt, np.ndarray): # If Xt is a regular numpy array, convert it to standard DataFrame\n Xt = pd.DataFrame(Xt, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(Xt.shape[1])])\n elif isinstance(Xt, csr_matrix): # If Xt is a sparse matrix, convert it to a SparseDataFrame\n Xt = pd.SparseDataFrame(Xt, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(Xt.shape[1])])\n\n return self.steps[-1][-1].predict_log_proba(Xt)\n\n def transform(self, X, y = None, additional_data = None):\n \"\"\"\n Apply transforms, and transform with the final estimator\n\n Parameters\n ----------\n X : pd.DataFrame\n Data to predict on. Must fulfill input requirements of first step of the pipeline.\n\n y : pd.Series (default = None)\n This is the target associated with the X data.\n\n additional_data : object\n Object containing additional data that must be used during transform\n \n Returns\n -------\n Xt : pd.DataFrame\n Transformed data.\n \"\"\"\n\n Xt = X\n\n for name, transform in self.steps:\n if transform is not None:\n if self.to_pandas:\n step_index = Xt.index\n\n if \"y\" in list(dict(signature(transform.transform).parameters).keys()) and \"additional_data\" in list(dict(signature(transform.transform).parameters).keys()):\n Xt = transform.transform(Xt, y, additional_data)\n elif \"y\" in list(dict(signature(transform.transform).parameters).keys()):\n Xt = transform.transform(Xt, y)\n else:\n Xt = transform.transform(Xt)\n \n # If we want to keep Pandas format\n if self.to_pandas and not isinstance(Xt, pd.DataFrame) and not isinstance(Xt, pd.SparseDataFrame):\n if isinstance(Xt, np.ndarray): # If Xt is a regular numpy array, convert it to standard DataFrame\n Xt = pd.DataFrame(Xt, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(Xt.shape[1])])\n elif isinstance(Xt, csr_matrix): # If Xt is a sparse matrix, convert it to a SparseDataFrame\n Xt = pd.SparseDataFrame(Xt, index = step_index, columns = [name + \"_col_\" + str(i) for i in range(Xt.shape[1])])\n\n return Xt","sub_path":"python_code/M5_Forecasting_Accuracy/m5_forecasting_accuracy/model_utils/efficient_pipeline.py","file_name":"efficient_pipeline.py","file_ext":"py","file_size_in_byte":21663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"58161797","text":"#Mekhelef Yassine\n#Bensitel Younes\nfrom tkinter import *\nfrom tkinter.messagebox import *\nfrom random import randint\nimport math\n\n\n#A. La classe Piece et ses descendantes\n\nclass Piece(object):\n __nbCotes=8\n def __init__(self,can,x,y,r,nbCotes=8):\n self.__can=can\n self.x=x\n self.y=y\n self.r=r\n if nbCotes%2==1:\n Piece.__nbCotes=nbCotes-1 \n else:\n Piece.__nbCotes=nbCotes \n self.generer() \n self.dessinerPiece() \n @classmethod\n def getNbCotes(cls):\n return cls.__nbCotes\n def __eq__(self,p):\n def mod(l1): # Pour retirer les 1 si il y a un 2 ou un 3 dans les troues\n if 1 in l1:\n if 2 in l1 or 3 in l1:\n for i in range(l1.count(1)):\n l1[l1.index(1)]=0\n elif l1.count(1)>1:\n for i in range(l1.count(1)-1):\n l1[l1.index(1)]=0\n \n return l1\n\n l1=mod(self.getTrou())\n l2=mod(p.getTrou()) \n return l1==l2 and self.getTrait()==p.getTrait()\n \n def dessinerPiece(self):\n #dessine octogone\n rotation=9\n segment=math.pi*2/self.__nbCotes\n points = [(self.r+math.sin(segment * i + rotation) * self.r,self.r+math.cos(segment * i + rotation) * self.r)for i in range(self.__nbCotes)]\n self.__can.create_polygon(points,outline='gray', fill='gray', width=2)\n #trait\n rp = 5 # distance pour les petit cercles\n for i in range(len(self.getTrait())):\n if self.getTrait()[i]!=0:\n if i==0:self.__can.create_line(0,50,100,50,width=self.getTrait()[i],fill=\"black\")\n if i==1:self.__can.create_line(15,15,85,85,width=self.getTrait()[i],fill=\"black\")\n if i==2:self.__can.create_line(50,0,50,100,width=self.getTrait()[i],fill=\"black\")\n if i==3:self.__can.create_line(85,15,15,85,width=self.getTrait()[i],fill=\"black\")\n #trou\n for i in range (len(self.getTrou())):\n if i==1:\n if self.getTrou()[i]==1:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\")\n if self.getTrou()[i]==2:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(15-rp,30-rp,15+rp,30+rp,fill=\"white\",outline=\"white\")\n if self.getTrou()[i]==3:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(15-rp,30-rp,15+rp,30+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(85-rp,70-rp,85+rp,70+rp,fill=\"white\",outline=\"white\")\n if i==0:\n if self.getTrou()[i]==1:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\")\n if self.getTrou()[i]==2:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(rp,50-rp,rp+2*rp,50-rp+2*rp,fill=\"white\",outline=\"white\")\n if self.getTrou()[i]==3:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(rp,50-rp,rp+2*rp,50-rp+2*rp,fill=\"white\",outline=\"white\");self.__can.create_oval(100-4*rp,50-rp,100-2*rp,50+rp,fill=\"white\",outline=\"white\")\n if i==2:\n if self.getTrou()[i]==1:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\")\n if self.getTrou()[i]==2:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(50-rp,rp,50+rp,rp+2*rp,fill=\"white\",outline=\"white\")\n if self.getTrou()[i]==3:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(50-rp,rp,50+rp,rp+2*rp,fill=\"white\",outline=\"white\");self.__can.create_oval(50-rp,100-3*rp,50+rp,100-rp,fill=\"white\",outline=\"white\")\n if i==3:\n if self.getTrou()[i]==1:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\")\n if self.getTrou()[i]==2:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(50+4*rp,4*rp,100-4*rp,50-4*rp,fill=\"white\",outline=\"white\")\n if self.getTrou()[i]==3:self.__can.create_oval(50-rp,50-rp,50+rp,50+rp,fill=\"white\",outline=\"white\");self.__can.create_oval(50+4*rp,4*rp,100-4*rp,50-4*rp,fill=\"white\",outline=\"white\");self.__can.create_oval(0+4*rp,50+4*rp,50-4*rp,100-4*rp,fill=\"white\",outline=\"white\")\n \n def getCan(self):\n return self.__can\n def raz(self): \n self.getCan().delete(ALL)\n def generer(self):\n raise NotImplementedError(\"Problème de génération dû aux données entrées ?\")\n \n\nclass PieceModele(Piece):\n def __init__(self,can,x,y,r,nbCotes):\n Piece.__init__(self,can,x,y,r,nbCotes)\n def generer(self):\n #au hasard\n self.__trous=[]\n self.__traits=[]\n for element in range(int(Piece.getNbCotes()/2)): \n self.__trous.append(randint(0,3))\n self.__traits.append(randint(0,3))\n #pas dans la consigne mais c'est pour verifié que ça marche\n def getTrou(self):\n return self.__trous\n def getTrait(self):\n return self.__traits\n def getTrouTrait(self):\n return (self.__trous,self.__traits)\n\nclass PieceUsine(Piece):\n def __init__(self,can,x,y,r,nbCotes):\n Piece.__init__(self,can,x,y,r,nbCotes)\n def generer(self):\n #vide\n self.__trous=[]\n self.__traits=[]\n for element in range(int(Piece.getNbCotes()/2)):\n self.__trous.append(0)\n self.__traits.append(0)\n def trouer(self,nb): \n self.__trous[0]=nb\n def tracer(self,epaisseur): \n self.__traits[0]=epaisseur\n def tourner(self,angle):#décale les élément suivant le numéro de angle (1,2,3)\n taille= angle%len(self.__trous)#on aurait pu prendre trait car même taille\n self.__trous=self.__trous[-taille:] + self.__trous[:-taille]\n self.__traits=self.__traits[-taille:]+ self.__traits[:-taille]\n #(self.getTrouTrait())\n def getTrou(self):\n return self.__trous\n def getTrait(self):\n return self.__traits\n def getTrouTrait(self):\n return (self.__trous,self.__traits)\n\n\n#B.La classe Machine et ses descendantes\n\nclass Machine(object):\n def __init__(self,config=0):\n self.__config=config\n def getConfig(self):\n return self.__config\n def setConfig(self,val):\n self.__config=val\n\nclass MPassive(Machine):\n def usiner(self,p):\n pass #A REVOIR\n\nclass MTrou(Machine):\n def __init__(self,config=1):\n Machine.__init__(self,config)\n self.__config=config\n def usiner(self,p):\n p.trouer(int(self.getConfig()))\n \nclass MTrait(Machine):\n def __init__(self,config=1):\n Machine.__init__(self,config)\n self.__config=config\n def usiner(self,p):\n p.tracer(int(self.getConfig()))\n\nclass MRoue(Machine):\n def __init__(self,config=1):\n Machine.__init__(self,config)\n self.__config=config\n def usiner(self,p):\n p.tourner(int(self.getConfig()))\n\n#C.La classe Chaine\n\nclass Chaine(list):\n __machines={0:MPassive,1:MTrou,2:MTrait,3:MRoue}\n def __init__(self,nbMachine):\n for x in range(nbMachine):\n self.append(MPassive(0))\n @classmethod\n def getMachines(cls):\n return cls.__machines\n def setMachine(self,i,typee=0): \n self[i]=Chaine.__machines[typee]()#*\n def setConfMachine(self,i,config): \n self[i].setConfig(config)\n def usiner(self,p): #bouton ok\n for i in range(len(self)):\n self[i].usiner(p)\n def raz(self): #bouton recommencer\n for i in range(len(self)):\n self[i]=MPassive(0)\n\n#D. Les classes VueMachine et VueChaine\nclass VueMachine(Frame):\n chaine=None\n NomPho=['Ima/trou.gif', 'Ima/trait.gif','Ima/roue.gif', 'Ima/vide.gif']\n def __init__(self,master,num):\n Frame.__init__(self,master)\n self.num=num\n self.photo=PhotoImage(file='Ima/vide.gif')\n #A COMPLETER\n self.can=Canvas(self, width=100, height=100)\n self.can.pack()\n self.can.create_image(50,50,image=self.photo)\n self.scale=Scale(self,command=self.scaller,orient=HORIZONTAL,from_=1,to=3)\n self.scale.pack()\n \n #MENU POP UP POUR CHOISIR LE TYPE DE MACHINE\n self.pho=[PhotoImage(file=fichier).subsample(2,2) for fichier in VueMachine.NomPho]\n self.popup= Menu(self,tearoff=False)\n for i in range(4):\n self.popup.add_command(image=self.pho[i],command=lambda i=i:self.affiche(i))\n self.can.bind(\"\",self.onbind)\n\n def onbind(self,event):\n self.popup.tk_popup(event.x_root, event.y_root, 0)\n\n def affiche(self,i): \n self.photo.configure(file=VueMachine.NomPho[i])\n if VueMachine.NomPho[i]=='Ima/trou.gif':\n VueMachine.chaine.setMachine(self.num,1)#trous\n if VueMachine.NomPho[i]=='Ima/trait.gif':\n VueMachine.chaine.setMachine(self.num,2)\n if VueMachine.NomPho[i]=='Ima/roue.gif':\n VueMachine.chaine.setMachine(self.num,3)\n if VueMachine.NomPho[i]=='Ima/vide.gif':\n VueMachine.chaine.setMachine(self.num,0)\n app.pieceu=PieceUsine(app.c1,10,50,50,8)\n app.chaine.usiner(app.pieceu)\n app.pieceu.dessinerPiece()\n \n def scaller(self,val):\n VueMachine.chaine.setConfMachine(self.num,val)\n app.pieceu=PieceUsine(app.c1,10,50,50,8)\n app.chaine.usiner(app.pieceu)\n app.pieceu.dessinerPiece()\n\nclass VueChaine(Frame):\n def __init__(self,master,nb,**kw):\n Frame.__init__(self,master,**kw)\n VueMachine.chaine=self.master.chaine\n #A compléter\n x=0\n y=0\n for nbmachine in range(0,nb): #Je le fais à l'envers car sinon la premiere machine est à la fin lors du positionnement sur tkinter... \n VueMachine(self,nbmachine).grid(row=x,column=y) #on les met à 0 car dans Chaine._machine, Mpassive est à 0\n y+=1\n if y==5:\n y=0\n x+=1\n def raz(self):\n self.destroy()\n \n\n \n#E.La classe Application\n\nclass Application(Tk):\n def __init__(self):\n Tk.__init__(self) \n #Chaine\n self.chaine=Chaine(11)#changer par rapport au nombres\n self.vuechaine=VueChaine(self,11) #changer par rapport au nombres\n self.vuechaine.grid(row=0,column=0,columnspan=2)\n #Canvas Piece\n FrameACanvas=Frame(self)\n self.c1=Canvas(FrameACanvas,heigh=100,width=100,bg=\"yellow\")\n self.c1.pack(side=LEFT)\n self.c2=Canvas(FrameACanvas,heigh=100,width=100,bg=\"red\")\n self.c2.pack(side=RIGHT)\n FrameACanvas.grid(row=2,column=0)\n #Bouton\n FrameABouton=Frame(self)\n self.b1=Button(FrameABouton,text=\"Tester\",command=self.ok).pack(side=LEFT)\n self.b2=Button(FrameABouton,text=\"Nouveau\",command=self.reboot).pack(side=LEFT)\n self.b3=Button(FrameABouton,text=\"Quitter\",command=lambda : self.destroy()).pack(side=LEFT)\n FrameABouton.grid(row=2,column=1)\n #Creation des pieces\n self.pieceu=PieceUsine(self.c1,10,50,50,8)\n self.piecem=PieceModele(self.c2,10,50,50,8)\n \n\n def ok(self):\n #usiner\n self.pieceu=PieceUsine(self.c1,10,50,50,8)\n self.chaine.usiner(self.pieceu)\n #DESSIN\n self.pieceu.dessinerPiece() \n #CONDITION FIN\n if self.pieceu==self.piecem:\n showinfo(\"Fin\",\"GAGNE !!!\")\n else:\n showinfo(\"Fin\",\"PERDU\")\n print(self.pieceu.getTrouTrait())\n print(\"modele\",self.piecem.getTrouTrait())\n #Recommence\n self.reboot()\n\n def reboot(self):\n #La chaine\n self.chaine.raz()\n #laffiche de la chaine\n self.vuechaine.raz()\n self.vuechaine=VueChaine(self,11) #changer par rapport au nombres\n self.vuechaine.grid(row=0,column=0,columnspan=2)\n #REDESSINER les CANVAS à zero\n self.pieceu=PieceUsine(self.c1,10,50,50,8)\n self.piecem.raz()\n self.piecem=PieceModele(self.c2,10,50,50,8)\n\n\n \napp=Application()\napp.mainloop()\n\n\n\n","sub_path":"L2/Semestre 3/POO/DM POO/dm_pooLAST_ROUND.py","file_name":"dm_pooLAST_ROUND.py","file_ext":"py","file_size_in_byte":12337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"530847985","text":"from RPS_Error import RPS_Error\n\nclass RPS():\n\tdef __init__(self):\n\t\tself.playerOneNum = -1\n\t\tself.playerOneInput = None\n\t\tself.playerTwoNum = -1\n\t\tself.playerTwoInput = None\n\t\n\tdef StringToNum(self, playerString = \"\"):\n\t\toutput = -1\n\t\t\n\t\tif(playerString == \"rock\"):\n\t\t\toutput = 0\n\t\telif(playerString == \"paper\"):\n\t\t\toutput = 1\n\t\telif(playerString == \"scissors\"):\n\t\t\toutput = 2\n\t\telse:\n\t\t\toutput = -1\n\t\t\traise RPS_Error(101)\n\t\t\n\t\treturn output\n\t\t\t\n\tdef Play(self):\n\t\tprint(\"\\n\")\n\t\tself.playerOneInput = input(\"Player 1 Choice (Rock/Paper/Scissors): \").lower()\n\t\tself.playerOneNum = self.StringToNum(self.playerOneInput)\n\n\t\tself.playerTwoInput = input(\"Player 2 Choice (Rock/Paper/Scissors): \").lower()\n\t\tself.playerTwoNum = self.StringToNum(self.playerTwoInput)\n\n\t\tremainder = (self.playerOneNum - self.playerTwoNum) % 3\n\n\t\tif(remainder == 0):\n\t\t\twinner = \"Nobody. It's a tie!\"\n\t\telif(remainder == 1):\n\t\t\twinner = \"Player 1\"\n\t\telif(remainder == 2):\n\t\t\twinner = \"Player 2\"\n\t\t\n\t\tprint(\"~\" * 50)\n\t\tprint(\"Player 1 has chosen: {}\".format(self.playerOneInput.capitalize()))\n\t\tprint(\"Player 2 has chosen: {}\".format(self.playerTwoInput.capitalize()))\n\t\tprint(\"~\" * 50)\n\n\t\tprint(\"The winner is: {}\".format(winner) + \"\\n\")\n\nif __name__ == \"__main__\":\n\tgame = RPS()\n\tgame.Play()","sub_path":"Zadaća_3_/RPS.py","file_name":"RPS.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"269524871","text":"# Daniel Holmes\n# 2018/09/26\n# Level Generation\n# GUI for creating levels\n\nimport pygame\nimport os\n\nfrom pygame.locals import *\nfrom classes.level_generation.editor_class import Editor\nfrom functions.level_functions import read_level_editor\n\npygame.init()\n\nscreen_width = 1540\nscreen_height = 960\nsize = screen_width, screen_height\n\nlevel_groups_path = \"data\\levels\"\nlevel_groups = os.listdir(level_groups_path)\n\nprint(\"Level Groups:\")\nfor level_group in level_groups:\n print(level_group)\n\nrequested_group = str(input(\"Select a level group: \"))\nrequested_group_path = level_groups_path + os.sep + requested_group\n\nif not os.path.exists(requested_group_path):\n os.mkdir(requested_group_path)\n\nlevels = os.listdir(requested_group_path)\n\nprint(requested_group+\" Levels:\")\nfor level in levels:\n print(level.strip('.txt'))\n\nrequested_level = str(input(\"Select a level: \"))\nrequested_level_path = requested_group_path + os.sep + requested_level+'.txt'\n\nif not os.path.exists(requested_level_path):\n f = open(requested_level_path, 'w+')\n f.close()\n\neditor = Editor([\"walls\", \"breakable_wall\", \"acceleration_zone\", \"void\", \"enemy\", \"jumping_enemy\", \"platform\", \"pipe\", \"checkpoint\", \"booster\", \"room\"], [16, 32, 64, 128], requested_level_path, screen_width, screen_height)\neditor = read_level_editor(editor, requested_level_path)\n\nscreen = pygame.display.set_mode(size)\n\ngame = True\nwhile game:\n screen.fill((255, 255, 255))\n\n for event in pygame.event.get():\n if event.type == QUIT:\n game = False\n pygame.quit()\n\n elif event.type == MOUSEBUTTONDOWN:\n x,y = pygame.mouse.get_pos()\n\n if editor.check_mode_button_clicks(x, y):\n editor.reset_info()\n\n elif editor.check_grid_button_clicks(x, y):\n editor.reset_info()\n\n elif event.type == KEYDOWN:\n # move screen\n if event.key == pygame.K_LEFT:\n editor.screen_difference_x -= 64\n\n elif event.key == pygame.K_RIGHT:\n editor.screen_difference_x += 64\n\n elif event.key == pygame.K_UP:\n editor.screen_difference_y -= 64\n\n elif event.key == pygame.K_DOWN:\n editor.screen_difference_y += 64\n\n # add to info\n elif event.key == pygame.K_c:\n x, y = pygame.mouse.get_pos()\n editor.info += str(\" coordinate \"+str(x + editor.screen_difference_x)+\" \"+str(y + editor.screen_difference_y))+\"\"\n\n elif event.key == pygame.K_x:\n x, y = pygame.mouse.get_pos()\n editor.info += str(\" point \"+str(x + editor.screen_difference_x)+\" \"+str(y + editor.screen_difference_y))+\"\"\n\n elif event.key == pygame.K_f:\n speed = str(input('speed: '))\n editor.info += str(\" speed \"+speed)\n\n # writing/display\n elif event.key == pygame.K_p:\n editor.print_info_list()\n\n elif event.key == pygame.K_i:\n editor.print_screen_differences()\n\n elif event.key == pygame.K_r:\n editor.reset_info()\n\n elif event.key == pygame.K_d:\n editor.delete_last_object()\n\n elif event.key == pygame.K_s:\n editor.create_object_from_info()\n editor.reset_info()\n\n elif event.key == pygame.K_w:\n editor.write_text_file()\n game = False\n pygame.quit()\n\n editor.draw_all_objects(screen)\n editor.draw_gui(screen)\n editor.update_rendered_info_text()\n\n pygame.display.flip()\n pygame.time.wait(12)","sub_path":"main level generation.py","file_name":"main level generation.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"566860148","text":"from macropy.core.macros import *\nfrom macropy.core.quotes import macros, q\nmacros = Macros()\n\n@macros.block\ndef my_macro(tree, **kw):\n with q as code:\n x = x / 2\n y = 1 / x\n x = x / 2\n y = 1 / x\n x = x / 2\n y = 1 / x\n return code\n","sub_path":"macropy/core/test/macros/quote_macro.py","file_name":"quote_macro.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"32392850","text":"import feedparser\nimport sys\nimport datetime\nfrom pymongo import MongoClient\nimport pymongo\nfrom bs4 import BeautifulSoup\nimport urllib2\nimport lxml\nfrom opinion_analysis import get_score_from_title_summary\n\nclient = MongoClient()\ndb = client.heatnews\n\ndef main():\n urls = {}\n urls[\"TechCrunch\"] = 'http://feeds.feedburner.com/TechCrunch/'\n urls[\"WSJ\"] = 'http://www.wsj.com/xml/rss/3_7041.xml'\n urls[\"The Verge\"] = 'http://www.theverge.com/google/rss/index.xml'\n urls[\"CNN\"] = 'http://rss.cnn.com/rss/cnn_topstories.rss'\n parsing(urls)\n remove_expired()\n\ndef parsing(urls):\n now = datetime.datetime.now().strftime(\"%a %Y-%m-%d %H:%M:%S %Z\")\n for publisher, url in urls.items():\n feed = feedparser.parse(url)\n for entry in feed.entries:\n articleurl = encodeElement(entry.link)\n if not inDB(articleurl):\n title = encodeElement(entry.title)\n published_date = encodeElement(entry.published)\n if entry.has_key(\"media_content\"):\n imgurl = encodeElement(entry.media_content[0][\"url\"])\n elif entry.has_key(\"media_thumbnail\"):\n imgurl = encodeElement(entry.media_thumbnail[0][\"url\"])\n else:\n soup = BeautifulSoup(entry.summary, \"html.parser\")\n if soup.find('img'):\n imgurl = soup.find('img').get(\"src\")\n else:\n imgurl = \"\"\n if imgurl:\n soup = BeautifulSoup(entry.summary, \"lxml\")\n summary = encodeElement(soup.get_text())\n opinion_score = get_score_from_title_summary(title, summary)\n result = db.parsedRSS.insert(\n {\n \"articleurl\": articleurl,\n \"title\": title,\n \"publisher\": publisher,\n \"published_date\": published_date,\n \"imgurl\": imgurl,\n \"summary\": summary,\n \"first_parsed_date\": now,\n \"visited_times\": 0,\n \"parsed_times\": 0,\n \"opinion_score\": opinion_score\n }\n )\n else:\n feed = db.parsedRSS.find({\n \"articleurl\": articleurl\n })\n parsed_times = feed[0][\"parsed_times\"] + 1\n result = db.parsedRSS.update_one(\n {\"articleurl\": articleurl},\n {\n \"$set\": {\n \"parsed_times\": parsed_times\n },\n \"$currentDate\": {\"lastModified\": True}\n }\n )\n\ndef remove_expired():\n result = db.parsedRSS.delete_many({\"parsed_times\": {\"$gt\": 60}})\n\ndef inDB(articleurl):\n url_list = get_url_list(articleurl)\n if not url_list:\n return False\n else:\n return True\n\ndef get_url_list(articleurl):\n url_list = []\n cursor = db.parsedRSS.find({\"articleurl\": articleurl})\n for result in cursor:\n url_list.append(result[\"articleurl\"])\n return url_list\n\ndef encodeElement(element):\n return element.encode('ascii', 'ignore')\n\nif __name__ == '__main__':\n main()\n","sub_path":"parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"562625754","text":"#!/usr/bin/env python3\n\nimport numpy as np\nfrom scipy import ndimage\nfrom skimage.morphology import medial_axis\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport yaml, glob, pickle\nfrom PIL import Image\nfrom os import getcwd\nimport progressbar as pb\n\n\ndef make_heat_array(map_path, data_path):\n #Set up necessary constants, arrays for later\n step = 1\n map_params = yaml.load(open(map_path + 'map.yaml', 'rb'))\n origin = map_params['origin'] #origin offset from data\n res = map_params['resolution'] #meters per pixel\n\n I = Image.open(map_path + 'map.pgm')\n w, h = I.size\n im_w = int(w/step)\n im_h = int(h/step)\n im = np.zeros((im_w, im_h), dtype=int)\n\n files = glob.glob(data_path + '*.p')\n\n #Iterate through all the data, counting the number of times the\n #robot is at a given position\n for file in pb.progressbar(files):\n dataset = pickle.load(open(file, 'rb'))\n for trial in dataset:\n if trial[1] > 1000:\n continue\n for point in trial[2]:\n x = point.position.x - origin[0]\n y = point.position.y - origin[1]\n x_coord = int(x/res)\n y_coord = im_h - int(y/res)\n im[y_coord, x_coord] = im[y_coord, x_coord] + 1\n\n return im, im_w, im_h\n\ndef make_bmap(map_path, data_path):\n #Find a thresholding value that gets rid of the bottom\n #30% of data\n im, im_w, im_h = make_heat_array(map_path, data_path)\n\n im_thresh = np.zeros((im_w, im_h), dtype=int)\n\n ct_dist = []\n for i in np.ndarray.flatten(im):\n if i != 0:\n ct_dist.append(i)\n thresh = np.percentile(ct_dist, 50)\n\n print(\"Thresholding at\", int(thresh), \"visits\")\n\n i = 0\n for row in pb.progressbar(im):\n im_thresh[i] = [0 if i <=thresh else 1 for i in row]\n i+=1\n\n plt.imsave('thresholded_data.png', im_thresh, cmap=cm.gray, vmin=0, vmax=1)\n\n return im_thresh\n\nif __name__ == \"__main__\":\n cwd = getcwd()\n map_path = cwd + '/'\n data_path = cwd + '/etu_1_condensed/'\n\n\n data = make_bmap(map_path, data_path)\n\n skel, distance = medial_axis(data, return_distance=True)\n\n # Distance to the background for pixels of the skeleton\n dist_on_skel = distance * skel\n\n\n plt.imshow(dist_on_skel, cmap=plt.cm.spectral, interpolation='nearest')\n plt.contour(data, [0.5], colors='w')\n\n plt.show()\n plt.imsave('skel.png', dist_on_skel, cmap=plt.cm.spectral)\n","sub_path":"old_files/skeletonizer.py","file_name":"skeletonizer.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"7066114","text":"import requests\n\nclass Slack(object):\n\tdef __init__(self):\n\t\tself.token = None\n\t\tself.verify_path = requests.certs.where()\n\n\tdef set_slack_api_token(self, slack_api_token):\n\t\tself.token = slack_api_token\n\n\tdef update_slack_status(self, current): \n\t\tpayload_dict = {\n\t\t\t\"status_text\": current,\n\t\t\t\"status_emoji\": \":spotify:\" # you need to add this custom emoji\n\t\t}\n\n\t\ttry:\n\t\t\tr = requests.post(\"https://slack.com/api/users.profile.set?token={}&profile={}\".format(self.token, str(payload_dict)), verify=self.verify_path)\n\t\t\t\n\t\t\tif r.json()['ok']:\n\t\t\t\treturn True\n\t\t\treturn False\n\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\t\t\treturn False\n","sub_path":"classes/slack.py","file_name":"slack.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"618139848","text":"\n\nimport common\nimport turtle\n\n\nfrom common import *\nfrom turtle import Turtle\n\n\nclass Room():\n Verbose = False\n Current = None\n XMin = 0\n YMin = 8\n XSize = common.XSize - XMin\n YSize = common.YSize - YMin\n XMax = XSize - 1 + XMin\n YMax = YSize - 1 + YMin\n XCenter = XSize // 2 + XMin\n YCenter = YSize // 2 + YMin\n \n\n @classmethod\n def dprint(selfClass, msg): # debug print()\n if selfClass.Verbose:\n print(msg)\n\n def __init__(self, level, info = {\"roomX\": 1, \"roomY\": 1}):\n self.info = info\n self.level = level\n \n self.x = info[\"roomX\" ]\n self.y = info[\"roomY\" ]\n self.pellets = info[\"pellets\" ] if \"pellets\" in info else None\n self.monster1 = info[\"monster1\" ] if \"monster1\" in info else []\n self.monster2 = info[\"monster2\" ] if \"monster2\" in info else []\n self.monster3 = info[\"monster3\" ] if \"monster3\" in info else []\n self.monster4 = info[\"monster4\" ] if \"monster4\" in info else []\n self.animList = info[\"animList\" ] if \"animList\" in info else []\n self.drawScripts = info[\"drawScripts\"] if \"drawScripts\" in info else []\n self.keys = info[\"keys\" ] if \"keys\" in info else []\n self.presents = info[\"presents\" ] if \"presents\" in info else []\n self.shadowfill = info[\"shadowfill\" ] if \"shadowfill\" in info else False\n\n self.roomState = {\"complete\": False}\n\n print(\"room.py: created room for %s, %s\" % (self.x, self.y))\n\n def isComplete(self):\n return self.getState(\"complete\")\n\n def isShadowFill(self):\n return self.shadowfill\n \n def monsterInfoList(self, monsterClass):\n\n if monsterClass.key in self.info:\n return self.info[monsterClass.key]\n\n return [] \n \n def monsterInfoListDelete(self, monsterClass):\n self.info[monsterClass.key] = []\n\n def addMonsters(self, monsterClass):\n infoList = self.monsterInfoList(monsterClass)\n\n if infoList != []:\n for monsterInfo in infoList:\n monsterClass.addMonster(None, None, monsterInfo)\n\n self.monsterInfoListDelete(monsterClass)\n else:\n self.dprint(\"No monster '%s' is here\" % monsterClass.key)\n\n def drawWalls(self):\n\n for scriptInfo in self.drawScripts: \n script = scriptInfo[\"script\"]\n\n # example: script == {\"script\": \"big-box-doors.room\", \"conditions\": {\"cyan-key\": false}}\n \n draw = True\n\n if \"conditions\" in scriptInfo:\n scriptConditions = scriptInfo[\"conditions\"]\n\n # example: scriptConditions == {\"cyan-key\": false}\n # example: roomState == {\"cyan-key\": false, \"completed\": false}\n\n for conditionKey in scriptConditions:\n if conditionKey in self.roomState:\n roomCondition = self.roomState[conditionKey]\n else:\n roomCondition = False\n \n if scriptConditions[conditionKey] != roomCondition:\n draw = False\n break\n if draw:\n Turtle.fileExec(script)\n\n def setState(self, key, value):\n \n if key in self.roomState:\n oldValue = self.roomState[key]\n else:\n oldValue = False\n \n self.roomState[key] = value\n\n if oldValue != value:\n self.redraw()\n\n def getState(self, key):\n return self.roomState[key] if key in self.roomState else None\n\n def addDrawScript(self, scriptFile, conditions = {}):\n self.drawScripts.append({\"script\": scriptFile, \"conditions\": conditions})\n \n def drawKeys(self):\n if not self.isComplete():\n for key in self.keys:\n common.plot(key[\"x\"], key[\"y\"], key[\"color\"], MGZ, key[\"color\"])\n\n def deleteKey(self, x, y):\n return deleteXYItem(x, y, self.keys)\n\n def drawPellets(self):\n if self.pellets and not self.isComplete():\n Turtle.fileExec(self.pellets)\n\n def deletePellet(self, x, y):\n pass\n\n def drawPresents(self):\n if not self.isComplete():\n for present in self.presents:\n common.plot(present[\"x\"], present[\"y\"], present[\"color\"], MGZ, present[\"color\"])\n\n def deletePresent(self, x, y):\n return deleteXYItem(x, y, self.presents)\n\n \"\"\"\n def addArrows(self):\n\n if self.level.IsRoomRightOfHere(self.x, self.y):\n self.addDrawScript(\"right-arrow.room\", {\"complete\": True})\n\n if self.level.IsRoomLeftOfHere(self.x, self.y):\n self.addDrawScript(\"left-arrow.room\", {\"complete\": True})\n\n if self.level.IsRoomBelowHere(self.x, self.y):\n self.addDrawScript(\"down-arrow.room\", {\"complete\": True})\n\n if self.level.IsRoomAboveHere(self.x, self.y):\n self.addDrawScript(\"up-arrow.room\", {\"complete\": True})\n \"\"\"\n \n def drawBorder(self):\n \n if not self.level.IsRoomRightOfHere(self.x, self.y):\n v_line(XMax, self.YMin, self.YSize, self.level.LevelColor()) \n\n if not self.level.IsRoomLeftOfHere(self.x, self.y):\n v_line(self.XMin, self.YMin, self.YSize, self.level.LevelColor()) \n\n if not self.level.IsRoomBelowHere(self.x, self.y):\n h_line(self.XMin, YMax, self.XSize, self.level.LevelColor())\n\n if not self.level.IsRoomAboveHere(self.x, self.y):\n h_line(self.XMin, self.YMin, self.XSize, self.level.LevelColor())\n \n def draw(self):\n self.drawPellets()\n self.redraw()\n \n def redraw(self):\n #self.addArrows()\n self.drawWalls()\n self.drawKeys()\n self.drawPresents()\n self.drawBorder()\n \n def countPixels(self, color):\n count = 0\n color = common.validColor(color)\n\n for y in range(self.YMin, self.YMax + 1):\n for x in range(self.XMin, self.XMax + 1): \n if common.colorAtMG(x, y) == color:\n count += 1\n \n return count\n\n def findEmptyCoord(self):\n while True:\n x = random.randint(self.XMin, self.XMax)\n y = random.randint(self.YMin, self.YMax)\n\n if common.isEmptyAt(x, y):\n return {\"x\": x, \"y\": y}\n\n def showTypeIDs(self):\n for y in range(self.YMin, self.YMin + self.YSize):\n for x in range(self.XMin, self.XMin + self.XSize):\n common.drawPixel(x, y, common.Colors[common.typeIDAt(x, y)])\n\n def showMG(self):\n for y in range(self.YMin, self.YMin + self.YSize):\n for x in range(self.XMin, self.XMin + self.XSize):\n color = common.colorAtMG(x, y)\n\n if color != common.BlackI:\n common.drawPixel(x, y, common.White)\n\n def showFG(self):\n for y in range(self.YMin, self.YMin + self.YSize):\n for x in range(self.XMin, self.XMin + self.XSize):\n color = common.colorAtFG(x, y)\n\n if color != common.BlackI:\n common.drawPixel(x, y, common.White)\n\n def roomChangeDX(self, x, dirID):\n \n if dirID == -1:\n return 0\n \n x += common.DirX[dirID]\n\n if x > self.XMax:\n return 1\n elif x < self.XMin:\n return -1\n else:\n return 0\n \n def roomChangeDY(self, y, dirID):\n \n if dirID == -1:\n return 0\n \n y += common.DirY[dirID]\n\n if y > self.YMax:\n return 1\n elif y < self.YMin:\n return -1\n else:\n return 0\n \n def moveX(self, x, dirID):\n \n if dirID == -1:\n return x\n \n x += common.DirX[dirID]\n\n if x > self.XMax:\n return self.XMax\n elif x < self.XMin:\n return self.XMin\n else:\n return x\n\n def moveY(self, y, dirID):\n \n if dirID == -1:\n return y\n \n y += common.DirY[dirID]\n \n if y > self.YMax:\n return self.YMax\n elif y < self.YMin:\n return self.YMin\n else:\n return y\n\n def isLeaving(self, x, y, dirID):\n\n x += common.DirX[dirID]\n y += common.DirY[dirID]\n \n return y > self.YMax or y < self.YMin or x > self.XMax or x < self.XMin\n\n def isLeavingDXDY(self, x, y, dx, dy):\n\n x += dx\n y += dy\n \n return y > self.YMax or y < self.YMin or x > self.XMax or x < self.XMin\n\n def invertColors(self, z = 0):\n\n for y in range(self.YMin, self.YMax + 1):\n for x in range(self.XMin, self.XMax + 1):\n common.plot(x, y, common.invertColor(common.colorAtZ(x, y, z)), z)\n\n def colorize(self, color, z = BGZ):\n\n for y in range(self.YMin, self.YMax + 1):\n for x in range(self.XMin, self.XMax + 1):\n common.plot(x, y, common.colorAverage(common.colorAtZ(x, y, z), color), z)\n\n def centeredX(self, xSize, scale = 1):\n return self.XCenter - xSize * scale // 2\n\n def centeredY(self, ySize, scale = 1):\n return self.YCenter - ySize * scale // 2\n\n def stringCenteredX(self, s, scale = 1):\n return self.centeredX(common.stringXSize(s), scale)\n\n def stringCenteredY(self, s, scale = 1):\n return self.centeredY(common.stringYSize(s), scale)\n\n def drawStringCentered(self, s, scale = 1, color = None, z = FGZ):\n common.drawString2(self.stringCenteredX(s, scale), self.stringCenteredY(s, scale), s, scale, color, z)\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 \n\n\n \n \n \n\n \n \n \n \n \n \n","sub_path":"Monster_Game/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":10089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"251957777","text":"from tkinter import*\r\nimport random\r\nimport time\r\n\r\nroot=Tk()\r\nroot.geometry('1600x1600+0+0')\r\nroot.title(\"restaurant management system\")\r\n\r\nf1=Frame(root,width=1600,height=200,relief=SUNKEN)\r\nf1.pack(side=TOP)\r\n\r\nf2=Frame(root,width=900,height=600,relief=SUNKEN)\r\nf2.pack(side=LEFT)\r\n\r\nf3=Frame(root,width=600,height=600,relief=SUNKEN)\r\nf3.pack(side=RIGHT)\r\n#=============================================time=============================\r\nlocaltime=time.asctime(time.localtime(time.time()))\r\n#=========================================information==================================\r\nlbl=Label(f1,text=\"Restaurant Management System\",font=('Arial Bold',50),bd=16,anchor='w',relief=RAISED)\r\nlbl.grid(column=0,row=0)\r\nlbl=Label(f1,text=localtime,font=('Arial Bold',20),bd=10,anchor='w')\r\nlbl.grid(column=0,row=1)\r\n#================================calculator=============================\r\noperator=\"\"\r\ntext_Input=IntVar()\r\ntxt=Entry(f3,font=('Arial Bold',20),insertwidth=4,bg=\"powder blue\",justify=RIGHT,textvariable=text_Input,bd=30)\r\ntxt.grid(columnspan=4)\r\ndef click(numbers):\r\n global operator\r\n operator = operator + str(numbers)\r\n text_Input.set(operator)\r\n\r\n\r\ndef clear():\r\n global operator\r\n operator = \"\"\r\n text_Input.set(\"\")\r\n\r\n\r\ndef equals():\r\n global operator\r\n sumup=str(eval(operator))\r\n text_Input.set(sumup)\r\n operator = \"\"\r\n \r\nbtn7=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"7\",command=lambda:click(7))\r\nbtn7.grid(column=0,row=2)\r\n\r\nbtn8=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"8\",command=lambda:click(8))\r\nbtn8.grid(column=1,row=2)\r\n\r\nbtn9=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"9\",command=lambda:click(9))\r\nbtn9.grid(column=2,row=2)\r\n\r\nAddition=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"+\",command=lambda:click(\"+\"))\r\nAddition.grid(column=3,row=2)\r\n\r\nbtn4=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"4\",command=lambda:click(4))\r\nbtn4.grid(column=0,row=3)\r\n\r\nbtn5=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"5\",command=lambda:click(5))\r\nbtn5.grid(column=1,row=3)\r\n\r\nbtn6=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"6\",command=lambda:click(6))\r\nbtn6.grid(column=2,row=3)\r\n\r\nsubstraction=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"-\",command=lambda:click(\"-\"))\r\nsubstraction.grid(column=3,row=3)\r\n\r\nbtn1=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"1\",command=lambda:click(1))\r\nbtn1.grid(column=0,row=4)\r\n\r\nbtn2=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"2\",command=lambda:click(2))\r\nbtn2.grid(column=1,row=4)\r\n\r\nbtn3=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"3\",command=lambda:click(3))\r\nbtn3.grid(column=2,row=4)\r\n\r\nmultiply=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"*\",command=lambda:click(\"*\"))\r\nmultiply.grid(column=3,row=4)\r\n\r\nbtn0=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"0\",command=lambda:click(0))\r\nbtn0.grid(column=0,row=5)\r\n\r\n\r\nbtnclear=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"c\",command=clear)\r\nbtnclear.grid(column=1,row=5)\r\n\r\n\r\nbtnequal=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"=\",command=equals)\r\nbtnequal.grid(column=2,row=5)\r\n\r\ndivision=Button(f3,padx=16,pady=16,bd=8,fg=\"Black\",font=('arial bold',20),bg=\"powder blue\",text=\"/\",command=lambda:click(\"/\"))\r\ndivision.grid(column=3,row=5)\r\n#===============================================================================productdisplaydef Ref():\r\ndef Ref():\r\n x=random.randint(1000,500000)\r\n randomRef=str(x)\r\n rand.set(randomRef)\r\n SD=float(rand1.get())\r\n CB=float(rand2.get())\r\n VC=float(rand3.get())\r\n VB=float(rand4.get())\r\n FF=float(rand5.get())\r\n GB=float(rand6.get())\r\n\r\n sambher_dosa=SD*0.99\r\n chole_bhature=CB*1.44\r\n VEG_CHOWMIEN=VC*3.87\r\n veg_burger=VB*2.88\r\n FRENCH_FRIES=FF*3.67\r\n garlic_bread=GB*6.09\r\n\r\n cost_of_meal=\"$\" , str('%.2f' % (sambher_dosa + chole_bhature + VEG_CHOWMIEN + veg_burger + FRENCH_FRIES + garlic_bread))\r\n\r\n Paycharges = ((sambher_dosa + chole_bhature + VEG_CHOWMIEN + veg_burger + FRENCH_FRIES + garlic_bread)*0.2)\r\n\r\n Totalcost =(sambher_dosa + chole_bhature + VEG_CHOWMIEN + veg_burger + FRENCH_FRIES + garlic_bread)\r\n\r\n rand7.set(cost_of_meal)\r\n service = \"$\" , str('%.2f' % (Paycharges))\r\n rand8.set(service)\r\n total = \"$\" , str('%.2f' % (Totalcost))\r\n rand10.set(total)\r\n \r\n \r\n \r\n\r\ndef qexit():\r\n root.destroy()\r\n\r\ndef reset():\r\n rand1.set(\"\")\r\n rand2.set(\"\")\r\n rand3.set(\"\")\r\n rand4.set(\"\")\r\n rand5.set(\"\")\r\n rand6.set(\"\")\r\n rand7.set(\"\")\r\n rand8.set(\"\")\r\n rand.set(\"\")\r\n rand10.set(\"\")\r\n\r\nrand1=StringVar()\r\nrand2=StringVar()\r\nrand3=StringVar()\r\nrand4=StringVar()\r\nrand5=StringVar()\r\nrand6=StringVar()\r\nrand7=StringVar()\r\nrand8=StringVar()\r\nrand=StringVar()\r\nrand10=StringVar()\r\nlbl=Label(f2,text=\"sambher dosa\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=0,column=0)\r\n\r\ntxt=Entry(f2,textvariable=rand1,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"powder blue\")\r\ntxt.grid(row=0,column=1)\r\n\r\nlbl=Label(f2,text=\"chole bhature\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=1,column=0)\r\n\r\ntxt=Entry(f2,textvariable=rand2,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"powder blue\")\r\ntxt.grid(row=1,column=1)\r\n\r\nlbl=Label(f2,text=\"veg chowmien\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=2,column=0)\r\n\r\ntxt=Entry(f2,textvariable=rand3,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"powder blue\")\r\ntxt.grid(row=2,column=1)\r\n\r\nlbl=Label(f2,text=\"veg burger\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=3,column=0)\r\n\r\ntxt=Entry(f2,textvariable=rand4,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"powder blue\")\r\ntxt.grid(row=3,column=1)\r\n\r\nlbl=Label(f2,text=\"french fries\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=4,column=0)\r\n\r\ntxt=Entry(f2,textvariable=rand5,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"powder blue\")\r\ntxt.grid(row=4,column=1)\r\n\r\nlbl=Label(f2,text=\"garlic bread\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=0,column=3)\r\n\r\ntxt=Entry(f2,textvariable=rand6,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"#ffffff\")\r\ntxt.grid(row=0,column=4)\r\n\r\nlbl=Label(f2,text=\"cost of meal\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=1,column=3)\r\n\r\ntxt=Entry(f2,textvariable=rand7,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"#ffffff\")\r\ntxt.grid(row=1,column=4)\r\n\r\nlbl=Label(f2,text=\"service charges\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=2,column=3)\r\n\r\ntxt=Entry(f2,textvariable=rand8,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"#ffffff\")\r\ntxt.grid(row=2,column=4)\r\n\r\nlbl=Label(f2,text=\"reference\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=3,column=3)\r\n\r\ntxt=Entry(f2,textvariable=rand,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"#ffffff\")\r\ntxt.grid(row=3,column=4)\r\n\r\nlbl=Label(f2,text=\"Total cost\",font=('arial bold',16),bd=16,anchor='w')\r\nlbl.grid(row=4,column=3)\r\n\r\ntxt=Entry(f2,textvariable=rand10,font=('arial bold',10),bd=10,insertwidth=4,justify=RIGHT,bg=\"#ffffff\")\r\ntxt.grid(row=4,column=4)\r\n#=========================================================================BUTTONS==============================================================================================\r\n \r\nbtnTotal=Button(f2,padx=16,pady=10,bd=16,font=('arial bold',16),fg=\"black\",width=10,text=\"Total\",bg=\"#ffffff\",command=Ref)\r\nbtnTotal.grid(row=6,column=1)\r\n\r\nbtnqexit=Button(f2,padx=16,pady=10,bd=16,font=('arial bold',16),fg=\"black\",width=10,text=\"exit\",bg=\"#ffffff\",command=qexit)\r\nbtnqexit.grid(row=6,column=3)\r\n\r\nbtnreset=Button(f2,padx=16,pady=10,bd=16,font=('arial bold',16),fg=\"black\",width=10,text=\"reset\",bg=\"#ffffff\",command=reset)\r\nbtnreset.grid(row=6,column=2)\r\n\r\n\r\n \r\nroot.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nroot.mainloop()\r\n","sub_path":"restaurant management system.py","file_name":"restaurant management system.py","file_ext":"py","file_size_in_byte":8480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"168442938","text":"# cook your dish here \nt=int(input())\nfor _ in range(t): \n n=int(input()) \n a=list(map(int,input().split())) \n m =0 \n s=0 \n for i in range(n): \n s+=a[i] \n m=max(a[i],m)\n if (s-m)>m: \n print(\"Yes\") \n else: \n print(\"No\")\n print(\"\") ","sub_path":"data/docker-generated-data/code_clones/p72.py","file_name":"p72.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"52936022","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import loader,Context\nfrom django.http import JsonResponse\nfrom models import Psw\nfrom django.views.decorators.csrf import csrf_exempt, csrf_protect\nfrom urllib import unquote\nimport os\n# Create your views here.\n\n\ndef index(request):\n if request.GET.get('pingtai'):\n pingtai = request.GET.get('pingtai')\n fangjianhao = request.GET.get('fangjianhao')\n with open('G:\\live\\lovelive\\static\\douyuspider.py') as fp:\n line = fp.readlines()\n line[15] =\" start_urls = ['http://www.\"+pingtai+\".tv/\"+fangjianhao+\"']\\n\"\n line[19] =\" driver.get('http://www.\"+pingtai+\".tv/\"+fangjianhao+\"')\\n\" \n open('G:\\live\\lovelive\\static\\douyuspider.py','w+').writelines(line)\n os.popen('cmd.exe /k scrapy runspider G:\\live\\lovelive\\static\\douyuspider.py').read()\n json = eval(open('G:\\live\\lovelive\\static\\moban.json').read())\n return JsonResponse(json)\n else:\n a = Psw.objects.get(name = 'lsf')\n a.password = \"111\"\n a.save()\n t = loader.get_template(\"index.html\")\n return HttpResponse(t.render())\n\n\ndef moban(request):\n t = loader.get_template(\"moban.html\")\n return HttpResponse(t.render())\n\n\ndef frame(request):\n t = loader.get_template(\"bridge frame.html\")\n return HttpResponse(t.render())\n\n\n@csrf_exempt\ndef cookie(request):\n t = loader.get_template(\"cookiedemo.html\")\n if not request.COOKIES:\n return HttpResponse(t.render())\n else:\n bas = unquote(request.COOKIES['username'])\n c = Context({'result': 'use cookie', 'name': bas})\n return HttpResponse(t.render(c))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"lovelive/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"415728021","text":"'''Exercício Python 034: Escreva um programa que pergunte o salário de um funcionário e calcule o valor do\nseu aumento. Para salários superiores a R$1250,00, calcule um aumento de 10%. Para os inferiores ou iguais,\no aumento é de 15%.'''\n\nsal = float(input('Digite seu Sálario: '))\naumento_baixo = sal * 0.15\naumento_alto = sal * 0.10\nif sal <= 1250.00:\n salario_novo = sal + aumento_baixo\nelse:\n salario_novo = sal + aumento_alto\nprint('Seu Aumento de Sálario foi: {:.2f}'.format(salario_novo))\n","sub_path":"curso_em_video/Exercicios_Python/Desafio_34_IF_else_Aumento_salario_porcentagem.py","file_name":"Desafio_34_IF_else_Aumento_salario_porcentagem.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"273433108","text":"from _20 import get_country_text\nimport argparse\nimport re\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-f', '--filename', default='./data/jawiki-country.json')\n args = parser.parse_args()\n country_text = get_country_text(args.filename, country='イギリス')\n\n for line in country_text.split('\\n'):\n result = re.search(r'Category:(?P.*)]]', line)\n if result:\n print(result.group('categoryname'))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"chapter3/_22.py","file_name":"_22.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"394095196","text":"#############################################\n# Log Sensor Value to SQL Database V1\n#############################################\n\n# Debug (0=OFF, 1=ON)\n_DEBUG = 0\n\nimport os\n\nimport sqlite3\n\nimport config\n\nimport datetime\n\nimport growbox\n\n#now = datetime.datetime.now()\n#now = datetime.datetime.now(datetime.timezone.utc)\nnow = datetime.datetime.utcnow()\n\n################################################\t\n# Get Config\n################################################\ngrowbox_db = growbox.db()\ngrowbox_db.connect()\n\ngrwconfig = growbox_db.get_config()\n\nif (grwconfig[\"RunHandler\"]==1) or ((now.minute % 10) == 0):\n\tgrowbox_db.set_config(\"RunHandler\", 0)\n\tos.system('sudo python /home/pi/bin/growbox/growbox_handler.py >> /var/log/growbox.log 2>&1')\n\ngrowbox_db.disconnect()\n\nif _DEBUG == 1:\n\t#now2 = datetime.datetime.now()\n\t#now2 = datetime.datetime.now(datetime.timezone.utc)\n\tnow2 = datetime.datetime.utcnow()\n\tdelta = now2 - now\n\tprint(now.strftime(\"%Y/%m/%d, %H:%M:%S\"), delta.total_seconds())\n\n","sub_path":"home.pi.bin.growbox/growbox_run_handler.py","file_name":"growbox_run_handler.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"429328011","text":"# 필요한 PyTorch 라이브러리 불러오기\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nfrom common.layers import TacotronSTFT\nfrom common.utils import load_wav_to_torch\n\nimport copy\nimport PIL\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport librosa.display\n\n# GPU 장치 사용 설정\nGPU_NUM = 1\ndevice = torch.device(f'cuda:{GPU_NUM}' if torch.cuda.is_available() else 'cpu')\ntorch.cuda.set_device(device) # change allocation of current GPU\n\nimport time\n\n\n# 이미지를 불러와 다운받아 텐서(Tensor) 객체로 변환하는 함수\ndef image_loader(img_path):\n loader = transforms.Compose([\n transforms.ToTensor() # torch.Tensor 형식으로 변경 [0, 255] → [0, 1]\n ])\n image = PIL.Image.open(img_path).convert('RGB')\n # 네트워크 입력에 들어갈 이미지에 배치 목적의 차원(dimension) 추가\n image = loader(image).unsqueeze(0)\n return image.to(device, torch.float) # GPU로 올리기\n\n\ndef get_png_name(pt_path):\n # pt_path = 'emotion_dataset/Personality/pfa/wav/pfa00001.wav'\n pt_path = pt_path.split('/')\n pt_path[3] = 'img'\n png_name = pt_path[4].replace('.wav', '.png')\n pt_path[4] = png_name\n style_png_name = '/'.join(pt_path)\n\n return style_png_name\n\n# torch.Tensor 형태의 이미지를 화면에 출력하는 함수\ndef imshow(tensor):\n # matplotlib는 CPU 기반이므로 CPU로 옮기기\n image = tensor.cpu().clone()\n # torch.Tensor에서 사용되는 배치 목적의 차원(dimension) 제거\n image = image.squeeze(0)\n # PIL 객체로 변경\n image = transforms.ToPILImage()(image)\n # 이미지를 화면에 출력(matplotlib는 [0, 1] 사이의 값이라고 해도 정상적으로 처리)\n plt.imshow(image)\n plt.show()\n\n\ndef eshow(image):\n img = Image.open(image)\n img.show()\n\nclass Normalization(nn.Module):\n def __init__(self, mean, std):\n super(Normalization, self).__init__()\n self.mean = mean.clone().view(-1, 1, 1)\n self.std = std.clone().view(-1, 1, 1)\n\n def forward(self, img):\n return (img - self.mean) / self.std\n\ndef gram_matrix(input):\n # a는 배치 크기, b는 특징 맵의 개수, (c, d)는 특징 맵의 차원을 의미\n a, b, c, d = input.size()\n # 논문에서는 i = 특징 맵의 개수, j = 각 위치(position)\n features = input.view(a * b, c * d)\n # 행렬 곱으로 한 번에 Gram 내적 계산 가능\n G = torch.mm(features, features.t())\n # Normalize 목적으로 값 나누기\n return G.div(a * b * c * d)\n\n\n# 스타일 손실(style loss) 계산을 위한 클래스 정의\nclass StyleLoss(nn.Module):\n def __init__(self, target_feature):\n super(StyleLoss, self).__init__()\n self.target = gram_matrix(target_feature).detach()\n\n def forward(self, input):\n G = gram_matrix(input)\n self.loss = F.mse_loss(G, self.target)\n return input\n\n\n# 스타일 손실(style loss)을 계산하는 함수\ndef get_style_losses(cnn, style_img, noise_image):\n cnn = copy.deepcopy(cnn)\n normalization = Normalization(cnn_normalization_mean, cnn_normalization_std).to(device)\n style_losses = []\n\n # 가장 먼저 입력 이미지가 입력 정규화(input normalization)를 수행하도록\n model = nn.Sequential(normalization)\n\n # 현재 CNN 모델에 포함되어 있는 모든 레이어를 확인하며\n i = 0\n for layer in cnn.children():\n if isinstance(layer, nn.Conv2d):\n i += 1\n name = 'conv_{}'.format(i)\n elif isinstance(layer, nn.ReLU):\n name = 'relu_{}'.format(i)\n layer = nn.ReLU(inplace=False)\n elif isinstance(layer, nn.MaxPool2d):\n name = 'pool_{}'.format(i)\n elif isinstance(layer, nn.BatchNorm2d):\n name = 'bn_{}'.format(i)\n else:\n raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))\n\n model.add_module(name, layer)\n\n # 설정한 style layer까지의 결과를 이용해 style loss를 계산\n if name in style_layers:\n target_feature = model(style_img).detach()\n style_loss = StyleLoss(target_feature)\n model.add_module(\"style_loss_{}\".format(i), style_loss)\n style_losses.append(style_loss)\n\n # 마지막 style loss 이후의 레이어는 사용하지 않도록\n for i in range(len(model) - 1, -1, -1):\n if isinstance(model[i], StyleLoss):\n break\n\n model = model[:(i + 1)]\n return model, style_losses\n\n\ndef style_reconstruction(cnn, style_img, input_img, iters):\n model, style_losses = get_style_losses(cnn, style_img, input_img)\n optimizer = optim.LBFGS([input_img.requires_grad_()])\n\n print(\"[ Start ]\")\n #imshow(input_img)\n\n flag = True\n now_score = 100000000\n\n # 하나의 값만 이용하기 위해 배열 형태로 사용\n run = [0]\n while flag:\n\n def closure():\n input_img.data.clamp_(0, 1)\n\n optimizer.zero_grad()\n model(input_img)\n style_score = 0\n\n for sl in style_losses:\n style_score += sl.loss\n\n style_score *= 1e6\n style_score.backward()\n run[0] += 1\n\n nonlocal flag, now_score\n\n if style_score.item() < 10:\n # print(f\"[ Step: {run[0]} / Style loss: {style_score.item()}]\")\n # imshow(input_img)\n flag = False\n\n if style_score.item() <= now_score:\n now_score = style_score.item()\n\n return style_score\n\n\n optimizer.step(closure)\n\n # 결과적으로 이미지의 각 픽셀의 값이 [0, 1] 사이의 값이 되도록 자르기\n input_img.data.clamp_(0, 1)\n\n return input_img\n\ndef load_mel(path):\n stft = TacotronSTFT()\n audio, sampling_rate = load_wav_to_torch(path)\n if sampling_rate != 16000:\n raise ValueError(\"{} SR doesn't match target {} SR\".format(\n sampling_rate, stft.sampling_rate))\n audio_norm = audio / 32768.0 # hparams.max_wav_value\n audio_norm = audio_norm.unsqueeze(0)\n audio_norm = torch.autograd.Variable(audio_norm, requires_grad=False)\n melspec = stft.mel_spectrogram(audio_norm)\n #melspec = melspec.cuda()\n melspec = torch.squeeze(melspec, 0)\n return melspec\n\n\n# 뉴럴 네트워크 모델을 불러옵니다.\n\ncnn = models.vgg19(pretrained=True).features.to(device).eval()\n\nstyle_layers = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']\n\ncnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)\ncnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)\n\nfile_path = 'filelists/sum_multy_filelist2.txt'\nf = open(file_path, 'r', encoding='utf-8')\nlines = f.readlines()\nf.close()\n\nnum = 0\n\ntotal_lines_len = len(lines)\n# style transfer\nfor line in lines[total_lines_len//2:]:\n print('변경 시작 : ', line.split('|')[0])\n wav_path = line.split('|')[0] # .wav 경로\n\n # 저장할 png file 이름\n png_name = get_png_name(wav_path)\n print(png_name)\n\n # 기존 .pt파일을 png파일로 저장\n m = load_mel(wav_path)\n m = m.numpy() # 이미지로 만들기 위해 넘파이로 변경\n a, b = m.shape\n\n librosa.display.specshow(m)\n plt.Figure()\n plt.axis('off'), plt.xticks([]), plt.yticks([])\n plt.tight_layout()\n plt.subplots_adjust(left=0, bottom=0, right=1, top=1, hspace=0, wspace=0)\n plt.savefig(png_name, bbox_inches='tight', pad_inches=0)\n plt.close()\n\n # 이미지 resize\n img = Image.open(png_name)\n shape_check_img = image_loader(png_name)\n resize_image = img.resize((int(b * 1.5), shape_check_img.shape[2]))\n resize_image.save(png_name)\n target_image = image_loader(png_name)\n\n # 콘텐츠 이미지와 동일한 크기의 노이즈 이미지 준비하기\n input_img = torch.empty_like(target_image).uniform_(0, 1).to(device)\n\n # style transfer 시작\n # style reconstruction 수행\n print('style 추출 중')\n output = style_reconstruction(cnn, style_img=target_image, input_img=input_img, iters=1000)\n print('style 추출 끝남')\n\n # style transfer한 이미지 저장\n # matplotlib는 CPU 기반이므로 CPU로 옮기기\n image = output.cpu().clone()\n # torch.Tensor에서 사용되는 배치 목적의 차원(dimension) 제거\n image = image.squeeze(0)\n # PIL 객체로 변경\n image = transforms.ToPILImage()(image)\n # 이미지를 화면에 출력(matplotlib는 [0, 1] 사이의 값이라고 해도 정상적으로 처리)\n\n fig = plt.figure()\n plt.imshow(image)\n\n plt.axis('off'), plt.xticks([]), plt.yticks([])\n plt.tight_layout()\n plt.subplots_adjust(left=0, bottom=0, right=1, top=1, hspace=0, wspace=0)\n\n plt.savefig(png_name, bbox_inches='tight', pad_inches=0)\n plt.close(fig)\n\n final_temp_img = Image.open(png_name)\n final_img_shape = image_loader(png_name)\n final_img = final_temp_img.resize((int(b * 1.5), output.shape[2]))\n final_img.save(png_name)\n\n num += 1\n print('{}개 중 {}개 완료'.format(total_lines_len, num))\n print('============png 파일 저장 완료============')","sub_path":"make_img2.py","file_name":"make_img2.py","file_ext":"py","file_size_in_byte":9292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"243610411","text":"import json\nimport logging\n\nfrom aio_pika import IncomingMessage\nfrom ..load_all import bot, dp\nfrom ..db.models import BotUser, Group\nfrom ..dialogs.admin import texts\n\n\nasync def process_donation(message: IncomingMessage):\n don = json.loads(message.body.decode(\"utf-8\"))\n try:\n logging.info(\"NEW DONATION, trying to identify who is it.\")\n admin = await BotUser.get(tg_id=don[\"additionalParameters\"][\"admin_tg_id\"])\n group = await Group.get(tg_id=don[\"additionalParameters\"][\"group_id\"])\n except KeyError:\n logging.info(\"Not successful.\")\n else:\n if admin and group:\n logging.info(\"Sending messages to admin.\")\n await bot.send_message(chat_id=don[\"additionalParameters\"][\"admin_tg_id\"],\n text=texts.new_donation(don))\n if group.is_report_donations:\n logging.info(\"Sending messages to group.\")\n await bot.send_message(chat_id=don[\"additionalParameters\"][\"group_id\"],\n text=texts.new_donation(don))\n","sub_path":"tg_bot/modules/donation.py","file_name":"donation.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"603538739","text":"def insertSort(arr, total_num):\n for i in range(1, total_num):\n v = arr[i]\n j = i - 1\n while j >= 0 and arr[j] > v:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = v\n print(\" \".join([str(x) for x in arr]))\n\n\nif __name__ == \"__main__\":\n inputs = []\n for i in range(2):\n inputs.append([int(x) for x in input().split(\" \")])\n arr, total_num = inputs[1], inputs[0][0]\n print(\" \".join([str(x) for x in arr]))\n insertSort(arr, total_num)\n","sub_path":"AOJ/Lesson-ALDS1/alds1_1_a.py","file_name":"alds1_1_a.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"627416139","text":"from tkinter import *\r\nimport tkinter.messagebox\r\ndef tip():\r\n root15=Tk()\r\n root15.title(\"SUGGESTIONS & TIPS\")\r\n root15.geometry(\"500x500\")\r\n state=\"IMPROVING IS THE KEY TO SUCCESS ,FILL THE ENTRY TO HELP US IMPROVE\"\r\n msg= Message(root15,text=state)\r\n msg.config(fg=\"white\",bg=\"lightgreen\",font=(\"verdena\",20,\"italic\"))\r\n msg.pack()\r\n entrytip=Entry(root15)\r\n entrytip.pack()\r\n def catch():\r\n f2=open(\"suggestion.txt\",\"a\")\r\n f2.write(entrytip.get()+\"\\n\")\r\n labelres=Label(root15,text=\"---Thank You---\",fg=\"purple\",bg=\"white\")\r\n labelres.pack()\r\n\r\n buttontip=Button(root15,text=\"_SUBMIT\",fg=\"red\",bg=\"yellow\",command=catch)\r\n buttontip.pack()\r\n \r\n \r\n\r\n root15.mainloop()\r\n\r\ndef security():\r\n root13=Tk()\r\n root13.title(\"!!!Innovative security services.!!!\")\r\n root13.geometry(\"600x400\")\r\n\r\n label2=Label(root13,text=\"******WELCOME TO OUR SECURITY******\",fg=\"purple\",bg=\"white\")\r\n label2.grid(row=0,sticky=\"n\")\r\n\r\n label1=Label(root13,text=\"Enter your name\",fg=\"purple\",bg=\"white\")\r\n label1.grid(row=1,sticky=\"w\")\r\n\r\n entry1=Entry(root13)\r\n entry1.grid(row=1,column=2)\r\n\r\n label2=Label(root13,text=\"Enter D.O.B(-)\",fg=\"purple\",bg=\"white\")\r\n label2.grid(row=2,sticky=\"w\")\r\n\r\n entry2=Entry(root13)\r\n entry2.grid(row=2,column=2)\r\n\r\n label3=Label(root13,text=\"Enter your income\",fg=\"purple\",bg=\"white\")\r\n label3.grid(row=3,sticky=\"w\")\r\n\r\n entry3=Entry(root13)\r\n entry3.grid(row=3,column=2)\r\n \r\n label4=Label(root13,text=\"Enter your Aadhar\",fg=\"purple\",bg=\"white\")\r\n label4.grid(row=4,sticky=\"w\")\r\n\r\n entry4=Entry(root13)\r\n entry4.grid(row=4,column=2)\r\n\r\n label5=Label(root13,text=\"Enter your wife or father name\",fg=\"purple\",bg=\"white\")\r\n label5.grid(row=5,sticky=\"w\")\r\n\r\n entry5=Entry(root13)\r\n entry5.grid(row=5,column=2)\r\n\r\n \r\n def protect():\r\n \r\n codes = { 'A':'.-', 'B':'-...', \r\n 'C':'-.-.', 'D':'-..', 'E':'.', \r\n 'F':'..-.', 'G':'--.', 'H':'....', \r\n 'I':'..', 'J':'.---', 'K':'-.-', \r\n 'L':'.-..', 'M':'--', 'N':'-.', \r\n 'O':'---', 'P':'.--.', 'Q':'--.-', \r\n 'R':'.-.', 'S':'...', 'T':'-', \r\n 'U':'..-', 'V':'...-', 'W':'.--', \r\n 'X':'-..-', 'Y':'-.--', 'Z':'--..', \r\n '1':'.----', '2':'..---', '3':'...--', \r\n '4':'....-', '5':'.....', '6':'-....', \r\n '7':'--...', '8':'---..', '9':'----.', \r\n '0':'-----', ', ':'--..--', '.':'.-.-.-', \r\n '?':'..--..', '/':'-..-.', '-':'-....-', \r\n '(':'-.--.', ')':'-.--.-'}\r\n value1=entry1.get()\r\n value2=entry2.get()\r\n value3=entry3.get()\r\n value4=entry4.get()\r\n value5=entry5.get()\r\n \r\n\r\n \r\n if len(value1) and len(value2) and len(value3) and len(value4) and len(value5)>0:\r\n\r\n root14 = Tk()\r\n root14.geometry(\"1200x500\")\r\n root14.title(\"MORSE :The modern security expert....\")\r\n\r\n def encrypt(message): \r\n x = '' \r\n for letter in message: \r\n if letter != ' ': \r\n \r\n \r\n x += codes[letter] + ' '\r\n else: \r\n \r\n x += ' '\r\n \r\n return x\r\n \r\n \r\n\r\n label1=Label(root14,text=\"NAME in MORSE\",fg=\"orange\",bg=\"white\")\r\n label1.grid(row=0,sticky=\"w\")\r\n\r\n label2=Label(root14)\r\n label2[\"text\"]= encrypt(value1.upper())\r\n label2.grid(row=0,column=1)\r\n\r\n label3=Label(root14,text=\"D.O.B in MORSE\",fg=\"orange\",bg=\"white\")\r\n label3.grid(row=1,sticky=\"w\")\r\n\r\n label4=Label(root14)\r\n label4[\"text\"]= encrypt(value2.upper())\r\n label4.grid(row=1,column=1)\r\n\r\n label5=Label(root14,text=\"INCOME in MORSE\",fg=\"orange\",bg=\"white\")\r\n label5.grid(row=2,sticky=\"w\")\r\n\r\n label6=Label(root14)\r\n label6[\"text\"]= encrypt(value3.upper())\r\n label6.grid(row=2,column=1)\r\n\r\n label7=Label(root14,text=\"AADHAR in MORSE\",fg=\"orange\",bg=\"white\")\r\n label7.grid(row=3,sticky=\"w\")\r\n\r\n label8=Label(root14)\r\n label8[\"text\"]= encrypt(value4.upper())\r\n label8.grid(row=3,column=1)\r\n\r\n label9=Label(root14,text=\"WIFE OR FATHER NAME in MORSE\",fg=\"orange\",bg=\"white\")\r\n label9.grid(row=4,sticky=\"w\")\r\n\r\n label10=Label(root14)\r\n label10[\"text\"]= encrypt(value5.upper())\r\n label10.grid(row=4,column=1)\r\n\r\n labelwarn=Label(root14,text=\"DEAR USERS\\n This morse code is the most valuable asset of PESU Bank\\n 100% security of info is Guaranteed\",fg=\"purple\",bg=\"yellow\")\r\n labelwarn.grid(row=6,sticky=\"w\")\r\n status=Label(root14,text=\"Securing your details >>>.... -by BHAVANI SHANKAR,PES1201801864------\",relief =SUNKEN,anchor=W,bd=1)\r\n status.grid(row=10,column=2)\r\n root14.mainloop() \r\n else:\r\n labelq=Label(root13,text=\"*__* ENTER DETAILS CAREFULLY *__*\",fg=\"red\",bg=\"yellow\")\r\n labelq.grid(row=8,column=17)\r\n button1=Button(root13,text=\"_Submit\",fg=\"blue\",bg=\"orange\",command=protect)\r\n button1.grid(row=7,column=15)\r\n \r\n root13.mainloop()\r\n#################\r\ndef home_loan():\r\n root7=Tk()\r\n root7.geometry(\"1200x150\")\r\n root7.title(\"Home_loans\")\r\n\r\n label_homeloan1=Label(root7,text=\"Enter your full name\",fg=\"orange\",bg=\"white\")\r\n label_homeloan1.grid(row=0,sticky=\"w\")\r\n\r\n label_homeloan2=Label(root7,text=\"Enter the builders Name\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan2.grid(row=1,sticky=\"w\")\r\n\r\n label_homeloan3=Label(root7,text=\"Enter the Name of the witness \" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan3.grid(row=2,sticky=\"w\")\r\n\r\n label_homeloan4=Label(root7,text=\"Enter the name of your wife or father\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan4.grid(row=3,sticky=\"w\")\r\n\r\n label_homeloan5=Label(root7,text=\"house area in 'in square_feet'\",fg=\"orange\",bg=\"white\")\r\n label_homeloan5.grid(row=4,sticky=\"w\")\r\n\r\n entry1=Entry(root7)\r\n entry1.grid(row=0, column=1)\r\n\r\n \r\n entry2=Entry(root7)\r\n entry2.grid(row=1, column=1)\r\n \r\n \r\n entry3=Entry(root7)\r\n entry3.grid(row=2, column=1)\r\n \r\n\r\n entry4=Entry(root7)\r\n entry4.grid(row=3, column=1)\r\n \r\n entry5=Entry(root7)\r\n entry5.grid(row=4, column=1)\r\n def sanction():\r\n value = entry1.get() \r\n value1= entry2.get()\r\n value2= entry3.get()\r\n value3= entry4.get()\r\n value4= entry5.get() \r\n air=\"***CONGRATULATIONS!! LOAN SANCTIONED ***\\nCOLLECT THE SANCTION LETTER FROM THE OFFICE\\n THE INTEREST RATE IS 6%pa \"\r\n labelsanction=Label(root7)\r\n \r\n\r\n if len(value)and len(value1) and len(value2) and len(value3) and len(value4) >0:\r\n labelsanction[\"text\"]= air \r\n labelsanction.grid(row=5,column=5)\r\n check_enter=Checkbutton(root7, text=\"I agree to all terms and conditions of the loan\")\r\n check_enter.grid(row=5,column=3)\r\n button_enter=Button(root7,text=\"SUBMIT\",fg=\"green\", bg=\"cyan\",command=sanction)\r\n button_enter.grid(row=6,column=3)\r\n root7.mainloop()\r\n#####################\r\ndef car_loan():\r\n root9=Tk()\r\n root9.geometry(\"1200x150\")\r\n root9.title(\"Car_loans\")\r\n\r\n label_homeloan1=Label(root9,text=\"Enter your full name\",fg=\"orange\",bg=\"white\")\r\n label_homeloan1.grid(row=0,sticky=\"w\")\r\n\r\n label_homeloan2=Label(root9,text=\"Enter name of the car \" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan2.grid(row=1,sticky=\"w\")\r\n\r\n label_homeloan3=Label(root9,text=\"Enter the Name of the witness \" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan3.grid(row=2,sticky=\"w\")\r\n\r\n label_homeloan4=Label(root9,text=\"Enter the name of your wife or father\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan4.grid(row=3,sticky=\"w\")\r\n\r\n label_homeloan5=Label(root9,text=\"Enter the model,colour\",fg=\"orange\",bg=\"white\")\r\n label_homeloan5.grid(row=4,sticky=\"w\")\r\n\r\n entry1=Entry(root9)\r\n entry1.grid(row=0, column=1)\r\n\r\n \r\n entry2=Entry(root9)\r\n entry2.grid(row=1, column=1)\r\n \r\n \r\n entry3=Entry(root9)\r\n entry3.grid(row=2, column=1)\r\n \r\n\r\n entry4=Entry(root9)\r\n entry4.grid(row=3, column=1)\r\n \r\n entry5=Entry(root9)\r\n entry5.grid(row=4, column=1)\r\n def sanctioncar():\r\n value = entry1.get() \r\n value1= entry2.get()\r\n value2= entry3.get()\r\n value3= entry4.get()\r\n value4= entry5.get() \r\n air=\"***CONGRATULATIONS!! LOAN SANCTIONED ***\\nCOLLECT THE SANCTION LETTER FROM THE OFFICE\\n THE INTEREST RATE IS 8%pa \"\r\n labelsanctioncar=Label(root9)\r\n \r\n\r\n if len(value)and len(value1) and len(value2) and len(value3) and len(value4) >0:\r\n labelsanctioncar[\"text\"]= air \r\n labelsanctioncar.grid(row=5,column=5)\r\n check_enter=Checkbutton(root9, text=\"I agree to all terms and conditions of the loan\")\r\n check_enter.grid(row=5,column=3)\r\n button_enter=Button(root9,text=\"SUBMIT\",fg=\"green\", bg=\"cyan\",command=sanctioncar)\r\n button_enter.grid(row=6,column=3)\r\n root9.mainloop()\r\n########################\r\ndef student_loan():\r\n root10=Tk()\r\n root10.geometry(\"1200x150\")\r\n root10.title(\"Student_loan\")\r\n label_homeloan1=Label(root10,text=\"Enter your full name\",fg=\"orange\",bg=\"white\")\r\n label_homeloan1.grid(row=0,sticky=\"w\")\r\n\r\n label_homeloan2=Label(root10,text=\"Enter the name of institution\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan2.grid(row=1,sticky=\"w\")\r\n\r\n label_homeloan3=Label(root10,text=\"Enter the Name of the course,fees \" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan3.grid(row=2,sticky=\"w\")\r\n\r\n label_homeloan4=Label(root10,text=\"Enter the name of your wife or father\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan4.grid(row=3,sticky=\"w\")\r\n\r\n label_homeloan5=Label(root10,text=\"Enter the period of the course 20xx-20yy\",fg=\"orange\",bg=\"white\")\r\n label_homeloan5.grid(row=4,sticky=\"w\")\r\n\r\n entry1=Entry(root10)\r\n entry1.grid(row=0, column=1)\r\n\r\n \r\n entry2=Entry(root10)\r\n entry2.grid(row=1, column=1)\r\n \r\n \r\n entry3=Entry(root10)\r\n entry3.grid(row=2, column=1)\r\n \r\n\r\n entry4=Entry(root10)\r\n entry4.grid(row=3, column=1)\r\n \r\n entry5=Entry(root10)\r\n entry5.grid(row=4, column=1)\r\n def sanction():\r\n value = entry1.get() \r\n value1= entry2.get()\r\n value2= entry3.get()\r\n value3= entry4.get()\r\n value4= entry5.get() \r\n air=\"***CONGRATULATIONS!! LOAN SANCTIONED ***\\nCOLLECT THE SANCTION LETTER FROM THE OFFICE\\n THE INTEREST RATE IS 4%pa \"\r\n labelsanction=Label(root10)\r\n \r\n\r\n if len(value)and len(value1) and len(value2) and len(value3) and len(value4) >0:\r\n labelsanction[\"text\"]= air \r\n labelsanction.grid(row=5,column=5)\r\n check_enter=Checkbutton(root10, text=\"I agree to all terms and conditions of the loan\")\r\n check_enter.grid(row=5,column=3)\r\n button_enter=Button(root10,text=\"SUBMIT\",fg=\"green\", bg=\"cyan\",command=sanction)\r\n button_enter.grid(row=6,column=3)\r\n root10.mainloop()\r\n######################\r\ndef food_coupons():\r\n root11=Tk()\r\n root11.geometry(\"1200x350\")\r\n root11.title(\"PES FOOD COUPONS: HUNGER ENDS HERE......Discover great coupons to eat around !!\")\r\n label_homeloan6=Label(root11,text=\"COUPONS AVAILABLE\\n BREAKFAST COUPON @ Rs 5per coupon\\n LUNCH COUPON @ Rs 10 per coupon\\n DINNER COUPONS @ Rs 15 per coupon\",fg=\"green\" ,bg=\"white\")\r\n label_homeloan6.grid(row=0,sticky=\"w\")\r\n\r\n\r\n label_homeloan1=Label(root11,text=\"Enter your full name\",fg=\"orange\",bg=\"white\")\r\n label_homeloan1.grid(row=1,sticky=\"w\")\r\n\r\n label_homeloan2=Label(root11,text=\"Enter your room No or class\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan2.grid(row=2,sticky=\"w\")\r\n\r\n label_homeloan3=Label(root11,text=\"Enter the name of mess(NORTH INDIAN|SOUTH INDIAN)\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan3.grid(row=3,sticky=\"w\")\r\n\r\n label_homeloan4=Label(root11,text=\"Enter the your SRN\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan4.grid(row=4,sticky=\"w\")\r\n\r\n label_homeloan5=Label(root11,text=\"Enter the no of coupons needed\",fg=\"orange\",bg=\"white\")\r\n label_homeloan5.grid(row=5,sticky=\"w\")\r\n\r\n label_homeloan7=Label(root11,text=\"Select the type of coupon \")\r\n label_homeloan7.grid(row=6,sticky=\"w\")\r\n\r\n \r\n entry1=Entry(root11)\r\n entry1.grid(row=1, column=1)\r\n\r\n \r\n entry2=Entry(root11)\r\n entry2.grid(row=2, column=1)\r\n \r\n \r\n entry3=Entry(root11)\r\n entry3.grid(row=3, column=1)\r\n \r\n\r\n entry4=Entry(root11)\r\n entry4.grid(row=4, column=1)\r\n \r\n entry5=Entry(root11)\r\n entry5.grid(row=5, column=1)\r\n def b():\r\n value=int(entry5.get())\r\n labelhome_loan8=Label(root11)\r\n labelhome_loan8[\"text\"]=\"Your total breakfast counpons costs\"+\" \"+\"Rs\"+str(float(value*5))\r\n labelhome_loan8.grid(row=10,column=5)\r\n def l():\r\n value=int(entry5.get())\r\n labelhome_loan8=Label(root11)\r\n labelhome_loan8[\"text\"]=\"Your total lunch coupons costs\"+\" \"+\"Rs\"+str(float(value*10))\r\n labelhome_loan8.grid(row=10,column=5)\r\n def d():\r\n value=int(entry5.get())\r\n labelhome_loan8=Label(root11)\r\n labelhome_loan8[\"text\"]=\"Your total dinner coupons costs\"+\" \"+\"Rs\"+str(float(value*15))\r\n labelhome_loan8.grid(row=10,column=5)\r\n\r\n \r\n\r\n\r\n\r\n \r\n buttoncoupon=Button(root11,text=\"BREAKFAST COUPON\",fg=\"blue\",bg=\"yellow\",command=b)\r\n buttoncoupon.grid(row=6,column=10)\r\n\r\n buttoncoupon1=Button(root11,text=\"LUNCH COUPON\",fg=\"blue\",bg=\"yellow\",command=l)\r\n buttoncoupon1.grid(row=6,column=20)\r\n \r\n buttoncoupon2=Button(root11,text=\"DINNER COUPON\",fg=\"blue\",bg=\"yellow\",command=d)\r\n buttoncoupon2.grid(row=6,column=30)\r\n\r\n\r\n\r\n def sanction():\r\n value = entry1.get() \r\n value1= entry2.get()\r\n value2= entry3.get()\r\n value3= entry4.get()\r\n value4= entry5.get() \r\n air=\"***CONGRATULATIONS!! FOOD COUPONS PURCHASED***\\n FOOD COUPONS WILL DELIVERED TO YOU WITHIN 30min\\n THE COUPONS CHARGES\\INCLUDED IN THE FEES \"\r\n \r\n labelsanction=Label(root11)\r\n \r\n\r\n if len(value)and len(value1) and len(value2) and len(value3) and len(value4) >0:\r\n labelsanction[\"text\"]= air \r\n labelsanction.grid(row=7,column=5)\r\n check_enter=Checkbutton(root11, text=\"I agree \")\r\n check_enter.grid(row=8,column=3)\r\n button_enter=Button(root11,text=\"Proceed to pay__\",fg=\"green\", bg=\"cyan\",command=sanction)\r\n button_enter.grid(row=9,column=3)\r\n root11.mainloop()\r\n########################\r\ndef travel_loans():\r\n root12=Tk()\r\n root12.geometry(\"1200x650\")\r\n root12.title(\"PESU YATRA ....Making travel Simple!!!!....\")\r\n label_homeloan1=Label(root12,text=\"Enter your full name\",fg=\"orange\",bg=\"white\")\r\n label_homeloan1.grid(row=0,sticky=\"w\")\r\n\r\n label_homeloan2=Label(root12,text=\"From \" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan2.grid(row=1,sticky=\"w\")\r\n\r\n label_homeloan3=Label(root12,text=\"To \" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan3.grid(row=2,sticky=\"w\")\r\n\r\n label_homeloan4=Label(root12,text=\"Start date\" ,fg=\"orange\",bg=\"white\")\r\n label_homeloan4.grid(row=3,sticky=\"w\")\r\n\r\n label_homeloan5=Label(root12,text=\"Return date\",fg=\"orange\",bg=\"white\")\r\n label_homeloan5.grid(row=4,sticky=\"w\")\r\n\r\n label_homeloan6=Label(root12,text=\"Enter the no of passenger travelling\",fg=\"orange\",bg=\"white\")\r\n label_homeloan6.grid(row=5,sticky=\"w\")\r\n\r\n label_homeloan7=Label(root12,text=\"Enter the no of passenger travelling back \",fg=\"orange\",bg=\"white\")\r\n label_homeloan7.grid(row=6,sticky=\"w\")\r\n \r\n label_homeloan8=Label(root12,text=\"Select the mode of travel\",fg=\"orange\",bg=\"white\")\r\n label_homeloan8.grid(row=7,sticky=\"w\")\r\n\r\n \r\n \r\n def t():\r\n value1 = entry1.get() \r\n value2= entry2.get()\r\n value3= entry3.get()\r\n value4= entry4.get()\r\n value5= entry5.get() \r\n value6= int(entry6.get())\r\n value7= int(entry7.get())\r\n def pt():\r\n n=[]\r\n l=[\"Rajdhani\",\"Shatabadi\",\"Durronto\"]\r\n import random\r\n train=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n trainno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your Train is\"+\" \"+train+\"\\n\"+\"Your train No:\"+\" \"+str(trainno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your Train is\"+\" \"+train+\"\\n\"+\"Your train No:\"+\" \"+str(trainno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*2300))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*2300))\r\n totallabel2.grid(row=24,column=17)\r\n def ds():\r\n n=[]\r\n l=[\"intercity Superfast\",\"Mahanagari Superfast\",\"Deccan queen Superfast \"]\r\n import random\r\n train=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n trainno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your Train is\"+\" \"+train+\"\\n\"+\"Your train No:\"+\" \"+str(trainno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your Train is\"+\" \"+train+\"\\n\"+\"Your train No:\"+\" \"+str(trainno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*1300))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*1300))\r\n totallabel2.grid(row=24,column=17)\r\n\r\n def gr():\r\n n=[]\r\n l=[\"Bagvati garib rath\",\"Sampark garib rath \",\"Musafir garib rath\"]\r\n import random\r\n train=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n trainno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your Train is\"+\" \"+train+\"\\n\"+\"Your train No:\"+\" \"+str(trainno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your Train is\"+\" \"+train+\"\\n\"+\"Your train No:\"+\" \"+str(trainno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*1000))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*1000))\r\n totallabel2.grid(row=24,column=17) \r\n\r\n buttontrains1=Button(root12 ,text=\"Premium trains\",fg=\"blue\",bg=\"orange\",command=pt)\r\n buttontrains1.grid(row=8,column=10)\r\n\r\n buttontrains2=Button(root12 ,text=\"Daily Superfast\",fg=\"blue\",bg=\"orange\",command=ds)\r\n buttontrains2.grid(row=10,column=10)\r\n\r\n buttontrains3=Button(root12 ,text=\"Garib Rath\",fg=\"blue\",bg=\"orange\",command=gr)\r\n buttontrains3.grid(row=12,column=10)\r\n\r\n\r\n def f():\r\n value1 = entry1.get() \r\n value2= entry2.get()\r\n value3= entry3.get()\r\n value4= entry4.get()\r\n value5= entry5.get() \r\n value6= int(entry6.get())\r\n value7= int(entry7.get())\r\n def business():\r\n n=[]\r\n l=[\"Lufthansa\",\"Air India\",\"Emirates\",\"Qatar Airways\",\"Kingfisher\"]\r\n import random\r\n flight=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n flightno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your flight is\"+\" \"+flight+\"\\n\"+\"Your flight No:\"+\" \"+str(flightno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your flight is\"+\" \"+flight+\"\\n\"+\"Your flight No:\"+\" \"+str(flightno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*7000))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*7000))\r\n totallabel2.grid(row=24,column=17)\r\n def premiumeconomy():\r\n n=[]\r\n l=[\"Air Asia\",\"Air India\",\"Air India Express\",\"GoAir\",\"Indigo\",\"Vistara\",\"Jet Airways\"]\r\n import random\r\n flight=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n flightno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your flight is\"+\" \"+flight+\"\\n\"+\"Your flight No:\"+\" \"+str(flightno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your flight is\"+\" \"+flight+\"\\n\"+\"Your flight No:\"+\" \"+str(flightno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*5300))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*5300))\r\n totallabel2.grid(row=24,column=17)\r\n\r\n def economy():\r\n n=[]\r\n l=[\"Jetlite\",\"SpiceJet\",\"AirCoasta\",\"Air CarnivalJet\",\"Airpegasus\"]\r\n import random\r\n flight=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n flightno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your flight is\"+\" \"+flight+\"\\n\"+\"Your flight No:\"+\" \"+str(flightno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your flight is\"+\" \"+flight+\"\\n\"+\"Your flight No:\"+\" \"+str(flightno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*4000))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*4000))\r\n totallabel2.grid(row=24,column=17) \r\n\r\n buttonflight1=Button(root12 ,text=\"Business\",fg=\"blue\",bg=\"orange\",command=business)\r\n buttonflight1.grid(row=8,column=20)\r\n\r\n buttonflight2=Button(root12 ,text=\"Premium Economy\",fg=\"blue\",bg=\"orange\",command=premiumeconomy)\r\n buttonflight2.grid(row=10,column=20)\r\n\r\n buttonflight3=Button(root12 ,text=\"Economy\",fg=\"blue\",bg=\"orange\",command=economy)\r\n buttonflight3.grid(row=12,column=20)\r\n\r\n\r\n def b():\r\n value1 = entry1.get() \r\n value2= entry2.get()\r\n value3= entry3.get()\r\n value4= entry4.get()\r\n value5= entry5.get() \r\n value6= int(entry6.get())\r\n value7= int(entry7.get())\r\n def sleeperAC():\r\n n=[]\r\n l=[\"SRS Travels\",\"VRL Travels\",\"VOLVO\",\"HEBRON\",\"K.S.R.T.C\"]\r\n rajya=[\"KA-\",\"MH-\",\"TN-\",\"UP-\",\"RJ-\",\"GJ-\",\"KL-\",\"WB-\",\"MP-\",\"AP-\",\"DL-\"]\r\n import random\r\n busstate=random.choice(rajya)\r\n bus=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n busno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your bus is\"+\" \"+bus+\"\\n\"+\"Your bus No:\"+busstate+\" \"+str(busno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your bus is\"+\" \"+bus+\"\\n\"+\"Your bus No:\"+busstate+\" \"+str(busno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*1500))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*1500))\r\n totallabel2.grid(row=24,column=17)\r\n def semisleeperAC():\r\n n=[]\r\n l=[\"SRS Travels\",\"VRL Travels\",\"VOLVO\",\"HEBRON\",\"K.S.R.T.C\"]\r\n rajya=[\"KA-\",\"MH-\",\"TN-\",\"UP-\",\"RJ-\",\"GJ-\",\"KL-\",\"WB-\",\"MP-\",\"AP-\",\"DL-\"] \r\n import random\r\n busstate=random.choice(rajya)\r\n bus=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n busno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your bus is\"+\" \"+bus+\"\\n\"+\"Your bus No:\"+busstate+\" \"+str(busno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your bus is\"+\" \"+bus+\"\\n\"+\"Your bus No:\"+busstate+\" \"+str(busno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*900))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*900))\r\n totallabel2.grid(row=24,column=17)\r\n\r\n def sleeperNonAC():\r\n n=[]\r\n l=[\"SRS Travels\",\"VRL Travels\",\"VOLVO\",\"HEBRON\",\"K.S.R.T.C\"]\r\n rajya=[\"KA-\",\"MH-\",\"TN-\",\"UP-\",\"RJ-\",\"GJ-\",\"KL-\",\"WB-\",\"MP-\",\"AP-\",\"DL-\"]\r\n import random\r\n busstate=random.choice(rajya)\r\n bus=random.choice(l)\r\n for i in range(1000,10000):\r\n n.append(i)\r\n busno=random.choice(n)\r\n labelticket=Label(root12)\r\n labelticket1=Label(root12)\r\n totallabel1=Label(root12)\r\n totallabel2=Label(root12)\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5) and len(str(value6)) >0:\r\n labelticket[\"text\"]=\"first trip\"+\"\\n\"+\"Your bus is\"+\" \"+bus+\"\\n\"+\"Your bus No:\"+busstate+\" \"+str(busno)+\"\\n\"+\"date\"+value4+\"\\n\"+\"time 16:00\"+\"no of passengers\"+str(value6)\r\n labelticket.grid(row=14,column=15)\r\n labelticket1[\"text\"]=\"second trip\"+\"\\n\"+\"Your bus is\"+\" \"+bus+\"\\n\"+\"Your bus No:\"+busstate+\" \"+str(busno)+\"\\n\"+\"date\"+value5+\"\\n\"+\"time 10:00\"+\"no of passengers\"+str(value7)\r\n labelticket1.grid(row=16,column=15)\r\n totallabel1[\"text\"]=\"first_trip cost\"+\"=>>\"+\"Rs\"+str(float((value6)*600))\r\n totallabel1.grid(row=20,column=17)\r\n totallabel2[\"text\"]=\"second_trip cost\"+\"=>>\"+\"Rs\"+str(float((value7)*600))\r\n totallabel2.grid(row=24,column=17) \r\n\r\n buttonbus1=Button(root12 ,text=\"sleeperAC\",fg=\"blue\",bg=\"orange\",command=sleeperAC)\r\n buttonbus1.grid(row=8,column=30)\r\n\r\n buttonbus2=Button(root12 ,text=\"semisleeperAC\",fg=\"blue\",bg=\"orange\",command=semisleeperAC)\r\n buttonbus2.grid(row=10,column=30)\r\n\r\n buttonbus3=Button(root12 ,text=\"sleeperNonAC\",fg=\"blue\",bg=\"orange\",command=sleeperNonAC)\r\n buttonbus3.grid(row=12,column=30)\r\n\r\n\r\n\r\n button1=Button(root12,text=\"Train_\",fg=\"blue\",bg=\"yellow\",command=t)\r\n button1.grid(row=7,column=10)\r\n\r\n button2=Button(root12,text=\"Flight_\",fg=\"blue\",bg=\"yellow\",command=f)\r\n button2.grid(row=7,column=20)\r\n\r\n button3=Button(root12,text=\"Bus_\",fg=\"blue\",bg=\"yellow\",command=b)\r\n button3.grid(row=7,column=30)\r\n \r\n entry1=Entry(root12)\r\n entry1.grid(row=0, column=1)\r\n\r\n \r\n entry2=Entry(root12)\r\n entry2.grid(row=1, column=1)\r\n \r\n \r\n entry3=Entry(root12)\r\n entry3.grid(row=2, column=1)\r\n \r\n\r\n entry4=Entry(root12)\r\n entry4.grid(row=3, column=1)\r\n \r\n entry5=Entry(root12)\r\n entry5.grid(row=4, column=1)\r\n\r\n entry6=Entry(root12)\r\n entry6.grid(row=5,column=1)\r\n\r\n \r\n entry7=Entry(root12)\r\n entry7.grid(row=6,column=1)\r\n\r\n def sanctioncar():\r\n value1 = entry1.get() \r\n value2= entry2.get()\r\n value3= entry3.get()\r\n value4= entry4.get()\r\n value5= entry5.get() \r\n value6= entry6.get()\r\n \r\n air=\"***CONGRATULATIONS!! TICKETS BOOKED ***\\nTICKETS WILL BE GIVEN TO YOU WIHTIN 3 HOURS\\n THE TICKET COST WILL BE INCLUDED IN THE FEES\"\r\n labelsanctioncar=Label(root12)\r\n \r\n\r\n if len(value1)and len(value2) and len(value3) and len(value4) and len(value5)and len(str(value6)) >0:\r\n labelsanctioncar[\"text\"]= air \r\n labelsanctioncar.grid(row=5,column=5)\r\n check_enter=Checkbutton(root12, text=\"I hereby confirm my trip \")\r\n check_enter.grid(row=22,column=7)\r\n button_enter=Button(root12,text=\"Proceed to pay__\",fg=\"green\", bg=\"cyan\",command=sanctioncar)\r\n button_enter.grid(row=24,column=7)\r\n root12.mainloop()\r\n \r\n#############################\r\ndef enroll():\r\n root4=Tk()\r\n root4.geometry(\"400x200\")\r\n root4.title(\"*_*OUR SERVICES*_*\")\r\n\r\n button1=Button(root4 ,text=\"HOME LOANS\",command=home_loan)\r\n button2=Button(root4 ,text=\"CAR LOANS \" ,command=car_loan)\r\n button3=Button(root4 ,text=\"STUDENT LOANS\",command=student_loan)\r\n button4=Button(root4 ,text=\"FOOD COUPONS \",command=food_coupons)\r\n button5=Button(root4 ,text=\"TRAVEL LOANS \",command=travel_loans)\r\n button1.pack()\r\n button2.pack()\r\n button3.pack()\r\n button4.pack()\r\n button5.pack()\r\n root4.mainloop()\r\n\r\ndef service():\r\n root3=Tk()\r\n root3.title(\"OUR SERVICES\")\r\n root3.geometry(\"500x500\")\r\n topframe=Frame(root3)\r\n topframe.pack()\r\n label=Label(topframe,text=\"OUR OTHER FEATURES:-\\n HOME LOANS\\nCAR LOANS\\nSTUDENT LOANS\\n FOOD COUPONS \\n TRAVEL LOANS\",fg=\"black\")\r\n label.pack(side=LEFT)\r\n button=Button(root3, text =\"Enroll Now\",fg=\"blue\",bg=\"white\",command=enroll)\r\n button.pack(side=BOTTOM)\r\n root3.mainloop()\r\n###################\r\ndef enter():\r\n root2=Tk()\r\n root2.title(\"SIGN UP_PAGE\")\r\n root2.geometry(\"1200x150\")\r\n\r\n label_enter1=Label(root2,text=\"Enter your first name\",fg=\"violet\",bg=\"white\")\r\n label_enter1.grid(row=0,sticky='w')\r\n\r\n label_enter2=Label(root2,text=\"Enter your last name\",fg=\"violet\",bg=\"white\")\r\n label_enter2.grid(row =1,sticky=\"w\")\r\n\r\n label_enter3=Label(root2 ,text=\"Enter your age\",fg=\"violet\",bg=\"white\")\r\n label_enter3.grid(row=2,sticky=\"w\")\r\n\r\n label_enter4=Label(root2,text=\"Enter your gender \",fg=\"violet\",bg=\"white\")\r\n label_enter4.grid(row=3,sticky=\"w\")\r\n\r\n\r\n def save():\r\n root5=Tk()\r\n root5.title(\"YOUR PERSONAL DETAILS\")\r\n root5.geometry(\"1200x150\")\r\n name_save = entry1.get()\r\n name1_save = entry2.get()\r\n age_save = entry3.get()\r\n gender_save = entry4.get()\r\n label_save1=Label(root5)\r\n label_save2=Label(root5)\r\n label_save3=Label(root5)\r\n label_save4=Label(root5)\r\n \r\n if len(name_save)and len(name1_save) and len(age_save) and len(gender_save) >0:\r\n label_enter5=Label(root2,text=\"----LOGIN SUCCESSFULL----\")\r\n label_enter5.grid(row = 6, column=1)\r\n label_save1[\"text\"]= name_save\r\n label_save2[\"text\"]= name1_save\r\n label_save3[\"text\"]= age_save\r\n label_save4[\"text\"]= gender_save\r\n label_save1.grid(row=0,sticky=\"w\")\r\n label_save2.grid(row=1,sticky=\"w\")\r\n label_save3.grid(row=2,sticky=\"w\")\r\n label_save4.grid(row=3,sticky=\"w\")\r\n import random\r\n #for password\r\n l=[]\r\n for i in range(1000,10000):\r\n l.append(str(i))\r\n a=random.choice(l)\r\n f= open(\"pesudir.txt\",\"a\")\r\n f.write(name_save+\"\\n\")\r\n f.write(name1_save+\"\\n\")\r\n f.write(age_save+\"\\n\")\r\n f.write(gender_save+\"\\n\")\r\n f.write(str(a)+\"\\n\")\r\n\r\n label_save5=Label(root5,text=\"YOUR PIN IS \"+\"===> \"+a,fg=\"green\",bg=\"white\")\r\n label_save5.grid(row=4,sticky=\"w\")\r\n \r\n \r\n\r\n entry1=Entry(root2)\r\n entry1.grid(row=0 ,column=1)\r\n entry2=Entry(root2)\r\n entry2.grid(row=1 ,column=1)\r\n entry3=(Entry(root2))\r\n entry3.grid(row=2 ,column=1)\r\n entry4=Entry(root2)\r\n entry4.grid(row=3, column=1)\r\n check_enter=Checkbutton(root2, text=\"I agree to all terms and conditions of the bank\")\r\n check_enter.grid(row=5,column=3)\r\n button_enter=Button(root2,text=\"SUBMIT\",fg=\"green\", bg=\"cyan\",command=save)\r\n button_enter.grid(row=6,column=3)\r\n root2.mainloop()\r\n######################## \r\n\r\n#######################\r\ndef crow():\r\n root8=Tk()\r\n root8.geometry(\"700x200\")\r\n root8.title(\"WITHDRAWAL\")\r\n \r\n label1=Label(root8,text=\"----PLEASE INSERT THE CARD----\",fg=\"orange\",bg=\"white\")\r\n label1.grid(row=1,column=5)\r\n label3=Label(root8,text=\"Available Denominations in 100x,200x,500x,2000x\",fg=\"orange\",bg=\"white\")\r\n label3.grid(row=2,sticky=\"w\")\r\n label2=Label(root8,text='Enter the amount',fg=\"orange\",bg=\"white\")\r\n label2.grid(row=3,sticky='w')\r\n enter1=Entry(root8)\r\n enter1.grid(row=3,column=6)\r\n label6=Label(root8,text=\"Enter the pin\",fg=\"orange\",bg=\"white\")\r\n label6.grid(row=4,sticky='w')\r\n enter2=Entry(root8)\r\n enter2.grid(row=4,column=6)\r\n def money():\r\n value=enter1.get()\r\n pin=enter2.get()\r\n label4=Label(root8)\r\n label5=Label(root8)\r\n f=open(\"pesudir.txt\",\"r\")\r\n k=f.readlines()\r\n \r\n if len(value)>0 and pin+\"\\n\" in k:\r\n label4[\"text\"]= \"transaction of \"+\"Rs\"+\" \"+value+\" \"+\"is getting processed\"\r\n label4.grid(row=7,column=0)\r\n label7=Label(root8,text=k[k.index(pin+\"\\n\")-4]+\" \"+k[k.index(pin+\"\\n\")-3],fg=\"blue\",bg=\"white\")\r\n label7.grid(row=8,column=0)\r\n else:\r\n label5[\"text\"]=\"Enter proper amount and pin carefully \"\r\n label5.grid(row=10,column=2)\r\n def rep():\r\n value=enter1.get()\r\n label5=Label(root8)\r\n label5[\"text\"]=\"amount withdrawn\"+\"\"+\"Rs\"+value\r\n label5.grid(row=6,column=5)\r\n button2=Button(root8,text=\"RECEIPT\",fg=\"orange\",bg='white',command=rep)\r\n\r\n button2.grid(row=5,column=7)\r\n button1=Button(root8,text=\"Next_\",fg=\"blue\",bg=\"white\",command=money)\r\n button1.grid(row=5,column=5)\r\n root8.mainloop()\r\n########################### \r\ndef moo():\r\n def result():\r\n value = (entry1.get())\r\n if (value) ==\"\":\r\n label_moo_error=Label(root1,text=\"!!! PLEASE ENTER PROPER AMOUNT !!!\",fg=\"red\")\r\n label_moo_error.grid(row=3,column=2)\r\n \r\n string_to_display = \"Rs\"+\" \"+str(10000+float(value))\r\n label_moo=Label(root1)\r\n label_moo1=Label(root1)\r\n label_moo2=Label(root1)\r\n f=open(\"pesudir.txt\",\"r\")\r\n k=f.readlines()\r\n \r\n \r\n \r\n if len(value)>0 and entry2.get()+\"\\n\" in k :\r\n label7=Label(root1,text=k[k.index(entry2.get()+\"\\n\")-4]+\" \"+k[k.index(entry2.get()+\"\\n\")-3],fg=\"blue\",bg=\"white\")\r\n label7.grid(row=10,column=0)\r\n label_moo[\"text\"]= string_to_display\r\n label_moo.grid(row=2,column=2)\r\n label_moo1[\"text\"]=\"*_* THANK YOU *_*\"\r\n label_moo1.grid(row=3,column=2)\r\n label_moo2[\"text\"]=\">>>> YOUR NEW BALANCE <<<<\"+\"Rs\"+\" \"+str(10000+float(value))\r\n label_moo2.grid(row=4,column=3)\r\n else :\r\n labelw=Label(root1,text=\"incorrect pin !TRY AGAIN\",fg=\"red\")\r\n labelw.grid(row=10,column=0)\r\n\r\n root1=Tk()\r\n root1.title(\"ADD MONEY\")\r\n root1.geometry(\"600x600\")\r\n labelmoo1=Label(root1,text=\"ENTER THE AMOUNT TO BE DEPOSITED\",fg=\"cyan\",bg=\"grey\")\r\n labelmoo1.grid(row=0,sticky =\"w\")\r\n entry1=Entry(root1)\r\n entry1.grid(row=0,column=1)\r\n labelpin=Label(root1,text=\"Enter the pin\",fg=\"orange\",bg=\"white\")\r\n labelpin.grid(row=1,sticky=\"w\")\r\n entry2=Entry(root1)\r\n entry2.grid(row=1,column=1)\r\n\r\n button7=Button(root1,text=\"<<-DEPOSIT->>\",command=result)\r\n button7.grid(row=0,column=3)\r\n button12=Button(root1)\r\n button12.grid(row=0,column=6)\r\n root1.mainloop()\r\n\r\nroot=Tk()\r\nroot.geometry(\"1100x900\")\r\nroot.title(\"PESU BANK\")\r\nstate=\"PESU\"\r\nmsg= Message(root,text=state)\r\nmsg.config(fg=\"white\",bg=\"lightgreen\",font=(\"verdena\",20,\"italic\"))\r\nmsg.pack()\r\nstate1=\"BANK\"\r\nmsg1= Message(root,text=state1)\r\nmsg1.config(fg=\"white\",bg=\"lightgreen\",font=(\"verdena\",20,\"italic\"))\r\nmsg1.pack()\r\nlabel3=Label(root,text=\"Bank for life!! Zindagi ke saath bhi aur Zindagi ke baad bhi\",fg=\"green\",bg=\"yellow\")\r\nlabel3.pack()\r\nlabel2=Label(root,text=\"PES UNIVERSITY\",fg=\"orange\")\r\nlabel2.pack()\r\nlabel9=Label(root,text=\"PLACE WHERE INDIA BANKS !!!!\",fg=\"black\",bg=\"orange\")\r\nlabel9.pack()\r\nlabel5=Label(root,text=\"COME ONN!!! INDIA LET'S! BANK \",fg=\"red\")\r\nlabel5.pack()\r\nlabel6=Label(root,text=\"OUR COSTUMERS ,OUR GOD \",fg=\"green\")\r\nlabel6.pack()\r\nlabel7=Label(root,text=\"BELOW IS OUR USER GUI FOR VIRTUAL ATM\",fg=\"violet\",bg=\"yellow\")\r\nlabel7.pack()\r\nlabel10=Label(root,text=\"-by ROHIT VISHWAKARMA PES1201800152\",fg=\"brown\",bg=\"white\")\r\nlabel10.pack(side=\"right\")\r\nbutton1=Button(root,text=\"start or LOGIN\",command=enter)\r\nbutton1.pack(side=LEFT)\r\nbutton2=Button(root,text=\"-SUGGESTIONS & TIPS-\",command=tip)\r\nbutton2.pack(side=RIGHT)\r\nbutton3=Button(root,text=\"-REFRESH-\")\r\nbutton3.pack(side=RIGHT)\r\nbutton4=Button(root,text=\"-MONEY WITHDRAWAL-\",command=crow)\r\nbutton4.pack(side=RIGHT)\r\nbutton5=Button(root,text=\"-SAVING ACCOUNT DETAILS-\")\r\nbutton5.pack(side=RIGHT)\r\nbutton6=Button(root,text=\"-DEPOSIT-\",command=moo)\r\nbutton6.pack(side=RIGHT)\r\n\r\ndef custombox_quit():\r\n answer=tkinter.messagebox.showinfo(\"---WARNING---\",\"Are you sure you want to cancel?\")\r\n if answer:\r\n root.destroy()\r\nbutton8=Button(root,text=\"---EXIT---\",fg=\"red\",bg=\"yellow\",command=custombox_quit)\r\nbutton8.pack(side=LEFT)\r\ndef myinfo():\r\n root6=Tk()\r\n root6.title(\"INFO\")\r\n label_info=Label(root6,text=\"PESU BANK\\n CHAIRMAN Mr ROHIT VISHWAKARMA \\n VICE CHAIRMAN Mr B SHANKAR \\n CONTACT:-9880218337\")\r\n label_info.pack(side=LEFT)\r\n label_info1=Label(root6,text=\"A GOVERNMENT OF INDIA UNDERTAKING\",fg=\"white\",bg=\"black\")\r\n label_info1.pack(side=TOP)\r\n root6.mainloop()\r\nbutton9=Button(root,text=\"INFO\",fg=\"green\",bg=\"white\",command=myinfo)\r\nbutton9.pack(side=BOTTOM) \r\nstatus=Label(root,text=\"Running >>>.... -by ROHIT VISHWAKARMA,PES1201800152------\",relief =SUNKEN,anchor=W,bd=1)\r\nstatus.pack(side=BOTTOM,fill=X)\r\nbutton10=Button(root,text=\"other SERVICES..\",fg=\"indigo\",command=service)\r\nbutton10.pack()\r\nbutton11=Button(root,text=\"SECURITY\",fg=\"green\",bg=\"white\",command=security)\r\nbutton11.pack(side=BOTTOM)\r\nroot.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Bank.py","file_name":"Bank.py","file_ext":"py","file_size_in_byte":42422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"66252804","text":"batch_size = 20 #@param {type:\"slider\", min:1,max:200}\ntest_batch_size = batch_size\n# testing_frequency=100 # Depricated in favor of half of every round\n# epochs = 1001\nnum_rounds=7\nseed = 1\nlog_interval = 400\nlog_test_value = 100\nK = 5 #@param {type:\"slider\", min:5, max:50, step:1}\nlearning_rate = 5e-4 # Was 5e-4, which overtrained\ndiscrete_data = True\ncuda = torch.cuda.is_available()\n\ndata_name = 'silhouettes' #@param['silhouettes','omniglot','freyfaces']\n\nalpha = .5 #@param [0, 1] {type:\"raw\"}\nmodel_type = 'vralpha' #@param['iwae','vrmax','vae','general_alpha']\ntorch.manual_seed(seed)\n\nif model_type not in [\"general_alpha\",\"vralpha\"]:\n\tmodel_name=model_type\nelse:\n\tmodel_name = model_type+str(alpha)\n\nlogging_filename = f'{model_name}_{data_name}_K{K}_M{batch_size}.log'\nlogging.basicConfig(filename=logging_filename,level=logging.DEBUG)","sub_path":"experiments/replication_increased_lr/silhouettes/vralpha.5_silhouettes_K5_M20/train_and_hyperparameters.py","file_name":"train_and_hyperparameters.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"233854604","text":"from sensor import *\nfrom sensim import *\nfrom math import sin\n\nprint(\"Define parking...\")\nparking_place = FunctionSensor(function=lambda x: 1).turnedOnBetweenTime(\"1h\", \"15h\").named(\"one parking slot\")\nparking = (parking_place * 5).named(\"parking\")\n\nprint(\"Define weather...\")\nweather = MarkovChain(step=\"1s\").turnedOffAt(\"1d\").named(\"Weather Sensor\")\n# step is the time between two steps in the chain\nweather.addNodes(\"sunny\", \"rainy\", \"snowy\")\nweather.addTransition(\"sunny\", \"rainy\", 0.1)\nweather.addTransition(\"sunny\", \"sunny\", 0.9)\nweather.addTransition(\"rainy\", \"sunny\", 0.3)\nweather.addTransition(\"rainy\", \"rainy\", 0.5)\nweather.addTransition(\"snowy\", \"snowy\", 0.7)\nweather.addTransition(\"snowy\", \"rainy\", 0.3)\nweather.setStartNode(\"sunny\")\n\nprint(\"Define computers...\")\ncomputer_consumption = FunctionSensor(function=lambda t: (1+sin(t.hour))*20).named(\"computer consumption\").turnedOffAt(\"1d\")\n\nprint(\"Define doors...\")\ndoor_open = MarkovChain().named(\"door open\").turnedOffAt(\"1d\")\ndoor_open.addNodes(0, 1)\ndoor_open.addTransition(0, 1, 0.3)\ndoor_open.addTransition(1, 0, 0.3)\n# the markov chain will implicitely put the remaining probabilities to 0.7\ndoor_open.setStartNode(0)\n\nprint(\"Define office...\")\noffice = (computer_consumption + door_open).named(\"office\")\n\nprint(\"Define laboratory...\")\nlaboratory = (office * 3).named(\"laboratory\")\n\nprint(\"Define ENS...\")\nens = (laboratory + weather + parking).named(\"ENS\")\n\nprint(\"Prepare display...\")\ndisplay = JsonDisplay(\"test_ens.raw\")\n\nprint(\"Prepare Simulation...\")\nsimu = Simulation(display=display, sensors=[ens], speed=1, stop=\"1h\")\n\nprint(\"Run simulation\")\nsimu.run()\n","sub_path":"lab_2/examples/ens_simulation.py","file_name":"ens_simulation.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"337294646","text":"import mysql.connector as mysql\nfrom book import Book\nfrom activeReservation import ActiveReservation\nfrom datetime import date, datetime, timedelta\nimport mysql.connector as mysql\nimport copy\nimport settings\ndb = mysql.connect(\n host = \"localhost\",\n user = settings.user,\n passwd = \"1234\",\n database = \"lis\"\n)\ncursor = db.cursor(dictionary = True)\n\n# changes\n## make all fucntions non static maybe\n## no member called currUID\n## changes in the arguments of a lot of functions\n## might want to pass LIbrary member to IssueBook etc and make changes to its data members then update database using its own method\ndef UpdateReminders():\n cursor.execute(\"SELECT * FROM MEMBERS\")\n changedMembers = []\n for row in cursor:\n if(row[\"GotReminder\"]==False):\n continue\n BooksIssued = row[\"ListOfBooksIssued\"]\n ListBooksIssued = SplitTableEntry(BooksIssued)\n period = 0\n if(row[\"MemberType\"]==\"UG\"):\n period = 1\n elif row[\"MemberType\"]==\"PG\":\n period = 1\n elif row[\"MemberType\"]==\"RS\":\n period = 3\n else:\n period = 6\n flag = False\n for bookUID in ListBooksIssued:\n book = {\n 'bookUID' : int(bookUID)\n }\n cursor2 = db.cursor(dictionary = True)\n cursor2.execute((\"SELECT LastIssued FROM BOOKS WHERE UniqueID = %(bookUID)s\"),book)\n row2 = cursor2.fetchone()\n db.commit()\n if (date.today() - row2[\"LastIssued\"]).days > 30*self.GetMaxMonthsAllowed():\n flag = True\n # db.commit()\n if flag == False:\n changedMembers.append(row[\"MemberID\"])\n db.commit()\n for member in changedMembers:\n mem = {\n 'memId' : member\n }\n cursor.execute((\"UPDATE MEMBERS SET GotReminder = 0 WHERE MemberID = %(memId)s\"), mem)\n db.commit()\n # db.commit()\n\nclass BookHandler:\n instance = None\n currUID = None\n currISBN = None\n available = []\n taken = []\n waitList = []\n readyToClaimUsers = []\n readyToClaimUIDs = []\n numberOfCopies = 0\n \n @staticmethod \n # Static Access Method\n def Create():\n if BookHandler.instance == None:\n BookHandler()\n return BookHandler.instance\n \n # Virtually private constructor\n def __init__(self):\n if BookHandler.instance != None:\n raise Exception(\"This class is a singleton!\")\n else:\n BookHandler.instance = self\n\n @staticmethod \n def OpenBook(book):\n if (isinstance(book,str)):\n BookHandler.currISBN = book\n elif(isinstance(book,Book)):\n BookHandler.currISBN = book.GetISBN()\n BookHandler.currUID = str(book.GetUID())\n\n selectISBN = (\"SELECT * FROM RESERVATIONS WHERE ISBN = %(ISBN)s\")\n isbn = {\n 'ISBN' : BookHandler.currISBN\n }\n cursor.execute(selectISBN, isbn)\n for row in cursor:\n BookHandler.available = SplitTableEntry(row['AvailableUIDs'])\n BookHandler.taken = SplitTableEntry(row['TakenUIDs'])\n BookHandler.waitList = SplitTableEntry(row['PendingReservations'])\n \n activeReservationPair = [x.split('*') for x in SplitTableEntry(row['ActiveReservations'])]\n claimByDateYMD = [x[0].split('-') for x in activeReservationPair]\n claimByDateYMD = [date(int(x[0]), int(x[1]), int(x[2])) for x in claimByDateYMD]\n memberID = [x[1] for x in activeReservationPair]\n for i in range(len(memberID)):\n BookHandler.readyToClaimUsers.append(ActiveReservation(memberID[i], claimByDateYMD[i]))\n \n BookHandler.readyToClaimUIDs = SplitTableEntry(row['ActiveReservedUIDs'])\n BookHandler.numberOfCopies = row['NumberOfCopiesAvailable']\n db.commit()\n\n @staticmethod\n def UpdateBook():\n deleteMemberReservation = (\"UPDATE MEMBERS SET ReservedBook = NULL WHERE MemberID = %(MemberID)s\")\n member = {\n 'MemberID' : None\n }\n for entry in BookHandler.readyToClaimUsers:\n member['MemberID'] = entry.memberID\n if entry.claimByDate < date.today():\n # if True:\n cursor.execute(deleteMemberReservation, member)\n db.commit()\n if len(BookHandler.waitList): # if pending reservations, then make them active\n newActive = BookHandler.waitList.pop(0)\n BookHandler.readyToClaimUsers.append(ActiveReservation(newActive, (datetime.now()+timedelta(days = 7)).date()))\n else:\n reservationFree = BookHandler.readyToClaimUIDs.pop()\n BookHandler.available.append(reservationFree)\n BookHandler.readyToClaimUsers = [item for item in BookHandler.readyToClaimUsers if item.claimByDate >= date.today()]\n BookHandler.numberOfCopies = len(BookHandler.available)\n \n \n @staticmethod\n def UpdateDatabase():\n copyavail = copy.deepcopy(BookHandler.available)\n for currUID in BookHandler.available:\n if(len(BookHandler.waitList)==0):\n break\n if(len(copyavail)==0):\n break\n BookHandler.readyToClaimUIDs.append(currUID)\n memberActivated = BookHandler.waitList.pop(0)\n newActive = ActiveReservation(memberActivated, (datetime.now()+timedelta(days = 7)).date())\n BookHandler.readyToClaimUsers.append(newActive)\n copyavail.remove(currUID)\n BookHandler.available = copyavail\n BookHandler.numberOfCopies = len(BookHandler.available)\n readyToClaimUsers = list(map(lambda x: str(x.claimByDate)+'*'+x.memberID, BookHandler.readyToClaimUsers)) \n updateReservationTable = (\"UPDATE RESERVATIONS SET AvailableUIDs = %(AvailableUIDs)s, TakenUIDs = %(TakenUIDs)s, PendingReservations = %(PendingReservations)s, ActiveReservations = %(ActiveReservations)s, ActiveReservedUIDs = %(ActiveReservedUIDs)s, NumberOfCopiesAvailable = %(NumberOfCopiesAvailable)s WHERE ISBN = %(ISBN)s\")\n dataReservation = {\n 'ISBN' : str(BookHandler.currISBN),\n 'AvailableUIDs' : JoinTableEntry(BookHandler.available),\n 'TakenUIDs' : JoinTableEntry(BookHandler.taken),\n 'PendingReservations' : JoinTableEntry(BookHandler.waitList),\n 'ActiveReservations' : JoinTableEntry(readyToClaimUsers),\n 'ActiveReservedUIDs' : JoinTableEntry(BookHandler.readyToClaimUIDs),\n 'NumberOfCopiesAvailable' : BookHandler.numberOfCopies\n }\n cursor.execute(updateReservationTable, dataReservation)\n db.commit()\n \n @staticmethod\n def IssueSelected(memberID: str):\n BookHandler.taken.append(BookHandler.currUID)\n if(BookHandler.currUID in BookHandler.available):\n BookHandler.available.remove(BookHandler.currUID)\n elif(BookHandler.currUID in BookHandler.readyToClaimUIDs):\n BookHandler.readyToClaimUIDs.remove(BookHandler.currUID)\n BookHandler.readyToClaimUsers = [x for x in BookHandler.readyToClaimUsers if x.memberID != memberID]\n cursor.execute(str(\"UPDATE MEMBERS SET ReservedBook = NULL WHERE MemberId = \\\"\"+memberID+\"\\\"\"))\n db.commit()\n lastdate = {\n 'date' : date.today(),\n 'uid' : int(BookHandler.currUID)\n }\n cursor.execute(\"UPDATE BOOKS SET LastIssued = %(date)s WHERE UniqueID = %(uid)s\", lastdate)\n db.commit()\n BookHandler.UpdateDatabase()\n\n @staticmethod\n def ReturnSelected(memberID: str):\n BookHandler.taken.remove(str(BookHandler.currUID))\n if len(BookHandler.waitList)==0:\n BookHandler.available.append(BookHandler.currUID)\n else:\n BookHandler.readyToClaimUIDs.append(BookHandler.currUID)\n memberActivated = BookHandler.waitList.pop(0)\n newActive = ActiveReservation(memberActivated, (datetime.now()+timedelta(days = 7)).date())\n BookHandler.readyToClaimUsers.append(newActive)\n BookHandler.UpdateDatabase()\n\n @staticmethod\n def ReserveSelected(memberID : str):\n BookHandler.waitList.append(memberID)\n BookHandler.UpdateDatabase()\n \n def CloseBook(self):\n self.UpdateDatabase()\n BookHandler.currISBN = None\n BookHandler.available = []\n BookHandler.taken = []\n BookHandler.waitList = []\n BookHandler.readyToClaimUsers = []\n BookHandler.readyToClaimUIDs = []\n BookHandler.numberOfCopies = None\n\n @staticmethod\n def GetActiveReservedUIDs():\n return BookHandler.readyToClaimUIDs\n\n @staticmethod\n def GetAvailableUIDs():\n return BookHandler.available\n \n @staticmethod\n def GetActiveReservations():\n return BookHandler.readyToClaimUsers\n @staticmethod\n def IsActive(memberID: str):\n return memberID in [x.memberID for x in BookHandler.readyToClaimUsers] \n \n @staticmethod\n def IsAvailable(UID: str):\n return UID in BookHandler.available\n\n @staticmethod\n def AddToPending(memberID: str):\n BookHandler.waitList.append(memberID)\n \ndef SplitTableEntry(s: str):\n if(s is None):\n return []\n return s.split(',')[0:-1]\n\ndef JoinTableEntry(l):\n if(len(l) == 0):\n return None\n return ','.join(l) + ','","sub_path":"src/bookHandler.py","file_name":"bookHandler.py","file_ext":"py","file_size_in_byte":9507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"615090726","text":"from tkinter import *\nimport pyautogui\n\ngui = Tk()\ngui.title(\"Full test\")\ngui.geometry(\"208x212\")\ngui.configure(background=\"black\")\n\ntxtX = Label(gui, text=\"Coord X:\").place(relx=0.025, rely=0.03)\ntxtY = Label(gui, text=\"Coord Y:\").place(relx=0.025, rely=0.175)\ntxtLag = Label(gui, text=\"Delay: \").place(relx=0.025, rely=0.32)\n\n'''\ndef asa():\n return pyautogui.moveTo(200, 500, 2)\n\n\nb_macro = Button(gui, text=' 9 ', fg='black', bg='red', command=asa, height=1, width=7).pack()\n\nclass Application(Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.master = master\n self.pack()\n self.create_widgets()\n\n def create_widgets(self):\n b_hi = Button(self, text = \"Hello World\\n(click me)\", command = self.say_hi).pack()\n\n\n self.hi_there = Button(self)\n self.hi_there[\"text\"] = \"Hello World\\n(click me)\"\n self.hi_there[\"command\"] = self.say_hi\n self.hi_there.pack(side=\"top\")\n\n\n b_quit = Button(self, text=\"QUIT\", fg=\"red\", command=self.master.destroy)\n b_quit.pack(side=\"bottom\")\n\n def say_hi(self):\n print(\"hi there, everyone!\")\n\n\napp = Application(master=gui)\napp.mainloop()\n\napp = master = gui\napp.mainloop()\n'''\n\n\nclass App(Frame):\n def __init__(self, master=None):\n super().__init__(master)\n self.pack()\n\n # Entry - X #\n self.entrythingyX = Entry()\n self.entrythingyX.place(relx=0.3, rely=0.035)\n\n self.contentsX = StringVar()\n self.contentsX.set(\"\")\n self.entrythingyX[\"textvariable\"] = self.contentsX\n self.entrythingyX[\"width\"] = 12\n\n b_enter = Button(gui, text=' Go ', fg='black', bg='red', height=1,\n command=self.print_contentsx, width=7).place(relx=0.7, rely=0.02)\n\n self.entrythingyX.bind('', self.print_contentsx)\n\n # Entry - Y #\n self.entrythingyY = Entry()\n self.entrythingyY.place(relx=0.3, rely=0.18)\n\n self.contentsY = StringVar()\n self.contentsY.set(\"\")\n self.entrythingyY[\"textvariable\"] = self.contentsY\n self.entrythingyY[\"width\"] = 12\n\n b_enter = Button(gui, text=' Go ', fg='black', bg='red', command=self.print_contentsy,\n height=1, width=7).place(relx=0.7, rely=0.17)\n\n self.entrythingyY.bind('', self.print_contentsy)\n\n # Entry - Lag #\n self.entrythingyLag = Entry()\n self.entrythingyLag.place(relx=0.247, rely=0.325)\n\n self.contentsLag = StringVar()\n self.contentsLag.set(\"\")\n self.entrythingyLag[\"textvariable\"] = self.contentsLag\n self.entrythingyLag[\"width\"] = 14\n\n b_enter = Button(gui, text=' Go ', fg='black', bg='red', command=self.print_contentslag,\n height=1, width=7).place(relx=0.7, rely=0.32)\n\n self.entrythingyLag.bind('', self.print_contentslag)\n\n def print_contentsx(self, event=''):\n print(\"X: \", self.contentsX.get())\n\n def print_contentsy(self, event=''):\n print(\"Y: \", self.contentsY.get())\n\n def print_contentslag(self, event=''):\n print(\"Lag: \", self.contentsLag.get())\n\ngui = App(master=gui).mainloop()\n# gui.mainloop()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"607872903","text":"#!/usr/bin/python\n# coding: UTF-8\n\nstart_raw = 50\nend_raw = 57\n\nimport subprocess\nimport re\nimport numpy as np\nimport csv\nimport sys\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\ndef main():\n p_list, st_list, sr_list, r_list = create_list()\n dif_tsc = check_tsc_diff()\n min_tsc, max_tsc = def_range(start_raw, end_raw, st_list)\n print_ple(min_tsc, max_tsc, dif_tsc, st_list, p_list, r_list)\n\ndef create_list():\n pf = open(\"pleData.csv\", 'r')\n preader = csv.reader(pf)\n pheader = next(preader)\n stf = open(\"spinlockTryData.csv\", 'r')\n streader = csv.reader(stf)\n stheader = next(streader)\n srf = open(\"spinlockRlsData.csv\", 'r')\n srreader = csv.reader(srf)\n srheader = next(srreader)\n rf = open(\"searchResult.csv\", 'r')\n rreader = csv.reader(rf)\n rheader = next(rreader)\n p_list = csv_to_list(preader)\n st_list = csv_to_list(streader)\n sr_list = csv_to_list(srreader)\n r_list = csv_to_list(rreader)\n return (p_list, st_list, sr_list, r_list)\n\ndef def_range(start, end, st_list):\n min = sys.maxsize\n max = 0\n for i in range (start, end + 1):\n if(int(st_list[i][1]) < min):\n min = int(st_list[i][1])\n if(int(st_list[i][2]) > max):\n max = int(st_list[i][2])\n return (min, max)\n\ndef csv_to_list(reader):\n nList = []\n for row in reader:\n list = []\n for i in range(0, len(row)):\n list.append(row[i])\n nList.append(list)\n# print(nList)\n return nList\n \ndef check_tsc_diff():\n tsc_result = \"\"\n for line in open(\"tscResult.txt\", 'r'):\n tsc_result += line\n tsc_result = tsc_result.encode('utf-8')\n re_tsc = re.compile(b'diff (.+?)$')\n tsc_diff = re_tsc.search(tsc_result)\n return int(tsc_diff.group(1))\n\ndef print_ple(min, max, diff, st_list, p_list, r_list):\n# tsc_range = [min, max]\n mod_min = min + diff\n mod_max = max + diff\n ple_time, vcpu, p_color, ple_pc = make_ple_list(mod_min, mod_max, st_list, p_list)\n try_acq, cpu_num, s_color= make_spinlock_list(diff, st_list)\n ann_list = make_annotate_list(r_list)\n\n ax = plt.subplot()\n plt.scatter(ple_time, vcpu, c=p_color, edgecolors=\"none\", marker=\"o\")\n #plt.plot(ple_time, vcpu, \".\", color=p_color)\n #s_color = set_spinlock_color(diff, try_acq_pc, ple_pc, p_color)\n plt.scatter(try_acq, cpu_num, s=50, c=s_color, label=\"100\", edgecolors=\"none\", marker='x')\n plt.title(\"\")\n plt.xlabel(\"Time\")\n plt.ylabel(\"vCPU\")\n plt.xlim(mod_min - 500000, mod_max + 500000)\n #ax.yaxis.set_major_formatter(ptick.ScalarFormatter(useMathText=True))\n for i, txt in enumerate(ann_list):\n ax.annotate(txt, (try_acq[i], str(int(cpu_num[i]) + 0.1)))\n ax.yaxis.offsetText.set_fontsize(14)\n ax.ticklabel_format(style='sci',axis='y',scilimits=(0,0))\n plt.savefig(\"vcpu_data.png\")\n plt.show()\n plt.clf()\n\ndef make_ple_list(min, max, st_list, p_list):\n ple_list = []\n vcpu_list = []\n color_list = []\n lock_list = []\n addr_list = []\n for i in range(0, len(p_list)):\n ple_time = int(p_list[i][4])\n vcpu_num = int(p_list[i][1])\n lock = p_list[i][3]\n if (ple_time > min) and (ple_time < max):\n ple_list.append(ple_time)\n vcpu_list.append(vcpu_num)\n addr_list.append(lock)\n if lock in lock_list:\n color_list.append(lock_list.index(lock))\n else:\n lock_list.append(lock)\n color_list.append(lock_list.index(lock))\n #print(color_list)\n return (ple_list, vcpu_list, color_list, addr_list)\n\ndef make_spinlock_list(diff, st_list):\n try_acq_list = []\n cpu_num_list = []\n color_list = []\n for i in range(start_raw, end_raw + 1):\n try_tsc = int(st_list[i][1])\n mod_try_tsc = try_tsc + diff\n acq_tsc = int(st_list[i][2])\n mod_acq_tsc = acq_tsc + diff\n try_acq_list.append(str(mod_try_tsc))\n cpu_num_list.append(str(st_list[i][8]))\n color_list.append(\"r\")\n try_acq_list.append(str(mod_acq_tsc))\n cpu_num_list.append(str(st_list[i][8]))\n color_list.append(\"g\")\n return (try_acq_list, cpu_num_list, color_list)\n\ndef make_annotate_list(r_list):\n count_list = []\n for i in range(start_raw, end_raw + 1):\n for j in range(0 , len(r_list)):\n if r_list[j][0] == str(i):\n count_list.append(r_list[j][3])\n count_list.append(\"\")\n if j > end_raw + 1:\n break\n return count_list\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"makeGraph.py","file_name":"makeGraph.py","file_ext":"py","file_size_in_byte":4598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"19588029","text":"import email\nimport logging\nimport quopri\nimport re\nfrom datetime import datetime\nfrom email.message import EmailMessage\nfrom typing import List, Set, Tuple\n\nfrom aiohttp.web_exceptions import HTTPBadRequest\nfrom bs4 import BeautifulSoup\nfrom buildpg.asyncpg import BuildPgConnection\n\nfrom em2.background import push_all, push_multiple\nfrom em2.core import (\n ActionModel,\n ActionTypes,\n Connections,\n CreateConvModel,\n MsgFormat,\n UserTypes,\n apply_actions,\n create_conv,\n get_create_user,\n)\nfrom em2.utils.smtp import find_smtp_files\n\nlogger = logging.getLogger('em2.protocol.views.smtp')\n\n__all__ = ['remove_participants', 'get_email_recipients', 'process_smtp']\n\n\nasync def remove_participants(conn: BuildPgConnection, conv_id: int, ts: datetime, user_ids: List[int]):\n \"\"\"\n Remove participants from a conversation, doesn't use actions since apply_actions is not used, and actor changes.\n\n Should be called inside a transaction.\n \"\"\"\n await conn.execute('delete from participants where conv=$1 and user_id=any($2)', conv_id, user_ids)\n\n # TODO add reason when removing participant\n r = await conn.fetch(\n \"\"\"\n insert into actions (conv, ts, act, actor, participant_user)\n (select $1, $2, 'participant:remove', unnest($3::int[]), unnest($3::int[]))\n returning id\n \"\"\",\n conv_id,\n ts,\n user_ids,\n )\n await conn.execute('update participants set seen=false where conv=$1', conv_id)\n return [r_[0] for r_ in r]\n\n\nasync def get_email_recipients(to: List[str], cc: List[str], message_id: str, conn: BuildPgConnection) -> Set[str]:\n recipients = email.utils.getaddresses(to + cc)\n recipients = {a for n, a in recipients}\n if not recipients:\n logger.warning('email with no recipient, ignoring %s', message_id)\n raise HTTPBadRequest(text='no recipient, ignoring')\n\n loc_users = await conn.fetchval(\"select 1 from users where user_type='local' and email=any($1) limit 1\", recipients)\n if not loc_users:\n logger.warning('email with no local recipient (%r), ignoring %s', recipients, message_id)\n raise HTTPBadRequest(text='no local recipient, ignoring')\n return recipients\n\n\nasync def process_smtp(\n conns: Connections,\n msg: EmailMessage,\n recipients: Set[str],\n storage: str,\n *,\n spam: bool = None,\n warnings: dict = None,\n):\n assert not msg['EM2-ID'], 'messages with EM2-ID header should be filtered out before this'\n p = ProcessSMTP(conns)\n await p.run(msg, recipients, storage, spam, warnings)\n\n\ninline_regex = re.compile(' src')\n\n\nclass ProcessSMTP:\n __slots__ = 'conns', 'conn'\n\n def __init__(self, conns: Connections):\n self.conns: Connections = conns\n self.conn: BuildPgConnection = conns.main\n\n async def run(self, msg: EmailMessage, recipients: Set[str], storage: str, spam: bool, warnings: dict):\n # TODO deal with non multipart\n _, actor_email = email.utils.parseaddr(msg['From'])\n assert actor_email, actor_email\n actor_email = actor_email.lower()\n\n message_id = msg.get('Message-ID', '').strip('<> ')\n timestamp = email.utils.parsedate_to_datetime(msg['Date'])\n\n conv_id, original_actor_id = await self.get_conv(msg)\n actor_id = await get_create_user(self.conns, actor_email, UserTypes.remote_other)\n\n existing_conv = bool(conv_id)\n body, is_html = get_smtp_body(msg, message_id, existing_conv)\n async with self.conn.transaction():\n if existing_conv:\n existing_prts = await self.conn.fetch(\n 'select email from participants p join users u on p.user_id=u.id where conv=$1', conv_id\n )\n existing_prts = {r[0] for r in existing_prts}\n if actor_email not in existing_prts:\n # reply from different address, we need to add the new address to the conversation\n a = ActionModel(act=ActionTypes.prt_add, participant=actor_email)\n _, all_action_ids = await apply_actions(self.conns, original_actor_id, conv_id, [a])\n assert all_action_ids\n else:\n all_action_ids = []\n\n new_prts = recipients - existing_prts\n\n msg_format = MsgFormat.html if is_html else MsgFormat.plain\n actions = [ActionModel(act=ActionTypes.msg_add, body=body or '', msg_format=msg_format)]\n\n actions += [ActionModel(act=ActionTypes.prt_add, participant=addr) for addr in new_prts]\n\n _, action_ids = await apply_actions(\n conns=self.conns,\n actor_user_id=actor_id,\n conv_ref=conv_id,\n actions=actions,\n spam=spam,\n warnings=warnings,\n files=find_smtp_files(msg),\n )\n assert action_ids\n\n all_action_ids += action_ids\n await self.conn.execute(\n 'update actions set ts=$1 where conv=$2 and id=any($3)', timestamp, conv_id, all_action_ids\n )\n send_id, add_action_pk = await self.conn.fetchrow(\n \"\"\"\n insert into sends (action, ref, complete, storage)\n (select pk, $1, true, $2 from actions where conv=$3 and id=any($4) and act='message:add' limit 1)\n returning id, action\n \"\"\",\n message_id,\n storage,\n conv_id,\n action_ids,\n )\n await self.conn.execute('update files set send=$1 where action=$2', send_id, add_action_pk)\n await push_multiple(self.conns, conv_id, action_ids, transmit=False)\n else:\n conv = CreateConvModel(\n subject=msg['Subject'] or '-',\n message=body,\n msg_format=MsgFormat.html if is_html else MsgFormat.plain,\n publish=True,\n participants=[{'email': r} for r in recipients],\n )\n conv_id, conv_key = await create_conv(\n conns=self.conns,\n creator_email=actor_email,\n creator_id=actor_id,\n conv=conv,\n ts=timestamp,\n spam=spam,\n warnings=warnings,\n files=find_smtp_files(msg),\n )\n send_id, add_action_pk = await self.conn.fetchrow(\n \"\"\"\n insert into sends (action, ref, complete, storage)\n (select pk, $1, true, $2 from actions where conv=$3 and act='message:add' limit 1)\n returning id, action\n \"\"\",\n message_id,\n storage,\n conv_id,\n )\n await self.conn.execute('update files set send=$1 where action=$2', send_id, add_action_pk)\n await push_all(self.conns, conv_id, transmit=False)\n\n async def get_conv(self, msg: EmailMessage) -> Tuple[int, int]:\n conv_actor = None\n # find which conversation this relates to\n in_reply_to = msg['In-Reply-To']\n if in_reply_to:\n conv_actor = await self.conn.fetchrow(\n \"\"\"\n select a.conv, a.actor from sends\n join actions a on sends.action = a.pk\n where sends.node is null and sends.ref = $1\n order by a.id desc\n limit 1\n \"\"\",\n self.clean_msg_id(in_reply_to),\n )\n\n references = msg['References']\n if not conv_actor and references:\n # try references instead to try and get conv_id\n ref_msg_ids = {self.clean_msg_id(msg_id) for msg_id in references.split(' ') if msg_id}\n if ref_msg_ids:\n conv_actor = await self.conn.fetchrow(\n \"\"\"\n select a.conv, a.actor from sends\n join actions a on sends.action = a.pk\n where sends.node is null and sends.ref = any($1)\n order by a.id desc\n limit 1\n \"\"\",\n ref_msg_ids,\n )\n\n return conv_actor or (None, None)\n\n def clean_msg_id(self, msg_id):\n msg_id = msg_id.strip('<>\\r\\n')\n if msg_id.endswith(self.conns.settings.smtp_message_id_domain):\n msg_id = msg_id.split('@', 1)[0]\n return msg_id\n\n\nto_remove = 'div.gmail_quote', 'div.gmail_extra' # 'div.gmail_signature'\nhtml_regexes = [\n (re.compile(r' $', re.M), ''),\n (re.compile(r' $', re.M), ''),\n (re.compile(r'\\n{2,}'), '\\n'),\n]\n\n\ndef get_smtp_body(msg: EmailMessage, message_id: str, existing_conv: bool) -> Tuple[str, bool]:\n m: EmailMessage = msg.get_body(preferencelist=('html', 'plain'))\n if not m:\n raise RuntimeError('email with no content')\n\n body = m.get_content()\n is_html = m.get_content_type() == 'text/html'\n if is_html and m['Content-Transfer-Encoding'] == 'quoted-printable':\n body = quopri.decodestring(body).decode()\n\n if not body:\n logger.warning('Unable to find body in email \"%s\"', message_id)\n\n if is_html:\n soup = BeautifulSoup(body, 'html.parser')\n\n if existing_conv:\n # remove the body only if conversation already exists in the db\n for el_selector in to_remove:\n for el in soup.select(el_selector):\n el.decompose()\n\n # body = soup.prettify()\n body = str(soup)\n for regex, rep in html_regexes:\n body = regex.sub(rep, body)\n return body, is_html\n","sub_path":"em2/protocol/views/smtp_utils.py","file_name":"smtp_utils.py","file_ext":"py","file_size_in_byte":9941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"223654535","text":"# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai\nimport re\nimport os\n# import time\nimport json\nimport argparse\nimport datetime\nimport requests\nimport schedule\nimport httplib2\nimport concurrent.futures\n\nimport magsname\n\nfrom functools import reduce\n\nfrom apiclient.discovery import build\nfrom oauth2client.file import Storage\nfrom oauth2client import client\nfrom oauth2client import tools\n\n\nVERSION = '0.2.0'\n\n\nclass Hamiorg:\n APPLICATION_NAME = 'hamiorg'\n CLIENT_SECRET_FILE = 'client_secret.json'\n SCOPES = 'https://www.googleapis.com/auth/drive'\n KEEP_LAST = 360\n KEEP_LAST_MAGS = 180\n\n def __init__(self, args):\n storage = Storage('credentials.json')\n credentials = storage.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(self.CLIENT_SECRET_FILE, self.SCOPES)\n flow.user_agent = self.APPLICATION_NAME\n credentials = tools.run_flow(flow, storage)\n if credentials:\n storage.put(credentials)\n\n http = credentials.authorize(httplib2.Http())\n self.service = build('drive', 'v3', http=http)\n self.args = args\n self.org_dirs = ['全部', '最新', '最新/雜誌', '最新/報紙', '最新/書籍', '類別', '日期']\n self.org_dir_ids = {}\n self.bookid_re = re.compile('-(?P\\d{10}).pdf$')\n self.bookdata_re = re.compile('var _BOOK_DATA = (?P.*);')\n self.dir_id_cache = {}\n\n def __call__(self):\n self.hamiorg()\n # quota = self.about_quota()\n # print(quota)\n\n def _mkdirp_adir(self, prefix, adir):\n dbnames = os.path.split(adir)\n if not dbnames[0] == '':\n prefix = self._mkdirp_adir(prefix, dbnames[0])\n\n qbase = \"mimeType='application/vnd.google-apps.folder' and '{}' in parents and name='{}'\"\n fields = 'nextPageToken, files(id, name)'\n q = qbase.format(prefix, dbnames[1])\n alldirs = self.service.files().list(q=q, spaces='drive', fields=fields).execute().get('files', [])\n if len(alldirs) > 1:\n raise ValueError('there are more than one hami dirs')\n\n if len(alldirs) == 0:\n ndir = {'mimeType': 'application/vnd.google-apps.folder',\n 'name': dbnames[1], 'parents': [prefix]}\n cdir = self.service.files().create(body=ndir, fields='id').execute()\n return cdir['id']\n else:\n return alldirs[0]['id']\n\n def mkdirp_org_dirs(self, adirs=None):\n mdirs = self.org_dirs if adirs is None else adirs\n prefix = self.hamis['id']\n org_dir_ids = {d: self._mkdirp_adir(prefix, d) for d in mdirs}\n self.org_dir_ids = org_dir_ids\n if (self.args.verbose > 0):\n print(org_dir_ids)\n\n return self\n\n def get_book_info(self, b):\n match = self.bookid_re.search(b['name'])\n if match is None:\n raise ValueError('Error RE bookid; {}'.format(b['name']))\n bookid = match.group('bookid')\n url = ('http://bookstore.emome.net/reader/viewer?type=own&book_id={}&pkgid=PKG_10001'.format(bookid))\n r = requests.get(url)\n match = self.bookdata_re.search(r.text)\n if match is None:\n print('not match')\n return {}\n\n binfo = json.loads(match.group('bookdata'))\n keys = ['book_id', 'book_name', 'book_author', 'book_cp', 'book_isbn_name', 'book_category_name',\n 'format', 'book_cover_large', 'book_releaseTime_t', 'modified_date', 'modified_date_t']\n if len(list(filter(lambda k: k not in binfo, keys))) > 0:\n return {}\n return {k: binfo[k] for k in keys}\n\n def _add_parent(self, b, pid):\n fields = 'id, name, parents, createdTime'\n if pid not in b['parents']:\n if (self.args.verbose > 1):\n print('push book into')\n nb = self.service.files().update(fileId=b['id'], addParents=pid,\n fields=fields).execute()\n return nb\n else:\n return b\n\n def _remove_parent(self, b, pid):\n fields = 'id, name, parents, createdTime'\n if pid in b['parents']:\n print('pull book out')\n nb = self.service.files().update(fileId=b['id'], removeParents=pid,\n fields=fields).execute()\n return nb\n else:\n return b\n\n def list_books(self, pids=None):\n parentids = pids if pids is not None else [self.hamis['id']]\n qbase = \"mimeType!='application/vnd.google-apps.folder' and '{}' in parents\"\n fields = 'nextPageToken, files(id, name, parents, createdTime)'\n\n def _list_books_in_dir(pid):\n q = qbase.format(pid)\n page_token = None\n books = []\n while True:\n response = self.service.files().list(q=q, spaces='drive', pageToken=page_token,\n orderBy='createdTime desc',\n fields=fields).execute()\n books.extend(response.get('files', []))\n page_token = response.get('nextPageToken', None)\n if page_token is None:\n break\n return books\n\n bookss = [_list_books_in_dir(pid) for pid in parentids]\n books = reduce(lambda x, y: x.extend(y), bookss)\n\n # print(books)\n # print(len(books))\n return books\n\n def find_hamis_dir(self):\n hamisdirs = self.service.files().list(q=\"mimeType='application/vnd.google-apps.folder' and name='hamis'\",\n spaces='drive',\n fields='nextPageToken, files(id, name)').execute().get('files', [])\n if len(hamisdirs) != 1:\n raise ValueError('there are more than one hami dirs')\n\n self.hamis = hamisdirs[0]\n\n return self\n\n def org_books_in_recent(self):\n books = self.list_books([self.org_dir_ids['最新']])\n print(len(books))\n\n # make sure in all\n for b in books:\n self._add_parent(b, self.org_dir_ids['全部'])\n\n # keep lastest\n for b in books[self.KEEP_LAST:]:\n self._remove_parent(b, self.org_dir_ids['最新'])\n\n for b in books[:self.KEEP_LAST]:\n b.update(self.get_book_info(b))\n\n # recent\n if 'book_category_name' not in b:\n continue\n if b['book_category_name'] == '雜誌-報紙':\n self._add_parent(b, self.org_dir_ids['最新/報紙'])\n elif b['book_category_name'].startswith('雜誌-'):\n self._add_parent(b, self.org_dir_ids['最新/雜誌'])\n elif b['book_category_name'].startswith('書籍-'):\n self._add_parent(b, self.org_dir_ids['最新/書籍'])\n else:\n pass\n\n # cats\n cat = magsname.get_mags_cat(b)\n if cat is not None:\n pid = self.get_dir_id(self.org_dir_ids['類別'], cat)\n self._add_parent(b, pid)\n\n # date\n date = datetime.datetime.fromtimestamp(int(b['book_releaseTime_t']))\n cat = date.strftime('%Y年/%Y年-%m月')\n pid = self.get_dir_id(self.org_dir_ids['日期'], cat)\n self._add_parent(b, pid)\n\n for r in ['最新/報紙', '最新/雜誌', '最新/書籍']:\n rbooks = self.list_books([self.org_dir_ids[r]])\n for b in rbooks:\n self._add_parent(b, self.org_dir_ids['全部'])\n for b in rbooks[self.KEEP_LAST_MAGS:]:\n self._remove_parent(b, self.org_dir_ids[r])\n\n def get_dir_id(self, prefix, adir):\n if prefix not in self.dir_id_cache:\n self.dir_id_cache[prefix] = {}\n cache = self.dir_id_cache[prefix]\n if adir not in cache:\n dirid = self._mkdirp_adir(prefix, adir)\n cache[adir] = dirid\n else:\n dirid = cache[adir]\n return dirid\n\n def _get_cat(self, b):\n b.update(self.get_book_info(b))\n cat = magsname.get_mags_cat(b)\n if cat is not None:\n print(cat)\n pid = self.get_dir_id(self.org_dir_ids['類別'], cat)\n self._add_parent(b, pid)\n return cat\n\n def org_books_in_all(self):\n books = self.list_books([self.org_dir_ids['全部']])\n if (self.args.verbose > 0):\n print('全部: {}'.format(len(books)))\n\n \"\"\"\n with concurrent.futures.ProcessPoolExecutor() as executor:\n executor.map(self._get_cat, books[:])\n \"\"\"\n\n \"\"\"\n for b in books[:]:\n # for b in books:\n b.update(self.get_book_info(b))\n cat = magsname.get_mags_cat(b)\n if cat is not None:\n if (self.args.verbose > 1):\n print(cat)\n pid = self.get_dir_id(self.org_dir_ids['類別'], cat)\n self._add_parent(b, pid)\n \"\"\"\n\n for b in books[:]:\n b.update(self.get_book_info(b))\n date = datetime.datetime.fromtimestamp(int(b['book_releaseTime_t']))\n cat = date.strftime('%Y年/%Y年-%m月')\n if (self.args.verbose > 1):\n print('{} {}'.format(b['book_name'], cat))\n pid = self.get_dir_id(self.org_dir_ids['日期'], cat)\n self._add_parent(b, pid)\n\n def hamiorg(self):\n # get self.org_books\n self.find_hamis_dir().mkdirp_org_dirs()\n\n # org '最新'\n self.org_books_in_recent()\n\n def standalone(self):\n # get self.org_books\n self.find_hamis_dir().mkdirp_org_dirs()\n\n # '全部'\n self.org_books_in_all()\n\n def about_quota(self):\n results = self.service.about().get(fields='kind, storageQuota').execute()\n return results.get('storageQuota')\n\n\ndef main():\n parser = argparse.ArgumentParser(description='hamiorg')\n parser.add_argument('-v', '--verbose', help='show more debug information', action='count', default=0)\n parser.add_argument('-V', '--version', action='version', version=VERSION, help='show version infomation')\n parser.add_argument('-s', '--standalone', action='store_true', help='run as standalone')\n args = parser.parse_args()\n\n if args.standalone:\n org = Hamiorg(args)\n org.standalone()\n return\n\n org = Hamiorg(args)\n schedule.every().hours.do(org)\n schedule.every().day.at(\"00:30\").do(org)\n\n org()\n\n '''\n while True:\n schedule.run_pending()\n time.sleep(1)\n '''\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"android/hamiorg/hamiorg.py","file_name":"hamiorg.py","file_ext":"py","file_size_in_byte":10764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"300267248","text":"\"\"\"Tests for CuminExecution class.\"\"\"\nimport unittest\nfrom unittest.mock import patch, MagicMock\n\nfrom transferpy.RemoteExecution.CuminExecution import CuminExecution\n\n\nclass TestCuminExecution(unittest.TestCase):\n \"\"\"Test cases for CuminExecution.\"\"\"\n\n def setUp(self):\n self.executor = CuminExecution()\n\n @patch('transferpy.RemoteExecution.CuminExecution.cumin.Config')\n def test_config(self, config_mock):\n config_mock.return_value = MagicMock()\n\n conf1 = self.executor.config\n conf2 = self.executor.config\n\n self.assertEqual(config_mock.return_value, conf1)\n self.assertEqual(config_mock.return_value, conf2)\n self.assertEqual(1, config_mock.call_count)\n\n def test_format_command_str(self):\n orig_cmd = \"some command\"\n formatted_command = self.executor.format_command(orig_cmd)\n\n self.assertEqual(orig_cmd, formatted_command)\n\n def test_format_command_list(self):\n orig_cmd = [\"some\", \"command\"]\n formatted_command = self.executor.format_command(orig_cmd)\n\n self.assertEqual(' '.join(orig_cmd), formatted_command)\n\n @patch('transferpy.RemoteExecution.CuminExecution.cumin.Config',\n return_value={'transport': 'clustershell', 'default_backend': 'knownhosts'})\n def test_run_invalid_host(self, config_mock):\n host = 'wrong_host.eqiad.wmnet'\n command_return = self.executor.run(host, 'some command')\n\n self.assertEqual(command_return.returncode, 1)\n self.assertEqual(command_return.stdout, None)\n self.assertEqual(command_return.stderr, 'host is wrong or does not match rules')\n","sub_path":"transferpy/test/unit/test_CuminExecution.py","file_name":"test_CuminExecution.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"570147673","text":"# 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 logging\nfrom airavata_sdk.clients.group_manager_client import GroupManagerClient\n\nfrom airavata_sdk.clients.keycloak_token_fetcher import Authenticator\n\nfrom airavata.api.error.ttypes import TException\n\nfrom airavata.model.group.ttypes import GroupModel\n\nlogger = logging.getLogger(__name__)\n\nlogger.setLevel(logging.DEBUG)\n\nauthenticator = Authenticator();\ntoken = authenticator.get_token_and_user_info_password_flow(\"default-admin\", \"123456\", \"default\")\n\n# load GroupManagerClient with default configuration\nclient = GroupManagerClient()\n\n\n# load client with given configuration file (e.g customized_settings.ini)\n\n#client = GroupManagerClient('../transport/settings.ini')\n\n\n# create group in airavata\ndef create_group():\n try:\n group_model = GroupModel()\n group_model.id = \"testing_group\"\n group_model.name = \"testing_group_name\"\n group_model.ownerId = \"default-admin\"\n group_model.description = \"This group is used for testing users\"\n\n users = ['default-admin']\n\n group_model.members = users\n group_model.admins = users\n\n created_group = client.create_group(token, group_model)\n print(created_group)\n except TException:\n logger.exception(\"Exception occurred\")\n\n\n# get all groups\ndef get_groups():\n try:\n created_group = client.get_groups(token)\n print(\"Groups :\", created_group)\n except TException:\n logger.exception(\"Exception occurred\")\n\n\ndef add_group_admin():\n try:\n created_group = client.add_group_admins(token, \"testing_group\", \"default-admin\")\n print(\"Groups :\", created_group)\n except TException:\n logger.exception(\"Exception occurred\")\n\n\ndef has_owner_access():\n try:\n has_access = client.has_owner_access(token, \"testing_group\", \"default-admin\")\n print(\"Is have accesss \", has_access)\n except TException:\n logger.exception(\"Exception occurred\")\n\nget_groups()\n","sub_path":"airavata-api/airavata-client-sdks/airavata-python-sdk/airavata_sdk/samples/group_manager_client_samples.py","file_name":"group_manager_client_samples.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"240193205","text":"import pygit2\nimport logging\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef get_repo_from_path(path):\n repository_path = pygit2.discover_repository(path)\n return pygit2.Repository(repository_path)\n\n\ndef repo_data(repo):\n \"\"\"\n This is a helper utility that doesn't get used by the main execution\n Its been invaluable enough times that it gets to stay\n \"\"\"\n objects = {\n 'tags': [],\n 'commits': [],\n }\n\n for objhex in repo:\n obj = repo[objhex]\n if obj.type == pygit2.GIT_OBJ_COMMIT:\n objects['commits'].append({\n 'hash': obj.hex,\n 'message': obj.message,\n 'commit_date': obj.commit_time,\n 'author_name': obj.author.name,\n 'author_email': obj.author.email,\n 'parents': [c.hex for c in obj.parents],\n })\n elif obj.type == pygit2.GIT_OBJ_TAG:\n objects['tags'].append({\n 'hex': obj.hex,\n 'name': obj.name,\n 'message': obj.message,\n 'target': str(obj.target),\n 'tagger_name': obj.tagger.name,\n 'tagger_email': obj.tagger.email,\n })\n else:\n # ignore blobs and trees\n pass\n\n return objects\n\n\ndef jsonify_git_data(data):\n pretty = {}\n\n for k, v in data.items():\n if isinstance(v, pygit2.Signature):\n pretty.update({k: \"{} <{}>\".format(v.name, v.email)})\n elif isinstance(v, dict):\n pretty.update({k: jsonify_git_data(v)})\n elif isinstance(v, list):\n pretty.update({k: [jsonify_git_data(item) for item in v]})\n else:\n pretty.update({k: v})\n\n return pretty\n\n\ndef analyze_head(repo):\n data = {\n 'committer': repo.default_signature,\n }\n head_ref = repo.head.name\n short_ref = repo.head.shorthand\n\n if head_ref.startswith('refs/heads/'):\n data['branch'] = short_ref\n data['branch_ref'] = head_ref\n else:\n _LOGGER.warning(\"Could not figure out branch from %s -> %s\", head_ref, short_ref)\n\n commit = repo.get(repo.head.target)\n data['author'] = commit.author\n data['message'] = commit.message\n data['dirty'] = check_dirty(repo)\n\n data['tags'] = [\n analyze_tag(repo, tagref)\n for tagref in get_all_tags(repo, repo.head.target)\n ]\n\n return data\n\n\ndef check_dirty(repo):\n working = repo.diff()\n last_commit = repo.diff('HEAD')\n staged = repo.diff('HEAD', cached=True)\n\n if len(staged) + len(working) + len(last_commit):\n return True\n else:\n return False\n\n\ndef analyze_tag(repo, tagref):\n \"\"\"\n Return a dictionary containing protorepo relevant data from a specific tagref\n e.g. 'refs/tags/helloworld/1.0.0'\n \"\"\"\n\n try:\n tagname = tagref.split('refs/tags/')[1]\n except IndexError:\n raise ValueError(\"tagref '{}' was not of the form 'refs/tags/mytag'\".format(tagref))\n\n _LOGGER.debug(\"Processing tag: %s\", tagname)\n\n tagobj = repo.get(repo.lookup_reference(tagref).target)\n\n if isinstance(tagobj, pygit2.Tag):\n _LOGGER.debug(\"Tag object %s is an annotated tag\", tagobj)\n tagger = tagobj.tagger\n message = tagobj.message\n else:\n _LOGGER.debug(\"Tag object %s is a lightweight tag, using commit data\", tagobj)\n tagger = repo.get(repo.head.target).author\n message = \"{}\\n\".format(tagname)\n\n data = {\n 'name': tagname,\n 'tag_ref': tagref,\n 'tagger': tagger,\n 'message': message,\n }\n\n tag_parts = tagname.split('/')\n if len(tag_parts) == 2:\n data['service'] = tag_parts[0]\n data['version'] = tag_parts[1]\n\n return data\n\n\ndef get_all_tags(repo, target):\n \"\"\"\n All the possible tags which describe a particular commit\n get_all_tags(repo, repo.head.target) -> ['refs/tags/1.0.0.beta', 'refs/tags/1.0.0']\n \"\"\"\n return [\n ref\n for ref in repo.listall_references()\n if ref.startswith('refs/tags/') and get_target_from_tagref(repo, ref) == target\n ]\n\n\ndef get_target_from_tagref(repo, tagref):\n \"\"\"\n Resolve both lightweight and annotated tags to a commit target\n \"\"\"\n target = repo.lookup_reference(tagref).target\n tagobj = repo.get(target)\n if isinstance(tagobj, pygit2.Tag):\n return tagobj.target\n else:\n return target\n","sub_path":"protobuilder/gitutils.py","file_name":"gitutils.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"302927953","text":"'''\nupdate-rating-tags-for-library.py\n\nThis script goes through all songs in the music library and ensures the RATING tag is correctly\nset, based on the current values in the VOTES array tag. All songs with an incorrect RATING tag\nare corrected and reported when the script finishes.\n\n'''\n\n# Do setup processing so that this script can import all the needed modules from the \"mlu\" package.\n# This is necessary because these scripts are not located in the root directory of the project, but\n# instead in the 'scripts' folder.\nimport envsetup\nenvsetup.PreparePythonProjectEnvironment()\n\n# import external Python modules\nfrom prettytable import PrettyTable\n\nfrom mlu.settings import MLUSettings\n\nfrom com.nwrobel import mypycommons\nimport com.nwrobel.mypycommons.logger\nimport com.nwrobel.mypycommons.file\nimport com.nwrobel.mypycommons.time\n\nmypycommons.logger.initSharedLogger(logDir=MLUSettings.logDir)\nmypycommons.logger.setSharedLoggerConsoleOutputLogLevel(\"info\")\nmypycommons.logger.setSharedLoggerFileOutputLogLevel(\"info\")\nlogger = mypycommons.logger.getSharedLogger()\n\n# import project-related modules\nimport mlu.tags.backup\nimport mlu.ratestats\nimport mlu.library.musiclib\n\ndef _getRatingTagUpdatesSummaryFilepath():\n '''\n Returns the filepath for the ratestat tags updates summary log file.\n '''\n backupFilename = \"[{}] update-rating-tags-for-library_tag-updates-summary.txt\".format(\n mypycommons.time.getCurrentTimestampForFilename()\n )\n filepath = mypycommons.file.JoinPaths(MLUSettings.logDir, backupFilename)\n\n return filepath\n\ndef _writeRatingTagUpdatesSummaryFile(updatedAudioFilesResults, summaryFilepath):\n '''\n Writes out a log file containing a table in pretty format with the ratestat tags updates.\n\n Params:\n audioFileVoteDataList: list of AudioFileVoteData objects, the new votes data\n summaryFilepath: path of the log output file to be written\n '''\n tagUpdatesTable = PrettyTable()\n tagUpdatesTable.field_names = [\"Title\", \"Artist\", \"Old Rating\", \"New Rating\"]\n tagUpdatesTable.align[\"Title\"] = \"l\"\n tagUpdatesTable.align[\"Artist\"] = \"l\"\n tagUpdatesTable.align[\"Old Rating\"] = \"r\"\n tagUpdatesTable.align[\"New Rating\"] = \"r\"\n\n for updateResult in updatedAudioFilesResults:\n tagHandler = mlu.tags.io.AudioFileTagIOHandler(updateResult.audioFilepath)\n currentTags = tagHandler.getTags()\n\n tagUpdatesTable.add_row([\n currentTags.title, \n currentTags.artist, \n updateResult.oldRating,\n updateResult.newRating\n ])\n\n mypycommons.file.writeToFile(filepath=summaryFilepath, content=tagUpdatesTable.get_string())\n\n# ------------------------------- Main script procedure --------------------------------------------\n#\nif __name__ == \"__main__\":\n logger.info(\"Performing full backup (checkpoint) of all music library audio files tags\")\n tagsBackupFilepath = mlu.tags.backup.backupMusicLibraryAudioTags()\n\n logger.info(\"Searching for all audio under music library root path '{}'\".format(MLUSettings.musicLibraryRootDir))\n libraryAudioFiles = mlu.library.musiclib.getAllMusicLibraryAudioFilepaths()\n\n libraryAudioFilesCount = len(libraryAudioFiles)\n logger.info(\"Found {} audio files in music library root path\".format(libraryAudioFilesCount))\n\n logger.info(\"Checking RATING tags for all audio files and fixing incorrect values\")\n updatedAudioFilesResults = []\n erroredAudioFiles = []\n\n for i, songFilepath in enumerate(libraryAudioFiles):\n try:\n updateResult = mlu.ratestats.updateRatingTag(songFilepath)\n if (updateResult.wasUpdated):\n logger.info(\"Fixed incorrect RATING tag for file '{}'\".format(songFilepath))\n updatedAudioFilesResults.append(updateResult)\n \n except:\n logger.exception(\"updateRatingTag operation failed: File='{}'\".format(songFilepath))\n erroredAudioFiles.append(songFilepath) \n\n mypycommons.display.printProgressBar(i + 1, libraryAudioFilesCount, prefix='Checking/fixing {} audio files:'.format(libraryAudioFilesCount), suffix='Complete', length=100)\n\n logger.info(\"RATING tag checking process complete\")\n logger.info(\"{} songs had an incorrect RATING fixed successfully\".format(len(updatedAudioFilesResults)))\n logger.info(\"{} songs files failed to have the RATING fixed\".format(len(erroredAudioFiles)))\n\n if (not erroredAudioFiles):\n logger.info(\"Process completed successfully: all songs RATING tags verified\")\n logger.info(\"Writing RATING tag updates summary file\")\n\n summaryFilepath = _getRatingTagUpdatesSummaryFilepath()\n _writeRatingTagUpdatesSummaryFile(updatedAudioFilesResults, summaryFilepath)\n logger.info(\"Summary file written successfully: File='{}'\".format(summaryFilepath))\n\n else:\n erroredAudioFilesFmt = \"\\n\".join(erroredAudioFiles)\n logger.info(\"Failed to fix RATING tag for the following files:\\n{}\".format(erroredAudioFilesFmt))\n \n logger.info(\"Process completed with failures: undoing all tag changes to the music library (reverting to checkpoint)\")\n mlu.tags.backup.restoreMusicLibraryAudioTagsFromBackup(tagsBackupFilepath)\n\n logger.info(\"Tags backup restored successfully: all changes were undone - run this script again to retry\")\n\n logger.info('Script complete')","sub_path":"scripts/update-rating-tags-for-library.py","file_name":"update-rating-tags-for-library.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"519275595","text":"# -*- coding: utf-8 -*-\n\ndef batched_results(qry, batch_size=10000):\n max_pk = qry.order_by('-pk')[0].pk\n if max_pk is None:\n return\n\n pk = None\n while True:\n batch_qry = (qry.filter(pk__gt=pk)\n if pk is not None\n else qry)\n for row in batch_qry.filter(pk__lte=max_pk)[:batch_size]:\n yield row\n pk = row.pk\n if pk >= max_pk:\n return\n\n\n","sub_path":"utils/batched_results.py","file_name":"batched_results.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"479297991","text":"import math\r\n\r\nN_Nodes_width = 25\r\nN_Nodes_height = 25\r\nN_Nodes = N_Nodes_width * N_Nodes_height\r\n\r\nvertical_destance_between_two_cells = 30\r\n'in meters, 30 meteres and four combined cell out of 100 cells to make 25 cells'\r\nhorizontal_destance_between_two_cells = 30\r\n\r\northogonal_destance_between_two_cells = 42.43\r\n\r\nposition = {}\r\n\r\nshift = 2\r\n\r\nB = 5\r\n'Budget'\r\n\r\nDistance = 30\r\n'Distance from center of cell i to center of cell j'\r\n\r\nProbIgnition = [0.1 for i in range(N_Nodes)]\r\n\r\nProbDuration = [1]\r\nDuration = [24*60]\r\n\r\nValueAtRisk = []\r\nwith open('../../data/Cell Value.dat', 'r') as g:\r\n Value_Data = g.readlines()\r\n\r\n for vline in Value_Data:\r\n vrow = vline.split() \r\n\r\n for i in range(len(vrow)):\r\n if float(vrow[i]) > 1 :\r\n ValueAtRisk.append(float(vrow[i]))\r\n elif float(vrow[i]) == 1 :\r\n ValueAtRisk.append(float(vrow[i]))\r\n \r\nValueAtRisk = [1 for i in range(N_Nodes)]\r\n\r\nSetOfHighFireIntensity = [i for i in range(N_Nodes)]\r\n\r\nSetOfPotentialIgnitionPoints = [i for i in range(N_Nodes)]\r\n\r\nDelay = max(Duration)+10\r\n'Delay in Minute occured for spread of fire when harvested'\r\n\r\nimport networkx as nx\r\n\r\n' =============================================================================='\r\n# Build a grid network\r\n' =============================================================================='\r\n\r\nDGG = nx.DiGraph()\r\nDGG.add_node(N_Nodes-1)\r\n\r\ne = 0\r\n\r\ne = 0\r\n\r\nfor j in range(N_Nodes_height):\r\n\r\n for i in range(N_Nodes_width):\r\n e = j*(N_Nodes_width)\r\n\r\n position[e+i] = (i*shift,j*shift)\r\n\r\nfor j in range(N_Nodes_height):\r\n for i in range(N_Nodes_width-1):\r\n e = j*(N_Nodes_width)\r\n DGG.add_edge(e+i,e+i+1, weight = horizontal_destance_between_two_cells)\r\n DGG.add_edge(e+i+1,e+i, weight = horizontal_destance_between_two_cells)\r\n\r\nfor i in range(N_Nodes_width):\r\n for j in range(N_Nodes_height-1):\r\n DGG.add_edge(i+j*N_Nodes_width,i+(j+1)*N_Nodes_width, weight = vertical_destance_between_two_cells)\r\n DGG.add_edge(i+(j+1)*N_Nodes_width,i+j*N_Nodes_width, weight = vertical_destance_between_two_cells)\r\n\r\nfor h in range(N_Nodes_height-1):\r\n for w in range(N_Nodes_width):\r\n\r\n e = h*N_Nodes_width + w\r\n\r\n if (w < N_Nodes_width-1):\r\n DGG.add_edge(e , e+N_Nodes_width+1, weight = orthogonal_destance_between_two_cells)\r\n DGG.add_edge(e+N_Nodes_width+1 , e, weight = orthogonal_destance_between_two_cells)\r\n\r\n if (w > 0):\r\n DGG.add_edge(e , e+N_Nodes_width-1, weight = orthogonal_destance_between_two_cells)\r\n DGG.add_edge(e+N_Nodes_width-1 , e, weight = orthogonal_destance_between_two_cells)\r\n\r\n\r\n' =============================================================================='\r\n\r\n\r\n# Finding neighbors of each cell and the Distance between them\r\nNeighbor = []\r\nfor i in range(N_Nodes):\r\n Neighbor.append(DGG.neighbors(i))\r\n\r\n\r\n\r\n'=============================================================================='\r\n# Finding ROS or the Rate of Spread\r\n'=============================================================================='\r\n'From the Wei paper here are the ROS :'\r\n'assuming that wind direction is from south west to north east, 45` and the network is situated such that'\r\n'(0,0) is south west and (n,n) is north east, and teta be the angle between wind direction and direction fire'\r\n'spreading from cell r to q then we have (teta, ROS) = (0, 0.6), (45,0.464 ), (90, 0.3), (135, 0.222), (180, 0.2) and '\r\n'it is the same for (-teta, ROS) to cover the clockwise'\r\n\r\n# ===================================================\r\n# ===================================================\r\n\r\nROS = [ [0 for i in range(N_Nodes)] for i in range(N_Nodes)]\r\n\r\n'===== Reading Data, teta, b and c========'\r\n\r\nCell_Direction_Fire = []\r\n\r\nwith open('../../data/Umpqua/Direction Data Umpqua.dat', 'r') as f:\r\n Direction_Data = f.readlines()\r\n \r\n for line in Direction_Data:\r\n row = line.split() \r\n\r\n for i in range(len(row)): \r\n Cell_Direction_Fire.append(float(row[i]))\r\n\r\nbEllipse = []\r\nwith open('../../data/Umpqua/b Data Umpqua.dat', 'r') as ff:\r\n bData = ff.readlines()\r\n \r\n for line in bData:\r\n row = line.split() \r\n\r\n for i in range(len(row)): \r\n bEllipse.append(float(row[i]))\r\n\r\ncEllipse = []\r\nwith open('../../data/Umpqua/c Data Umpqua.dat', 'r') as fff:\r\n cData = fff.readlines()\r\n \r\n for line in cData:\r\n row = line.split() \r\n\r\n for i in range(len(row)): \r\n cEllipse.append(float(row[i])) \r\n\r\nfor a in range(N_Nodes):\r\n for b in Neighbor[a]:\r\n Fire_Direction = Cell_Direction_Fire[a]\r\n\r\n bEllipse_length = bEllipse[a]\r\n \r\n if b == a + 1:\r\n\r\n Angle_with_Neighbor_cell = 0\r\n\r\n if b == a - 1:\r\n \r\n Angle_with_Neighbor_cell = 180\r\n\r\n if b == a + N_Nodes_width:\r\n\r\n Angle_with_Neighbor_cell = 90\r\n\r\n if b == a - N_Nodes_width:\r\n\r\n Angle_with_Neighbor_cell = 270\r\n\r\n if b == a + N_Nodes_width + 1:\r\n\r\n Angle_with_Neighbor_cell = 45\r\n\r\n if b == a - N_Nodes_width - 1:\r\n\r\n Angle_with_Neighbor_cell = 225\r\n\r\n if b == a + N_Nodes_width - 1:\r\n\r\n Angle_with_Neighbor_cell = 135\r\n\r\n if b == a - (N_Nodes_width - 1):\r\n\r\n Angle_with_Neighbor_cell = 315\r\n\r\n\r\n Teta = abs(Fire_Direction - Angle_with_Neighbor_cell)\r\n\r\n if Teta > 180:\r\n Teta = 360 - Teta\r\n\r\n if Teta < 90:\r\n ROS[a][b] = (bEllipse[a]**2 - cEllipse[a]**2)/(bEllipse[a] - (cEllipse[a]*math.cos((math.pi)/180*Teta)))\r\n\r\n if Teta >= 90:\r\n ROS[a][b] = (bEllipse[a]**2 - cEllipse[a]**2)/(bEllipse[a] + (cEllipse[a]*math.cos((180 - Teta)*(math.pi/180))))\r\n \r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n","sub_path":"src/opt/Data_Umpqua.py","file_name":"Data_Umpqua.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"299080321","text":"# ThinkPython\r\n# drawing circles using TurtleWorld\r\n\r\nimport swampy\r\nfrom swampy.TurtleWorld import *\r\n\r\nworld = TurtleWorld()\r\nbob = Turtle()\r\nbob.delay = 0.01 # to make turtle move faster\r\n\r\nfrom math import *\r\n\r\n# Exercise 4.3.5\r\n# drawing an arc\r\n\r\n# defining a function \"polyline\" with four parameters\r\n# -> it draws \"n\" line segments\r\ndef polyline(t, length, n, angle):\r\n for i in range(n):\r\n fd(t, length)\r\n lt(t, angle)\r\n # length = length of each segment, n = number of segments, angle = degrees between segments\r\n \r\n# defining a function \"arc\" with three paramenters\r\n# -> it draws approximate arc by calling \"polyline\" function\r\ndef arc(t, r, theta):\r\n arc_l = (pi/180.0)*theta*r\r\n n = int(arc_l )+1 # n -> number of segments, the arc is made of\r\n # defining n in terms of arc_length rather than arbitrary number \r\n #n = 80 or arbitrary choice\r\n l = arc_l /n\r\n angle = float(theta) / n\r\n polyline(t, l, n, angle)\r\n\r\narc(bob, r=100, theta=36)\r\n","sub_path":"4.3 - 5.py","file_name":"4.3 - 5.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"96927429","text":"\nfrom Utility.UtilityDataStructures import UtilityDataStructures\nutil = UtilityDataStructures()\nflag: bool = True\nwhile flag:\n\n try:\n list1 = [1, 2, 3, 4, -1, 5]\n # printing the min value in the list using the min function\n print(\"Smallest element is \", min(list1))\n print(\"To exit press 0 else press any other number\")\n if input() == 0:\n flag = False\n except Exception as e:\n print(\"Process stopped because %s\" % e)\n","sub_path":"Week2/ListQ3.py","file_name":"ListQ3.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"609266708","text":"# coding=utf-8\n\nimport itertools\nimport operator\nimport functools\n\nfrom tornado import gen\n\nfrom conf import path\nfrom service.page.base import PageService\nfrom service.page.customize.customize import CustomizePageService\nfrom tests.dev_data.user_company_config import COMPANY_CONFIG\nfrom util.common import ObjectDict\nfrom util.tool import temp_data_tool, iterable_tool\nfrom util.tool.str_tool import gen_salary, split\nfrom util.tool.url_tool import make_url, make_static_url\nfrom util.common.decorator import log_coro\n\n\nclass TeamPageService(PageService):\n def __init__(self):\n super().__init__()\n\n @gen.coroutine\n def get_sub_company(self, sub_company_id):\n sub_company = yield self.hr_company_ds.get_company(\n conds={'id': sub_company_id})\n\n raise gen.Return(sub_company)\n\n @log_coro(threshold=20)\n @gen.coroutine\n def get_team_by_id(self, team_id):\n team = yield self.hr_team_ds.get_team(conds={'id': team_id, 'disable': 0})\n\n raise gen.Return(team)\n\n @gen.coroutine\n def get_team(self, conds):\n team = yield self.hr_team_ds.get_team(conds=conds)\n\n raise gen.Return(team)\n\n @gen.coroutine\n def get_team_by_name(self, department, company_id):\n team = yield self.hr_team_ds.get_team(\n conds={'company_id': company_id, 'name': department, 'disable': 0})\n\n raise gen.Return(team)\n\n @gen.coroutine\n def get_team_index(self, locale, company, handler_param, sub_flag=False, parent_company=None):\n \"\"\"\n\n :param company: 当前需要获取数据的公司\n :param handler_param: 请求中参数\n :param sub_flag: 区分母公司和子公司标识,用以明确团队资源获取方式\n :param parent_company: 当sub_flag为True时, 表示母公司信息\n :return:\n \"\"\"\n data = ObjectDict(templates=[])\n\n # 根据母公司,子公司区分对待,获取团队信息\n if sub_flag:\n teams = yield self._get_sub_company_teams(company.id)\n else:\n teams = yield self.hr_team_ds.get_team_list(\n conds={'company_id': company.id, 'is_show': 1, 'disable': 0, 'res_id': [0, '>']})\n teams.sort(key=lambda t: t.show_order)\n\n # 获取团队成员以及所需要的media信息\n team_resource_dict = yield self.hr_resource_ds.get_resource_by_ids(\n [t.res_id for t in teams])\n all_members_dict = yield self._get_all_team_members(\n [t.id for t in teams])\n member_head_img_dict = yield self.hr_resource_ds.get_resource_by_ids(\n all_members_dict.get('all_head_img_list'))\n\n # 拼装模板数据\n teamname_custom = parent_company.conf_teamname_custom\n # 如果是中文,使用中文\"团队\",或者使用用户自定义的团队名称。\n if locale.code == 'zh_CN':\n teamname_custom.update(\n teamname_custom=locale.translate(\n teamname_custom.teamname_custom,\n plural_message=teamname_custom.teamname_custom, count=2\n )\n )\n # 如果是英文, 默认使用 \"Teams\"\n elif locale.code == 'en_US':\n teamname_custom.update(\n teamname_custom=locale.translate(\n '团队',\n plural_message='团队',\n count=2\n )\n )\n else:\n assert False # should not be here as we just support 2 above locales\n\n data.bottombar = teamname_custom\n data.header = temp_data_tool.make_header(locale, company, team_index=True, **teamname_custom)\n\n # 蓝色光标做定制化需求\n # customize_ps = CustomizePageService()\n # customize_ps.blue_focus_team_index_show_summary_not_description(parent_company, teams)\n\n # 解析生成团队列表页中每个团队信息子模块\n data.templates = [\n temp_data_tool.make_team_index_template(\n team=t,\n team_resource=team_resource_dict.get(t.res_id),\n more_link=make_url(path.TEAM_PATH.format(t.id), handler_param, self.settings.platform_host),\n member_list=[\n temp_data_tool.make_team_member(\n member=m,\n head_img=member_head_img_dict.get(m.res_id)\n ) for m in all_members_dict.get(t.id)\n ]\n ) for t in teams\n ]\n data.template_total = len(data.templates)\n\n raise gen.Return(data)\n\n @gen.coroutine\n def get_team_detail(self, locale, user, company, team, handler_param, position_num=3, is_gamma=False):\n \"\"\"\n\n :param user: handler中的current_user\n :param company: 当前需要获取数据的公司\n :param team: 当前需要获取详情的team\n :param handler_param: 请求中参数\n :param position_num: 该团队在招职位的展示数量\n :param is_gamma: 是否来自 gamma 需求\n :return:\n \"\"\"\n data = ObjectDict()\n\n # 根据母公司,子公司区分对待,获取对应的职位信息,其他团队信息\n position_fields = 'id title status city team_id \\\n salary_bottom salary_top department'.split()\n\n if company.id != user.company.id and not is_gamma:\n # 子公司 -> 子公司所属hr(pulishers) -> positions -> teams\n company_positions = yield self._get_sub_company_positions(\n company.id, position_fields)\n\n # 朴素版本\n # team_positions = [p for p in company_positions if p.team_id == team.id][:position_num]\n # 高端版本, let me show you some Python skill...\n team_positions = list(filter(lambda p: p.team_id == team.id, company_positions))\n\n team_id_list = list(set([p.team_id for p in company_positions\n if p.team_id != team.id]))\n other_teams = yield self._get_sub_company_teams(\n company_id=None, team_ids=team_id_list)\n else:\n team_positions = yield self.job_position_ds.get_positions_list(\n conds={\n 'company_id': company.id,\n 'status': 0,\n 'team_id': team.id\n },\n fields=position_fields,\n appends=[\"ORDER BY priority asc, update_time desc\"]\n )\n\n other_teams = yield self.hr_team_ds.get_team_list(\n conds={'id': [team.id, '<>'],\n 'company_id': company.id,\n 'is_show': 1,\n 'disable': 0})\n other_teams.sort(key=lambda t: t.show_order)\n\n team_members = yield self.hr_team_member_ds.get_team_member_list(\n conds='team_id = {} and disable=0 order by orders, id'.format(team.id))\n\n templates, medias = yield self._get_team_detail_cms(team.id)\n\n detail_media_list = medias\n detail_media_list.sort(key=operator.itemgetter(\"orders\"))\n res_id_list = [m.res_id for m in team_members] + \\\n [m.res_id for m in detail_media_list] + \\\n [t.res_id for t in other_teams]\n res_id_list += [team.res_id]\n res_dict = yield self.hr_resource_ds.get_resource_by_ids(res_id_list)\n\n # 拼装模板数据\n teamname_custom = user.company.conf_teamname_custom\n # 如果是中文,使用中文\"团队\",或者使用用户自定义的团队名称。\n if locale.code == 'zh_CN':\n teamname_custom.update(\n teamname_custom=locale.translate(\n teamname_custom.teamname_custom,\n plural_message=teamname_custom.teamname_custom, count=2\n )\n )\n # 如果是英文, 默认使用 \"Teams\"\n elif locale.code == 'en_US':\n teamname_custom.update(\n teamname_custom=locale.translate(\n '团队',\n plural_message='团队',\n count=2\n )\n )\n else:\n assert False # should not be here as we just support 2 above locales\n data.bottombar = teamname_custom\n data.header = temp_data_tool.make_header(locale, company, True, team)\n\n data.relation = ObjectDict()\n\n # 玛氏定制\n company_config = COMPANY_CONFIG.get(company.id)\n if company_config and company_config.get('custom_visit_recipe', False):\n data.relation.custom_visit_recipe = company_config.custom_visit_recipe\n else:\n data.relation.custom_visit_recipe = []\n\n data.templates = temp_data_tool.make_team_detail_template(\n locale,\n team,\n team_members,\n templates,\n team_positions,\n other_teams,\n res_dict,\n handler_param,\n teamname_custom=teamname_custom\n )\n data.templates_total = len(data.templates)\n\n raise gen.Return(data)\n\n @gen.coroutine\n def _get_team_detail_cms(self, team_id):\n # 默认的空值\n # 从业务要求来看, 这里有数据完整性的要求, 有cms_page, 必须有cms_module, 必须有cms_media\n # 所以, 这里还是兼容了存在脏数据的情况\n # hr_cms_pages拿团队详情页的配置信息\n cms_page = yield self.hr_cms_pages_ds.get_page(conds={\n \"config_id\": team_id,\n \"type\": self.constant.CMS_PAGES_TYPE_TEAM_DETAIL,\n \"disable\": 0\n })\n templates = []\n if not cms_page:\n return templates, []\n\n page_id = cms_page.id\n cms_modules = yield self.hr_cms_module_ds.get_module_list(conds={\n \"page_id\": page_id,\n \"disable\": 0\n })\n if not cms_modules:\n return templates, []\n\n cms_modules.sort(key=operator.itemgetter('orders'))\n cms_modules_ids = [m.id for m in cms_modules]\n cms_medias = yield self.hr_cms_media_ds.get_media_list(\n conds=\"module_id in {} and disable=0 order by orders, id\".format(tuple(cms_modules_ids)).replace(',)', ')')\n )\n cms_medias_res_ids = [m.res_id for m in cms_medias]\n resources_dict = yield self.hr_resource_ds.get_resource_by_ids(cms_medias_res_ids)\n for m in cms_medias:\n res = resources_dict.get(m.res_id, False)\n m.media_url = res.res_url if res else ''\n m.media_type = res.res_type if res else 0\n\n cms_medias_map = iterable_tool.group(cms_medias, \"module_id\")\n templates = [\n getattr(temp_data_tool, \"make_company_module_type_{}\".format(module.type))(\n cms_medias_map.get(module.id, []),\n module.module_name, module.link)\n for module in cms_modules\n ]\n return templates, cms_medias\n\n @gen.coroutine\n def _get_all_team_members(self, team_id_list):\n \"\"\"\n 根据团队id信息,获取所有团队,所有成员\n :param team_id_list:\n :return: {\n 'all_headimg_list': [hr_resource_1, hr_resource_2],\n team_id_1: [hr_team_member_1, ],\n team_id_2: [hr_team_member_2, ],\n ...\n }\n \"\"\"\n if not team_id_list:\n member_list = []\n else:\n member_list = yield self.hr_team_member_ds.get_team_member_list(\n conds='team_id in {} and disable=0 order by orders, id'.format(tuple(team_id_list)).replace(',)', ')'))\n\n result = {tid: [] for tid in team_id_list}\n result['all_head_img_list'] = []\n for member in member_list:\n result['all_head_img_list'].append(member.res_id)\n result[member.team_id].append(member)\n\n raise gen.Return(result)\n\n @gen.coroutine\n def _get_sub_company_positions(self, company_id, fields=None):\n publishers = yield self.hr_company_account_ds.get_company_accounts_list(\n conds={'company_id': company_id})\n if not publishers:\n company_positions = []\n else:\n cond1 = \"status = {}\".format(self.constant.POSITION_STATUS_RECRUITING)\n cond2 = 'publisher in {}'.format(tuple(\n [p.account_id for p in publishers])).replace(',)', ')')\n company_positions = yield self.job_position_ds.get_positions_list(\n conds=\" and \".join([cond1, cond2]),\n fields=fields,\n appends=[\"ORDER BY priority desc, update_time desc\"])\n\n raise gen.Return(company_positions)\n\n @gen.coroutine\n def _get_sub_company_teams(self, company_id, team_ids=None):\n \"\"\"\n 获取团队信息\n 当只给定company_id,通过position信息中team_id寻找出所有相关团队\n 当给定team_ids时获取所有对应的团队\n :param self:\n :param company_id:\n :param team_ids:\n :return: [object_of_hr_team, ...]\n \"\"\"\n if not team_ids:\n publishers = yield self.hr_company_account_ds.get_company_accounts_list(\n conds={'company_id': company_id}, fields=None)\n publisher_id_tuple = tuple([p.account_id for p in publishers])\n\n if not publisher_id_tuple:\n raise gen.Return([])\n\n team_ids = yield self.job_position_ds.get_positions_list(\n conds='publisher in {} and status = {}'.format(publisher_id_tuple,\n self.constant.POSITION_STATUS_RECRUITING)\n .replace(',)', ')'),\n fields=['team_id'], options=['DISTINCT'])\n team_id_tuple = tuple([t.team_id for t in team_ids])\n else:\n team_id_tuple = tuple(team_ids)\n\n if not team_id_tuple:\n raise gen.Return([])\n\n teams = yield self.hr_team_ds.get_team_list(\n conds='id in {} and is_show=1 and disable=0'.format(\n team_id_tuple).replace(',)', ')'))\n\n raise gen.Return(teams)\n\n @gen.coroutine\n def get_gamma_company_team(self, company_id):\n \"\"\"\n 获得团队在招职位数\n :param company_id:\n :return:\n \"\"\"\n\n teams = yield self.hr_team_ds.get_team_list(\n conds={'company_id': company_id, 'is_show': 1, 'disable': 0})\n teams.sort(key=lambda t: t.show_order)\n\n team_list = list()\n for team in teams:\n position_cnt = yield self.job_position_ds.get_position_cnt(conds={\n \"team_id\": team.id,\n \"status\": 0\n }, fields=[\"id\"])\n\n # 职位数为0不显示\n if position_cnt.get(\"count_id\", 0) == 0:\n continue\n\n item = ObjectDict()\n item[\"name\"] = team.name\n item[\"id\"] = team.id\n item[\"count\"] = position_cnt.get(\"count_id\", 0)\n team_list.append(item)\n\n return team_list\n\n @gen.coroutine\n def get_gamma_team_positions(self, team_id, page_no, page_size=5):\n # gamma 团队页获得团队在招职位\n\n page_from = (page_no - 1) * page_size\n\n team_positions = yield self.job_position_ds.get_positions_list(\n conds={\n 'status': 0,\n 'team_id': team_id\n },\n appends=[\"ORDER BY update_time desc\", \"LIMIT %d, %d\" % (page_from, page_size)]\n )\n\n res_list = list()\n for item in team_positions:\n pos = ObjectDict()\n pos.title = item.title\n pos.id = item.id\n pos.salary = gen_salary(item.salary_top, item.salary_bottom)\n pos.image_url = make_static_url(\"\")\n pos.city = split(item.city, [\",\", \",\"])\n pos.team_name = \"\"\n res_list.append(pos)\n\n return res_list\n","sub_path":"service/page/hr/team.py","file_name":"team.py","file_ext":"py","file_size_in_byte":15983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"440570590","text":"# coding: utf-8\r\n\r\nimport sys\r\nimport time\r\nimport random\r\n\r\nimport Template\r\n\r\n\r\ndef match(game, template, timeout=sys.float_info.max):\r\n beginTime = time.time()\r\n while time.time() - beginTime < timeout:\r\n scene = game.capture()\r\n target = template.matchOn(scene)\r\n if target is not None:\r\n print(\"匹配[{0}]成功。\".format(template.name))\r\n return target\r\n else:\r\n print(\"匹配[{0}]失败。\".format(template.name))\r\n print(\"匹配[{0}]超时。\".format(template.name))\r\n return None\r\n\r\n\r\ndef matchList(game, templates):\r\n scene = game.capture()\r\n for i in range(len(templates)):\r\n template = templates[i]\r\n target = template.matchOn(scene)\r\n if target is not None:\r\n print(\"匹配[{0}]成功。\".format(template.name))\r\n return target, i\r\n else:\r\n print(\"匹配[{0}]失败。\".format(template.name))\r\n return None, -1\r\n\r\n\r\ndef click(game, template, timeout=sys.float_info.max):\r\n target = match(game, template, timeout)\r\n if target is not None:\r\n target.click()\r\n return True\r\n else:\r\n return False\r\n\r\n\r\nclass Scene:\r\n def __init__(self, game):\r\n self.game = game\r\n\r\n def sleep(self, min=1.0, max=2.0):\r\n time.sleep(random.uniform(min, max))\r\n\r\n\r\nclass MainScene(Scene):\r\n def __init__(self, game):\r\n super().__init__(game)\r\n self.weighAnchor = Template.Template(game, \"出击\", \"./Main/WeighAnchor.png\")\r\n\r\n self.maid = Template.Template(game, \"演习作战\", \"./Events/Maid.png\")\r\n\r\n def enterPrecombat(self):\r\n click(self.game, self.weighAnchor)\r\n\r\n def enterMaid(self):\r\n return click(self.game, self.maid, 5.0)\r\n\r\n\r\nclass PrecombatScene(Scene):\r\n def __init__(self, game):\r\n super().__init__(game)\r\n self.back1 = Template.Template(game, \"返回\", \"./Precombat/Back.png\")\r\n self.exercise = Template.Template(game, \"演习\", \"./Precombat/Exercise.png\")\r\n self.goNow = Template.Template(game, \"立刻前往\", \"./Precombat/GoNow.png\")\r\n self.goNow2 = Template.Template(game, \"立刻前往2\", \"./Precombat/GoNow2.png\")\r\n\r\n self.chapters = []\r\n self.chapters.append(Template.Template(game, \"第1章\", \"./Precombat/Chapter01.png\"))\r\n self.chapters.append(Template.Template(game, \"第2章\", \"./Precombat/Chapter02.png\"))\r\n self.chapters.append(Template.Template(game, \"第3章\", \"./Precombat/Chapter03.png\"))\r\n self.chapters.append(Template.Template(game, \"第4章\", \"./Precombat/Chapter04.png\"))\r\n self.chapters.append(Template.Template(game, \"第5章\", \"./Precombat/Chapter05.png\"))\r\n self.chapters.append(Template.Template(game, \"第6章\", \"./Precombat/Chapter06.png\"))\r\n self.chapters.append(Template.Template(game, \"第7章\", \"./Precombat/Chapter07.png\"))\r\n self.chapters.append(Template.Template(game, \"第8章\", \"./Precombat/Chapter08.png\"))\r\n self.chapters.append(Template.Template(game, \"第9章\", \"./Precombat/Chapter09.png\"))\r\n self.chapters.append(Template.Template(game, \"第10章\", \"./Precombat/Chapter10.png\"))\r\n self.chapters.append(Template.Template(game, \"第11章\", \"./Precombat/Chapter11.png\"))\r\n self.chapters.append(Template.Template(game, \"第12章\", \"./Precombat/Chapter12.png\"))\r\n\r\n self.subcapters = {}\r\n self.subcapters[100 * 1 + 1] = Template.Target(game, (160, 376), (114, 24))\r\n self.subcapters[100 * 3 + 4] = Template.Target(game, (507, 306), (137, 25))\r\n\r\n self.prevPageTarget = Template.Target(game, (40, 300), (25, 35))\r\n self.nextPageTarget = Template.Target(game, (910, 300), (25, 35))\r\n\r\n def back(self):\r\n click(self.game, self.back1)\r\n\r\n def enterExercise(self):\r\n click(self.game, self.exercise)\r\n\r\n def enterSubcapter(self, c, sc):\r\n time.sleep(5.0)\r\n curTarget, curChapter = matchList(self.game, self.chapters)\r\n if curTarget is None:\r\n print(\"获取海图章数失败。\")\r\n return False\r\n curChapter += 1\r\n if c < curChapter:\r\n for i in range(curChapter - c):\r\n self.prevPageTarget.click()\r\n time.sleep(3.0)\r\n if c > curChapter:\r\n for i in range(c - curChapter):\r\n self.nextPageTarget.click()\r\n time.sleep(3.0)\r\n\r\n key = 100 * c + sc\r\n if key not in self.subcapters:\r\n print(\"{0}-{1}模板图片不存在。\".format(c, sc))\r\n return False\r\n subcapterTarget = self.subcapters[key]\r\n subcapterTarget.click()\r\n click(self.game, self.goNow)\r\n time.sleep(1.0)\r\n click(self.game, self.goNow2)\r\n return True\r\n\r\n\r\nclass ExerciseScene(Scene):\r\n def __init__(self, game):\r\n super().__init__(game)\r\n self.back1 = Template.Template(game, \"返回\", \"./Exercise/Back.png\")\r\n self.operation = Template.Template(game, \"演习\", \"./Exercise/Operation.png\")\r\n self.firstOne = Template.Target(game, (50, 128), (160, 228))\r\n self.startExercise = Template.Template(game, \"开始演习\", \"./Exercise/StartExercise.png\")\r\n self.weighAnchor = Template.Template(game, \"出击\", \"./Exercise/WeighAnchor.png\")\r\n\r\n def back(self):\r\n click(self.game, self.back1)\r\n\r\n def enterExercise(self):\r\n target = match(self.game, self.operation)\r\n if target is not None:\r\n self.firstOne.click()\r\n click(self.game, self.startExercise)\r\n click(self.game, self.weighAnchor)\r\n # 演习次数不足\r\n time.sleep(5.0)\r\n target = match(self.game, self.weighAnchor, 3.0)\r\n if target is not None:\r\n self.back()\r\n return False\r\n else:\r\n return True\r\n\r\n\r\nclass MaidScene(ExerciseScene):\r\n def __init__(self, game):\r\n super().__init__(game)\r\n self.advanced = Template.Template(game, \"高级演习\", \"./Events/Advanced.png\")\r\n\r\n def enterExercise(self):\r\n click(self.game, self.advanced)\r\n click(self.game, self.weighAnchor)\r\n\r\n\r\nclass C01S01Scene(Scene):\r\n def __init__(self, game):\r\n super().__init__(game)\r\n self.enterAmbushTarget = Template.Target(game, (330, 252), (87, 64))\r\n self.leaveAmbushTarget = Template.Target(game, (238, 252), (83, 64))\r\n self.meet = Template.Template(game, \"迎击\", \"./Subchapter/Meet.png\")\r\n self.weighAnchor = Template.Template(game, \"出击\", \"./Subchapter/WeighAnchor.png\")\r\n\r\n def enterAmbush(self):\r\n time.sleep(5.0)\r\n self.enterAmbushTarget.click()\r\n time.sleep(5.0)\r\n click(self.game, self.meet)\r\n click(self.game, self.weighAnchor)\r\n\r\n def leaveAmbush(self):\r\n time.sleep(5.0)\r\n self.leaveAmbushTarget.click()\r\n time.sleep(5.0)\r\n\r\n\r\nclass C03S04Scene(Scene):\r\n def __init__(self, game):\r\n super().__init__(game)\r\n self.enemies = []\r\n self.enemies.append(Template.Template(game, \"BOSS舰队\", \"./Subchapter/BossFleet.png\"))\r\n self.enemies.append(Template.Template(game, \"侦查舰队\", \"./Subchapter/RecFleet.png\"))\r\n self.enemies.append(Template.Template(game, \"航空舰队\", \"./Subchapter/AirFleet.png\"))\r\n self.enemies.append(Template.Template(game, \"主力舰队\", \"./Subchapter/MainFleet.png\"))\r\n\r\n self.weighAnchor1 = Template.Template(game, \"出击\", \"./Subchapter/WeighAnchor.png\")\r\n\r\n self.bossExist = True\r\n\r\n def weighAnchor(self):\r\n time.sleep(5.0)\r\n target, i = matchList(self.game, self.enemies)\r\n if target is None:\r\n print(\"匹配敌人失败。\")\r\n return False\r\n target.click()\r\n click(self.game, self.weighAnchor1)\r\n if i == 0:\r\n self.bossExist = False\r\n return True\r\n\r\n\r\nclass BattleScene(Scene):\r\n def __init__(self, game):\r\n super().__init__(game)\r\n self.auto = Template.Template(game, \"自律战斗\", \"./Battle/Auto.png\")\r\n self.gotIt = Template.Template(game, \"知道了\", \"./Battle/GotIt.png\")\r\n self.ttc = Template.Template(game, \"点击继续\", \"./Battle/TTC.png\")\r\n self.ttc2 = Template.Template(game, \"点击继续2\", \"./Battle/TTC2.png\")\r\n self.performance = Template.Template(game, \"性能\", \"./Battle/Performance.png\")\r\n self.ok = Template.Template(game, \"确定\", \"./Battle/OK.png\")\r\n self.victory = Template.Template(game, \"大获全胜\", \"./Battle/Victory.png\")\r\n self.confirm = Template.Template(game, \"确认\", \"./Battle/Confirm.png\")\r\n self.autoFlag = False\r\n\r\n def enterBattle(self):\r\n if not self.autoFlag:\r\n if click(self.game, self.auto, 20.0):\r\n click(self.game, self.gotIt, 3.0)\r\n self.autoFlag = True\r\n\r\n def leaveBattle(self, drops=True):\r\n click(self.game, self.ttc)\r\n click(self.game, self.ttc2)\r\n if drops:\r\n if click(self.game, self.performance, 5.0):\r\n click(self.game, self.ok)\r\n click(self.game, self.confirm)\r\n","sub_path":"Scene.py","file_name":"Scene.py","file_ext":"py","file_size_in_byte":9171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"144731878","text":"\n# -*- coding: utf-8 -*-\n# Порядок работы:\n# Добавили функцию\n# Добавили в patterns эту функцию\n# Готово\n\nfrom bs4 import BeautifulSoup\nimport datetime\n\n# Функция парсер\ndef TEST_PARSER(html):\n text = []\n soup = BeautifulSoup(html, 'xml')\n ####################### Сдесь находится логика парсера ##############################\n row_count_1 = soup.find_all('div', class_='stat__value')\n for i in row_count_1:\n text.append(i.text.replace(\" \", \"\").replace(\"\", \"\"))\n ################# Так должен выглядеть возвращаемый словарь #########################\n result_data = {\n 'investors': text[3], # Число \"инвесторов\" (на сайте)\n 'investments': text[1], # Сумма пополнений (на сайте)\n 'payments': text[2], # Сумма выплат (на сайте)\n 'project_time': text[0], # Время существования проекта (на сайте)\n }\n return result_data\n\ndef bitTrade(html):\n text = []\n soup = BeautifulSoup(html, 'html.parser')\n\n row_count_1 = soup.find_all('span', class_='timer')\n\n for i in row_count_1:\n text.append(i.text)\n\n result_data = {\n 'investors': int(text[0]), # Число \"инвесторов\" (на сайте)\n 'investments': int(text[1].replace(\",\", '').split(\".\")[0]), # Сумма пополнений (на сайте)\n 'payments': int(text[2].replace(\",\", '').split(\".\")[0]), # Сумма выплат (на сайте)\n 'project_time': 'None', # Время существования проекта (на сайте)\n }\n\n return result_data\n\n\ndef moneyIsland(html):\n text = []\n soup = BeautifulSoup(html, 'html.parser')\n\n row_count_1 = soup.find_all('tr', class_='htt')\n\n for i in row_count_1:\n text.append(i.text)\n\n # print(text)\n\n result_data = {\n 'investors': 0, # Число \"инвесторов\" (на сайте)\n 'investments': int(text[1].replace(\"\\n\", '').replace(\" \", \"\").replace(\"Пополнено:\", \"\").split(\".\")[0]),\n 'payments': int(text[2].replace(\"\\n\", '').replace(\" \", \"\").replace(\"Выплачено:\", \"\").split(\".\")[0]),\n 'project_time': int(text[4].replace(\"\\n\", '').replace(\" \", '').split(\":\")[1][:3])\n }\n\n return result_data\n\n\ndef sbercom(html): # https://sbercom.online\n text = []\n soup = BeautifulSoup(html, 'html.parser')\n\n row_count_1 = soup.find_all('div', class_='stat_block')\n\n for i in row_count_1:\n text.append(i.text.replace(\"\\n\", '').replace(\" \", '').replace(\",\", \"\"))\n\n res = []\n\n sym = \"\"\n\n for i in text[0]:\n if i.isdigit():\n sym += i\n else:\n if sym:\n res.append(int(sym))\n sym = \"\"\n\n # print(text)\n\n result_data = {\n 'investors': res[3],\n 'investments': res[1],\n 'payments': res[2],\n 'project_time': res[0]\n }\n\n return result_data\n\n\ndef investmoneyspace(html): # https://invest-money.space\n text = []\n soup = BeautifulSoup(html, 'html.parser')\n\n row_count_1 = soup.find_all('span', class_='stata__result')\n\n for i in row_count_1[1:]:\n text.append(int(i.text.replace(\",\", \"\").split(\".\")[0]))\n\n # print(text)\n\n result_data = {\n 'investors': text[0],\n 'investments': text[1],\n 'payments': text[2],\n 'project_time': \"None\"\n }\n\n # return text\n return result_data\n\n\ndef vectorinvest(html): # https://vectorinvest.site\n text = []\n soup = BeautifulSoup(html, 'html.parser')\n\n row_count_1 = soup.find_all('div', class_='statistic-item__value')\n\n for i in row_count_1:\n text.append(int(i.text.replace(\"\\n\", '').strip().replace(\" \", '').split(\".\")[0]))\n\n # print(text)\n\n result_data = {\n 'investors': text[0],\n 'investments': text[2],\n 'payments': text[1],\n 'project_time': \"None\"\n }\n\n # return text\n return result_data\n\n\ndef montrade(html): # https://montrade.biz\n text = []\n soup = BeautifulSoup(html, 'html.parser')\n\n row_count_1 = soup.find_all('h3', class_='klademug')\n\n for i in row_count_1:\n text.append(int(i.text.strip().replace(\"\\n\", '').replace(\" \", '').split(\".\")[0]))\n\n # print(text)\n\n result_data = {\n 'investors': text[1],\n 'investments': text[2],\n 'payments': text[3],\n 'project_time': text[0]\n }\n\n # return text\n return result_data\n\n\ndef yesss(html): # https://yesss.cc\n text = []\n soup = BeautifulSoup(html, 'html.parser')\n\n row_count_1 = soup.find_all('div', class_='centered_content')\n\n for i in row_count_1:\n text.append(i.text.strip().replace(\"\\n\", '').replace(\" \", ''))\n\n text = text[1:4]\n\n for index, i in enumerate(text):\n text[index] = int(text[index].split(\":\")[1].replace(\",\", '').replace(\"$\", '').split(\".\")[0])\n # print(text)\n\n result_data = {\n 'investors': 0,\n 'investments': text[1],\n 'payments': text[2],\n 'project_time': text[0]\n }\n\n # return text\n return result_data\n\n\n############################################################################\n\n# Словарь, где ключём является название парсера, а значением функция-парсер\npatterns = {\n 'TEST_PARSER': TEST_PARSER,\n 'bitTrade': bitTrade, # 'https://maniday.com'\n 'moneyIsland': moneyIsland, # 'https://money-island.biz'\n 'sbercom': sbercom, # https://sbercom.online\n 'investmoneyspace': investmoneyspace, # https://invest-money.space\n 'vectorinvest': vectorinvest, # https://vectorinvest.site\n 'montrade': montrade, # https://montrade.biz\n 'yesss': yesss # https://yesss.cc\n }\n\ndef get_parser(pattern):\n for key in list(patterns.keys()):\n if key == pattern:\n return patterns[pattern]","sub_path":"Parsers.py","file_name":"Parsers.py","file_ext":"py","file_size_in_byte":6058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"643622820","text":"\nimport csv\nimport sys\nimport os\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nimport time\n\noutput_file = 'blog_data.csv'\n\ndef setUpChrome():\n global driver\n # Using Chrome\n chrome_options = webdriver.ChromeOptions()\n #prefs = {\"profile.managed_default_content_settings.images\": 2}\n #chrome_options.add_experimental_option(\"prefs\", prefs)\n chrome_options.add_argument('--ignore-certificate-errors')\n chrome_options.add_argument('--ignore-ssl-errors')\n #chrome_options.add_argument('headless')\n\n scriptpath = os.path.realpath(__file__)\n foldername = os.path.basename(scriptpath)\n scriptpath = scriptpath[:scriptpath.find(foldername)]\n\n scriptpath += 'chromedriver'\n\n driver = webdriver.Chrome(scriptpath, chrome_options=chrome_options)\n return driver\n\ndef add_csv_head():\n with open(output_file, 'w', newline='') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(['date', 'title', 'content'])\n\ndef add_csv_row(date, title, content):\n with open(output_file, 'a', newline='', encoding=\"utf-8\") as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(\n [date, title, content])\n\ndef pull_blog(url):\n driver.get(url)\n\n article_dates = []\n article_titles = []\n article_contents = []\n\n blogs = driver.find_elements_by_class_name('type-post')\n # print(len(blogs))\n for blog in blogs:\n postdates = blog.find_elements_by_tag_name('time')\n # article_dates.append(postdates.text)\n for postdate in postdates:\n article_dates.append(postdate.text)\n\n article_titles.append(blog.find_element_by_tag_name('h2').text)\n\n for i in range(0, len(article_dates)):\n # print(article_contents[i])\n add_csv_row(article_dates[i], article_titles[i], \"\")\n\ndriver = setUpChrome()\nadd_csv_head()\n\ni = 2019\nwhile i > 2011:\n j = 12\n while j > 0:\n url = 'https://directorsblog.nih.gov/' + str(i) +'/'\n if i == 2019 and j > 9:\n continue\n if i == 2012 and j == 10:\n break\n url += str(j) + '/'\n print(url)\n # pull_blog(url)\n # sleep(4)\n j -= 1\n time.sleep(5)\n i -= 1\n\nprint(\"done\")\n\n\n\n","sub_path":"second step/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"648841432","text":"from django.shortcuts import render\nimport jwt\nfrom django.conf import settings\nfrom datetime import datetime\nimport requests\nimport json\n\ndef token_creation(request):\n\tepoch = datetime.utcfromtimestamp(0)\n\ttimestamp = round((datetime.now() - epoch).total_seconds())\n\tclientId = settings.SHOP_ID\n\tsecretKey = settings.SHOP_SECRET\n\turl_base = \"https://api.demo.uapay.ua/api/\"\n\tcreate_session_uri = url_base + \"sessions/create\"\n\tpayload = { \n \t\t\t\"params\":{\n \t\t\t\t\"clientId\":clientId\n \t\t\t\t\t},\n \t\t\t\"data\":{\n \t\t\t},\n \t\t\t\"iat\":timestamp\n\t\t\t}\n\tencoded = jwt.encode(payload, secretKey, algorithm='HS256').decode('utf-8')\n\tpayload_with_token = {\n \t\t\t\"params\":{\n \t\t\t\t\"clientId\":clientId\n \t\t\t\t\t},\n \t\t\t\"data\":{\n \t\t\t},\n \t\t\t\"iat\":timestamp,\n \t\t\t\"token\":encoded\n\t\t\t\t}\n\tsession_create_request = payload_with_token\n\trequest_reply= requests.post(create_session_uri, json = session_create_request)\n\treply_token = request_reply.json().get('data').get('token')\n\treply_decoded=jwt.decode(reply_token, secretKey, algorithms=['HS256'])\n\tcontext = {\n\t\t\t\"token\":encoded,\n\t\t\t\"send_request\":session_create_request,\n\t\t\t\"url\":create_session_uri,\n\t\t\t\"request_reply\":request_reply.json(),\n\t\t\t\"reply_encoded\":reply_decoded\n\t\t\t}\n\t\n\treturn render(request, 'postings/test.html', context)\n# 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg'\n\n# >>> jwt.decode(encoded, 'secret', algorithms=['HS256'])\n# {'some': 'payload'","sub_path":"postings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"425859284","text":"import tensorflow\n\nsession = tensorflow.Session()\n\nhello = tensorflow.constant('Hello, TensorFlow!')\n\nprint(session.run(hello))\n\na = tensorflow.constant(2)\nb = tensorflow.constant(3)\n\nprint(\"Addition with constants: %i\" % session.run(a + b))\nprint(\"Multiplication with constants: %i\" % session.run(a * b))\n\na = tensorflow.placeholder(tensorflow.int16)\nb = tensorflow.placeholder(tensorflow.int16)\n\nadd = tensorflow.add(a, b)\nmul = tensorflow.mul(a, b)\n\nprint(\"Addition with variables: %i\" % session.run(add, feed_dict={a: 2, b: 3}))\nprint(\"Multiplication with variables: %i\" % session.run(mul, feed_dict={a: 2, b: 3}))\n\nmatrix1 = tensorflow.constant([[3., 3.]])\nmatrix2 = tensorflow.constant([[2.],[2.]])\n\nproduct = tensorflow.matmul(matrix1, matrix2)\n\nprint(session.run(product))","sub_path":"hello_tensorflow.py","file_name":"hello_tensorflow.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"291704974","text":"#!/usr/bin/env python3\n\n########################################################################\n\n# A quick tool to strip FASTA headers from stdin and turn the text\n# strings into single lines for easy Python hacking.\n\nimport sys\n\nif __name__==\"__main__\":\n g = \"\"\n first = True\n for line in sys.stdin:\n if line[0] == \">\":\n if not first:\n print(g)\n g = \"\"\n else:\n first = False\n else:\n g += line.strip()\n print(g)\n","sub_path":"problems/level-5/revp/fasta_stripper.py","file_name":"fasta_stripper.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"64430305","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Carla Backend code\n# Copyright (C) 2011-2013 Filipe Coelho \n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation; either version 2 of\n# the License, or 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# For a full copy of the GNU General Public License see the GPL.txt file\n\n# ------------------------------------------------------------------------------------------------------------\n# Imports (Global)\n\nfrom ctypes import *\nfrom platform import architecture\nfrom sys import platform, maxsize\n\n# ------------------------------------------------------------------------------------------------------------\n# 64bit check\n\nkIs64bit = bool(architecture()[0] == \"64bit\" and maxsize > 2**32)\n\n# ------------------------------------------------------------------------------------------------------------\n# Set Platform\n\nif platform == \"darwin\":\n HAIKU = False\n LINUX = False\n MACOS = True\n WINDOWS = False\nelif \"haiku\" in platform:\n HAIKU = True\n LINUX = False\n MACOS = False\n WINDOWS = False\nelif \"linux\" in platform:\n HAIKU = False\n LINUX = True\n MACOS = False\n WINDOWS = False\nelif platform in (\"win32\", \"win64\", \"cygwin\"):\n HAIKU = False\n LINUX = False\n MACOS = False\n WINDOWS = True\nelse:\n HAIKU = False\n LINUX = False\n MACOS = False\n WINDOWS = False\n\n# ------------------------------------------------------------------------------------------------------------\n# Convert a ctypes char** into a python string list\n\ndef charStringList(charPtr):\n i = 0\n retList = []\n\n if not charPtr:\n return retList\n\n while True:\n char_p = charPtr[i]\n\n if not char_p:\n break\n\n retList.append(char_p.decode(\"utf-8\", errors=\"ignore\"))\n i += 1\n\n return retList\n\n# ------------------------------------------------------------------------------------------------------------\n# Convert a ctypes struct into a python dict\n\ndef structToDict(struct):\n return dict((attr, getattr(struct, attr)) for attr, value in struct._fields_)\n\n# ------------------------------------------------------------------------------------------------\n# Backend defines\n\nMAX_DEFAULT_PLUGINS = 99\nMAX_RACK_PLUGINS = 16\nMAX_PATCHBAY_PLUGINS = 999\nMAX_DEFAULT_PARAMETERS = 200\n\n# Plugin Hints\nPLUGIN_IS_BRIDGE = 0x001\nPLUGIN_IS_RTSAFE = 0x002\nPLUGIN_IS_SYNTH = 0x004\nPLUGIN_HAS_GUI = 0x010\nPLUGIN_HAS_GUI_AS_FILE = 0x020\nPLUGIN_HAS_SINGLE_THREAD = 0x040\nPLUGIN_CAN_DRYWET = 0x100\nPLUGIN_CAN_VOLUME = 0x200\nPLUGIN_CAN_BALANCE = 0x400\nPLUGIN_CAN_PANNING = 0x800\n\n# Plugin Options\nPLUGIN_OPTION_FIXED_BUFFER = 0x001\nPLUGIN_OPTION_FORCE_STEREO = 0x002\nPLUGIN_OPTION_MAP_PROGRAM_CHANGES = 0x004\nPLUGIN_OPTION_USE_CHUNKS = 0x008\nPLUGIN_OPTION_SEND_CONTROL_CHANGES = 0x010\nPLUGIN_OPTION_SEND_CHANNEL_PRESSURE = 0x020\nPLUGIN_OPTION_SEND_NOTE_AFTERTOUCH = 0x040\nPLUGIN_OPTION_SEND_PITCHBEND = 0x080\nPLUGIN_OPTION_SEND_ALL_SOUND_OFF = 0x100\n\n# Parameter Hints\nPARAMETER_IS_BOOLEAN = 0x001\nPARAMETER_IS_INTEGER = 0x002\nPARAMETER_IS_LOGARITHMIC = 0x004\nPARAMETER_IS_ENABLED = 0x008\nPARAMETER_IS_AUTOMABLE = 0x010\nPARAMETER_IS_READ_ONLY = 0x020\nPARAMETER_USES_SAMPLERATE = 0x040\nPARAMETER_USES_SCALEPOINTS = 0x080\nPARAMETER_USES_CUSTOM_TEXT = 0x100\n\n# Custom Data types\nCUSTOM_DATA_INVALID = None\nCUSTOM_DATA_CHUNK = \"http://kxstudio.sf.net/ns/carla/chunk\"\nCUSTOM_DATA_STRING = \"http://kxstudio.sf.net/ns/carla/string\"\n\n# Patchbay Port Hints\nPATCHBAY_PORT_IS_INPUT = 0x01\nPATCHBAY_PORT_IS_OUTPUT = 0x02\nPATCHBAY_PORT_IS_AUDIO = 0x04\nPATCHBAY_PORT_IS_CV = 0x08\nPATCHBAY_PORT_IS_MIDI = 0x10\n\n# Binary Type\nBINARY_NONE = 0\nBINARY_POSIX32 = 1\nBINARY_POSIX64 = 2\nBINARY_WIN32 = 3\nBINARY_WIN64 = 4\nBINARY_OTHER = 5\n\n# Plugin Type\nPLUGIN_NONE = 0\nPLUGIN_INTERNAL = 1\nPLUGIN_LADSPA = 2\nPLUGIN_DSSI = 3\nPLUGIN_LV2 = 4\nPLUGIN_VST = 5\nPLUGIN_VST3 = 6\nPLUGIN_GIG = 7\nPLUGIN_SF2 = 8\nPLUGIN_SFZ = 9\n\n# Plugin Category\nPLUGIN_CATEGORY_NONE = 0\nPLUGIN_CATEGORY_SYNTH = 1\nPLUGIN_CATEGORY_DELAY = 2 # also Reverb\nPLUGIN_CATEGORY_EQ = 3\nPLUGIN_CATEGORY_FILTER = 4\nPLUGIN_CATEGORY_DYNAMICS = 5 # Amplifier, Compressor, Gate\nPLUGIN_CATEGORY_MODULATOR = 6 # Chorus, Flanger, Phaser\nPLUGIN_CATEGORY_UTILITY = 7 # Analyzer, Converter, Mixer\nPLUGIN_CATEGORY_OTHER = 8 # used to check if a plugin has a category\n\n# Parameter Type\nPARAMETER_UNKNOWN = 0\nPARAMETER_INPUT = 1\nPARAMETER_OUTPUT = 2\nPARAMETER_LATENCY = 3\nPARAMETER_SAMPLE_RATE = 4\nPARAMETER_LV2_FREEWHEEL = 5\nPARAMETER_LV2_TIME = 6\n\n# Internal Parameters Index\nPARAMETER_NULL = -1\nPARAMETER_ACTIVE = -2\nPARAMETER_DRYWET = -3\nPARAMETER_VOLUME = -4\nPARAMETER_BALANCE_LEFT = -5\nPARAMETER_BALANCE_RIGHT = -6\nPARAMETER_PANNING = -7\nPARAMETER_CTRL_CHANNEL = -8\nPARAMETER_MAX = -9\n\n# Patchbay Icon Type\nPATCHBAY_ICON_APPLICATION = 0\nPATCHBAY_ICON_HARDWARE = 1\nPATCHBAY_ICON_CARLA = 2\nPATCHBAY_ICON_DISTRHO = 3\nPATCHBAY_ICON_FILE = 4\nPATCHBAY_ICON_PLUGIN = 5\n\n# Options Type\nOPTION_PROCESS_NAME = 0\nOPTION_PROCESS_MODE = 1\nOPTION_TRANSPORT_MODE = 2\nOPTION_FORCE_STEREO = 3\nOPTION_PREFER_PLUGIN_BRIDGES = 4\nOPTION_PREFER_UI_BRIDGES = 5\nOPTION_USE_DSSI_VST_CHUNKS = 6\nOPTION_MAX_PARAMETERS = 7\nOPTION_OSC_UI_TIMEOUT = 8\nOPTION_JACK_AUTOCONNECT = 9\nOPTION_JACK_TIMEMASTER = 10\nOPTION_RTAUDIO_BUFFER_SIZE = 11\nOPTION_RTAUDIO_SAMPLE_RATE = 12\nOPTION_RTAUDIO_DEVICE = 13\nOPTION_PATH_RESOURCES = 14\nOPTION_PATH_BRIDGE_NATIVE = 15\nOPTION_PATH_BRIDGE_POSIX32 = 16\nOPTION_PATH_BRIDGE_POSIX64 = 17\nOPTION_PATH_BRIDGE_WIN32 = 18\nOPTION_PATH_BRIDGE_WIN64 = 19\nOPTION_PATH_BRIDGE_LV2_GTK2 = 20\nOPTION_PATH_BRIDGE_LV2_GTK3 = 21\nOPTION_PATH_BRIDGE_LV2_QT4 = 22\nOPTION_PATH_BRIDGE_LV2_QT5 = 23\nOPTION_PATH_BRIDGE_LV2_COCOA = 24\nOPTION_PATH_BRIDGE_LV2_WINDOWS = 25\nOPTION_PATH_BRIDGE_LV2_X11 = 26\nOPTION_PATH_BRIDGE_VST_COCOA = 27\nOPTION_PATH_BRIDGE_VST_HWND = 28\nOPTION_PATH_BRIDGE_VST_X11 = 29\n\n# Callback Type\nCALLBACK_DEBUG = 0\nCALLBACK_PLUGIN_ADDED = 1\nCALLBACK_PLUGIN_REMOVED = 2\nCALLBACK_PLUGIN_RENAMED = 3\nCALLBACK_PARAMETER_VALUE_CHANGED = 4\nCALLBACK_PARAMETER_DEFAULT_CHANGED = 5\nCALLBACK_PARAMETER_MIDI_CHANNEL_CHANGED = 6\nCALLBACK_PARAMETER_MIDI_CC_CHANGED = 7\nCALLBACK_PROGRAM_CHANGED = 8\nCALLBACK_MIDI_PROGRAM_CHANGED = 9\nCALLBACK_NOTE_ON = 10\nCALLBACK_NOTE_OFF = 11\nCALLBACK_SHOW_GUI = 12\nCALLBACK_UPDATE = 13\nCALLBACK_RELOAD_INFO = 14\nCALLBACK_RELOAD_PARAMETERS = 15\nCALLBACK_RELOAD_PROGRAMS = 16\nCALLBACK_RELOAD_ALL = 17\nCALLBACK_PATCHBAY_CLIENT_ADDED = 18\nCALLBACK_PATCHBAY_CLIENT_REMOVED = 19\nCALLBACK_PATCHBAY_CLIENT_RENAMED = 20\nCALLBACK_PATCHBAY_PORT_ADDED = 21\nCALLBACK_PATCHBAY_PORT_REMOVED = 22\nCALLBACK_PATCHBAY_PORT_RENAMED = 23\nCALLBACK_PATCHBAY_CONNECTION_ADDED = 24\nCALLBACK_PATCHBAY_CONNECTION_REMOVED = 25\nCALLBACK_PATCHBAY_ICON_CHANGED = 26\nCALLBACK_BUFFER_SIZE_CHANGED = 27\nCALLBACK_SAMPLE_RATE_CHANGED = 28\nCALLBACK_PROCESS_MODE_CHANGED = 29\nCALLBACK_NSM_ANNOUNCE = 30\nCALLBACK_NSM_OPEN = 31\nCALLBACK_NSM_SAVE = 32\nCALLBACK_ERROR = 33\nCALLBACK_INFO = 34\nCALLBACK_QUIT = 35\n\n# Process Mode\nPROCESS_MODE_SINGLE_CLIENT = 0\nPROCESS_MODE_MULTIPLE_CLIENTS = 1\nPROCESS_MODE_CONTINUOUS_RACK = 2\nPROCESS_MODE_PATCHBAY = 3\nPROCESS_MODE_BRIDGE = 4\n\n# Transport Mode\nTRANSPORT_MODE_INTERNAL = 0\nTRANSPORT_MODE_JACK = 1\nTRANSPORT_MODE_PLUGIN = 2\nTRANSPORT_MODE_BRIDGE = 3\n\n# Set BINARY_NATIVE\nif HAIKU or LINUX or MACOS:\n BINARY_NATIVE = BINARY_POSIX64 if kIs64bit else BINARY_POSIX32\nelif WINDOWS:\n BINARY_NATIVE = BINARY_WIN64 if kIs64bit else BINARY_WIN32\nelse:\n BINARY_NATIVE = BINARY_OTHER\n\n# ------------------------------------------------------------------------------------------------------------\n# Backend C++ -> Python variables\n\nc_enum = c_int\nc_nullptr = None\n\nCallbackFunc = CFUNCTYPE(None, c_void_p, c_enum, c_uint, c_int, c_int, c_float, c_char_p)\n\nclass ParameterData(Structure):\n _fields_ = [\n (\"type\", c_enum),\n (\"index\", c_int32),\n (\"rindex\", c_int32),\n (\"hints\", c_uint32),\n (\"midiChannel\", c_uint8),\n (\"midiCC\", c_int16)\n ]\n\nclass ParameterRanges(Structure):\n _fields_ = [\n (\"def\", c_float),\n (\"min\", c_float),\n (\"max\", c_float),\n (\"step\", c_float),\n (\"stepSmall\", c_float),\n (\"stepLarge\", c_float)\n ]\n\nclass MidiProgramData(Structure):\n _fields_ = [\n (\"bank\", c_uint32),\n (\"program\", c_uint32),\n (\"name\", c_char_p)\n ]\n\nclass CustomData(Structure):\n _fields_ = [\n (\"type\", c_char_p),\n (\"key\", c_char_p),\n (\"value\", c_char_p)\n ]\n\n# ------------------------------------------------------------------------------------------------------------\n# Standalone C++ -> Python variables\n\nclass CarlaPluginInfo(Structure):\n _fields_ = [\n (\"type\", c_enum),\n (\"category\", c_enum),\n (\"hints\", c_uint),\n (\"optionsAvailable\", c_uint),\n (\"optionsEnabled\", c_uint),\n (\"binary\", c_char_p),\n (\"name\", c_char_p),\n (\"label\", c_char_p),\n (\"maker\", c_char_p),\n (\"copyright\", c_char_p),\n (\"iconName\", c_char_p),\n (\"uniqueId\", c_long),\n (\"latency\", c_uint32)\n ]\n\nclass CarlaNativePluginInfo(Structure):\n _fields_ = [\n (\"category\", c_enum),\n (\"hints\", c_uint),\n (\"audioIns\", c_uint32),\n (\"audioOuts\", c_uint32),\n (\"midiIns\", c_uint32),\n (\"midiOuts\", c_uint32),\n (\"parameterIns\", c_uint32),\n (\"parameterOuts\", c_uint32),\n (\"name\", c_char_p),\n (\"label\", c_char_p),\n (\"maker\", c_char_p),\n (\"copyright\", c_char_p)\n ]\n\nclass CarlaPortCountInfo(Structure):\n _fields_ = [\n (\"ins\", c_uint32),\n (\"outs\", c_uint32),\n (\"total\", c_uint32)\n ]\n\nclass CarlaParameterInfo(Structure):\n _fields_ = [\n (\"name\", c_char_p),\n (\"symbol\", c_char_p),\n (\"unit\", c_char_p),\n (\"scalePointCount\", c_uint32)\n ]\n\nclass CarlaScalePointInfo(Structure):\n _fields_ = [\n (\"value\", c_float),\n (\"label\", c_char_p)\n ]\n\nclass CarlaTransportInfo(Structure):\n _fields_ = [\n (\"playing\", c_bool),\n (\"frame\", c_uint32),\n (\"bar\", c_int32),\n (\"beat\", c_int32),\n (\"tick\", c_int32),\n (\"bpm\", c_double)\n ]\n\n# ------------------------------------------------------------------------------------------------------------\n# Standalone Python object\n\nclass Host(object):\n def __init__(self, libName):\n object.__init__(self)\n\n self.lib = cdll.LoadLibrary(libName)\n\n self.lib.carla_get_extended_license_text.argtypes = None\n self.lib.carla_get_extended_license_text.restype = c_char_p\n\n self.lib.carla_get_supported_file_types.argtypes = None\n self.lib.carla_get_supported_file_types.restype = c_char_p\n\n self.lib.carla_get_engine_driver_count.argtypes = None\n self.lib.carla_get_engine_driver_count.restype = c_uint\n\n self.lib.carla_get_engine_driver_name.argtypes = [c_uint]\n self.lib.carla_get_engine_driver_name.restype = c_char_p\n\n self.lib.carla_get_engine_driver_device_names.argtypes = [c_uint]\n self.lib.carla_get_engine_driver_device_names.restype = POINTER(c_char_p)\n\n self.lib.carla_get_internal_plugin_count.argtypes = None\n self.lib.carla_get_internal_plugin_count.restype = c_uint\n\n self.lib.carla_get_internal_plugin_info.argtypes = [c_uint]\n self.lib.carla_get_internal_plugin_info.restype = POINTER(CarlaNativePluginInfo)\n\n self.lib.carla_engine_init.argtypes = [c_char_p, c_char_p]\n self.lib.carla_engine_init.restype = c_bool\n\n self.lib.carla_engine_close.argtypes = None\n self.lib.carla_engine_close.restype = c_bool\n\n self.lib.carla_engine_idle.argtypes = None\n self.lib.carla_engine_idle.restype = None\n\n self.lib.carla_is_engine_running.argtypes = None\n self.lib.carla_is_engine_running.restype = c_bool\n\n self.lib.carla_set_engine_about_to_close.argtypes = None\n self.lib.carla_set_engine_about_to_close.restype = None\n\n self.lib.carla_set_engine_callback.argtypes = [CallbackFunc, c_void_p]\n self.lib.carla_set_engine_callback.restype = None\n\n self.lib.carla_set_engine_option.argtypes = [c_enum, c_int, c_char_p]\n self.lib.carla_set_engine_option.restype = None\n\n self.lib.carla_load_filename.argtypes = [c_char_p]\n self.lib.carla_load_filename.restype = c_bool\n\n self.lib.carla_load_project.argtypes = [c_char_p]\n self.lib.carla_load_project.restype = c_bool\n\n self.lib.carla_save_project.argtypes = [c_char_p]\n self.lib.carla_save_project.restype = c_bool\n\n self.lib.carla_patchbay_connect.argtypes = [c_int, c_int]\n self.lib.carla_patchbay_connect.restype = c_bool\n\n self.lib.carla_patchbay_disconnect.argtypes = [c_int]\n self.lib.carla_patchbay_disconnect.restype = c_bool\n\n self.lib.carla_patchbay_refresh.argtypes = None\n self.lib.carla_patchbay_refresh.restype = None\n\n self.lib.carla_transport_play.argtypes = None\n self.lib.carla_transport_play.restype = None\n\n self.lib.carla_transport_pause.argtypes = None\n self.lib.carla_transport_pause.restype = None\n\n self.lib.carla_transport_relocate.argtypes = [c_uint32]\n self.lib.carla_transport_relocate.restype = None\n\n self.lib.carla_get_current_transport_frame.argtypes = None\n self.lib.carla_get_current_transport_frame.restype = c_uint32\n\n self.lib.carla_get_transport_info.argtypes = None\n self.lib.carla_get_transport_info.restype = POINTER(CarlaTransportInfo)\n\n self.lib.carla_add_plugin.argtypes = [c_enum, c_enum, c_char_p, c_char_p, c_char_p, c_void_p]\n self.lib.carla_add_plugin.restype = c_bool\n\n self.lib.carla_remove_plugin.argtypes = [c_uint]\n self.lib.carla_remove_plugin.restype = c_bool\n\n self.lib.carla_remove_all_plugins.argtypes = None\n self.lib.carla_remove_all_plugins.restype = None\n\n self.lib.carla_rename_plugin.argtypes = [c_uint, c_char_p]\n self.lib.carla_rename_plugin.restype = c_char_p\n\n self.lib.carla_clone_plugin.argtypes = [c_uint]\n self.lib.carla_clone_plugin.restype = c_bool\n\n self.lib.carla_replace_plugin.argtypes = [c_uint]\n self.lib.carla_replace_plugin.restype = c_bool\n\n self.lib.carla_switch_plugins.argtypes = [c_uint, c_uint]\n self.lib.carla_switch_plugins.restype = c_bool\n\n self.lib.carla_load_plugin_state.argtypes = [c_uint, c_char_p]\n self.lib.carla_load_plugin_state.restype = c_bool\n\n self.lib.carla_save_plugin_state.argtypes = [c_uint, c_char_p]\n self.lib.carla_save_plugin_state.restype = c_bool\n\n self.lib.carla_get_plugin_info.argtypes = [c_uint]\n self.lib.carla_get_plugin_info.restype = POINTER(CarlaPluginInfo)\n\n self.lib.carla_get_audio_port_count_info.argtypes = [c_uint]\n self.lib.carla_get_audio_port_count_info.restype = POINTER(CarlaPortCountInfo)\n\n self.lib.carla_get_midi_port_count_info.argtypes = [c_uint]\n self.lib.carla_get_midi_port_count_info.restype = POINTER(CarlaPortCountInfo)\n\n self.lib.carla_get_parameter_count_info.argtypes = [c_uint]\n self.lib.carla_get_parameter_count_info.restype = POINTER(CarlaPortCountInfo)\n\n self.lib.carla_get_parameter_info.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_parameter_info.restype = POINTER(CarlaParameterInfo)\n\n self.lib.carla_get_parameter_scalepoint_info.argtypes = [c_uint, c_uint32, c_uint32]\n self.lib.carla_get_parameter_scalepoint_info.restype = POINTER(CarlaScalePointInfo)\n\n self.lib.carla_get_parameter_data.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_parameter_data.restype = POINTER(ParameterData)\n\n self.lib.carla_get_parameter_ranges.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_parameter_ranges.restype = POINTER(ParameterRanges)\n\n self.lib.carla_get_midi_program_data.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_midi_program_data.restype = POINTER(MidiProgramData)\n\n self.lib.carla_get_custom_data.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_custom_data.restype = POINTER(CustomData)\n\n self.lib.carla_get_chunk_data.argtypes = [c_uint]\n self.lib.carla_get_chunk_data.restype = c_char_p\n\n self.lib.carla_get_parameter_count.argtypes = [c_uint]\n self.lib.carla_get_parameter_count.restype = c_uint32\n\n self.lib.carla_get_program_count.argtypes = [c_uint]\n self.lib.carla_get_program_count.restype = c_uint32\n\n self.lib.carla_get_midi_program_count.argtypes = [c_uint]\n self.lib.carla_get_midi_program_count.restype = c_uint32\n\n self.lib.carla_get_custom_data_count.argtypes = [c_uint]\n self.lib.carla_get_custom_data_count.restype = c_uint32\n\n self.lib.carla_get_parameter_text.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_parameter_text.restype = c_char_p\n\n self.lib.carla_get_program_name.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_program_name.restype = c_char_p\n\n self.lib.carla_get_midi_program_name.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_midi_program_name.restype = c_char_p\n\n self.lib.carla_get_real_plugin_name.argtypes = [c_uint]\n self.lib.carla_get_real_plugin_name.restype = c_char_p\n\n self.lib.carla_get_current_program_index.argtypes = [c_uint]\n self.lib.carla_get_current_program_index.restype = c_int32\n\n self.lib.carla_get_current_midi_program_index.argtypes = [c_uint]\n self.lib.carla_get_current_midi_program_index.restype = c_int32\n\n self.lib.carla_get_default_parameter_value.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_default_parameter_value.restype = c_float\n\n self.lib.carla_get_current_parameter_value.argtypes = [c_uint, c_uint32]\n self.lib.carla_get_current_parameter_value.restype = c_float\n\n self.lib.carla_get_input_peak_value.argtypes = [c_uint, c_ushort]\n self.lib.carla_get_input_peak_value.restype = c_float\n\n self.lib.carla_get_output_peak_value.argtypes = [c_uint, c_ushort]\n self.lib.carla_get_output_peak_value.restype = c_float\n\n self.lib.carla_set_option.argtypes = [c_uint, c_uint, c_bool]\n self.lib.carla_set_option.restype = None\n\n self.lib.carla_set_active.argtypes = [c_uint, c_bool]\n self.lib.carla_set_active.restype = None\n\n self.lib.carla_set_drywet.argtypes = [c_uint, c_float]\n self.lib.carla_set_drywet.restype = None\n\n self.lib.carla_set_volume.argtypes = [c_uint, c_float]\n self.lib.carla_set_volume.restype = None\n\n self.lib.carla_set_balance_left.argtypes = [c_uint, c_float]\n self.lib.carla_set_balance_left.restype = None\n\n self.lib.carla_set_balance_right.argtypes = [c_uint, c_float]\n self.lib.carla_set_balance_right.restype = None\n\n self.lib.carla_set_panning.argtypes = [c_uint, c_float]\n self.lib.carla_set_panning.restype = None\n\n self.lib.carla_set_ctrl_channel.argtypes = [c_uint, c_int8]\n self.lib.carla_set_ctrl_channel.restype = None\n\n self.lib.carla_set_parameter_value.argtypes = [c_uint, c_uint32, c_float]\n self.lib.carla_set_parameter_value.restype = None\n\n self.lib.carla_set_parameter_midi_cc.argtypes = [c_uint, c_uint32, c_int16]\n self.lib.carla_set_parameter_midi_cc.restype = None\n\n self.lib.carla_set_parameter_midi_channel.argtypes = [c_uint, c_uint32, c_uint8]\n self.lib.carla_set_parameter_midi_channel.restype = None\n\n self.lib.carla_set_program.argtypes = [c_uint, c_uint32]\n self.lib.carla_set_program.restype = None\n\n self.lib.carla_set_midi_program.argtypes = [c_uint, c_uint32]\n self.lib.carla_set_midi_program.restype = None\n\n self.lib.carla_set_custom_data.argtypes = [c_uint, c_char_p, c_char_p, c_char_p]\n self.lib.carla_set_custom_data.restype = None\n\n self.lib.carla_set_chunk_data.argtypes = [c_uint, c_char_p]\n self.lib.carla_set_chunk_data.restype = None\n\n self.lib.carla_prepare_for_save.argtypes = [c_uint]\n self.lib.carla_prepare_for_save.restype = None\n\n self.lib.carla_send_midi_note.argtypes = [c_uint, c_uint8, c_uint8, c_uint8]\n self.lib.carla_send_midi_note.restype = None\n\n self.lib.carla_show_gui.argtypes = [c_uint, c_bool]\n self.lib.carla_show_gui.restype = None\n\n self.lib.carla_get_buffer_size.argtypes = None\n self.lib.carla_get_buffer_size.restype = c_uint32\n\n self.lib.carla_get_sample_rate.argtypes = None\n self.lib.carla_get_sample_rate.restype = c_double\n\n self.lib.carla_get_last_error.argtypes = None\n self.lib.carla_get_last_error.restype = c_char_p\n\n self.lib.carla_get_host_osc_url_tcp.argtypes = None\n self.lib.carla_get_host_osc_url_tcp.restype = c_char_p\n\n self.lib.carla_get_host_osc_url_udp.argtypes = None\n self.lib.carla_get_host_osc_url_udp.restype = c_char_p\n\n self.lib.carla_nsm_announce.argtypes = [c_char_p, c_char_p, c_int]\n self.lib.carla_nsm_announce.restype = None\n\n self.lib.carla_nsm_ready.argtypes = None\n self.lib.carla_nsm_ready.restype = None\n\n self.lib.carla_nsm_reply_open.argtypes = None\n self.lib.carla_nsm_reply_open.restype = None\n\n self.lib.carla_nsm_reply_save.argtypes = None\n self.lib.carla_nsm_reply_save.restype = None\n\n def get_extended_license_text(self):\n return self.lib.carla_get_extended_license_text()\n\n def get_supported_file_types(self):\n return self.lib.carla_get_supported_file_types()\n\n def get_engine_driver_count(self):\n return self.lib.carla_get_engine_driver_count()\n\n def get_engine_driver_name(self, index):\n return self.lib.carla_get_engine_driver_name(index)\n\n def get_engine_driver_device_names(self, index):\n return charStringList(self.lib.carla_get_engine_driver_device_names(index))\n\n def get_internal_plugin_count(self):\n return self.lib.carla_get_internal_plugin_count()\n\n def get_internal_plugin_info(self, internalPluginId):\n return structToDict(self.lib.carla_get_internal_plugin_info(internalPluginId).contents)\n\n def engine_init(self, driverName, clientName):\n return self.lib.carla_engine_init(driverName.encode(\"utf-8\"), clientName.encode(\"utf-8\"))\n\n def engine_close(self):\n return self.lib.carla_engine_close()\n\n def engine_idle(self):\n self.lib.carla_engine_idle()\n\n def is_engine_running(self):\n return self.lib.carla_is_engine_running()\n\n def set_engine_about_to_close(self):\n self.lib.carla_set_engine_about_to_close()\n\n def set_engine_callback(self, func):\n self._callback = CallbackFunc(func)\n self.lib.carla_set_engine_callback(self._callback, c_nullptr)\n\n def set_engine_option(self, option, value, valueStr):\n self.lib.carla_set_engine_option(option, value, valueStr.encode(\"utf-8\"))\n\n def load_filename(self, filename):\n return self.lib.carla_load_filename(filename.encode(\"utf-8\"))\n\n def load_project(self, filename):\n return self.lib.carla_load_project(filename.encode(\"utf-8\"))\n\n def save_project(self, filename):\n return self.lib.carla_save_project(filename.encode(\"utf-8\"))\n\n def patchbay_connect(self, portIdA, portIdB):\n return self.lib.carla_patchbay_connect(portIdA, portIdB)\n\n def patchbay_disconnect(self, connectionId):\n return self.lib.carla_patchbay_disconnect(connectionId)\n\n def patchbay_refresh(self):\n self.lib.carla_patchbay_refresh()\n\n def transport_play(self):\n self.lib.carla_transport_play()\n\n def transport_pause(self):\n self.lib.carla_transport_pause()\n\n def transport_relocate(self, frames):\n self.lib.carla_transport_relocate(frames)\n\n def get_current_transport_frame(self):\n return self.lib.carla_get_current_transport_frame()\n\n def get_transport_info(self):\n return structToDict(self.lib.carla_get_transport_info().contents)\n\n def add_plugin(self, btype, ptype, filename, name, label, extraStuff):\n cfilename = filename.encode(\"utf-8\") if filename else c_nullptr\n cname = name.encode(\"utf-8\") if name else c_nullptr\n clabel = label.encode(\"utf-8\") if label else c_nullptr\n return self.lib.carla_add_plugin(btype, ptype, cfilename, cname, clabel, cast(extraStuff, c_void_p))\n\n def remove_plugin(self, pluginId):\n return self.lib.carla_remove_plugin(pluginId)\n\n def remove_all_plugins(self):\n self.lib.carla_remove_all_plugins()\n\n def rename_plugin(self, pluginId, newName):\n return self.lib.carla_rename_plugin(pluginId, newName.encode(\"utf-8\"))\n\n def clone_plugin(self, pluginId):\n return self.lib.carla_clone_plugin(pluginId)\n\n def replace_plugin(self, pluginId):\n return self.lib.carla_replace_plugin(pluginId)\n\n def switch_plugins(self, pluginIdA, pluginIdB):\n return self.lib.carla_switch_plugins(pluginIdA, pluginIdB)\n\n def load_plugin_state(self, pluginId, filename):\n return self.lib.carla_load_plugin_state(pluginId, filename.encode(\"utf-8\"))\n\n def save_plugin_state(self, pluginId, filename):\n return self.lib.carla_save_plugin_state(pluginId, filename.encode(\"utf-8\"))\n\n def get_plugin_info(self, pluginId):\n return structToDict(self.lib.carla_get_plugin_info(pluginId).contents)\n\n def get_audio_port_count_info(self, pluginId):\n return structToDict(self.lib.carla_get_audio_port_count_info(pluginId).contents)\n\n def get_midi_port_count_info(self, pluginId):\n return structToDict(self.lib.carla_get_midi_port_count_info(pluginId).contents)\n\n def get_parameter_count_info(self, pluginId):\n return structToDict(self.lib.carla_get_parameter_count_info(pluginId).contents)\n\n def get_parameter_info(self, pluginId, parameterId):\n return structToDict(self.lib.carla_get_parameter_info(pluginId, parameterId).contents)\n\n def get_parameter_scalepoint_info(self, pluginId, parameterId, scalePointId):\n return structToDict(self.lib.carla_get_parameter_scalepoint_info(pluginId, parameterId, scalePointId).contents)\n\n def get_parameter_data(self, pluginId, parameterId):\n return structToDict(self.lib.carla_get_parameter_data(pluginId, parameterId).contents)\n\n def get_parameter_ranges(self, pluginId, parameterId):\n return structToDict(self.lib.carla_get_parameter_ranges(pluginId, parameterId).contents)\n\n def get_midi_program_data(self, pluginId, midiProgramId):\n return structToDict(self.lib.carla_get_midi_program_data(pluginId, midiProgramId).contents)\n\n def get_custom_data(self, pluginId, customDataId):\n return structToDict(self.lib.carla_get_custom_data(pluginId, customDataId).contents)\n\n def get_chunk_data(self, pluginId):\n return self.lib.carla_get_chunk_data(pluginId)\n\n def get_parameter_count(self, pluginId):\n return self.lib.carla_get_parameter_count(pluginId)\n\n def get_program_count(self, pluginId):\n return self.lib.carla_get_program_count(pluginId)\n\n def get_midi_program_count(self, pluginId):\n return self.lib.carla_get_midi_program_count(pluginId)\n\n def get_custom_data_count(self, pluginId):\n return self.lib.carla_get_custom_data_count(pluginId)\n\n def get_parameter_text(self, pluginId, parameterId):\n return self.lib.carla_get_parameter_text(pluginId, parameterId)\n\n def get_program_name(self, pluginId, programId):\n return self.lib.carla_get_program_name(pluginId, programId)\n\n def get_midi_program_name(self, pluginId, midiProgramId):\n return self.lib.carla_get_midi_program_name(pluginId, midiProgramId)\n\n def get_real_plugin_name(self, pluginId):\n return self.lib.carla_get_real_plugin_name(pluginId)\n\n def get_current_program_index(self, pluginId):\n return self.lib.carla_get_current_program_index(pluginId)\n\n def get_current_midi_program_index(self, pluginId):\n return self.lib.carla_get_current_midi_program_index(pluginId)\n\n def get_default_parameter_value(self, pluginId, parameterId):\n return self.lib.carla_get_default_parameter_value(pluginId, parameterId)\n\n def get_current_parameter_value(self, pluginId, parameterId):\n return self.lib.carla_get_current_parameter_value(pluginId, parameterId)\n\n def get_input_peak_value(self, pluginId, portId):\n return self.lib.carla_get_input_peak_value(pluginId, portId)\n\n def get_output_peak_value(self, pluginId, portId):\n return self.lib.carla_get_output_peak_value(pluginId, portId)\n\n def set_option(self, pluginId, option, yesNo):\n self.lib.carla_set_option(pluginId, option, yesNo)\n\n def set_active(self, pluginId, onOff):\n self.lib.carla_set_active(pluginId, onOff)\n\n def set_drywet(self, pluginId, value):\n self.lib.carla_set_drywet(pluginId, value)\n\n def set_volume(self, pluginId, value):\n self.lib.carla_set_volume(pluginId, value)\n\n def set_balance_left(self, pluginId, value):\n self.lib.carla_set_balance_left(pluginId, value)\n\n def set_balance_right(self, pluginId, value):\n self.lib.carla_set_balance_right(pluginId, value)\n\n def set_panning(self, pluginId, value):\n self.lib.carla_set_panning(pluginId, value)\n\n def set_ctrl_channel(self, pluginId, channel):\n self.lib.carla_set_ctrl_channel(pluginId, channel)\n\n def set_parameter_value(self, pluginId, parameterId, value):\n self.lib.carla_set_parameter_value(pluginId, parameterId, value)\n\n def set_parameter_midi_cc(self, pluginId, parameterId, cc):\n self.lib.carla_set_parameter_midi_cc(pluginId, parameterId, cc)\n\n def set_parameter_midi_channel(self, pluginId, parameterId, channel):\n self.lib.carla_set_parameter_midi_channel(pluginId, parameterId, channel)\n\n def set_program(self, pluginId, programId):\n self.lib.carla_set_program(pluginId, programId)\n\n def set_midi_program(self, pluginId, midiProgramId):\n self.lib.carla_set_midi_program(pluginId, midiProgramId)\n\n def set_custom_data(self, pluginId, type_, key, value):\n self.lib.carla_set_custom_data(pluginId, type_.encode(\"utf-8\"), key.encode(\"utf-8\"), value.encode(\"utf-8\"))\n\n def set_chunk_data(self, pluginId, chunkData):\n self.lib.carla_set_chunk_data(pluginId, chunkData.encode(\"utf-8\"))\n\n def prepare_for_save(self, pluginId):\n self.lib.carla_prepare_for_save(pluginId)\n\n def send_midi_note(self, pluginId, channel, note, velocity):\n self.lib.carla_send_midi_note(pluginId, channel, note, velocity)\n\n def show_gui(self, pluginId, yesNo):\n self.lib.carla_show_gui(pluginId, yesNo)\n\n def get_last_error(self):\n return self.lib.carla_get_last_error()\n\n def get_host_osc_url_tcp(self):\n return self.lib.carla_get_host_osc_url_tcp()\n\n def get_host_osc_url_udp(self):\n return self.lib.carla_get_host_osc_url_udp()\n\n def get_buffer_size(self):\n return self.lib.carla_get_buffer_size()\n\n def get_sample_rate(self):\n return self.lib.carla_get_sample_rate()\n\n def nsm_announce(self, url, appName_, pid):\n self.lib.carla_nsm_announce(url.encode(\"utf-8\"), appName_.encode(\"utf-8\"), pid)\n\n def nsm_ready(self):\n self.lib.carla_nsm_ready()\n\n def nsm_reply_open(self):\n self.lib.carla_nsm_reply_open()\n\n def nsm_reply_save(self):\n self.lib.carla_nsm_reply_save()\n","sub_path":"source/carla_backend.py","file_name":"carla_backend.py","file_ext":"py","file_size_in_byte":32744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"406528111","text":"# coding:utf-8\n# Author: aki\n# Date: 2018-09-24 09:56:30\n\n\ntry:\n from urllib.request import urlretrieve\nexcept ImportError:\n from urllib import urlretrieve\n\nfrom akitools import HEADER, filename_norm\nimport requests\nimport os\n\n\nclass Bing(object):\n\n def __init__(self):\n self.path = 'E:/images/bing/'\n if not os.path.exists(self.path):\n os.makedirs(self.path)\n\n def _request(self, url):\n \"\"\"网络请求\"\"\"\n return requests.get(url, headers=HEADER)\n\n def _images(self):\n \"\"\"获取Images列表\"\"\"\n url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&n=10&ensearch=1'\n result = self._request(url)\n return result.json()\n\n def _downImage(self, data):\n \"\"\"下载图片\"\"\"\n title = data['title']\n title = filename_norm(title)\n fileName = self.path + title + '.jpg'\n url = 'https://cn.bing.com{}'.format(data['url'])\n urlretrieve(url, fileName)\n print('Download {}'.format(title))\n\n def main(self):\n images = self._images()['images']\n for image in images:\n self._downImage(image)\n input('')\n\n\nif __name__ == '__main__':\n bing = Bing()\n bing.main()\n","sub_path":"python/bing.py","file_name":"bing.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"180928719","text":"from flask import Flask, request, render_template, redirect, flash, session, Blueprint\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom models import db, User, Watchlist, SavedMovie, Watchlist_Movie\nfrom forms import NewWatchlistForm, EditWatchlistForm, PickWatchlistForMovieForm\nimport json\nfrom flask_login import login_required, current_user\n\nbp_watchlists = Blueprint('bp_watchlists', __name__, template_folder='templates', static_folder='static')\n\n\n################ WATCHLIST HELPER FUNCTIONS #############\n\ndef get_movie_by_nfid(movie):\n # return instance of SavedMovie from database if exists\n # or create new SavedMovie if needed\n dbmovie = SavedMovie.query.filter(SavedMovie.netflix_id == movie.netflix_id).first()\n if dbmovie is not None:\n return dbmovie\n else:\n db.session.add(movie)\n db.session.commit()\n return movie\n \ndef current_user_is_list_owner(list_id):\n # authorize current user is owner of current watchlist\n curr_list = Watchlist.query.get(list_id)\n if curr_list.user_id != current_user.id or current_user.is_anonymous:\n return('Unauthorized action.',403)\n else:\n return True\n\n################### WATCHLIST ROUTES ###################\n\n@bp_watchlists.route('/watchlists')\ndef shared_watchlists():\n watchlists = Watchlist.query.filter_by(is_shared=True).all()\n return render_template('watchlists/watchlists.html', watchlists=watchlists)\n\n@bp_watchlists.route('/pick_watchlist_from_search')\ndef show_picks():\n # render dropdown of user watchlists. uses HTML template without base\n form = PickWatchlistForMovieForm()\n choices = db.session.query(Watchlist.id, Watchlist.title).filter_by(user_id=current_user.id).all()\n form.watchlist.choices = choices\n return render_template('watchlists/my_watchlists_dropdown.html', form=form)\n\n@bp_watchlists.route('/watchlist_add_from_search', methods=['POST'])\ndef add_movie_to_watchlist_from_search():\n list_id = int(request.json['watchlistId'])\n netflix_id = int(request.json['nfid'])\n title = request.json['title']\n video_type = request.json['vtype']\n\n if current_user_is_list_owner(list_id):\n movie_entry = get_movie_by_nfid(SavedMovie(\n netflix_id=netflix_id,\n title=title,\n video_type=video_type,\n ))\n watchlist_entry = Watchlist_Movie(watchlist_id=list_id, movie_id=movie_entry.id)\n try:\n db.session.add(watchlist_entry)\n db.session.commit()\n except:\n db.session.rollback()\n return ('Movie is already in the selected Watchlist.', 202)\n \n return ('Added to your Watchlist!', 200)\n\n@bp_watchlists.route('/watchlists//remove_movie/', methods=['POST'])\ndef remove_movie_from_watchlist(list_id, movie_id):\n if current_user_is_list_owner(list_id):\n watchlist_entry = Watchlist_Movie.query.filter_by(watchlist_id=list_id, movie_id=movie_id).first()\n movie = SavedMovie.query.get(movie_id)\n title = movie.title\n db.session.delete(watchlist_entry)\n db.session.commit()\n flash(f'Removed \"{title}\" from list','warning')\n return redirect(f'/watchlists/{list_id}')\n\n@bp_watchlists.route('/watchlists/')\ndef show_watchlist_detail(list_id):\n # list editing options should be displayed for authorized users\n watchlist = Watchlist.query.get_or_404(list_id)\n if current_user.is_authenticated:\n is_owner = True if watchlist.user_id == current_user.id else False\n else:\n is_owner = False\n return render_template('watchlists/watchlist_detail.html', watchlist=watchlist, is_owner=is_owner)\n\n@bp_watchlists.route('/watchlists/new', methods=['GET','POST'])\n@login_required\ndef new_watchlist():\n form = NewWatchlistForm()\n if form.validate_on_submit():\n watchlist = Watchlist(\n title = form.title.data,\n description = form.description.data,\n is_shared = form.is_shared.data,\n user_id = current_user.id\n )\n db.session.add(watchlist)\n db.session.commit()\n flash(f'Watchlist \"{watchlist.title}\" successfully added','info')\n return redirect('/my_lists')\n else:\n return render_template('watchlists/watchlist_new.html', form=form)\n\n@bp_watchlists.route('/watchlists//delete', methods=['POST'])\n@login_required\ndef delete_watchlist(list_id):\n watchlist = Watchlist.query.get_or_404(list_id)\n title = watchlist.title\n db.session.delete(watchlist)\n db.session.commit()\n flash(f'Watchlist \"{title}\" deleted','warning')\n return redirect(f'/user/{current_user.id}/watchlists')\n\n@bp_watchlists.route('/watchlists//edit', methods=['GET','POST'])\n@login_required\ndef edit_watchlist(list_id):\n watchlist = Watchlist.query.get_or_404(list_id)\n if current_user.id == watchlist.user_id:\n form = EditWatchlistForm(obj=watchlist)\n if form.validate_on_submit():\n watchlist.title = form.title.data\n watchlist.description = form.description.data\n watchlist.is_shared = form.is_shared.data\n db.session.commit()\n flash('Changes successfully made to watchlist','info')\n return redirect(f'/user/{current_user.id}/watchlists')\n return render_template('watchlists/watchlist_edit.html', form=form)\n else:\n return('',403)\n\n@bp_watchlists.route('/user//watchlists')\n@login_required\ndef user_watchlists(user_id):\n if current_user.id == user_id:\n watchlists = Watchlist.query.filter_by(user_id=user_id).all()\n return render_template('user/my_watchlists.html', watchlists=watchlists)\n else:\n return('',403)\n\n@bp_watchlists.route('/my_lists')\n@login_required\ndef redirect_to_user_watchlists():\n return redirect(f'/user/{current_user.id}/watchlists')","sub_path":"bp_watchlists/watchlists.py","file_name":"watchlists.py","file_ext":"py","file_size_in_byte":5929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"240905133","text":"import torch\nfrom efficientnet_pytorch import EfficientNet\nfrom efficientnet_pytorch.utils import load_pretrained_weights, get_model_params, relu_fn\n\n\nclass EfficientNetEncoder(EfficientNet):\n\n def __init__(self, model_name='efficientnet-b0'):\n blocks_args, global_params = get_model_params(model_name, override_params={})\n super().__init__(blocks_args, global_params)\n load_pretrained_weights(self, model_name=model_name, load_fc=True)\n self.model_name = model_name\n\n def extract_features(self, inputs):\n \"\"\" Returns output of the final convolution layer \"\"\"\n\n # Stem\n x = relu_fn(self._bn0(self._conv_stem(inputs)))\n\n # Blocks\n self.output_blocks = []\n for idx, block in enumerate(self._blocks):\n drop_connect_rate = self._global_params.drop_connect_rate\n if drop_connect_rate:\n drop_connect_rate *= float(idx) / len(self._blocks)\n x = block(x, drop_connect_rate=drop_connect_rate)\n self.output_blocks.append(x)\n # Head\n x = relu_fn(self._bn1(self._conv_head(x)))\n\n return self.output_blocks\n\n def forward(self, inputs):\n \"\"\" Calls extract_features to extract features, applies final linear layer, and returns logits. \"\"\"\n\n # Convolution layers\n connecting_layers = self.extract_features(inputs)\n connecting_layers = self._get_correct_connecting_layers(connecting_layers)\n return connecting_layers\n\n def _get_correct_connecting_layers(self, features):\n idxs = {'efficientnet-b0': [0, 2, 4, 10, -1],\n 'efficientnet-b1': [1, 4, 7, 15, -1],\n 'efficientnet-b2': [1, 4, 7, 15, -1],\n 'efficientnet-b3': [1, 4, 7, 17, -1]\n }[self.model_name]\n connecting_layers = [features[idx] for idx in idxs][::-1]\n return connecting_layers\n\n\n\nefficientnet_encoders = {\n 'efficientnet-b0': {\n 'encoder': EfficientNetEncoder,\n 'pretrained_settings': {'imagenet': {}},\n 'out_shapes': (320, 112, 40, 24, 16),\n 'params': {'model_name': 'efficientnet-b0'} # these are called by instantiation of EfficientNetEncoder\n },\n 'efficientnet-b1': {\n 'encoder': EfficientNetEncoder,\n 'pretrained_settings': {'imagenet': {}},\n 'out_shapes': (320, 112, 40, 24, 16),\n 'params': {'model_name': 'efficientnet-b1'} # these are called by instantiation of EfficientNetEncoder\n },\n 'efficientnet-b2': {\n 'encoder': EfficientNetEncoder,\n 'pretrained_settings': {'imagenet': {}},\n 'out_shapes': (352, 120, 48, 24, 16),\n 'params': {'model_name': 'efficientnet-b2'} # these are called by instantiation of EfficientNetEncoder\n },\n 'efficientnet-b3': {\n 'encoder': EfficientNetEncoder,\n 'pretrained_settings': {'imagenet': {}},\n 'out_shapes': (384, 136, 48, 32, 24),\n 'params': {'model_name': 'efficientnet-b3'} # these are called by instantiation of EfficientNetEncoder\n }\n}\n\nif __name__ == '__main__':\n model = EfficientNetEncoder(model_name='efficientnet-b0')\n\n x = torch.rand((11, 3, 256, 256))\n print([block.shape for block in model(x)])\n","sub_path":"segmentation_models_pytorch/encoders/efficient_net.py","file_name":"efficient_net.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"578401058","text":"#! /usr/bin/env python3\n# watch Rick and Morty\nimport os\nimport time\n\ndef safe(pin):\n RickandMorty = list({4, 5, 6, 7, 8, 9, 12, 13, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27})\n if pin in RickandMorty:\n pass\n else:\n print(\"NO..pin\", pin, \"is not safe to use with gpiostate\")\n exit()\ndef export(pin, dir):\n safe(pin)\n AmishCyborg = str(pin)\n if os.path.exists('/sys/class/gpio/gpio' + AmishCyborg) == True:\n #print(\"pin already exported\") # testing\n pass\n else:\n #print(\"exporting pin\") # testing\n MrMeeseeks = ('echo ' + AmishCyborg + ' > /sys/class/gpio/export')\n os.system(MrMeeseeks)\n if dir == \"out\":\n ScaryTerry = ('echo out > /sys/class/gpio/gpio' + AmishCyborg + '/direction')\n if dir == \"in\":\n ScaryTerry = ('echo in > /sys/class/gpio/gpio' + AmishCyborg + '/direction')\n os.system(ScaryTerry)\ndef unexport(pin):\n KingJellybean = str(pin)\n if os.path.exists('/sys/class/gpio/gpio' + KingJellybean) != True:\n #print(\"No pin to unexport there\") # testing\n pass\n else:\n #print(\"unexporting pin\")\n Birdperson = ('echo ' + KingJellybean + ' > /sys/class/gpio/unexport')\n os.system(Birdperson)\ndef read(pin):\n global sysClass, state\n sysClass = '/sys/class/gpio/gpio' + str(pin) + '/value'\n with open(sysClass) as gpState:\n state = int(gpState.read())\ndef write(pin, stateW):\n '''\n Relays are ether LOW=ON, or HIGH=ON,\n so you might need to switch the 1 and 0 to make the library work\n '''\n PrinceNebulon = str(pin)\n if stateW == \"on\":\n TinyRick = (\"echo 1 > /sys/class/gpio/gpio\" + PrinceNebulon + \"/value\")\n os.system(TinyRick)\n if stateW == \"off\":\n PrincipalGeneVagina = (\"echo 0 > /sys/class/gpio/gpio\" + PrinceNebulon + \"/value\")\n os.system(PrincipalGeneVagina)\ndef flip(pin):\n read(pin)\n MortySmith = state\n Snuffles = str(pin)\n if MortySmith == 0:\n AbradolfLincler = (\"echo 1 > /sys/class/gpio/gpio\" + Snuffles + \"/value\")\n os.system(AbradolfLincler)\n if MortySmith == 1:\n Gearhead = (\"echo 0 > /sys/class/gpio/gpio\" + Snuffles + \"/value\")\n os.system(Gearhead)\ndef flash(pin, dur, times):\n ScroopyNoopers = str(pin)\n KingFlippyNips = int(times)\n Gazorpazorpfield = int(dur)\n for x in range(0, KingFlippyNips):\n JerrySmith = (\"echo 0 > /sys/class/gpio/gpio\" + ScroopyNoopers + \"/value\")\n os.system(JerrySmith)\n time.sleep(Gazorpazorpfield)\n RickSanchez = (\"echo 1 > /sys/class/gpio/gpio\" + ScroopyNoopers + \"/value\")\n os.system(RickSanchez)\n time.sleep(Gazorpazorpfield)\ndef wait(pin):\n read(pin)\n Squanchy = state\n while True:\n time.sleep(0.002)\n read(pin)\n KrombopulosMichael = state\n if Squanchy != KrombopulosMichael:\n break\n\n","sub_path":"gpiostate.py","file_name":"gpiostate.py","file_ext":"py","file_size_in_byte":2920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"582056948","text":"\"\"\"Prepares a distribution for installation\n\"\"\"\n\nimport logging\nimport os\n\nfrom pip._vendor import requests\n\nfrom pip._internal.distributions import (\n make_distribution_for_install_requirement,\n)\nfrom pip._internal.distributions.installed import InstalledDistribution\nfrom pip._internal.download import (\n is_dir_url, is_file_url, is_vcs_url, unpack_url, url_to_path,\n)\nfrom pip._internal.exceptions import (\n DirectoryUrlHashUnsupported, HashUnpinned, InstallationError,\n PreviousBuildDirError, VcsHashUnsupported,\n)\nfrom pip._internal.utils.compat import expanduser\nfrom pip._internal.utils.hashes import MissingHashes\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import display_path, normalize_path\nfrom pip._internal.utils.typing import MYPY_CHECK_RUNNING\n\nif MYPY_CHECK_RUNNING:\n from typing import Optional\n\n from pip._internal.distributions import AbstractDistribution\n from pip._internal.download import PipSession\n from pip._internal.index import PackageFinder\n from pip._internal.req.req_install import InstallRequirement\n from pip._internal.req.req_tracker import RequirementTracker\n\nlogger = logging.getLogger(__name__)\n\n\nclass RequirementPreparer(object):\n \"\"\"Prepares a Requirement\n \"\"\"\n\n def __init__(\n self,\n build_dir, # type: str\n download_dir, # type: Optional[str]\n src_dir, # type: str\n wheel_download_dir, # type: Optional[str]\n progress_bar, # type: str\n build_isolation, # type: bool\n req_tracker # type: RequirementTracker\n ):\n # type: (...) -> None\n super(RequirementPreparer, self).__init__()\n\n self.src_dir = src_dir\n self.build_dir = build_dir\n self.req_tracker = req_tracker\n\n # Where still packed archives should be written to. If None, they are\n # not saved, and are deleted immediately after unpacking.\n self.download_dir = download_dir\n\n # Where still-packed .whl files should be written to. If None, they are\n # written to the download_dir parameter. Separate to download_dir to\n # permit only keeping wheel archives for pip wheel.\n if wheel_download_dir:\n wheel_download_dir = normalize_path(wheel_download_dir)\n self.wheel_download_dir = wheel_download_dir\n\n # NOTE\n # download_dir and wheel_download_dir overlap semantically and may\n # be combined if we're willing to have non-wheel archives present in\n # the wheelhouse output by 'pip wheel'.\n\n self.progress_bar = progress_bar\n\n # Is build isolation allowed?\n self.build_isolation = build_isolation\n\n @property\n def _download_should_save(self):\n # type: () -> bool\n # TODO: Modify to reduce indentation needed\n if self.download_dir:\n self.download_dir = expanduser(self.download_dir)\n if os.path.exists(self.download_dir):\n return True\n else:\n logger.critical('Could not find download directory')\n raise InstallationError(\n \"Could not find or access download directory '%s'\"\n % display_path(self.download_dir))\n return False\n\n def prepare_linked_requirement(\n self,\n req, # type: InstallRequirement\n session, # type: PipSession\n finder, # type: PackageFinder\n upgrade_allowed, # type: bool\n require_hashes # type: bool\n ):\n # type: (...) -> AbstractDistribution\n \"\"\"Prepare a requirement that would be obtained from req.link\n \"\"\"\n # TODO: Breakup into smaller functions\n if req.link and req.link.scheme == 'file':\n path = url_to_path(req.link.url)\n logger.info('Processing %s', display_path(path))\n else:\n logger.info('Collecting %s', req)\n\n with indent_log():\n # @@ if filesystem packages are not marked\n # editable in a req, a non deterministic error\n # occurs when the script attempts to unpack the\n # build directory\n req.ensure_has_source_dir(self.build_dir)\n # If a checkout exists, it's unwise to keep going. version\n # inconsistencies are logged later, but do not fail the\n # installation.\n # FIXME: this won't upgrade when there's an existing\n # package unpacked in `req.source_dir`\n # package unpacked in `req.source_dir`\n if os.path.exists(os.path.join(req.source_dir, 'setup.py')):\n raise PreviousBuildDirError(\n \"pip can't proceed with requirements '%s' due to a\"\n \" pre-existing build directory (%s). This is \"\n \"likely due to a previous installation that failed\"\n \". pip is being responsible and not assuming it \"\n \"can delete this. Please delete it and try again.\"\n % (req, req.source_dir)\n )\n req.populate_link(finder, upgrade_allowed, require_hashes)\n\n # We can't hit this spot and have populate_link return None.\n # req.satisfied_by is None here (because we're\n # guarded) and upgrade has no impact except when satisfied_by\n # is not None.\n # Then inside find_requirement existing_applicable -> False\n # If no new versions are found, DistributionNotFound is raised,\n # otherwise a result is guaranteed.\n assert req.link\n link = req.link\n\n # Now that we have the real link, we can tell what kind of\n # requirements we have and raise some more informative errors\n # than otherwise. (For example, we can raise VcsHashUnsupported\n # for a VCS URL rather than HashMissing.)\n if require_hashes:\n # We could check these first 2 conditions inside\n # unpack_url and save repetition of conditions, but then\n # we would report less-useful error messages for\n # unhashable requirements, complaining that there's no\n # hash provided.\n if is_vcs_url(link):\n raise VcsHashUnsupported()\n elif is_file_url(link) and is_dir_url(link):\n raise DirectoryUrlHashUnsupported()\n if not req.original_link and not req.is_pinned:\n # Unpinned packages are asking for trouble when a new\n # version is uploaded. This isn't a security check, but\n # it saves users a surprising hash mismatch in the\n # future.\n #\n # file:/// URLs aren't pinnable, so don't complain\n # about them not being pinned.\n raise HashUnpinned()\n\n hashes = req.hashes(trust_internet=not require_hashes)\n if require_hashes and not hashes:\n # Known-good hashes are missing for this requirement, so\n # shim it with a facade object that will provoke hash\n # computation and then raise a HashMissing exception\n # showing the user what the hash should be.\n hashes = MissingHashes()\n\n try:\n download_dir = self.download_dir\n # We always delete unpacked sdists after pip ran.\n autodelete_unpacked = True\n if req.link.is_wheel and self.wheel_download_dir:\n # when doing 'pip wheel` we download wheels to a\n # dedicated dir.\n download_dir = self.wheel_download_dir\n if req.link.is_wheel:\n if download_dir:\n # When downloading, we only unpack wheels to get\n # metadata.\n autodelete_unpacked = True\n else:\n # When installing a wheel, we use the unpacked\n # wheel.\n autodelete_unpacked = False\n unpack_url(\n req.link, req.source_dir,\n download_dir, autodelete_unpacked,\n session=session, hashes=hashes,\n progress_bar=self.progress_bar\n )\n except requests.HTTPError as exc:\n logger.critical(\n 'Could not install requirement %s because of error %s',\n req,\n exc,\n )\n raise InstallationError(\n 'Could not install requirement %s because of HTTP '\n 'error %s for URL %s' %\n (req, exc, req.link)\n )\n abstract_dist = make_distribution_for_install_requirement(req)\n with self.req_tracker.track(req):\n abstract_dist.prepare_distribution_metadata(\n finder, self.build_isolation,\n )\n if self._download_should_save:\n # Make a .zip of the source_dir we already created.\n if not req.link.is_artifact:\n req.archive(self.download_dir)\n return abstract_dist\n\n def prepare_editable_requirement(\n self,\n req, # type: InstallRequirement\n require_hashes, # type: bool\n use_user_site, # type: bool\n finder # type: PackageFinder\n ):\n # type: (...) -> AbstractDistribution\n \"\"\"Prepare an editable requirement\n \"\"\"\n assert req.editable, \"cannot prepare a non-editable req as editable\"\n\n logger.info('Obtaining %s', req)\n\n with indent_log():\n if require_hashes:\n raise InstallationError(\n 'The editable requirement %s cannot be installed when '\n 'requiring hashes, because there is no single file to '\n 'hash.' % req\n )\n req.ensure_has_source_dir(self.src_dir)\n req.update_editable(not self._download_should_save)\n\n abstract_dist = make_distribution_for_install_requirement(req)\n with self.req_tracker.track(req):\n abstract_dist.prepare_distribution_metadata(\n finder, self.build_isolation,\n )\n\n if self._download_should_save:\n req.archive(self.download_dir)\n req.check_if_exists(use_user_site)\n\n return abstract_dist\n\n def prepare_installed_requirement(\n self,\n req, # type: InstallRequirement\n require_hashes, # type: bool\n skip_reason # type: str\n ):\n # type: (...) -> AbstractDistribution\n \"\"\"Prepare an already-installed requirement\n \"\"\"\n assert req.satisfied_by, \"req should have been satisfied but isn't\"\n assert skip_reason is not None, (\n \"did not get skip reason skipped but req.satisfied_by \"\n \"is set to %r\" % (req.satisfied_by,)\n )\n logger.info(\n 'Requirement %s: %s (%s)',\n skip_reason, req, req.satisfied_by.version\n )\n with indent_log():\n if require_hashes:\n logger.debug(\n 'Since it is already installed, we are trusting this '\n 'package without checking its hash. To ensure a '\n 'completely repeatable environment, install into an '\n 'empty virtualenv.'\n )\n abstract_dist = InstalledDistribution(req)\n\n return abstract_dist\n","sub_path":"toolchain/riscv/MSYS/python/Lib/site-packages/pip/_internal/operations/prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":11728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"608743502","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# File : convert_txt_to_xls.py\n# Author : bssthu\n# Project : eso_zh_ui\n# Description : 将 .txt 文件转换为TAB分隔的文本,准备导入Excel\n# \n\n\nimport getopt\nimport os\nimport sys\nfrom utils import read_lua, read_translate_txt\n\n\ndef main():\n lang = 'zh'\n\n # getopt\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'l:')\n except getopt.GetoptError as e:\n print(e)\n sys.exit(2)\n for o, a in opts:\n if o == '-l':\n lang = a\n\n cd = sys.path[0]\n translation_path = os.path.join(cd, '../translation')\n dest_path = translation_path\n\n # load translation\n name_translation = {}\n translate_file = os.path.join(translation_path, '%s_translate.txt' % lang)\n read_translate_txt(translate_file, name_translation)\n\n # convert\n csv_xls_file = os.path.join(dest_path, '%s_translate.csv' % lang)\n convert(translate_file, csv_xls_file, name_translation)\n\n\ndef convert(src_file, dest_file, name_translation):\n # merge translation & save str file\n name_values = {}\n read_lua(src_file, name_values)\n\n count_total = 0\n count_translated = 0\n header = '编号\\t名称\\t原文\\t译文\\t初翻人员\\t校对\\t润色\\t备注\\n'\n with open(dest_file, 'wt', encoding='utf-8') as fp:\n fp.writelines(header)\n for name, (origin_text, version) in sorted(name_values.items()):\n count_total += 1\n # 原文、翻译文本\n if name in name_translation:\n count_translated += 1\n # apply translation\n trans_text = name_translation[name]\n else:\n trans_text = ''\n # 初翻、校对、润色\n translator = ''\n proofreader = ''\n refiner = ''\n comments = ''\n fp.write('\\t'.join(('UI-%d' % count_total, name, origin_text, trans_text,\n translator, proofreader, refiner, comments)) + '\\n')\n print('%d/%d translated in %s.' % (count_translated, count_total, dest_file))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/convert_txt_to_xls.py","file_name":"convert_txt_to_xls.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"339923445","text":"from flask import render_template, request, session, flash, redirect, url_for\nfrom PSAPDB import app, FCCDB\nfrom fccDatabase import UserModel, PsapModel\nfrom functools import wraps\nimport pymongo\nfrom mongokit import paginator\nfrom geocodio import GeocodioClient\nfrom PSAPDB import geoClient\n\n###########\n## FLASK functions for all the web pages\n###########\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\n\treturn render_template('index.html')\n\ndef login_required(test): \n\t@wraps(test)\n\tdef wrap(*args, **kwargs):\n\t\tif 'logged_in' in session:\n\t\t\treturn test(*args, **kwargs) \n\t\telse:\n\t\t\tflash('You need to login first.')\n\t\t\treturn redirect(url_for('login'))\n\treturn wrap\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login(message=\"\"):\n\tif 'message' in request.args:\n\t\treturn render_template('login.html', target='verify', message=request.args['message'])\n\treturn render_template('login.html', target='verify', message=\"\")\n\n@app.route('/verify', methods=['GET', 'POST'])\ndef verify():\n\temail = request.form['email']\n\tpassword = request.form['password']\n\n\tif not('email' in request.args) and ('password' in request.args):\n\t\treturn redirect(url_for('login', message='email or password missing'))\n\n\tif verify_password(email, password) == False:\n\t\treturn redirect(url_for('login', message='email or password wrong'))\n\n\tuser = FCCDB.UserModel.find({'email':email})\n\tfixedUser = fixCursor(user) \n\t\n\n\tsession['logged_in'] = True\n\tsession['email'] = email\n\tsession['read_access'] = fixedUser[0]['read_access']\n\tsession['write_access'] = fixedUser[0]['write_access']\n\tsession['subscription'] = fixedUser[0]['subscription']\n\n\treturn redirect(url_for('main'))\n\ndef verify_password(username, password):\n\t\tuser = FCCDB.UserModel.find_one({'email':unicode(username)});\n\t\t\n\t\t#hashed password for production\n\n\t\tif not user or not user.verifyPassSimp(password):\n\t\t#\tif not user or not user.verify_password(password):\n\t\t\treturn False \n\t\treturn True\n\n@app.route('/main')\n@login_required\ndef main():\n\tadminUser = False\n\n\tif ('all' in session['read_access'] ):\n\t\tadminUser = True\n\n\treturn render_template('main.html', email=session['email'], adminUser=adminUser)\n\n@app.route('/list', methods=['GET'])\n@login_required\ndef list():\n\temail=session['email']\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\n\tif ('all' in session['read_access'] ):\n\t\tdataList = FCCDB.PsapModel.find()\n\t\tcounter = FCCDB.PsapModel.find().count()\n\t\tadminUser = True\n\telse:\n\t\tdataList = FCCDB.PsapModel.find({'PSAP ID':{'$in': [int(i) for i in session['read_access']]}})\n\t\tcounter = FCCDB.PsapModel.find({'PSAP ID':{'$in': [int(i) for i in session['read_access']]}}).count()\n\n\tdataListSorted = dataList.sort('PSAP ID', pymongo.ASCENDING)\n\n\tif ((( int(request.args['page'])-1)* 10) > int(counter) ):\n\t\treturn page_not_found('500')\n\tpageSource = paginator.Paginator(dataListSorted, request.args['page'], 10)\n\n\treturn render_template('list.html', dataList= fixCursor(dataListSorted), email = email, pgSource=pageSource, adminUser=adminUser)\n\n\n@app.route('/logout')\ndef logout():\n\tsession.pop('logged_in', None)\n\tsession.pop('email', None)\n\tsession.pop('read_access', None)\n\tsession.pop('write_access', None)\n\treturn redirect(url_for('index'))\n\n@app.errorhandler(400)\n@app.errorhandler(404)\n@app.errorhandler(500)\ndef page_not_found(error):\n\t\treturn render_template('error.html', errorMessage = ('Error '+str(error)+': Sorry, that was a BAD request.'))\n\ndef error(error):\n\treturn render_template('error.html', errorMessage=error)\n\n@app.route('/delete', methods=['GET', 'DELETE'])\n@login_required\ndef delete():\n\n\temail=session['email']\n\ttemp = 0\n\n\tif ('psapid' in request.args):\n\t\tdeleteNode = FCCDB.PsapModel.find({'PSAP ID':int(request.args['psapid'])})\n\t\ttemp = deleteNode[0]\n\t\tdeleteNode[0].delete()\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\n\tif ('all' in session['write_access'] ):\n\t\tdataList = FCCDB.PsapModel.find()\n\t\tcounter = FCCDB.PsapModel.find().count()\n\t\tadminUser = True\n\n\telse:\t\n\t\tdataList = FCCDB.PsapModel.find({'PSAP ID':{'$in': [int(i) for i in session['write_access']]}})\n\t\tcounter = FCCDB.PsapModel.find({'PSAP ID':{'$in': [int(i) for i in session['write_access']]}}).count()\n\n\tdataListSorted = dataList.sort('PSAP ID', pymongo.ASCENDING)\n\t\n\tif ((( int(request.args['page'])-1)* 10) > int(counter) ):\n\t\treturn page_not_found('500')\n\t\n\tpageSource = paginator.Paginator(dataListSorted, request.args['page'], 10)\n\n\treturn render_template('delete.html', dataList= fixCursor(dataListSorted), email = email, pgSource=pageSource, deleted=temp, adminUser=adminUser)\n\n@app.route('/modify', methods=['GET', 'PUT'])\n@login_required\ndef modify():\n\tf = 0\n\tv1 = 0\n\tv2 = 0\n\tpsapHolder = 0\n\tif ('psapid' in request.args):\n\t\t# modifyNode = FCCDB.PsapModel.find({'PSAP ID':int(request.args['psapid'])})\n\t\tmodifyNode = FCCDB.PsapModel.find_one({'PSAP ID':int(request.args['psapid'])})\n\t\tpsapHolder = request.args['psapid']\n\t\t# temp = modifyNode[0]\n\n\t\tif 'pName' in request.args:\n\t\t\tv1 = modifyNode['PSAP Name']\n\t\t\tv2 = unicode(request.args['pName'])\n\t\t\tmodifyNode['PSAP Name'] = unicode(request.args['pName'])\n\t\t\tmodifyNode.save()\n\t\t\tf = 'PSAP Name'\n\t\tif 'state' in request.args:\n\t\t\tv1 = modifyNode['State']\n\t\t\tv2 = unicode(request.args['state'])\t\t\t\n\t\t\tmodifyNode['State'] = unicode(request.args['state'])\n\t\t\tf = 'State'\n\t\t\tmodifyNode.save()\n\t\tif 'county' in request.args:\n\t\t\tv1 = modifyNode['County']\n\t\t\tv2 = unicode(request.args['county'])\t\t\t\n\t\t\tmodifyNode['County'] = request.args['county']\n\t\t\tf = 'County'\n\t\t\tmodifyNode.save()\n\t\tif 'city' in request.args:\n\t\t\tv1 = modifyNode['City']\n\t\t\tv2 = unicode(request.args['city'])\t\t\t\n\t\t\tmodifyNode['City'] = request.args['city']\n\t\t\tf = 'City'\n\t\t\tmodifyNode.save()\n\t\tif 'toc' in request.args:\n\t\t\tv1 = modifyNode['Type of Change']\n\t\t\tv2 = unicode(request.args['toc'])\n\t\t\tmodifyNode['Type of Change'] = request.args['toc']\n\t\t\tf = 'Type of Change'\n\t\t\tmodifyNode.save()\n\t\tif 'comments' in request.args:\n\t\t\tv1 = modifyNode['Comments']\n\t\t\tv2 = unicode(request.args['comments'])\n\t\t\tmodifyNode['Comments'] = request.args['comments']\n\t\t\tf = 'Comments'\n\t\t\tmodifyNode.save()\n\t\tif 'text2911' in request.args:\n\t\t\tv1 = modifyNode['Text to 911']\n\t\t\tv2 = unicode(request.args['text2911'])\n\t\t\tmodifyNode['Text to 911'] = request.args['text2911']\n\t\t\tf = 'Text to 911'\n\t\t\tmodifyNode.save()\n\t\tif 'psapcontact' in request.args:\n\t\t\tv1 = modifyNode['PSAP Contact']\n\t\t\tv2 = unicode(request.args['psapcontact'])\n\t\t\tmodifyNode['PSAP Contact'] = request.args['psapcontact']\n\t\t\tf = 'PSAP Contact'\n\t\t\tmodifyNode.save()\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\n\tif ('all' in session['write_access'] ):\n\t\tdataList = FCCDB.PsapModel.find()\n\t\tcounter = FCCDB.PsapModel.find().count()\n\t\tadminUser = True\n\telse:\t\n\t\tdataList = FCCDB.PsapModel.find({'PSAP ID':{'$in': [int(i) for i in session['write_access']]}})\n\t\tcounter = FCCDB.PsapModel.find({'PSAP ID':{'$in': [int(i) for i in session['write_access']]}}).count()\n\n\tdataListSorted = dataList.sort('PSAP ID', pymongo.ASCENDING)\n\n\tif ((( int(request.args['page'])-1)* 10) > int(counter) ):\n\t\treturn page_not_found('500')\n\t\n\tpageSource = paginator.Paginator(dataListSorted, request.args['page'], 10)\n\n\treturn render_template('modify.html', dataList= fixCursor(dataListSorted), email = session['email'], pgSource=pageSource, cItem=f, v1=v1, v2=v2, psapidNum=psapHolder, adminUser=adminUser)\n\n\n@app.route('/search', methods=['GET'])\n@login_required\ndef search():\n\n\temail=session['email']\n\tsearch = False\n\ttemp = 0\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\tsearchResult = False\n\tsearchQuery=''\n\tf =''\n\n\tdataList = FCCDB.PsapModel.find()\n\tcounter = FCCDB.PsapModel.find().count()\n\n\tif ('all' in session['write_access'] ):\n\t\tadminUser = True\n\n\tif ('psapid' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'PSAP ID':int(request.args['psapid'])})\n\t\tcounter = FCCDB.PsapModel.find({'PSAP ID':int(request.args['psapid'])}).count()\n\t\tf = 'PSAP ID'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['psapid']\n\n\tif ('psapname' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'PSAP Name':unicode(request.args['psapname'])})\n\t\tcounter = FCCDB.PsapModel.find({'PSAP Name':unicode(request.args['psapname'])}).count()\n\t\tf = 'PSAP Name'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['psapname']\n\n\tif ('state' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'State':unicode(request.args['state'])})\n\t\tcounter = FCCDB.PsapModel.find({'State':unicode(request.args['state'])}).count()\n\t\tf = 'State'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['state']\n\n\tif ('county' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'County':unicode(request.args['county'])})\n\t\tcounter = FCCDB.PsapModel.find({'County':unicode(request.args['county'])}).count()\n\t\tf = 'County'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['county']\n\n\tif ('city' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'City':unicode(request.args['city'])})\n\t\tcounter = FCCDB.PsapModel.find({'City':unicode(request.args['city'])}).count()\n\t\tf = 'City'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['city']\n\n\tif ('toc' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'Type of Change':unicode(request.args['toc'])})\n\t\tcounter = FCCDB.PsapModel.find({'Type of Change':unicode(request.args['toc'])}).count()\n\t\tf = 'Type of Change'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['toc']\n\n\tif ('comments' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'Comments':unicode(request.args['comments'])})\n\t\tcounter = FCCDB.PsapModel.find({'Comments':unicode(request.args['comments'])}).count()\n\t\tf = 'Comments'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['comments']\n\n\tif ('text2911' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'Text to 911':unicode(request.args['text2911'])})\n\t\tcounter = FCCDB.PsapModel.find({'Text to 911':unicode(request.args['text2911'])}).count()\n\t\tf = 'Text to 911'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['text2911']\n\n\tif ('psapcontact' in request.args):\n\t\tdataList = FCCDB.PsapModel.find({'PSAP Contact':unicode(request.args['psapcontact'])})\n\t\tcounter = FCCDB.PsapModel.find({'PSAP Contact':unicode(request.args['psapcontact'])}).count()\n\t\tf = 'PSAP Contact'\n\t\tsearchResult = True\n\t\tsearchQuery = request.args['psapcontact']\n\n\n\tdataListSorted = dataList.sort('PSAP ID', pymongo.ASCENDING)\n\n\treturn render_template('search.html', dataList= fixCursor(dataListSorted), email = email, searchResult =searchResult, searchCategory=f, searchQuery=searchQuery, adminUser=adminUser, number= counter)\n\n@app.route('/subscribe', methods=['GET', 'POST'])\n@login_required\ndef subscribe():\n\n\n\temail=session['email']\n\ttemp = 0\n\tsubsNode = 0\n\tpsapinfo = 0;\n\t\n\n\tif ('psapid' in request.args):\n\t\tsubsNode = FCCDB.UserModel.find_one({'email':email})\n\t\ttemp = subsNode\n\t\tsubsNode.addSub('11')\n\t\tsubsNode['subscription'].append(unicode('11'))\n\t\tsubsNode.save()\n\t\tpsapinfo=unicode(request.args['psapid'])\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\n\tif ('all' in session['read_access'] ):\n\t\tdataList = FCCDB.PsapModel.find()\n\t\tcounter = FCCDB.PsapModel.find().count()\n\t\tadminUser = True\n\n\telse:\t\n\t\tdataList = FCCDB.PsapModel.find({'PSAP ID':{'$in': [int(i) for i in session['read_access']]}})\n\t\tcounter = FCCDB.PsapModel.find({'PSAP ID':{'$in': [int(i) for i in session['read_access']]}}).count()\n\n\tdataListSorted = dataList.sort('PSAP ID', pymongo.ASCENDING)\n\n\tif ((( int(request.args['page'])-1)* 10) > int(counter) ):\n\t\treturn page_not_found('500')\n\t\n\tpageSource = paginator.Paginator(dataListSorted, request.args['page'], 10)\n\n\treturn render_template('subscribe.html', dataList= fixCursor(dataListSorted), email = email, pgSource=pageSource, subscribed=temp, subscription=session['subscription'], subscribedNode=psapinfo, adminUser=adminUser)\n\n\n@app.route('/addpsap', methods=['GET', 'POST'])\n@login_required\ndef addpsap():\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\tadded = 0\n\n\tif ('all' in session['read_access'] ):\n\t\tdataList = FCCDB.UserModel.find()\n\t\tcounter = FCCDB.UserModel.find().count()\n\t\tadminUser = True\n\n\tif (request.form):\n\n\t\tnewPsap = FCCDB.PsapModel()\n\t\tnewPsap['PSAP ID'] = int(request.form['psapid'])\n\t\tnewPsap['PSAP Name'] = request.form['psapname']\n\t\tnewPsap['State'] = request.form['state']\n\t\tnewPsap['County'] = request.form['county']\n\t\tnewPsap['City'] = request.form['city']\n\t\tnewPsap['Type of Change'] = request.form['toc']\n\t\tnewPsap['Comments'] = request.form['comments']\n\t\tnewPsap['Text to 911'] = request.form['text2911']\n\t\tnewPsap['PSAP Contact'] = request.form['psapcontact']\n\t\tnewPsap.save()\n\t\tadded = request.form['psapid'] \n\n\treturn render_template('addpsap.html', adminUser= adminUser, added=added )\n\n\n@app.route('/addUser', methods=['GET', 'POST'])\n@login_required\ndef addUser():\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\tadded = 0\n\trd = []\n\twd = []\n\n\tif ('all' in session['read_access'] ):\n\t\tdataList = FCCDB.UserModel.find()\n\t\tcounter = FCCDB.UserModel.find().count()\n\t\tadminUser = True\n\telse:\n\t\treturn error( \"YOU ARE NOT AUTHORIZED FOR THIS PAGE\")\n\n\tif (request.form):\n\t\tnewUser = FCCDB.UserModel()\n\t\tnewUser.email = request.form['email']\n\t\t#hash the password for production\n\t\tnewUser.password = request.form['password']\n\t\t#newUser.password = hash_password(request.form['password'])\n\n\t\trd.append(request.form['read_access'])\n\t\twd.append(request.form['write_access'])\n\t\tnewUser.read_access = rd\n\t\tnewUser.write_access = wd\n\t\tnewUser.save()\n\t\tadded = request.form['email'] \n\n\treturn render_template('addUser.html', adminUser= adminUser, added=added )\n\n@app.route('/listUser', methods=['GET'])\n@login_required\ndef listUser():\n\temail=session['email']\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\n\tif ('all' in session['read_access'] ):\n\t\tdataList = FCCDB.UserModel.find()\n\t\tcounter = FCCDB.UserModel.find().count()\n\t\tadminUser = True\n\telse:\n\t\treturn error( \"YOU ARE NOT AUTHORIZED FOR THIS PAGE\")\n\t\n\n\tdataListSorted = dataList.sort('registered', pymongo.ASCENDING)\n\n\tif ((( int(request.args['page'])-1)* 10) > int(counter) ):\n\t\treturn page_not_found('500')\n\tpageSource = paginator.Paginator(dataListSorted, request.args['page'], 10)\n\n\treturn render_template('listUser.html', dataList= fixCursor(dataListSorted), email = email, pgSource=pageSource, adminUser=adminUser)\n\n\n@app.route('/modifyUser', methods=['GET', 'POST'])\n@login_required\ndef modifyUser():\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\n\tif ('all' in session['read_access'] ):\n\t\tdataList = FCCDB.UserModel.find()\n\t\tcounter = FCCDB.UserModel.find().count()\n\t\tadminUser = True\n\telse:\n\t\treturn error( \"YOU ARE NOT AUTHORIZED FOR THIS PAGE\")\n\n\tf = 0\n\tv1 = 0\n\tv2 = 0\n\tuserHolder = 0\n\tif ('email' in request.args):\n\t\tmodifyNode = FCCDB.UserModel.find_one({'email':unicode(request.args['email'])})\n\t\tuserHolder = request.args['email']\n\t\t\n\t\tif 'read_access' in request.args:\n\t\t\tv1 = modifyNode['read_access']\n\t\t\tv2 = unicode(request.args['read_access'])\n\n\t\t\tmodifyNode['read_access'] = unicode(request.args['read_access'])\n\t\t\tmodifyNode.save()\n\t\t\tf = 'PSAP Name'\n\n\t\tif 'write_access' in request.args:\n\t\t\tv1 = modifyNode['write_access']\n\t\t\tv2 = unicode(request.args['write_access'])\t\t\t\n\t\t\tmodifyNode['write_access'] = unicode(request.args['write_access'])\n\t\t\tf = 'Write Access'\n\t\t\tmodifyNode.save()\n\n\n\tdataList = FCCDB.UserModel.find()\n\tcounter = FCCDB.UserModel.find().count()\n\n\tdataListSorted = dataList.sort('PSAP ID', pymongo.ASCENDING)\n\n\tif ((( int(request.args['page'])-1)* 10) > int(counter) ):\n\t\treturn page_not_found('500')\n\t\n\tpageSource = paginator.Paginator(dataListSorted, request.args['page'], 10)\n\n\treturn render_template('modifyUser.html', dataList= fixCursor(dataListSorted), email = session['email'], pgSource=pageSource, cItem=f, v1=v1, v2=v2, psapidNum=userHolder, adminUser=adminUser)\n\n@app.route('/deleteUser', methods=['GET', 'DELETE'])\n@login_required\ndef deleteUser():\n\n\tdataList = 0;\n\tcounter = 0\n\tadminUser = False\n\n\tif ('all' in session['read_access'] ):\n\t\tdataList = FCCDB.UserModel.find()\n\t\tcounter = FCCDB.UserModel.find().count()\n\t\tadminUser = True\n\telse:\n\t\treturn error( \"YOU ARE NOT AUTHORIZED FOR THIS PAGE\")\n\n\n\temail=session['email']\n\ttemp = 0\n\n\tif ('email' in request.args):\n\t\tdeleteNode = FCCDB.UserModel.find({'email':unicode(request.args['email'])})\n\t\ttemp = deleteNode[0]\n\t\tdeleteNode[0].delete()\n\n\telse:\t\n\t\tdataList = FCCDB.UserModel.find()\n\t\tcounter = FCCDB.UserModel.find().count()\n\n\tdataListSorted = dataList.sort('PSAP ID', pymongo.ASCENDING)\n\n\tif ((( int(request.args['page'])-1)* 10) > int(counter) ):\n\t\treturn page_not_found('500')\n\t\n\tpageSource = paginator.Paginator(dataListSorted, request.args['page'], 10)\n\n\treturn render_template('deleteUser.html', dataList= fixCursor(dataListSorted), email = email, pgSource=pageSource, deleted=temp, adminUser=adminUser)\n\n# geocoding function\ndef geoCode(county, city, state):\n\n\taddress = str(county) + ' ' + str(city) + ' ' + str(state)\n\tgeoLocation = geoClient.geocode(address)\n\n\treturn geoLocation\n\n\n# sort columns\n\ndef sortColumn(dataList, sortby):\n\n\tdataListSorted = dataList.sort(str(sortby, pymongo.ASCENDING)\t)\n\n\treturn dataListSorted\n\n\ndef fixCursor(data):\n\tjsonData = []\n\tfor doc in data:\n\t\tjsonData.append(doc)\t\n\n\treturn jsonData","sub_path":"source code/PSAPDB/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"93706696","text":"import pickle\nimport json\n\nstuff = ['test1', 'test2']\nstuff_dict = {'name': 'Doug', 'age:': 49}\n\n# write items in list one at a time\nwith open('write_test.txt', 'w') as text:\n for item in stuff:\n text.write(f'{item}\\n')\n # text.write(f'{item}, ')\n\n# write txt file as a list. i.e. ['test1', 'test2']\nwith open('write_test_2.txt', 'w') as text:\n text.writelines(f'{stuff}\\n')\n\n# use pickle to write list as binary file (not human readable)\nwith open('pickle test.data', 'wb') as dill:\n pickle.dump(stuff, dill)\n\n# use pickle to read above created file back into a new list.\n# note that 'new_stuff' did not need to be declared as a list object\nwith open('pickle test.data', 'rb') as dilly:\n new_stuff = pickle.load(dilly)\n\nprint(f'Pickle data: {new_stuff}')\nprint(f'Pickle type: {type(new_stuff)}')\n\n# as json file\nwith open('test.json', 'w') as text:\n json.dump(stuff_dict, text)\n\n# read back in json data\nwith open('test.json') as text:\n new_stuff_dict = json.load(text)\n\nprint(f'json read: {new_stuff}')\nprint(new_stuff_dict)\n\nprint('cool')\nprint('Yes it is')\nprint('WHo did than?')\n","sub_path":"file write test.py","file_name":"file write test.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"479026489","text":"import json\n\n\ndef return_code(code, body):\n \"\"\"Returns a JSON response\n\n :param (int) code: The HTTP response code\n :param (dict) body: The data to return\n\n :return: A JSON object containing the code and body\n :rtype: dict\n \"\"\"\n return {\n \"statusCode\": code,\n \"body\": json.dumps(body)\n }\n","sub_path":"src/python/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"272300285","text":"import logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\ndef logged(func, level=logging.INFO):\n\n def wrap(*args, **kwargs):\n fqn = \"\"\n if func.__module__ is not None:\n fqn += func.__module__ + \".\"\n if func.__class__ is not None:\n fqn += func.__class__.__name__ + \".\"\n fqn += func.__name__ + \"( \" + repr(kwargs) + \" )\"\n logging.log(level, \"going go call %s\", fqn)\n func(*args, **kwargs)\n logging.log(level, \"%s was called without errors\", fqn)\n\n return wrap","sub_path":"morphdepot/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"594343412","text":"#Pong game written in Python by Jermaine Simon Davies\r\n\r\nimport turtle\r\n\r\nwn = turtle.Screen()\r\nwn.title(\"Pink Pong by @jermainedavies\")\r\nwn.bgcolor(\"black\")\r\nwn.setup(width=800, height=600)\r\nwn.tracer(0)\r\n\r\n#Scorekeeping\r\nscore_1 = 0\r\nscore_2 = 0\r\n\r\n\r\n#Padde 1\r\npaddle_1 = turtle.Turtle()\r\npaddle_1.speed(0)\r\npaddle_1.shape(\"square\")\r\npaddle_1.color(\"pink\")\r\npaddle_1.shapesize(stretch_wid=5, stretch_len=1)\r\npaddle_1.penup()\r\npaddle_1.goto(-350, 0)\r\n\r\n\r\n\r\n#Paddle 2\r\npaddle_2 = turtle.Turtle()\r\npaddle_2.speed(0)\r\npaddle_2.shape(\"square\")\r\npaddle_2.color(\"pink\")\r\npaddle_2.shapesize(stretch_wid=5, stretch_len=1)\r\npaddle_2.penup()\r\npaddle_2.goto(350, 0)\r\n\r\n#Ball\r\nball = turtle.Turtle()\r\nball.speed(0)\r\nball.shape(\"square\")\r\nball.color(\"pink\")\r\nball.penup()\r\nball.goto(0, 0)\r\nball.dx = 2\r\nball.dy = 2\r\n\r\n#Score system (pen)\r\npen = turtle.Turtle()\r\npen.speed(0)\r\npen.color(\"pink\")\r\npen.penup()\r\npen.hideturtle()\r\npen.goto(0,260)\r\npen.write(\"Player 1: 0 Player 2: 0\", align=\"center\", font= (\"Helvetica\", 24, \"bold\"))\r\n\r\n#Functions\r\ndef paddle_1_up():\r\n y = paddle_1.ycor()\r\n y += 20\r\n paddle_1.sety(y)\r\n\r\ndef paddle_1_down():\r\n y = paddle_1.ycor()\r\n y -= 20\r\n paddle_1.sety(y)\r\n\r\ndef paddle_2_up():\r\n y = paddle_2.ycor()\r\n y += 20\r\n paddle_2.sety(y)\r\n\r\ndef paddle_2_down():\r\n y = paddle_2.ycor()\r\n y -= 20\r\n paddle_2.sety(y)\r\n\r\n#Keyboard binding\r\nwn.listen()\r\nwn.onkeypress(paddle_1_up, \"w\")\r\nwn.onkeypress(paddle_1_down, \"s\")\r\nwn.onkeypress(paddle_2_up, \"Up\")\r\nwn.onkeypress(paddle_2_down, \"Down\")\r\n\r\n#main game loop\r\nwhile True:\r\n wn.update()\r\n\r\n #Ball movement\r\n ball.setx(ball.xcor() + ball.dx)\r\n ball.sety(ball.ycor() + ball.dy)\r\n\r\n #border checking\r\n if ball.ycor() > 290:\r\n ball.sety(290)\r\n ball.dy *= -1\r\n\r\n if ball.ycor() < -290:\r\n ball.sety(-290)\r\n ball.dy *= -1\r\n\r\n if ball.xcor() > 390:\r\n ball.goto(0, 0)\r\n ball.dx *= -1\r\n score_1 += 1\r\n pen.clear()\r\n pen.write(\"Player 1: {} Player 2: {} \".format(score_1, score_2), align=\"center\", font= (\"Helvetica\", 24, \"bold\"))\r\n\r\n if ball.xcor() < -390:\r\n ball.goto(0, 0)\r\n ball.dx *= -1\r\n score_2 += 1\r\n pen.clear()\r\n pen.write(\"Player 1: {} Player 2: {} \".format(score_1, score_2), align=\"center\", font= (\"Helvetica\", 24, \"bold\"))\r\n\r\n #Paddle and ball collisions\r\n if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_2.ycor() + 40 and ball.ycor() > paddle_2.ycor() -40):\r\n ball.setx(340)\r\n ball.dx *= -1\r\n\r\n if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_1.ycor() + 40 and ball.ycor() > paddle_1.ycor() -40):\r\n ball.setx(-340)\r\n ball.dx *= -1\r\n\r\n \r\n\r\n#find out how to get paddles to move simultaneously to allow for a true multiplayer experience","sub_path":".github/workflows/Pink_Pong.py","file_name":"Pink_Pong.py","file_ext":"py","file_size_in_byte":2843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"622485870","text":"from PIL import Image\nimport numpy as np\nimport sys\n\nstart = \"111111110\"\nstop = \"000000001\"\n\n\n# @Author: Kai Ding\n# @Param: image name\n# This program is going to decode the Steganography and return the plain text to the terminal\n\n# This function will decode the image and return the information in binary\ndef decode(image_name):\n im = Image.open(image_name)\n # Convert image to pixels matrix\n pixels = np.asarray(im)\n result_list = []\n return_result = []\n flag = False\n for row in pixels:\n for col in row:\n for element in col:\n ele = '{0:08b}'.format(element)[-1]\n result_list.append(ele)\n if flag:\n return_result.append(ele)\n if contain(return_result, stop):\n return return_result\n if not flag and contain(result_list, start):\n flag = True\n\n\n# This function implanted slide window algorithm to check the start/stop signal is in the result\ndef contain(result_list, pattern):\n if len(result_list) < len(pattern):\n return False\n for i in range(len(result_list) - len(pattern) + 1):\n if result_list[i:i + len(pattern)] == list(pattern):\n return True\n return False\n\n\nif __name__ == '__main__':\n image_name = sys.argv[1]\n return_list = decode(image_name)[:-len(stop)]\n bi_information = ''.join(return_list)\n p_information = ''\n # convert it back to utf-8 encode character\n for i in range(len(bi_information) // 8):\n p_information += (chr(int(bi_information[i * 8:i * 8 + 8], 2)))\n with open(\"new_output.txt\",\"w\") as f:\n f.write(p_information)\n\n","sub_path":"decode.py","file_name":"decode.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"635846353","text":"import pygame\nimport pygame_menu\nimport json\nimport random\nimport math\nimport sys\n\nimport Character\nimport UI\n\npygame.init()\npygame.font.SysFont(None, 30)\nclock = pygame.time.Clock()\nsurface = pygame.display.set_mode((1000, 600))\nmoving_sprites = pygame.sprite.Group()\nmount_olympus = pygame.image.load(\"./images/mount-olympus.png\")\ncamelot = pygame.image.load(\"./images/camelot.png\")\nplayer_idle = [\n pygame.image.load(\"./sprites/player/idle/00.png\"),\n pygame.image.load(\"./sprites/player/idle/01.png\"),\n pygame.image.load(\"./sprites/player/idle/02.png\"),\n pygame.image.load(\"./sprites/player/idle/03.png\")\n ]\n\nplayer_attack = [\n pygame.image.load(\"./sprites/player/attack/00.png\"),\n pygame.image.load(\"./sprites/player/attack/01.png\"),\n pygame.image.load(\"./sprites/player/attack/02.png\"),\n pygame.image.load(\"./sprites/player/attack/03.png\"),\n pygame.image.load(\"./sprites/player/attack/04.png\")\n ]\n\nplayer_heal = [\n pygame.image.load(\"./sprites/player/heal/00.png\"),\n pygame.image.load(\"./sprites/player/heal/01.png\"),\n pygame.image.load(\"./sprites/player/heal/02.png\")\n ]\n\narcher_idle = [\n pygame.image.load(\"./sprites/archer/idle/00.png\"),\n pygame.image.load(\"./sprites/archer/idle/01.png\"),\n pygame.image.load(\"./sprites/archer/idle/02.png\"),\n pygame.image.load(\"./sprites/archer/idle/03.png\")\n ]\n\narcher_attack = [\n pygame.image.load(\"./sprites/archer/attack/00.png\"),\n pygame.image.load(\"./sprites/archer/attack/01.png\"),\n pygame.image.load(\"./sprites/archer/attack/02.png\"),\n pygame.image.load(\"./sprites/archer/attack/03.png\"),\n pygame.image.load(\"./sprites/archer/attack/04.png\")\n ]\n\nmage_idle = [\n pygame.image.load(\"./sprites/mage/idle/00.png\"),\n pygame.image.load(\"./sprites/mage/idle/01.png\"),\n pygame.image.load(\"./sprites/mage/idle/02.png\"),\n pygame.image.load(\"./sprites/mage/idle/03.png\")\n ]\n\nmage_attack = [\n pygame.image.load(\"./sprites/mage/attack/00.png\"),\n pygame.image.load(\"./sprites/mage/attack/01.png\"),\n pygame.image.load(\"./sprites/mage/attack/02.png\"),\n pygame.image.load(\"./sprites/mage/attack/03.png\"),\n pygame.image.load(\"./sprites/mage/attack/04.png\")\n ]\n\nsnake_idle = [\n pygame.image.load(\"./sprites/snake/idle/00.png\"),\n pygame.image.load(\"./sprites/snake/idle/01.png\"),\n pygame.image.load(\"./sprites/snake/idle/02.png\"),\n pygame.image.load(\"./sprites/snake/idle/03.png\")\n ]\n\nsnake_attack = [\n pygame.image.load(\"./sprites/snake/attack/00.png\"),\n pygame.image.load(\"./sprites/snake/attack/01.png\"),\n pygame.image.load(\"./sprites/snake/attack/02.png\"),\n pygame.image.load(\"./sprites/snake/attack/03.png\"),\n pygame.image.load(\"./sprites/snake/attack/04.png\")\n ]\n\ncrow_idle = [\n pygame.image.load(\"./sprites/crow/idle/00.png\"),\n pygame.image.load(\"./sprites/crow/idle/01.png\"),\n pygame.image.load(\"./sprites/crow/idle/02.png\"),\n pygame.image.load(\"./sprites/crow/idle/03.png\")\n ]\n\ncrow_attack = [\n pygame.image.load(\"./sprites/crow/attack/00.png\"),\n pygame.image.load(\"./sprites/crow/attack/01.png\"),\n pygame.image.load(\"./sprites/crow/attack/02.png\"),\n pygame.image.load(\"./sprites/crow/attack/03.png\"),\n pygame.image.load(\"./sprites/crow/attack/04.png\")\n ]\n\ndeath_king_idle = [\n pygame.image.load(\"./sprites/death-king/idle/00.png\"),\n pygame.image.load(\"./sprites/death-king/idle/01.png\"),\n pygame.image.load(\"./sprites/death-king/idle/02.png\"),\n pygame.image.load(\"./sprites/death-king/idle/03.png\")\n ]\n\ndeath_king_attack = [\n pygame.image.load(\"./sprites/death-king/attack/00.png\"),\n pygame.image.load(\"./sprites/death-king/attack/01.png\"),\n pygame.image.load(\"./sprites/death-king/attack/02.png\"),\n pygame.image.load(\"./sprites/death-king/attack/03.png\"),\n pygame.image.load(\"./sprites/death-king/attack/04.png\")\n ]\n\nevil_wizard_idle = [\n pygame.image.load(\"./sprites/evil-wizard/idle/00.png\"),\n pygame.image.load(\"./sprites/evil-wizard/idle/01.png\"),\n pygame.image.load(\"./sprites/evil-wizard/idle/02.png\"),\n pygame.image.load(\"./sprites/evil-wizard/idle/03.png\")\n ]\n\nevil_wizard_attack = [\n pygame.image.load(\"./sprites/evil-wizard/attack/00.png\"),\n pygame.image.load(\"./sprites/evil-wizard/attack/01.png\"),\n pygame.image.load(\"./sprites/evil-wizard/attack/02.png\"),\n pygame.image.load(\"./sprites/evil-wizard/attack/03.png\"),\n pygame.image.load(\"./sprites/evil-wizard/attack/04.png\")\n ]\n\ndef startGame():\n userData = open(\"UserData.json\", \"r\")\n dataObj = json.load(userData)\n userData.close()\n\n if dataObj[\"newgame\"] == \"True\":\n registerUser()\n else:\n loadGame()\n\ndef registerUser():\n global name\n name = \"\"\n\n def start_the_game():\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n dataObj[\"name\"] = name\n dataObj[\"newgame\"] = \"False\"\n dataObj[\"characters\"].append([name, 500, 500, \"Protagonist\"])\n dataObj[\"currentCharacter\"] = [name, 500, 500, \"Protagonist\"]\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n loadGame()\n\n def setName(value):\n global name\n name = value;\n\n menu = pygame_menu.Menu('Welcome', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n menu.add.text_input('Name: ', default='', onchange=setName)\n menu.add.vertical_margin(10)\n menu.add.button('Play', start_the_game).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button('Quit', pygame_menu.events.EXIT).set_border(1, (255, 255, 255))\n menu.mainloop(surface)\n\ndef loadGame():\n\n #Battle Option\n def battle():\n\n def fight(title):\n UserData = open(\"UserData.json\", \"r\")\n lootValue = random.randint(1,10)\n global shards\n shards = 0\n if 1 <= lootValue <= 5:\n shards = 1\n elif 6 <= lootValue <= 10:\n shards = 2\n dataObj = json.load(UserData)\n UserData.close()\n global enemyHealth\n global playerName\n global playerHealth\n global playerAttack\n global enemyAttack\n global enemy\n global enemyTitle\n global cont\n global player\n global background\n global powerUps\n global healingPotions\n playerName = str(dataObj[\"currentCharacter\"][0])\n playerHealth = int(dataObj[\"currentCharacter\"][1])\n playerAttack= int(dataObj[\"currentCharacter\"][2])\n\n if dataObj[\"banner\"] == \"Mount Olympus\":\n playerHealth += 50\n if dataObj[\"banner\"] == \"Camelot\":\n playerAttack += 25\n\n powerUps = int(dataObj[\"inventory\"][\"Power Ups\"])\n healingPotions = int(dataObj[\"inventory\"][\"Healing Potions\"])\n if title == 'Mount Olympus':\n enemyList = [[\"crow\", 1000, 100], [\"death king\", 4000, 400]]\n background = mount_olympus\n elif title == 'Camelot':\n enemyList = [[\"snake\", 3000, 300], [\"evil wizard\", 9000, 1200]]\n background = camelot\n background = pygame.transform.scale(background, (1000, 600))\n randomNum = random.randint(0,3)\n enemyIndex = 0\n if randomNum == 0:\n enemyIndex = 1\n cont = False\n enemyTitle = enemyList[enemyIndex][0]\n enemyHealth = enemyList[enemyIndex][1]\n enemyAttack = enemyList[enemyIndex][2]\n width, height = pygame.display.get_surface().get_size()\n first = width / 4 / 2\n second = width / 4 + width / 4 / 2\n third = width * 2 / 4 + width / 4 / 2\n fourth = width * 3 / 4 + width / 4 / 2\n center = width / 2\n first_center = width / 4\n second_center = width / 2 + width / 4\n if enemyTitle == \"snake\":\n enemy = Character.Character(256, width * 2 / 4 + width / 8, 150, snake_idle, snake_attack)\n elif enemyTitle == \"crow\":\n enemy = Character.Character(256, width * 2 / 4 + width / 8, 150, crow_idle, crow_attack)\n elif enemyTitle == \"death king\":\n enemy = Character.Character(512, width * 2 / 4, -75, death_king_idle, death_king_attack)\n elif enemyTitle == \"evil wizard\":\n enemy = Character.Character(1048, width * 2 / 4 - width / 8, -200, evil_wizard_idle, evil_wizard_attack)\n if playerName == \"Arthur\":\n player = Character.Character(320, width / 8, 150, archer_idle, archer_attack)\n elif playerName == \"Merlin\":\n player = Character.Character(448, width / 8, 150, mage_idle, mage_attack)\n else:\n player = Character.Character(256, width / 8, 150, player_idle, player_attack, player_heal)\n moving_sprites.add(player)\n moving_sprites.add(enemy)\n attack_button = UI.Button(first - 50, 500, 150, 50, \"Attack\", (255, 0, 0))\n power_button = UI.Button(second - 50, 500, 150, 50, \"Power\", (0, 0, 255))\n heal_button = UI.Button(third - 50, 500, 150, 50, \"Heal\", (0, 255, 0))\n run_button = UI.Button(fourth - 50, 500, 150, 50, \"Run\", (0, 255, 255))\n enemy_label = UI.Label(center, 350, \"Enemy: \" + str(enemyTitle.title()))\n player_health = UI.Label(first_center, 400, \"Player Health: \" + str(playerHealth))\n enemy_health = UI.Label(second_center, 400, \"Enemy Health: \" + str(enemyHealth))\n\n powers_label = UI.Label(second, 450, \"Power Ups: \" + str(powerUps))\n potions_label = UI.Label(third, 450, \"Healing Potions: \" + str(healingPotions))\n\n def attackEnemy():\n global enemyHealth\n global playerHealth\n global playerAttack\n global enemyAttack\n global player\n global powerUps\n player.attack()\n enemy.attack()\n enemyHealth = enemyHealth - random.randint(playerAttack-50, playerAttack+50)\n playerHealth = playerHealth - random.randint(enemyAttack-20, enemyAttack+20)\n enemy_health.change_text(\"Enemy Health: \" + str(enemyHealth))\n player_health.change_text(\"Player Health: \" + str(playerHealth))\n\n def powerAttack():\n global enemyHealth\n global playerHealth\n global playerAttack\n global enemyAttack\n global player\n global powerUps\n if powerUps == 0:\n return\n player.attack()\n enemy.attack()\n enemyHealth = enemyHealth - random.randint(int(playerAttack*1.5-50), int(playerAttack*1.5+50))\n playerHealth = playerHealth - random.randint(enemyAttack-20, enemyAttack+20)\n enemy_health.change_text(\"Enemy Health: \" + str(enemyHealth))\n player_health.change_text(\"Player Health: \" + str(playerHealth))\n powerUps -= 1\n powers_label.change_text(\"Power Ups: \" + str(powerUps))\n\n def healPlayer():\n global enemyHealth\n global playerHealth\n global playerAttack\n global enemyAttack\n global healingPotions\n if healingPotions == 0 or playerHealth >= dataObj[\"currentCharacter\"][1]:\n return\n player.heal()\n enemy.attack()\n playerHealth = dataObj[\"currentCharacter\"][1]\n enemy_health.change_text(\"Enemy Health: \" + str(enemyHealth))\n player_health.change_text(\"Player Health: \" + str(playerHealth))\n playerHealth = playerHealth - random.randint(enemyAttack-20, enemyAttack+20);\n enemy_health.change_text(\"Enemy Health: \" + str(enemyHealth))\n player_health.change_text(\"Player Health: \" + str(playerHealth))\n healingPotions -= 1\n potions_label.change_text(\"Healing Potions: \" + str(healingPotions))\n\n def drawGame():\n attack_button.draw(surface)\n power_button.draw(surface)\n heal_button.draw(surface)\n run_button.draw(surface)\n enemy_label.draw(surface)\n enemy_health.draw(surface)\n player_health.draw(surface)\n powers_label.draw(surface)\n potions_label.draw(surface)\n\n def win(title):\n global menu\n global enemyTitle\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n\n menu = pygame_menu.Menu(title, 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n def continueGame():\n global cont\n cont = True\n menu.add.label(\"Victory\").update_font({'size': 80})\n menu.add.vertical_margin(30)\n if title == \"Mount Olympus\":\n menu.add.label(\"Gold +2,500\")\n if enemyTitle == \"death king\":\n menu.add.label(\"Gold +10,000\")\n menu.add.label(\"%s Fragments +5\" % (title))\n if title == \"Camelot\":\n menu.add.label(\"Gold +5,000\")\n if enemyTitle == \"evil wizard\":\n menu.add.label(\"Gold +20,000\")\n menu.add.label(\"%s Fragments +5\" % (title))\n if shards == 1:\n menu.add.label(\"%s Fragments +1\" % (title))\n elif shards == 2:\n menu.add.label(\"%s Fragments +2\" % (title))\n menu.add.vertical_margin(50)\n menu.add.button('Continue', continueGame).set_border(1, (255, 255, 255))\n menu.mainloop(surface, disable_loop=True)\n def lose(title):\n global menu\n menu = pygame_menu.Menu(title, 1000, 600,theme=pygame_menu.themes.THEME_DARK)\n def continueGame():\n global cont\n cont = True\n menu.add.label(\"Defeat\").update_font({'size': 80})\n menu.add.vertical_margin(10)\n menu.add.button('Continue', continueGame).set_border(1, (255, 255, 255))\n menu.mainloop(surface, disable_loop=True)\n def runAway():\n global enemyHealth\n global playerHealth\n global cont\n enemyHealth = 0\n playerHealth = 0\n cont = True\n menu.disable()\n while enemyHealth > 0 and playerHealth > 0:\n surface.blit(background, (0, 0))\n drawGame()\n for event in pygame.event.get():\n mouse_position = pygame.mouse.get_pos()\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.MOUSEBUTTONDOWN:\n if attack_button.on_button(mouse_position):\n attackEnemy()\n elif power_button.on_button(mouse_position):\n powerAttack()\n elif heal_button.on_button(mouse_position):\n healPlayer()\n elif run_button.on_button(mouse_position):\n runAway()\n moving_sprites.draw(surface)\n moving_sprites.update()\n pygame.display.update()\n clock.tick(10)\n moving_sprites.remove(player)\n moving_sprites.remove(enemy)\n menu.enable()\n dataObj[\"inventory\"][\"Healing Potions\"] = healingPotions\n dataObj[\"inventory\"][\"Power Ups\"] = powerUps\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n if playerHealth == 0 and enemyHealth == 0:\n pass\n elif enemyHealth <= 0:\n while cont == False:\n win(title)\n menu.mainloop(surface, disable_loop=True)\n if title == \"Mount Olympus\":\n dataObj[\"inventory\"][\"Gold\"] += 2500\n if enemyTitle == \"death king\":\n dataObj[\"inventory\"][\"Gold\"] += 10000\n dataObj[\"inventory\"][\"%s Fragments\" % (title)] += 5\n if title == \"Camelot\":\n dataObj[\"inventory\"][\"Gold\"] += 5000\n if enemyTitle == \"evil wizard\":\n dataObj[\"inventory\"][\"Gold\"] += 20000\n dataObj[\"inventory\"][\"%s Fragments\" % (title)] += 5\n if shards == 1:\n dataObj[\"inventory\"][\"%s Fragments\" % (title)] += 1\n elif shards == 2:\n dataObj[\"inventory\"][\"%s Fragments\" % (title)] += 2\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n elif playerHealth <= 0:\n while cont == False:\n lose(title)\n\n\n menu = pygame_menu.Menu('Select your destination', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n menu.add.button('Mount Olympus', fight, 'Mount Olympus').set_border(1, (255, 255, 255))\n menu.add.vertical_margin(20)\n menu.add.button('Camelot', fight, 'Camelot').set_border(1, (255, 255, 255))\n menu.add.vertical_margin(20)\n menu.add.button('Back', loadGame).set_border(1, (255, 255, 255))\n menu.mainloop(surface)\n\n #Characters Option\n def viewCharacters():\n global hero_label\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n charList = dataObj[\"characters\"]\n def characterInfo(n):\n global hero_label\n dataObj[\"currentCharacter\"] = charList[n]\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n hero_label.set_title(\"Current Hero: \" + dataObj[\"currentCharacter\"][0])\n menu = pygame_menu.Menu('Characters', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n hero_label = menu.add.label(\"Current Hero: \" + dataObj[\"currentCharacter\"][0]).update_font({\"size\": 40})\n for i in range(len(charList)):\n menu.add.label(\"Name: \" + charList[i][0] + \", Title: \"+ charList[i][3])\n menu.add.label(\"Damage: \" + str(charList[i][2]) + \", Health: \" + str(charList[i][1]))\n menu.add.button('Choose', characterInfo, i).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(20)\n menu.add.vertical_margin(30)\n menu.add.button(\"Back\", loadGame).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(50)\n menu.mainloop(surface)\n\n #Inventory Option\n def openInventory():\n menu = pygame_menu.Menu('Inventory', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n inventory = dataObj[\"inventory\"]\n for item in inventory:\n menu.add.label(item + \" x\"+str(inventory[item]))\n menu.add.vertical_margin(5)\n menu.add.vertical_margin(50)\n menu.add.button(\"Back\", loadGame).set_border(1, (255, 255, 255))\n menu.mainloop(surface)\n\n def goToShop():\n global shop_gold_label\n global shop_potions_label\n global shop_powers_label\n global shop_error\n def buyItem(item):\n global gold_label\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n if item == \"Healing Potions\" and dataObj[\"inventory\"][\"Gold\"] >= 1000:\n dataObj[\"inventory\"][\"Healing Potions\"] += 1\n dataObj[\"inventory\"][\"Gold\"] -= 1000\n shop_error.set_title(\"Bought 1 Healing Potions\").update_font({\"color\": (0, 255, 0)})\n elif item == \"Power Ups\" and dataObj[\"inventory\"][\"Gold\"] >= 2000:\n dataObj[\"inventory\"][\"Power Ups\"] += 1\n dataObj[\"inventory\"][\"Gold\"] -= 2000\n shop_error.set_title(\"Bought 1 Power Ups\").update_font({\"color\": (0, 255, 0)})\n elif item == \"Upgrade Health\" and dataObj[\"inventory\"][\"Gold\"] >= 5000:\n dataObj[\"currentCharacter\"][1] += 100\n dataObj[\"inventory\"][\"Gold\"] -= 5000\n shop_error.set_title(\"Your Hero's Health is Increased by 100\").update_font({\"color\": (0, 255, 0)})\n for i in range(0, len(dataObj[\"characters\"])):\n if dataObj[\"characters\"][i][0] == dataObj[\"currentCharacter\"][0]:\n dataObj[\"characters\"][i][1] += 100\n elif item == \"Upgrade Damage\" and dataObj[\"inventory\"][\"Gold\"] >= 5000:\n dataObj[\"currentCharacter\"][2] += 50\n dataObj[\"inventory\"][\"Gold\"] -= 5000\n shop_error.set_title(\"Your Hero's Damage is Increased by 50\").update_font({\"color\": (0, 255, 0)})\n for i in range(0, len(dataObj[\"characters\"])):\n if dataObj[\"characters\"][i][0] == dataObj[\"currentCharacter\"][0]:\n dataObj[\"characters\"][i][2] += 50\n else:\n shop_error.set_title(\"Error: Not Enough Gold\").update_font({\"color\": (255, 0, 0)})\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n shop_potions_label.set_title(\"Healing Potions: \" + str(dataObj[\"inventory\"][\"Healing Potions\"]))\n shop_powers_label.set_title(\"Power Ups: \" + str(dataObj[\"inventory\"][\"Power Ups\"]))\n shop_gold_label.set_title(\"Gold: \" + str(dataObj[\"inventory\"][\"Gold\"]))\n menu = pygame_menu.Menu('Shop', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n shop_gold_label = menu.add.label(\"Gold: \" + str(dataObj[\"inventory\"][\"Gold\"])).update_font({\"size\": 40})\n menu.add.vertical_margin(5)\n shop_potions_label = menu.add.label(\"Healing Potions: \" + str(dataObj[\"inventory\"][\"Healing Potions\"]))\n menu.add.vertical_margin(5)\n shop_powers_label = menu.add.label(\"Power Ups: \" + str(dataObj[\"inventory\"][\"Power Ups\"]))\n menu.add.vertical_margin(10)\n shop_error = menu.add.label(\"\").update_font({\"size\": 24})\n menu.add.vertical_margin(40)\n menu.add.label(\"Healing Potion, Cost: 1000\")\n menu.add.label(\"Description: Heal 100% of Health in Battle\")\n menu.add.button('Buy', buyItem, \"Healing Potions\").set_border(1, (255, 255, 255))\n menu.add.vertical_margin(20)\n menu.add.label(\"Power Ups, Cost: 2000\")\n menu.add.label(\"Description: Next Attack Deals 150% Damage\")\n menu.add.button('Buy', buyItem, \"Power Ups\").set_border(1, (255, 255, 255))\n menu.add.vertical_margin(20)\n menu.add.label(\"Upgrade Health, Cost: 5000\")\n menu.add.label(\"Description: Increase Health by 100 Permanently\")\n menu.add.button('Buy', buyItem, \"Upgrade Health\").set_border(1, (255, 255, 255))\n menu.add.vertical_margin(20)\n menu.add.label(\"Upgrade Attack, Cost: 5000\")\n menu.add.label(\"Description: Increase Attack Damage by 50 Permanently\")\n menu.add.button('Buy', buyItem, \"Upgrade Damage\").set_border(1, (255, 255, 255))\n menu.add.vertical_margin(50)\n menu.add.button(\"Back\", loadGame).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(50)\n menu.mainloop(surface)\n\n #Select Banner and Summon Option\n def openBanner():\n global banner_label\n global banner_bonus_label\n def setBanner(value):\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n dataObj[\"banner\"] = value\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n bonus = \"\"\n if value == \"Mount Olympus\":\n bonus = \"Gain 50 Health\"\n elif value == \"Camelot\":\n bonus = \"Gain 25 Damage\"\n global banner_label\n global banner_bonus_label\n banner_label.set_title(\"Current Banner: \" + value)\n banner_bonus_label.set_title(\"Current Bonus: \" + bonus)\n menu = pygame_menu.Menu(\"Banner\", 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n banner = dataObj[\"banner\"]\n bonus = \"\"\n if banner == \"Mount Olympus\":\n bonus = \"Gain 50 Health\"\n elif banner == \"Camelot\":\n bonus = \"Gain 25 Damage\"\n banner_label = menu.add.label(\"Current Banner: \" + banner).update_font({\"size\": 40})\n banner_bonus_label = menu.add.label(\"Current Bonus: \" + bonus)\n menu.add.vertical_margin(50)\n menu.add.label(\"Mount Olympus\")\n menu.add.label(\"Description: Gain 50 Health\")\n menu.add.button(\"Choose\", setBanner, \"Mount Olympus\").set_border(1, (255, 255, 255))\n menu.add.vertical_margin(20)\n menu.add.label(\"Camelot\")\n menu.add.label(\"Description: Gain 25 Damage\")\n menu.add.button(\"Choose\", setBanner, \"Camelot\").set_border(1, (255, 255, 255))\n menu.add.vertical_margin(50)\n menu.add.button(\"Back\", loadGame).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(50)\n menu.mainloop(surface)\n\n def summoningPortal():\n\n def summon():\n menu = pygame_menu.Menu(\"Summoning\", 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n mountOlympusFragments = dataObj[\"inventory\"][\"Mount Olympus Fragments\"]\n camelotFragments = dataObj[\"inventory\"][\"Camelot Fragments\"]\n if dataObj[\"banner\"] == \"Mount Olympus\":\n if mountOlympusFragments >= 10:\n dataObj[\"inventory\"][\"Mount Olympus Fragments\"] = dataObj[\"inventory\"][\"Mount Olympus Fragments\"]-10\n summonList = [[\"Arthur\", 1000, 1000, \"Archer\"]]\n summonEntity = random.choice(summonList)\n owned = []\n for i in range(0, len(dataObj[\"characters\"])):\n owned.append(dataObj[\"characters\"][i][0])\n if (summonEntity[0] in owned) == False:\n dataObj[\"characters\"].append(summonEntity)\n menu.add.label(\"Summoning Successful\").update_font({\"size\": 40})\n menu.add.vertical_margin(50)\n menu.add.label(\"Name: \" + summonEntity[0] + \", Title: \" + summonEntity[3])\n menu.add.label(\"Damage: \" + str(summonEntity[1]) + \", Health: \" + str(summonEntity[2]))\n else:\n menu.add.label(\"No Heroes Available to Summon\").update_font({\"size\": 40})\n menu.add.vertical_margin(10)\n menu.add.label(\"Gold +25,000\")\n dataObj[\"inventory\"][\"Gold\"] += 25000\n elif mountOlympusFragments < 10:\n menu.add.label(\"Mount Olympus Fragments: \" + str(dataObj[\"inventory\"][\"Mount Olympus Fragments\"])).update_font({\"size\": 40})\n menu.add.vertical_margin(50)\n menu.add.label(\"Summoning requires 10 Mount Olympus Fragments\")\n\n if dataObj[\"banner\"] == \"Camelot\":\n if camelotFragments >= 10:\n dataObj[\"inventory\"][\"Camelot Fragments\"] = dataObj[\"inventory\"][\"Camelot Fragments\"]-10\n summonList = [[\"Merlin\", 2000, 2000, \"Mage\"]]\n summonEntity = random.choice(summonList)\n owned = []\n for i in range(0, len(dataObj[\"characters\"])):\n owned.append(dataObj[\"characters\"][i][0])\n if (summonEntity[0] in owned) == False:\n dataObj[\"characters\"].append(summonEntity)\n menu.add.label(\"Summoning Successful\").update_font({\"size\": 40})\n menu.add.vertical_margin(50)\n menu.add.label(\"Name: \" + summonEntity[0] + \", Title: \" + summonEntity[3])\n menu.add.label(\"Damage: \" + str(summonEntity[1]) + \", Health: \" + str(summonEntity[2]))\n else:\n menu.add.label(\"No Heroes Available to Summon\").update_font({\"size\": 40})\n menu.add.vertical_margin(50)\n menu.add.label(\"Gold +50,000\")\n dataObj[\"inventory\"][\"Gold\"] += 50000\n elif camelotFragments < 10:\n menu.add.label(\"Camelot Fragments: \" + str(dataObj[\"inventory\"][\"Camelot Fragments\"])).update_font({\"size\": 40})\n menu.add.vertical_margin(10)\n menu.add.label(\"Summoning requires 10 Camelot Fragments\")\n\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n menu.add.vertical_margin(50)\n menu.add.button(\"Back\", summoningPortal).set_border(1, (255, 255, 255))\n menu.mainloop(surface)\n\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n menu = pygame_menu.Menu('Summoning Portal', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n menu.add.label(\"Current Banner: \" + dataObj[\"banner\"]).update_font({\"size\": 40})\n menu.add.vertical_margin(50)\n menu.add.button('Summon', summon).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(20)\n menu.add.button(\"Back\", loadGame).set_border(1, (255, 255, 255))\n menu.mainloop(surface)\n\n def demoMode():\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n dataObj[\"inventory\"][\"Gold\"] += 1000000\n dataObj[\"inventory\"][\"Mount Olympus Fragments\"] += 100\n dataObj[\"inventory\"][\"Camelot Fragments\"] += 100\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n UserData.close()\n menu = pygame_menu.Menu('Crimson', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n menu.add.label(\"Current Banner: \" + dataObj[\"banner\"])\n menu.add.button('Fight in Battle', battle).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button('View Heroes', viewCharacters).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button('Open Inventory', openInventory).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button('Go to Shop', goToShop).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button('Change Banner', openBanner).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button('Summoning Portal', summoningPortal).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button('Demo Mode', demoMode).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button('Exit', pygame_menu.events.EXIT).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.mainloop(surface)\n\ndef options():\n def resetGame(menu):\n UserData = open(\"UserData.json\", \"r\")\n dataObj = json.load(UserData)\n dataObj[\"newgame\"] = \"True\"\n dataObj[\"name\"] = \"\"\n dataObj[\"banner\"] = \"Mount Olympus\"\n dataObj[\"characters\"] = []\n dataObj[\"currentCharacter\"] = []\n dataObj[\"inventory\"] = {'Gold': 0, 'Mount Olympus Fragments': 0, 'Camelot Fragments': 0, 'Healing Potions': 0, 'Power Ups': 0}\n UserData.close()\n UserData = open(\"UserData.json\", \"w\")\n json.dump(dataObj, UserData)\n UserData.close()\n menu.disable()\n def backOption(menu):\n menu.disable()\n menu = pygame_menu.Menu('Options', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\n menu.add.button(\"Reset Game\", resetGame, menu).set_border(1, (255, 255, 255))\n menu.add.vertical_margin(10)\n menu.add.button(\"Back\", backOption, menu).set_border(1, (255, 255, 255))\n menu.mainloop(surface)\n\nmenu = pygame_menu.Menu('Crimson', 1000, 600, theme=pygame_menu.themes.THEME_DARK)\nmenu.add.button('Play', startGame).set_border(1, (255, 255, 255))\nmenu.add.vertical_margin(10)\nmenu.add.button('Options', options).set_border(1, (255, 255, 255))\nmenu.add.vertical_margin(10)\nmenu.add.button('Quit', pygame_menu.events.EXIT).set_border(1, (255, 255, 255))\n\nmenu.mainloop(surface)\n","sub_path":"Crimson/Crimson.py","file_name":"Crimson.py","file_ext":"py","file_size_in_byte":34458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"18741504","text":"from django.conf.urls import url, include\nfrom django.contrib import admin\nfrom pontoexpress.core.views import home\n\nurlpatterns = [\n url(r'^$', home, name='home'),\n url(r'^movimentos/', include('pontoexpress.movimentos.urls',\n namespace='movimentos')),\n url(r'^relatorios/', include('pontoexpress.reports.urls', namespace='relatorios')),\n url(r'^admin/', admin.site.urls),\n]\n","sub_path":"pontoexpress/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"208052772","text":"import logging,serial,requests,signal,time,datetime\nimport RPi.GPIO as GPIO\nimport dht11\nfrom pyhap.accessory import Accessory, Bridge\nfrom pyhap.accessory_driver import AccessoryDriver\nfrom pyhap.const import (CATEGORY_SENSOR)\nlogging.basicConfig(level=logging.INFO, format=\"[%(module)s] %(message)s\")\n# initialize GPIO\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\nGPIO.cleanup()\ninstance = dht11.DHT11(pin=14)\nglobal hum\nclass TemperatureSensor(Accessory):\n category = CATEGORY_SENSOR\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n serv_temp = self.add_preload_service('TemperatureSensor')\n self.char_temp = serv_temp.configure_char('CurrentTemperature')\n\n @Accessory.run_at_interval(3)\n async def run(self):\n global hum\n result = instance.read()\n if result.is_valid():\n self.char_temp.set_value(result.temperature)\n hum=result.humidity\n\nclass HumiditySensor(Accessory):\n category = CATEGORY_SENSOR\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n serv_temp = self.add_preload_service('HumiditySensor')\n self.char_temp = serv_temp.configure_char('CurrentRelativeHumidity')\n\n @Accessory.run_at_interval(3)\n async def run(self):\n global hum\n self.char_temp.set_value(hum)\n\n\ndef get_bridge(driver):\n bridge = Bridge(driver, 'Bridge')\n bridge.add_accessory(TemperatureSensor(driver, '温度'))\n bridge.add_accessory(HumiditySensor(driver, '湿度'))\n return bridge\ndriver = AccessoryDriver(port=51826, persist_file='test.state')\ndriver.add_accessory(accessory=get_bridge(driver))\nsignal.signal(signal.SIGTERM, driver.signal_handler)\ndriver.start()\n","sub_path":"test_temp.py","file_name":"test_temp.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"307246698","text":"# IMPORTS\r\nimport socket\r\nimport time\r\nimport threading\r\nfrom ast import literal_eval\r\n\r\n# SETTING THINGS UP\r\nIP = \"10.1.21.46\"\r\nPORT = 8001\r\n\r\n# IP TO PRIORITIZE\r\nSPECIAL_IP = \"10.1.20.115\"\r\n\r\n# LIST OF SERVERS\r\nservers = [(IP, 8000), (IP, 8002)]\r\n\r\n# ORIGINAL LIST\r\nL = [x for x in range(10)]\r\n\r\n# CREATE SOCKET\r\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nserversocket.bind((IP, PORT))\r\n\r\n# BECOME SERVER\r\nserversocket.listen(128)\r\nprint(\"Server is running! (IP address - %s, Port - %s)\" % (IP, PORT))\r\n\r\n# REQUEST POOL\r\nrequestPool = []\r\n\r\n# CONSENSUS THREAD\r\ndef commitRequests():\r\n \r\n global requestPool\r\n print(\"Consensus: Asking for requests.\")\r\n\r\n # CREATE TEMPORARY POOL\r\n tempPool = []\r\n \r\n # CONNECT TO EVERY SERVER AND RECEIVE REQUESTS\r\n for server in servers:\r\n consensussocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n consensussocket.connect(server)\r\n consensussocket.send(\"SERVER\".encode())\r\n \r\n # RECEIVE REQUESTS TILL YOU GET OVER FLAG\r\n while True:\r\n response = consensussocket.recv(1024).decode()\r\n if response == \"OVER\":\r\n break\r\n tempPool.append(literal_eval(response))\r\n \r\n # CLOSING CONNECTION\r\n consensussocket.close()\r\n\r\n # BUSY WAIT TO PRESERVE REQUEST POOL \r\n print(\"Consensus: Waiting.\")\r\n time.sleep(5)\r\n \r\n # ADD NEW REQUESTS TO REQUEST POOL\r\n requestPool = requestPool + tempPool\r\n\r\n # SORT BASED ON TIMESTAMP\r\n requestPool.sort(key=lambda x: x[0])\r\n \r\n # COMMIT REQUESTS FROM SPECIAL IP\r\n for request in requestPool:\r\n if request[1][0] == SPECIAL_IP:\r\n L[request[2]], L[request[3]] = L[request[3]], L[request[2]]\r\n\r\n # COMMIT REQUESTS FROM THE REMAINING IPs\r\n for request in requestPool:\r\n if request[1][0] == SPECIAL_IP:\r\n continue\r\n L[request[2]], L[request[3]] = L[request[3]], L[request[2]]\r\n\r\n # EMPTY REQUEST POOL\r\n requestPool = []\r\n print(\"CONSENSUS COMPLETE!\")\r\n\r\n # WAIT TO START NEXT CONSENSUS THREAD\r\n threading.Timer(60, commitRequests).start() \r\n \r\n\r\n# CLIENT THREAD\r\ndef checkingThread(clientsocket, address):\r\n\r\n # ACCEPT FLAG\r\n flag = clientsocket.recv(1024).decode()\r\n\r\n # IF CLIENT, SEND LIST AND ACCEPT i, j\r\n if flag == \"CLIENT\":\r\n print(\"Connected to client.\")\r\n clientsocket.send(str(L).encode())\r\n response = clientsocket.recv(1024).decode().split(\" \")\r\n ctime = time.time()\r\n i, j = int(response[0]), int(response[1])\r\n requestPool.append([ctime, address, i, j])\r\n clientsocket.close()\r\n \r\n # IF SERVER, SEND ALL REQUESTS FROM REQUEST POOL\r\n elif flag == \"SERVER\":\r\n print(\"Consensus: Sending Requests.\")\r\n for element in requestPool:\r\n clientsocket.send(str(element).encode())\r\n print(\"Sent Request\")\r\n clientsocket.send(\"OVER\".encode())\r\n clientsocket.close()\r\n\r\n return\r\n\r\n# START CONSENSUS THREAD\r\nthreading.Timer(60, commitRequests).start()\r\n\r\nwhile True:\r\n\r\n # ACCEPT CONNECTIONS\r\n (clientsocket, address) = serversocket.accept()\r\n print(\"Got a connection from \", address)\r\n\r\n # CREATE A THREAD AND START IT\r\n t1 = threading.Thread(target = checkingThread, args = (clientsocket, address, ))\r\n t1.start()","sub_path":"server2.py","file_name":"server2.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"139238250","text":"# Задание №3\n# В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.\n\nimport random\n\nSIZE = 10\nMIN_ITEM = -100\nMAX_ITEM = 100\narray = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)]\nprint(array)\n\nidx_min = 0\nidx_max = 0\nfor i in range(len(array)):\n if array[i] < array[idx_min]:\n idx_min = i\n elif array[i] > array[idx_max]:\n idx_max = i\nprint(f'Min = {array[idx_min]} в ячейке {idx_min}; Max = {array[idx_max]} в ячейке {idx_max}')\n\nspam = array[idx_min]\narray[idx_min] = array[idx_max]\narray[idx_max] = spam\nprint(array)\n","sub_path":"algorithms_and_data_structures/HW3/task_3.py","file_name":"task_3.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"244613019","text":"\"\"\"\nThis module was created to hold utility functions.\n\"\"\"\nfrom .config import Config\nfrom selenium import webdriver\n\n\ndef new_email():\n \"\"\"This function create new emails to be tested when registering.\"\"\"\n config = Config()\n iterator = config.get('iterator')\n iterator = str(iterator)\n email = 'test' + iterator + '@tmail.com'\n iterator = int(iterator)\n iterator += 1\n config.set('iterator', iterator)\n return email\n","sub_path":"framework/mlg/util/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"382652744","text":"import webserver\nimport random\n#*import asyncio\nimport discord\n#*from discord.ext.commands import Bot\nfrom discord.ext import commands,tasks\nimport general as gen\nimport praw\n\ncmdlist = gen.permu(gen.prefix)\n\nclient = commands.Bot(command_prefix = cmdlist, case_insensitive = True)\n\ngain_multiplier = 1.5\nloss_multiplier = 1\ngl = 0\nmeme_ids = []\n\n@tasks.loop(minutes = 5)\nasync def clear_meme_list():\n global meme_ids\n meme_ids.clear()\n\n@client.event\nasync def on_ready():\n print(\"Epicness shall s p r e a d\")\n change_status.start()\n clear_meme_list.start()\n\n@tasks.loop(seconds = gen.loop_time)\nasync def change_status():\n await client.change_presence(activity = discord.Game(next(gen.status)))\n\n\n@client.event\nasync def on_member_join(ctx, member : discord.Member):\n await ctx.send(f\" {member.mention} has joined the path to epicness.\")\n\n@client.event\nasync def on_member_remove(ctx, member : discord.Member):\n await ctx.send(f\" {member.mention} has abandoned the path to true epicness.\")\n\n@client.command()\nasync def ping(ctx):\n embed = discord.Embed(title = \"Meh Ping\", description = f\">>> Pong! {round(client.latency * 1000)}ms\", colour = discord.Color.dark_teal(), url = gen.epic_troll)\n await ctx.send(embed = embed)\n\n@client.command()\nasync def play(ctx, num, ammount):\n embed = discord.Embed(title = \"Betting Game\", description = \"So here are the results of your stupid game, get a life ffs\", colour = discord.Color.blurple(), url = gen.epic_troll)\n\n fate = float(random.uniform(0.1, 1.0))\n fate_result = round(fate * (10 ** (len(str(num)))))\n entry = float(int(num) / ( 10 ** len(num) ))\n\n embed.add_field(name = \"Your entry: \", value = str(num), inline = False)\n embed.add_field(name = \"My Epic Roll: : \", value = str(fate_result), inline = False)\n\n if round(fate, 1) == entry:\n gl = 2 * int(ammount)\n embed.add_field(name = \"RESULT \", value = f\" YOU HIT A JACKPOT! You have won {gl} coins\", inline = False)\n comp = True\n\n else:\n if fate > entry:\n gl = round((( (fate - entry) * loss_multiplier ) / 10 ) * int(ammount))\n embed.add_field(name = \"RESULT \", value = f\" YOU LOST! You have lost {gl} coins\", inline = False)\n comp = True\n\n elif fate < entry:\n gl = round(( (( 10 - (entry - fate) ) * gain_multiplier ) / 10 ) * int(ammount))\n embed.add_field(name = \"RESULT \", value = f\" YOU HIT A WIN! You have won {gl} coins\", inline = False)\n comp = True\n\n await ctx.send(embed = embed)\n\n@client.command(aliases = ['spank'])\nasync def spanky(ctx, taker : discord.Member = None):\n\n if taker == None:\n embed = discord.Embed(title = \"Spanky Spank\", description = \"You give a spanky to your friends.\", colour = discord.Color.dark_magenta(), url = gen.epic_troll)\n\n elif taker.mention == ctx.message.author.mention:\n embed = discord.Embed(title = \"Spanky Spank\", description = \"You are trying to spank yourself? you have mega gae.\", colour = discord.Color.dark_magenta(), url = gen.epic_troll)\n\n elif taker.display_name == 'EpiclyEpicEpicness (epic)':\n embed = discord.Embed(title = \"Spanky Spank\", description = \"I clap your ass cheeks for trying to spank me.\", colour = discord.Color.dark_magenta(), url = gen.epic_troll)\n\n else:\n taker_mention = taker.mention \n embed = discord.Embed(title = \"Spanky Spank\", description = f\"You give a spanky to {taker_mention}. Both of you truly enjoy this.\", colour = discord.Color.dark_magenta(), url = gen.epic_troll)\n\n await ctx.send(embed = embed) \n\n@client.command()\nasync def animeme(ctx, ammount = 2, type = 'hot'):\n sub_dic = {1 : \"animemes\", 2 : \"overlordmemes\", 3 : \"ShitPostCrusaders\", 4 : \"konosubamemes\"}\n sub_fate = random.randint(1, 4)\n\n try:\n sm = int(ammount)\n except:\n await ctx.send(\">>> The ammount of memes has to be an integer. You are clearly retarded.\")\n return\n\n if type.lower() == 'hot':\n\n for submission in gen.reddit.subreddit(sub_dic.get(sub_fate)).hot(limit = ammount):\n \n if submission.is_reddit_media_domain:\n meme_ids.append(submission.id)\n\n embed = discord.Embed(title = submission.title, description = \"\\n\", colour = discord.Color.gold(), url = submission.shortlink)\n\n embed.add_field(name = \"~~Spankies~~ Upvotes\", value = f\"{submission.ups / 1000}k\", inline = True)\n embed.add_field(name = \"Upvote Ratio\", value = f\"{round(submission.upvote_ratio * 100)}%\", inline = True)\n embed.add_field(name = \"Subreddit\", value = f\"r/{sub_dic.get(sub_fate)}\", inline = True)\n embed.set_author(name = f\"u/{str(submission.author)}\", icon_url = submission.author.icon_img)\n embed.set_footer(text = client.user.name, icon_url = client.user.avatar_url)\n embed.set_image(url = submission.url)\n embed.set_thumbnail(url = \"https://i.redd.it/62pxjzb7dtp21.png\")\n await ctx.send(embed = embed)\n\n elif type.lower() == 'new':\n\n for submission in gen.reddit.subreddit(sub_dic.get(sub_fate)).new(limit = ammount):\n if not submission.stickied:\n embed = discord.Embed(title = submission.title, description = \"\\n\", colour = discord.Color.gold(), url = submission.shortlink)\n\n embed.add_field(name = \"~~Spankies~~ Upvotes\", value = f\"{submission.ups / 1000}k\", inline = True)\n embed.add_field(name = \"Upvote Ratio\", value = f\"{round(submission.upvote_ratio * 100)}%\", inline = True)\n embed.add_field(name = \"Subreddit\", value = f\"r/{sub_dic.get(sub_fate)}\", inline = False)\n embed.set_author(name = str(submission.author), icon_url = submission.author.icon_img)\n embed.set_footer(text = client.user.name, icon_url = client.user.avatar_url)\n embed.set_image(url = submission.url)\n embed.set_thumbnail(url = \"https://i.redd.it/62pxjzb7dtp21.png\")\n await ctx.send(embed = embed)\n\n else:\n await ctx.send(\">>> Thats not a valid type you doof, you want a ~~head~~ spanky?\")\n\n@client.command()\nasync def info(ctx):\n info = (\"HELLO! I am a sexy ass epic bot owned by none other than the epicest man alive,**_ Blonteractor_ ** ᕙ(˵ ಠ ਊ ಠ ˵)ᕗ (his muscles) . \\n \\\nYou could say I am female but anyone that has seen the truth has not lived to tell the story.\\n \\\nSo be carefull or ``` I WILL make you horny. ```\")\n embed = discord.Embed(title = \"About Meh\", description = info, colour = discord.Color.dark_gold(), url = gen.epic_troll)\n\n await ctx.send(embed = embed)\nwebserver.keep_alive()\nclient.run(gen.bot_token) ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"399041114","text":"import game, simulation\nimport numpy as np\nimport random\nimport training\nfrom constants import NPLANETS, RMAX, OUTSIDEREWARD, COLLISIONREWARD, MAXT\n\ndef reward(sim):\n total = 0\n for mass in sim.masses:\n total += OUTSIDEREWARD * np.linalg.norm(mass.pos)\n if mass.collided:\n total += COLLISIONREWARD\n return total / MAXT\n\ndef doTraining():\n t = training.Training(runSim, 2*NPLANETS)\n t.main()\n return t.getBestIndividual().values\n\ndef runSim(vels):\n vels = np.array(vels).reshape(NPLANETS, 2)\n sim = simulation.Simulation(getInitConf(vels))\n totalReward = 0\n for t in range(MAXT):\n sim.handle()\n totalReward += reward(sim)\n return totalReward\n\ndef getInitConf(vels):\n masses = []\n masses.append(simulation.Mass(np.array([0.0, 0.0]), 10, 50))\n radius = 300\n for i in range(NPLANETS):\n pos = np.array([radius * np.cos(i / NPLANETS * 2 * np.pi), radius * np.sin(i / NPLANETS * 2 * np.pi)])\n mass = simulation.Mass(pos, 1, 20)\n mass.vel = vels[i]\n masses.append(mass)\n return masses\n\ndef main():\n vels = doTraining()\n sim = simulation.Simulation(getInitConf(vels))\n game.main(sim)\n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"342477988","text":"#!/usr/bin/env python2\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport math\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.ops import gradient_checker\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.client import timeline\nimport tensorflow.python.ops.nn_grad # pylint: disable=unused-import\nfrom tensorflow.python.platform import test\nimport tensorflow as tf\nimport random\nimport numpy as np\nimport time\nimport sparse_tools as sp\nfrom direct_sparse_module import sparse_nn_ops as sc_module\nfrom math import ceil as ceil\nimport os\nimport sys\n\ndef verifyValues(tensor_in_sizes, rho_data = 0.1, dim = 5, num_trials = 3):\n [t1ind, t1val, t1sh] = sp.createRandomSparseTensor(rho_data, tensor_in_sizes)\n [t2ind, t2val, t2sh] = sp.createRandomSparseTensor(rho_data, tensor_in_sizes)\n \n config = tf.ConfigProto()\n config.gpu_options.per_process_gpu_memory_fraction = 0.7\n\n #reorder data and generate block index lookup table\n with tf.device(\"/gpu:0\"):\n con1 = sc_module.direct_sparse_data_conversion(t1ind, t1val, t1sh)\n con2 = sc_module.direct_sparse_data_conversion(t2ind, t2val, t2sh)\n with tf.Session(config=config) as sess:\n pd1 = sess.run(con1)\n pd2 = sess.run(con2)\n tf.reset_default_graph()\n values1 = pd1.out_values\n\n ts = 0\n with tf.device(\"/gpu:0\"):\n concat = sc_module.direct_sparse_concat(\n pd1.out_indices, \n pd1.out_values, \n pd1.out_shape, \n pd1.out_block_channel_mapping, \n pd2.out_indices, \n pd2.out_values, \n pd2.out_shape, \n pd2.out_block_channel_mapping);\n\n with tf.Session(config=config) as sess:\n t6 = time.time()\n sv3 = sess.run(concat)\n t5 = time.time()\n for i in range(0, num_trials):\n sess.run(concat)\n t6 = time.time()\n ts = abs(t6 - t5) / max(num_trials,1)\n print(\"time sparse concat: \", ts)\n \n tf.reset_default_graph()\n print(\"pd1\", pd1)\n print(\"\")\n print(\"pd2\", pd2)\n print(\"\")\n print(\"sv3\", sv3) \n return 0\n\npid = os.getpid()\nprint(pid)\n#raw_input(\"Press Enter to continue...\")\n\nnum_trials = 0\nres = 3\nchannel_count = 2\nbatch_size = 3\nin_density = 1\nret_value = verifyValues(\n tensor_in_sizes=[batch_size, res, 1, 1, channel_count], #[batch, depth, height, width, in_channels]\n rho_data=1 * in_density,\n num_trials=num_trials)\n\nsys.exit(ret_value)\n","sub_path":"tensorflow/core/user_ops/gpu_tests/unit_test_direct_concat_gpu.py","file_name":"unit_test_direct_concat_gpu.py","file_ext":"py","file_size_in_byte":2505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"401876810","text":"#!/usr/bin/Python\n\nimport sys\nimport os\nfrom PyQt5 import QtWidgets, QtCore\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n widget = QtWidgets.QWidget()\n widget.resize(800, 600)\n widget.setWindowTitle(\"Hello, PyQt5\")\n widget.show()\n\n sys.exit(app.exec_())","sub_path":"pyqt5/hello_window.py","file_name":"hello_window.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"504889612","text":"# -*- coding: utf-8 -*-\nfrom .utils import exists, nlargest, removeMultiple\nfrom .spell import Spell\n\nclass KeyboardSpell(Spell):\n def __init__(self, spelldic=None, corpusfile=None, suffixfile=None, language=None, encoding=None, keyboardlayoutfile=None, weightObjFun=None):\n # call the parent constructor\n Spell.__init__(self, spelldic, corpusfile, suffixfile, language, encoding)\n #super(self.__class__, self).__init__(spelldic)\n # or Spell.__init__(self, dicFile)\n self.load_keyboard_layout(keyboardlayoutfile)\n self.set_weightObjFun(weightObjFun)\n #if weightObjFun is None:\n # self.weightObjFun = (0.5, 0.5)\n #else:\n # self.set_weightObjFun(weightObjFun)\n #if sum(weightObjFun) != 1:\n # raise TypeError(\"Weights do not sum 1.\")\n #self.weightObjFun = weightObjFun \n\n @classmethod\n def from_file(cls, spelldic=None, corpusfile=None, suffixfile=None, language=None, encoding=None, keyboardlayoutfile=None, weightObjFun=None):\n return cls(spelldic, corpusfile, suffixfile, language, encoding, keyboardlayoutfile, weightObjFun)\n #mySpell = super().from_file(filename)\n #mySpell.load_keyboard_layout(keyboardlayoutfile)\n #mySpell.set_weightObjFun(weightObjFun)\n #return mySpell\n\n# @classmethod\n# def from_dictionary(cls, spelldic, keyboardlayoutfile=None, weightObjFun=None):\n# mySpell = super().from_dictionary(spelldic)\n# mySpell.load_keyboard_layout(keyboardlayoutfile)\n# mySpell.set_weightObjFun(weightObjFun)\n# return mySpell\n\n# @classmethod\n# def from_text_corpus(cls, textfile=None, keyboardlayoutfile=None, weightObjFun=None):\n# mySpell = super().from_text_corpus(textfile)\n# mySpell.load_keyboard_layout(keyboardlayoutfile)\n# mySpell.set_weightObjFun(weightObjFun)\n# return mySpell\n\n def set_weightObjFun(self, weight):\n if weight is None:\n self.weightObjFun = (0.5, 0.5)\n else:\n if sum(weight) != 1:\n raise TypeError(\"Weights do not sum 1.\")\n self.weightObjFun = weight\n\n def load_keyboard_layout(self, keyboardlayoutfile):\n \"\"\" \n Read keyboard layout from JSON file or text file (in this case, performs a literal evaluation of the python string).\n Args:\n keyboardlayoutfile: A keyboard layout file in JSON format or using python syntax.\n \"\"\"\n import json\n if keyboardlayoutfile is not None:\n if keyboardlayoutfile.endswith('.json'):\n with open(keyboardlayoutfile, 'r') as f:\n self.kblayout = json.load(f)\n else:\n import ast\n with open(keyboardlayoutfile, 'r') as f:\n self.kblayout = ast.literal_eval(f.read())\n\n def getCharacterCoord(self, c):\n \"\"\"\n Finds a 2-tuple representing c's position on the given keyboard array.\n If the character is not in the given array, throws a ValueError\n \"\"\"\n row = -1\n column = -1\n if self.kblayout is None:\n raise Exception(\"Speller keyboard is empty!\")\n for kb in self.kblayout:\n for r in kb:\n if c in r:\n row = kb.index(r)\n column = r.index(c)\n return (row, column)\n raise ValueError(c + \" not found in given keyboard layout\")\n\n def typoDistance(self, s, t, saturation=1000):\n \"\"\"\n Finds the typo Manhattan distance (an integer) between two characters, based\n on the keyboard layout. The distance might be a saturated value.\n \"\"\"\n # add one if one is lowercase and other is not (shift diff)\n addShiftDiff = int( s.islower() != t.islower() )\n sc = self.getCharacterCoord(s.lower())\n tc = self.getCharacterCoord(t.lower())\n return min( sum( [abs(x-y) for x,y in zip(sc,tc)] ) + addShiftDiff, saturation)\n\n def keyboard_damerau_levenshtein_distance(self, s1, s2, saturation=4):\n \"\"\"\n Computes the Damerau-Levenshtein distance between two strings considering different typo distances according to their keyboard distance.\n The substitution cost is given by the keyboard distance between the two typos involved.\n The insertion and deletion cost is the minimum distance between the inserted/deleted typo and the previous and next typo.\n \"\"\"\n d = {}\n lenstr1 = len(s1)\n lenstr2 = len(s2)\n for i in range(-1,lenstr1+1):\n d[(i,-1)] = i+1\n for j in range(-1,lenstr2+1):\n d[(-1,j)] = j+1\n for i in range(lenstr1):\n for j in range(lenstr2):\n if s1[i] == s2[j]:\n cost = 0\n else:\n cost = self.typoDistance(s1[i], s2[j], saturation=saturation)\n delcost = min( self.typoDistance(s1[i], s1[i-1], saturation=saturation) if i > 0 and i < lenstr1 else 10, \n self.typoDistance(s1[i], s1[i+1], saturation=saturation) if i > -1 and i < lenstr1-1 else 10\n )\n inscost = min( self.typoDistance(s2[j], s2[j-1], saturation=saturation) if j > 0 and j < lenstr2 else 10,\n self.typoDistance(s2[j], s2[j+1], saturation=saturation) if j > -1 and j < lenstr2-1 else 10\n )\n #print 'delcost=' + str(delcost) + ', inscost=' + str(inscost) + ', cost=' + str(cost)\n d[(i,j)] = min(\n d[(i-1,j)] + delcost, # deletion\n d[(i,j-1)] + inscost, # insertion\n d[(i-1,j-1)] + cost, # substitution\n )\n if i and j and s1[i]==s2[j-1] and s1[i-1] == s2[j]:\n d[(i,j)] = min (d[(i,j)], d[i-2,j-2] + cost) # transposition\n return d[lenstr1-1,lenstr2-1]\n\n def ObjectiveFunction(self, candidate, word, saturation=4):\n \"\"\"\n Provides the objective function to the optimization process. \n It balances the probability of a candidate and its typing keyboard distance from the misspelled word.\n\n\t f\n\t log ---\n\t m log d\n\tw0 --------- - w1 ---------\n\t M log d \n\t log --- max\n\t m\n\n\tw_1 \\frac{\\log (f/m)}{\\log (M/m)} - w_2 \\frac{ \\log d}{\\log d_{max}} \n \"\"\"\n if self.weightObjFun[1] > 0:\n d = self.keyboard_damerau_levenshtein_distance(candidate, word, saturation)\n maxdist = saturation*max(len(candidate),len(word))\n if candidate in self.WORDS:\n return self.weightObjFun[0]*(log10(float(self.WORDS[candidate])/self.m) / log10(float(self.M)/self.m)) - self.weightObjFun[1]*(log10(float(d)) / log10(maxdist))\n else:\n return -d\n return Spell.ObjectiveFunction(self, candidate, word)\n else:\n return super(KeyboardSpell,self).ObjectiveFunction(candidate, word) \n return self.P(candidate)\n\n","sub_path":"spell/keyboardspell.py","file_name":"keyboardspell.py","file_ext":"py","file_size_in_byte":7134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"597387366","text":"#!/usr/bin/env python3\n# --- Day 12: Rain Risk ---\n\nfrom typing import Tuple\nfrom dataclasses import dataclass\nfrom math import cos, sin, radians\n\n\n@dataclass\nclass Position:\n x: int = 0\n y: int = 0\n\n def move(self, direction: str, units: int) -> None:\n if direction == \"N\":\n self.y += units\n elif direction == \"S\":\n self.y -= units\n elif direction == \"E\":\n self.x += units\n elif direction == \"W\":\n self.x -= units\n else:\n raise ValueError(f\"invalid direction {direction}\")\n\n def move_towards(self, waypoint: \"Position\", units: int) -> None:\n self.x += units * waypoint.x\n self.y += units * waypoint.y\n\n def rotate(self, direction: str, degrees: int) -> None:\n assert degrees % 90 == 0\n theta = radians(90)\n for _ in range(degrees // 90):\n (x, y) = self.x, self.y\n if direction == \"R\":\n self.x = x * cos(-theta) - y * sin(-theta)\n self.y = x * sin(-theta) + y * cos(-theta)\n elif direction == \"L\":\n self.x = x * cos(theta) - y * sin(theta)\n self.y = x * sin(theta) + y * cos(theta)\n else:\n raise ValueError(f\"invalid direction {direction}\")\n\n def manhattan(self) -> int:\n return round(abs(self.x) + abs(self.y))\n\n\nclass Ship:\n def __init__(self, position: Position) -> None:\n self._position = Position(position.x, position.y)\n self._orientation = 0\n\n def move(self, direction: str, units: int) -> None:\n self._position.move(direction, units)\n\n def move_towards(self, waypoint: \"Position\", units: int) -> None:\n self._position.move_towards(waypoint, units)\n\n def forward(self, units: int) -> None:\n self.move(self.cardinal, units)\n\n def rotate(self, direction: str, degrees: int) -> None:\n assert degrees % 90 == 0\n assert direction in [\"L\", \"R\"]\n if direction == \"R\":\n self._orientation -= degrees\n else:\n self._orientation += degrees\n self._orientation %= 360\n\n @property\n def position(self) -> Position:\n return self._position\n\n @property\n def degrees(self) -> int:\n return self._orientation\n\n @property\n def cardinal(self) -> int:\n if self._orientation == 0:\n return \"E\"\n elif self._orientation == 90:\n return \"N\"\n elif self._orientation == 180:\n return \"W\"\n elif self._orientation == 270:\n return \"S\"\n\n\ndef navigate(ship: Ship, instruction: str, waypoint: Position = None) -> None:\n (action, value) = (instruction[0], int(instruction[1:]))\n if action in [\"N\", \"S\", \"W\", \"E\"]:\n if waypoint:\n waypoint.move(action, value)\n else:\n ship.move(action, value)\n if action in [\"L\", \"R\"]:\n if waypoint:\n waypoint.rotate(action, value)\n else:\n ship.rotate(action, value)\n if action in [\"F\"]:\n if waypoint:\n ship.move_towards(waypoint, value)\n else:\n ship.forward(value)\n\n\nif __name__ == \"__main__\":\n data = None\n with open(\"input/day12.txt\") as f:\n data = f.read()\n\n starting_position = Position(0, 0)\n ship = Ship(starting_position)\n for i in data.split(\"\\n\")[:-1]:\n navigate(ship, i)\n\n print(\"part1 solution:\", ship.position.manhattan())\n\n starting_position = Position(0, 0)\n waypoint = Position(10, 1)\n ship = Ship(starting_position)\n for i in data.split(\"\\n\")[:-1]:\n navigate(ship, i, waypoint)\n\n print(\"part2 solution:\", ship.position.manhattan())\n","sub_path":"day12.py","file_name":"day12.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"138444200","text":"#Views for autocomplete\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom dal import autocomplete\n\nfrom db.models import *\nfrom db.models.object import Object\nfrom db.models.value import *\n\nclass ValueAutocomplete(autocomplete.Select2ListView):\n def get_list(self):\n return [x.base_name.capitalize() for x in Value.get_value_types()]\n\nclass CategoryAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = Category.objects.all()\n if self.q:\n qs = qs.filter(name__istartswith=self.q)\n return qs\n\nclass ObjectAutocomplete(autocomplete.Select2ListView):\n def get_list(self):\n return [x.base_name.capitalize() for x in Object.get_object_types()]\n\nclass SampleToFeatureAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = Feature.objects.all()\n if self.q:\n qs = qs.filter(name__istartswith=self.q)\n return qs\n\ndef object_relation_view_factory(from_object, to_object):\n from_object = Object.get_object_types(type_name=from_object)\n to_object = Object.get_object_types(type_name=to_object)\n\n class ObjectToObjectAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = to_object.objects.all()\n if self.q:\n qs = qs.filter(name__istartswith(self.q))\n return qs\n\n ObjectToObjectAutocomplete.__name__ = from_object.base_name.capitalize() + \"To\" + to_object.base_name.capitalize() + \"Autocomplete\"\n ObjectToObjectAutocomplete.__qualname__ = ObjectToObjectAutocomplete.__name__\n return ObjectToObjectAutocomplete\n\n#Register these at top level\nfor ObjA in Object.get_object_types():\n for ObjB in Object.get_object_types():\n generated_class = object_relation_view_factory(ObjA.base_name, ObjB.base_name)\n globals()[generated_class.__name__] = generated_class\n\ndef object_autocomplete_factory(object_name):\n obj = Object.get_object_types(type_name=object_name)\n\n class ObjectAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = obj.objects.all()\n if self.q:\n qs = qs.filter(name__icontains=self.q)\n pk = self.forwarded.get('pk', None)\n if pk:\n pks = pk.split(\",\")\n pks = [int(x) for x in pks]\n qs = qs.filter(pk__in=pks)\n return qs.distinct()\n\n ObjectAutocomplete.__name__ = obj.base_name.capitalize() + \"Autocomplete\"\n ObjectAutocomplete.__qualname__ = ObjectAutocomplete.__name__\n return ObjectAutocomplete\n\nfor Obj in Object.get_object_types():\n generated_class = object_autocomplete_factory(Obj.base_name)\n globals()[generated_class.__name__] = generated_class\n\nclass TreeResultAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = Result.objects.filter(values__signature__name=\"newick\")\n if self.q:\n qs = qs.filter(name__icontains=self.q)\n return qs.distinct()\n\nclass TaxonomyResultAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = Result.objects.filter(values__signature__name=\"taxonomic_classification\")\n if self.q:\n qs = qs.filter(name__icontains=self.q)\n return qs.distinct()\n\nclass CountMatrixAutocomplete(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n matrix_ct = ContentType.objects.get_for_model(Matrix)\n qs = Result.objects.filter(values__signature__value_type=matrix_ct)\n if self.q:\n qs = qs.filter(name__icontains=self.q)\n return qs.distinct()\n\nclass TaxonomicLevelAutocomplete(autocomplete.Select2ListView):\n def get_list(self):\n return [\"kingdom\",\"phylum\",\"class\",\"order\",\"family\",\"genus\",\"species\"]\n","sub_path":"db/autocomplete_views.py","file_name":"autocomplete_views.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"594115283","text":"# -*- coding: utf-8 -*-\n\"\"\"\n pygments.lexers.postgres\n ~~~~~~~~~~~~~~~~~~~~~~~~\n\n Lexers for PostgreSQL-specific SQL and psql interactive session.\n\n `PostgresLexer`\n A SQL lexer for the PostgreSQL dialect. Differences w.r.t. the SQL\n lexer are:\n\n - keywords and data types list parsed from the PG docs (run the\n `_postgres_builtins` module to update them);\n - Content of $-strings parsed using a specific lexer, e.g. the content\n of a PL/Python function is parsed using the Python lexer;\n - parse PG specific constructs: E-strings, $-strings, U&-strings,\n different operators and punctuation.\n\n `PlPgsqlLexer`\n A lexer for the PL/pgSQL language. Adds a few specific construct on\n top of the PG SQL lexer (such as <>).\n\n `PostgresConsoleLexer`\n A lexer to highlight an interactive psql session:\n\n - identifies the prompt and does its best to detect the end of command\n in multiline statement where not all the lines are prefixed by a\n prompt, telling them apart from the output;\n - highlights errors in the output and notification levels;\n - handles psql backslash commands.\n\n The ``tests/examplefiles`` contains a few test files with data to be\n parsed by these lexers.\n\n :copyright: Copyright 2006-2011 by the Pygments team, see AUTHORS.\n :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nfrom copy import deepcopy\n\nfrom pygments.lexer import Lexer, RegexLexer, do_insertions\nfrom pygments.token import Punctuation, \\\n Text, Comment, Operator, Keyword, Name, String, Number, Generic\nfrom pygments.lexers import get_lexer_by_name, ClassNotFound\n\nfrom pygments.lexers._postgres_builtins import KEYWORDS, DATATYPES, \\\n PSEUDO_TYPES, PLPGSQL_KEYWORDS\n\n\n__all__ = ['PostgresLexer', 'PlPgsqlLexer', 'PostgresConsoleLexer']\n\nline_re = re.compile('.*?\\n')\n\nlanguage_re = re.compile(r\"\\s+LANGUAGE\\s+'?(\\w+)'?\", re.IGNORECASE)\n\ndef language_callback(lexer, match):\n \"\"\"Parse the content of a $-string using a lexer\n\n The lexer is chosen looking for a nearby LANGUAGE.\n\n Note: this function should have been a `PostgresBase` method, but the\n rules deepcopy fails in this case.\n \"\"\"\n l = None\n m = language_re.match(lexer.text[match.end():match.end()+100])\n if m is not None:\n l = lexer._get_lexer(m.group(1))\n else:\n m = list(language_re.finditer(\n lexer.text[max(0, match.start()-100):match.start()]))\n if m:\n l = lexer._get_lexer(m[-1].group(1))\n\n if l:\n yield (match.start(1), String, match.group(1))\n for x in l.get_tokens_unprocessed(match.group(2)):\n yield x\n yield (match.start(3), String, match.group(3))\n\n else:\n yield (match.start(), String, match.group())\n\n\nclass PostgresBase(object):\n \"\"\"Base class for Postgres-related lexers.\n\n This is implemented as a mixin to avoid the Lexer metaclass kicking in.\n this way the different lexer don't have a common Lexer ancestor. If they\n had, _tokens could be created on this ancestor and not updated for the\n other classes, resulting e.g. in PL/pgSQL parsed as SQL. This shortcoming\n seem to suggest that regexp lexers are not really subclassable.\n\n `language_callback` should really be our method, but this breaks deepcopy.\n \"\"\"\n def get_tokens_unprocessed(self, text, *args):\n # Have a copy of the entire text to be used by `language_callback`.\n self.text = text\n for x in super(PostgresBase, self).get_tokens_unprocessed(\n text, *args):\n yield x\n\n def _get_lexer(self, lang):\n if lang.lower() == 'sql':\n return get_lexer_by_name('postgresql', **self.options)\n\n tries = [ lang ]\n if lang.startswith('pl'):\n tries.append(lang[2:])\n if lang.endswith('u'):\n tries.append(lang[:-1])\n if lang.startswith('pl') and lang.endswith('u'):\n tries.append(lang[2:-1])\n\n for l in tries:\n try:\n return get_lexer_by_name(l, **self.options)\n except ClassNotFound:\n pass\n else:\n # TODO: better logging\n # print >>sys.stderr, \"language not found:\", lang\n return None\n\n\nclass PostgresLexer(PostgresBase, RegexLexer):\n \"\"\"\n Lexer for the PostgreSQL dialect of SQL.\n\n *New in Pygments 1.5.*\n \"\"\"\n\n name = 'PostgreSQL SQL dialect'\n aliases = ['postgresql', 'postgres']\n mimetypes = ['text/x-postgresql']\n\n flags = re.IGNORECASE\n tokens = {\n 'root': [\n (r'\\s+', Text),\n (r'--.*?\\n', Comment.Single),\n (r'/\\*', Comment.Multiline, 'multiline-comments'),\n (r'(' + '|'.join([s.replace(\" \", \"\\s+\")\n for s in DATATYPES + PSEUDO_TYPES])\n + r')\\b', Name.Builtin),\n (r'(' + '|'.join(KEYWORDS) + r')\\b', Keyword),\n (r'[+*/<>=~!@#%^&|`?^-]+', Operator),\n (r'::', Operator), # cast\n (r'\\$\\d+', Name.Variable),\n (r'([0-9]*\\.[0-9]*|[0-9]+)(e[+-]?[0-9]+)?', Number.Float),\n (r'[0-9]+', Number.Integer),\n (r\"(E|U&)?'(''|[^'])*'\", String.Single),\n (r'(U&)?\"(\"\"|[^\"])*\"', String.Name), # quoted identifier\n (r'(?ms)(\\$[^\\$]*\\$)(.*?)(\\1)', language_callback),\n (r'[a-zA-Z_][a-zA-Z0-9_]*', Name),\n\n # psql variable in SQL\n (r\"\"\":(['\"]?)[a-z][a-z0-9_]*\\b\\1\"\"\", Name.Variable),\n\n (r'[;:()\\[\\]\\{\\},\\.]', Punctuation),\n ],\n 'multiline-comments': [\n (r'/\\*', Comment.Multiline, 'multiline-comments'),\n (r'\\*/', Comment.Multiline, '#pop'),\n (r'[^/\\*]+', Comment.Multiline),\n (r'[/*]', Comment.Multiline)\n ],\n }\n\n\nclass PlPgsqlLexer(PostgresBase, RegexLexer):\n \"\"\"\n Handle the extra syntax in Pl/pgSQL language.\n\n *New in Pygments 1.5.*\n \"\"\"\n name = 'PL/pgSQL'\n aliases = ['plpgsql']\n mimetypes = ['text/x-plpgsql']\n\n flags = re.IGNORECASE\n tokens = deepcopy(PostgresLexer.tokens)\n\n # extend the keywords list\n for i, pattern in enumerate(tokens['root']):\n if pattern[1] == Keyword:\n tokens['root'][i] = (\n r'(' + '|'.join(KEYWORDS + PLPGSQL_KEYWORDS) + r')\\b',\n Keyword)\n del i\n break\n else:\n assert 0, \"SQL keywords not found\"\n\n # Add specific PL/pgSQL rules (before the SQL ones)\n tokens['root'][:0] = [\n (r'\\%[a-z][a-z0-9_]*\\b', Name.Builtin), # actually, a datatype\n (r':=', Operator),\n (r'\\<\\<[a-z][a-z0-9_]*\\>\\>', Name.Label),\n (r'\\#[a-z][a-z0-9_]*\\b', Keyword.Pseudo), # #variable_conflict\n ]\n\n\nclass PsqlRegexLexer(PostgresBase, RegexLexer):\n \"\"\"\n Extend the PostgresLexer adding support specific for psql commands.\n\n This is not a complete psql lexer yet as it lacks prompt support\n and output rendering.\n \"\"\"\n\n name = 'PostgreSQL console - regexp based lexer'\n aliases = [] # not public\n\n flags = re.IGNORECASE\n tokens = deepcopy(PostgresLexer.tokens)\n\n tokens['root'].append(\n (r'\\\\[^\\s]+', Keyword.Pseudo, 'psql-command'))\n tokens['psql-command'] = [\n (r'\\n', Text, 'root'),\n (r'\\s+', Text),\n (r'\\\\[^\\s]+', Keyword.Pseudo),\n (r\"\"\":(['\"]?)[a-z][a-z0-9_]*\\b\\1\"\"\", Name.Variable),\n (r\"'(''|[^'])*'\", String.Single),\n (r\"`([^`])*`\", String.Backtick),\n (r\"[^\\s]+\", String.Symbol),\n ]\n\nre_prompt = re.compile(r'^(\\S.*?)??[=\\-\\(\\$\\'\\\"][#>]')\nre_psql_command = re.compile(r'\\s*\\\\')\nre_end_command = re.compile(r';\\s*(--.*?)?$')\nre_psql_command = re.compile(r'(\\s*)(\\\\.+?)(\\s+)$')\nre_error = re.compile(r'(ERROR|FATAL):')\nre_message = re.compile(\n r'((?:DEBUG|INFO|NOTICE|WARNING|ERROR|'\n r'FATAL|HINT|DETAIL|LINE [0-9]+):)(.*?\\n)')\n\ndef lookahead(x):\n \"\"\"Wrap an iterator and allow pushing back an item.\"\"\"\n for i in x:\n while 1:\n i = yield i\n if i is None:\n break\n yield i\n\n\nclass PostgresConsoleLexer(Lexer):\n \"\"\"\n Lexer for psql sessions.\n\n *New in Pygments 1.5.*\n \"\"\"\n\n name = 'PostgreSQL console (psql)'\n aliases = ['psql', 'postgresql-console', 'postgres-console']\n mimetypes = ['text/x-postgresql-psql']\n\n def get_tokens_unprocessed(self, data):\n sql = PsqlRegexLexer(**self.options)\n\n lines = lookahead(line_re.findall(data))\n\n # prompt-output cycle\n while 1:\n\n # consume the lines of the command: start with an optional prompt\n # and continue until the end of command is detected\n curcode = ''\n insertions = []\n while 1:\n try:\n line = lines.next()\n except StopIteration:\n # allow the emission of partially collected items\n # the repl loop will be broken below\n break\n\n # Identify a shell prompt in case of psql commandline example\n if line.startswith('$') and not curcode:\n lexer = get_lexer_by_name('console', **self.options)\n for x in lexer.get_tokens_unprocessed(line):\n yield x\n break\n\n # Identify a psql prompt\n mprompt = re_prompt.match(line)\n if mprompt is not None:\n insertions.append((len(curcode),\n [(0, Generic.Prompt, mprompt.group())]))\n curcode += line[len(mprompt.group()):]\n else:\n curcode += line\n\n # Check if this is the end of the command\n # TODO: better handle multiline comments at the end with\n # a lexer with an external state?\n if re_psql_command.match(curcode) \\\n or re_end_command.search(curcode):\n break\n\n # Emit the combined stream of command and prompt(s)\n for item in do_insertions(insertions,\n sql.get_tokens_unprocessed(curcode)):\n yield item\n\n # Emit the output lines\n out_token = Generic.Output\n while 1:\n line = lines.next()\n mprompt = re_prompt.match(line)\n if mprompt is not None:\n # push the line back to have it processed by the prompt\n lines.send(line)\n break\n\n mmsg = re_message.match(line)\n if mmsg is not None:\n if mmsg.group(1).startswith(\"ERROR\") \\\n or mmsg.group(1).startswith(\"FATAL\"):\n out_token = Generic.Error\n yield (mmsg.start(1), Generic.Strong, mmsg.group(1))\n yield (mmsg.start(2), out_token, mmsg.group(2))\n else:\n yield (0, out_token, line)\n","sub_path":"pygments/lexers/postgres.py","file_name":"postgres.py","file_ext":"py","file_size_in_byte":11115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"18684971","text":"import scipy.optimize as scp\nimport numpy as np\nimport Functions as fu\nimport copy\nimport matplotlib.pyplot as plt\n\nclass GainFinder(object):\n def __init__(self, ROOTFile):\n self.ROOTFile = ROOTFile\n self.initial_params = []\n self.hist_string = \"hist_charge_CNUM\"\n\n self.ped_mean = None\n self.ped_sigma = None\n self.ped_fit_y = None\n self.ped_fit_y_un = None\n self.ped_fit_x = None\n\n self.fitfunc = None\n self.lower_bounds = None\n self.upper_bounds = None\n\n\n def setFitFunction(self,fitfunc):\n self.fitfunc = fitfunc\n \n def setInitialFitParams(self,initial_params):\n self.initial_params = initial_params\n\n def setInitMean(self,mean):\n self.initial_params[1] = mean #FIXME: This is specific to how gauss1 is defined. generalize\n \n def setTauMax(self,tau):\n print(\"TAU MAX WILL BE: \" + str(tau))\n self.upper_bounds[8] = tau #FIXME: This is specific to how gauss1 is defined. generalize\n\n def setBounds(self,lower_bounds,upper_bounds):\n self.lower_bounds = lower_bounds\n self.upper_bounds = upper_bounds\n\n def FitPedestal(self,HistName,init_params,fit_range,fit_tail=False,exp_fit_range=[]):\n '''\n Uses a Gaussian from the Functions library to attempt to fit\n the pedestal peak of the distribution. A fit range can be\n given if helping down-select to the pedestal-dominant region.\n\n Inputs:\n\n HistName [string]\n string of histogram name in self.ROOTFile.\n\n init_params [array]\n Initial parameters to try fitting a single gaussian with.\n Format is [amplitude,mean,sigma].\n\n fit_range [array]\n Range of values to perform fit across. Helps to down-select\n to the ped-only range.\n '''\n print(\"FITTING TO PEDESTAL NOW\")\n thehist = self.ROOTFile.Get(HistName)\n #Get histogram information into ntuples\n bin_centers, evts,evts_unc =(), (), () #pandas wants ntuples\n fit_bin_centers, fit_evts,fit_evts_unc =(), (), () #pandas wants ntuples\n ped_indices = []\n for i in xrange(int(thehist.GetNbinsX()+1)):\n if i==0:\n continue\n bin_centers = bin_centers + ((float(thehist.GetBinWidth(i))/2.0) + float(thehist.GetBinLowEdge(i)),)\n evts = evts + (thehist.GetBinContent(i),)\n evts_unc = evts_unc + (thehist.GetBinError(i),)\n fit_bin_centers = fit_bin_centers + ((float(thehist.GetBinWidth(i))/2.0) + float(thehist.GetBinLowEdge(i)),)\n fit_evts = fit_evts + (thehist.GetBinContent(i),)\n fit_evts_unc = fit_evts_unc + (thehist.GetBinError(i),)\n bin_centers = np.array(bin_centers)\n evts = np.array(evts)\n evts_unc = np.array(evts_unc)\n fit_bin_centers = np.array(fit_bin_centers)\n fit_evts = np.array(fit_evts)\n fit_evts_unc = np.array(fit_evts_unc)\n if len(fit_range)>0:\n fit_bin_inds = np.where((bin_centers > fit_range[0]) & (bin_centers < fit_range[1]))[0]\n fit_bin_centers = fit_bin_centers[fit_bin_inds]\n fit_evts = fit_evts[fit_bin_inds]\n fit_vts_unc = fit_evts_unc[fit_bin_inds]\n print(\"TRYING INITIAL PARAMS: \" + str(init_params))\n try:\n popt, pcov = scp.curve_fit(fu.gauss1, bin_centers, evts, p0=init_params, maxfev=6000)\n except RuntimeError:\n print(\"NO SUCCESSFUL FIT TO PEDESTAL AFTER ITERATIONS...\")\n popt = None\n pcov = None\n return popt, pcov, bin_centers, evts, evts_unc\n self.ped_fit_x = bin_centers\n self.ped_fit_y =fu.gauss1(self.ped_fit_x,popt[0],popt[1],popt[2])\n perr = np.diag(pcov)\n self.ped_fit_y_unc =abs(fu.gauss1(self.ped_fit_x,popt[0]+perr[0],popt[1],popt[2]+perr[2]) - \n fu.gauss1(self.ped_fit_x,popt[0]-perr[0],popt[1],popt[2]-perr[2]))\n self.ped_mean = popt[1]\n self.ped_sigma = popt[2]\n #self.ped_fit_y =fu.OrderStat(self.ped_fit_x,popt[0],popt[1],popt[2],popt[3]) \n #self.ped_mean = popt[2]\n #self.ped_sigma = popt[3]\n if fit_tail is True:\n exp_ind = []\n if len(exp_fit_range) > 0:\n exp_ind = np.where((bin_centers > exp_fit_range[0]) & (bin_centers < exp_fit_range[1]))[0]\n else:\n exp_ind = np.where((bin_centers > self.ped_mean+self.ped_sigma) & (bin_centers < self.ped_mean + 3*self.ped_sigma))[0]\n exp_bins = bin_centers[exp_ind]\n exp_evts = evts[exp_ind]\n exp_evts_unc = evts_unc[exp_ind]\n #exp_init_params = [popt[0]/popt[2],popt[2],10*popt[1]]\n exp_init_params = [exp_evts[0],popt[2],10*popt[1]]\n print(\"EXPONENTIAL FIT: INIT PARAMS: \" + str(exp_init_params))\n try:\n eopt, ecov = scp.curve_fit(lambda x,D,tau,t: fu.gaussPlusExpo(x,popt[0],popt[1],popt[2],D,tau,t), \n exp_bins, exp_evts, p0=exp_init_params, sigma=exp_evts_unc, maxfev=12000)\n #eopt, ecov = scp.curve_fit(lambda x,D,tau,t: D*np.exp(-(x-t)/tau), \n # exp_bins, exp_evts, p0=exp_init_params, maxfev=12000)\n except RuntimeError:\n print(\"NO SUCCESSFUL FIT TO PEDESTAL AFTER ITERATIONS...\")\n popt = None\n pcov = None\n return popt, pcov, bin_centers, evts, evts_unc\n popt = np.concatenate((popt,eopt))\n #\n self.ped_fit_y =fu.gaussPlusExpo(self.ped_fit_x,popt[0],popt[1],\n popt[2],eopt[0],eopt[1],eopt[2]) \n return popt, pcov, bin_centers,evts,evts_unc\n\n def FitPEPeaks(self,HistName,exclude_ped = True, subtract_ped = False,\n fit_range = []):\n thehist = self.ROOTFile.Get(HistName)\n #Get histogram information into ntuples\n bin_centers, evts,evts_unc =(), (), () #pandas wants ntuples\n fit_bin_centers, fit_evts,fit_evts_unc =(), (), () #pandas wants ntuples\n for i in xrange(int(thehist.GetNbinsX()+1)):\n if i==0:\n continue\n bin_centers = bin_centers + ((float(thehist.GetBinWidth(i))/2.0) + float(thehist.GetBinLowEdge(i)),)\n evts = evts + (thehist.GetBinContent(i),)\n evts_unc = evts_unc + (thehist.GetBinError(i),)\n# if exclude_ped is True and ((float(thehist.GetBinWidth(i))/2.0) + \\\n# float(thehist.GetBinLowEdge(i)) < (self.ped_mean + 3*self.ped_sigma)):\n# continue\n fit_bin_centers = fit_bin_centers + ((float(thehist.GetBinWidth(i))/2.0) + float(thehist.GetBinLowEdge(i)),)\n fit_evts = fit_evts + (thehist.GetBinContent(i),)\n fit_evts_unc = fit_evts_unc + (thehist.GetBinError(i),)\n bin_centers = np.array(bin_centers)\n evts = np.array(evts)\n evts_unc = np.array(evts_unc)\n fit_bin_centers = np.array(fit_bin_centers)\n fit_evts = np.array(fit_evts)\n fit_evts_unc = np.array(fit_evts_unc)\n if len(fit_range)>0:\n fit_bin_inds = np.where((fit_bin_centers > fit_range[0]) & (fit_bin_centers < fit_range[1]))[0]\n fit_bin_centers = fit_bin_centers[fit_bin_inds]\n fit_evts = fit_evts[fit_bin_inds]\n fit_evts_unc = fit_evts_unc[fit_bin_inds]\n if subtract_ped:\n fit_evts = fit_evts - self.ped_fit_y\n fit_evts_unc = np.sqrt(evts_unc**2 + self.ped_fit_y_unc**2)\n if exclude_ped:\n fit_bin_inds = np.where(bin_centers>=(self.ped_mean + 1*self.ped_sigma))\n fit_evts = fit_evts[fit_bin_inds]\n fit_evts_unc = fit_evts_unc[fit_bin_inds]\n fit_bin_centers = fit_bin_centers[fit_bin_inds]\n zerobins = np.where(fit_evts_unc<=1)[0]\n fit_evts_unc[zerobins] = 1.15\n #plt.errorbar(fit_bin_centers,fit_evts,yerr=fit_evts_unc,marker='o',linestyle=\"None\")\n #plt.show()\n print(\"INITIAL PARAMS FOR FIT: \" + str(self.initial_params))\n try:\n if self.lower_bounds is None or self.upper_bounds is None:\n popt, pcov = scp.curve_fit(self.fitfunc, fit_bin_centers, fit_evts, p0=self.initial_params, \n sigma = fit_evts_unc, maxfev=6000)\n else:\n popt, pcov = scp.curve_fit(self.fitfunc, fit_bin_centers, fit_evts, p0=self.initial_params,\n bounds=(self.lower_bounds,self.upper_bounds),sigma = fit_evts_unc,maxfev=6000)\n except RuntimeError:\n print(\"NO SUCCESSFUL FIT AFTER ITERATIONS...\")\n popt = None\n pcov = None\n return popt, pcov, bin_centers, evts, evts_unc\n\n def FitPEPeaksV2(self,HistName,exclude_ped = True, subtract_ped = False):\n thehist = self.ROOTFile.Get(HistName)\n #Get histogram information into ntuples\n bin_centers, evts,evts_unc =(), (), () #pandas wants ntuples\n fit_bin_centers, fit_evts,fit_evts_unc =(), (), () #pandas wants ntuples\n for i in xrange(int(thehist.GetNbinsX()+1)):\n if i==0:\n continue\n bin_centers = bin_centers + ((float(thehist.GetBinWidth(i))/2.0) + float(thehist.GetBinLowEdge(i)),)\n evts = evts + (thehist.GetBinContent(i),)\n evts_unc = evts_unc + (thehist.GetBinError(i),)\n if exclude_ped is True and ((float(thehist.GetBinWidth(i))/2.0) + \\\n float(thehist.GetBinLowEdge(i)) < (self.ped_mean + 3*self.ped_sigma)):\n continue\n fit_bin_centers = fit_bin_centers + ((float(thehist.GetBinWidth(i))/2.0) + float(thehist.GetBinLowEdge(i)),)\n fit_evts = fit_evts + (thehist.GetBinContent(i),)\n fit_evts_unc = fit_evts_unc + (thehist.GetBinError(i),)\n bin_centers = np.array(bin_centers)\n evts = np.array(evts)\n evts_unc = np.array(evts_unc)\n fit_bin_centers = np.array(fit_bin_centers)\n fit_evts = np.array(fit_evts)\n fit_evts_unc = np.array(fit_evts_unc)\n if subtract_ped == True:\n #Subtract off the pedestal\n ped_sub_evts = copy.deepcopy(evts)\n ped_sub_evts_unc = copy.deepcopy(evts_unc)\n\n #Need to subtract across pedestal fit range\n ped_start_ind = np.where(bin_centers == min(self.ped_fit_x))[0]\n for i,b in enumerate(self.ped_fit_x):\n ped_sub_evts[ped_start_ind+i] = ped_sub_evts[ped_start_ind+i] - self.ped_fit_y[i]\n #FIXME: Also want to correct for uncertainty in fit\n evts = ped_sub_evts\n evts_unc = ped_sub_evts_unc\n\n try:\n self.initial_params.append(100000)\n newtry = lambda x,C1,m,s,Cf,f1,f2,P: fu.gauss1(P,self.ped_mean,self.ped_sigma)*fu.gauss2dep(C1,m,s,Cf,f1,f2)\n if self.lower_bounds is None or self.upper_bounds is None:\n popt, pcov = scp.curve_fit(newtry, fit_bin_centers, fit_evts, p0=self.initial_params, maxfev=6000)\n else:\n popt, pcov = scp.curve_fit(self.fitfunc, fit_bin_centers, fit_evts, p0=self.initial_params,\n bounds=(self.lower_bounds,self.upper_bounds),maxfev=6000)\n except RuntimeError:\n print(\"NO SUCCESSFUL FIT AFTER ITERATIONS...\")\n popt = None\n pcov = None\n return popt, pcov, bin_centers, evts, evts_unc\n","sub_path":"ANNIECableDelayCalculator/lib/GainFinder.py","file_name":"GainFinder.py","file_ext":"py","file_size_in_byte":11501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"266843169","text":"#!/usr/bin/env python3\n\nimport tensorflow as tf\nimport sys\n\ng = tf.Graph()\nwith g.as_default():\n x = tf.add(3, 5)\n\n#print(x)\n\nwith tf.Session(graph=g) as sess:\n print(sess.run(x))\n print(sess)\n","sub_path":"tf/separate_graph.py","file_name":"separate_graph.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"384078972","text":"from functools import reduce\n\"\"\"\ndef dovizkuru(dolar):\n return dolar * 4.83\n\ndolarlarim = [54,67.12]\n\nprint(list(map(dovizkuru,dolarlarim)))\n\"\"\"\n\"\"\"\ndef hepsinikucult(kelime):\n return kelime.lower()\n\nkelimeler = [\"Ahmet\",\"dErYaK\",\"tOLGa\"]\n\nkucukkelimeler = list(map(hepsinikucult,kelimeler))\nprint(kucukkelimeler)\n\n\ndef dovizkuru(para,hangisi):\n if hangisi == 1:\n return para * 4.85\n else:\n return para * 5.65\n\nparalarim = [54,67,12]\nhangisi_euro = [1,0,1]\n\nprint(list(map(dovizkuru,paralarim,hangisi_euro)))\n\"\"\"\n\neski_map = map\neski_filter = filter\n\ndef filter(func,liste):\n sonuc = []\n for i in liste:\n if func(i):\n sonuc.append(i)\n return sonuc\n\n\n\ndef map(func,liste):\n sonuc = []\n for i in liste:\n sonuc.append(func(i))\n return sonuc\n\nkisiler = [\"Ahmet\",\"İhsan\",\"Mustafa\",\"Deryak\",\"Tolga\"]\nsayilar = [\"1\",\"2\",\"3\",\"4\"]\nprint(list(map(int,sayilar)))\n\n\ndef abidikgubidikfonksiyon(gubidik):\n return gubidik * 1200\n\ndef hello(name):\n return \"Hello {}\".format(name)\n\ndef twist(dansci):\n if dansci == \"Deryak\":\n return True\n else:\n return False\n\nprint(list(filter(twist,kisiler)))\n\ndef birlestir(birinci,ikinci):\n print(birinci)\n print(ikinci)\n return birinci + \" \" + ikinci\n\nsaysay = 1\ndef ucuc(rakam1,rakam2):\n global saysay\n saysay +=1\n print(\"{asama}. Aşama 1. Parametre: {bir},2. Parametre: {iki} Sonuç:{sonuc}\".format(sonuc= rakam1 * rakam2,asama=saysay,bir=rakam1,iki=rakam2))\n return rakam1 * rakam2\n\nrakamlar = [1,2,3,4,5,6,7,8,9]\n\nprint(reduce(ucuc,rakamlar))\n\n\nprint(list(reduce(birlestir,kisiler)))","sub_path":"mapreducefilter_6gun.py","file_name":"mapreducefilter_6gun.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"624631045","text":"# !/usr/bin/python\n# coding: utf-8\n\nimport pandas as pd\n\n\n# Read Citibike data from csv file in one mouth\ndef read_data_one_mouth(csv_file_s):\n return pd.DataFrame(pd.read_csv(csv_file_s))\n\n\n# Read csv file by specific date\ndef read_data(year, start_month, end_month):\n data = None\n\n while start_month <= end_month:\n csv_filename = '%d%02d%s' % (year, start_month, '-citibike-tripdata.csv')\n month_data = read_data_one_mouth('data/' + csv_filename)\n if data is None:\n data = month_data\n else:\n data = data.append(month_data, ignore_index=False)\n start_month += 1\n return data\n","sub_path":"tools/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"551661927","text":"from collections import defaultdict\n\nfrom taxi.backends import BaseBackend, PushEntryFailed\nfrom taxi.projects import Activity, Project\n\nfrom taxi import __version__ as taxi_version\nfrom . import __version__ as taxi_tipee_version\n\nimport requests\nimport time\nimport hashlib\nimport datetime\n\nclass TipeeBackend(BaseBackend):\n def __init__(self, **kwargs):\n super(TipeeBackend, self).__init__(**kwargs)\n self.path = self.path.lstrip('/')\n self.settings = self.context['settings']\n\n self.app_name = kwargs['username']\n self.app_private_key = kwargs['password']\n self.hostname = kwargs['hostname']\n self.person_id = int(kwargs['options']['person'])\n\n def api_token(self):\n timestamp = time.time()\n application_hash = self.app_private_key + str(int(timestamp))\n\n return 'FORUM-TOKEN timestamp={} app={} hash={}'.format(\n int(timestamp),\n hashlib.sha1(self.app_name.encode()).hexdigest(),\n hashlib.sha1(application_hash.encode()).hexdigest()\n )\n\n def push_entry(self, date, entry):\n seconds = int(entry.hours * 3600)\n start_time = datetime.datetime.combine(date, entry.get_start_time())\n end_time = start_time + datetime.timedelta(seconds=seconds)\n\n r = requests.post(f'https://{self.hostname}/{self.path}/timeclock/timechecks/bulk', json=[\n {\n 'person': self.person_id,\n 'timeclock': f'taxi {taxi_version}, taxi-tipee {taxi_tipee_version}',\n 'time': start_time.strftime('%Y-%m-%d %H:%M:%S'),\n 'external_id': '',\n },\n {\n 'person': self.person_id,\n 'timeclock': f'taxi {taxi_version}, taxi-tipee {taxi_tipee_version}',\n 'time': end_time.strftime('%Y-%m-%d %H:%M:%S'),\n 'external_id': '',\n }\n ], headers={\n 'Authorization': self.api_token()\n })\n\n if r.status_code != 200:\n raise PushEntryFailed(r.json()['message'])\n\n def get_project_hash(self, project_name):\n result = 0\n for i, c in enumerate(project_name):\n result += ord(c) * pow(10, i * 3)\n\n return result\n\n def get_projects(self):\n projects_list = []\n\n for project_name, count in self.settings.config.items('tempo_projects'):\n project_name = project_name.upper()\n p = Project(self.get_project_hash(project_name), project_name, Project.STATUS_ACTIVE)\n for i in range(1, int(count) + 1):\n name = f'{project_name}-{i}'\n a = Activity(i, name, 0)\n p.add_activity(a)\n p.aliases[name] = a.id\n\n projects_list.append(p)\n\n return projects_list\n","sub_path":"taxi_tipee/backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":2799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"135884374","text":"\"\"\"\nThis solely triggers jenkins job. No parsing, mongo, anything is done here\n\"\"\"\nimport biothings.dataload.uploader as uploader\nimport requests\nfrom local import JENKINS_TOKEN, JENKINS_URL\n\n\nclass DoidUploader(uploader.BaseSourceUploader):\n name = \"doid\"\n main_source = \"doid\"\n keep_archive = 1\n\n def load_data(self, data_folder):\n yield {'_id': 'nothing'}\n\n def post_update_data(self, *args, **kwargs):\n super().post_update_data(*args, **kwargs)\n release = self.src_doc['release']\n self.logger.info(\"done uploading doid: {}\".format(release))\n print(\"done uploading doid: {}\".format(release))\n\n job = 'Disease_Ontology'\n params = {'token': JENKINS_TOKEN, 'job': job,\n 'JSON': \"http://purl.obolibrary.org/obo/doid/releases/{}/doid.json\".format(release)}\n url = JENKINS_URL + \"buildByToken/buildWithParameters\"\n r = requests.get(url, params=params)\n self.logger.info(\"job {} triggered: {}\".format(job, r.text))\n\n @classmethod\n def get_mapping(self):\n return {}\n","sub_path":"wdbiothings/contrib/doid/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"91392578","text":"from threading import Thread\nfrom kafka import KafkaConsumer\nimport json\nimport logging\n\nfrom app.config import kafka_consumer_config\nfrom app.user_service import UserService\nfrom app.models.user import User, map_from_json as user_from_json\nfrom app.domain_event import DomainEvent, DomainEventType\n\nlogger = logging.getLogger(\"app.account_consumer\")\n\nclass AccountConsumer():\n \"\"\"Class consuming account events. Works with threads.\"\"\"\n\n def __init__(self, user_service: UserService):\n super().__init__()\n self.consumer = KafkaConsumer(\n group_id=kafka_consumer_config[\"group_id\"],\n bootstrap_servers=[kafka_consumer_config[\"bootstrap_servers\"]],\n auto_offset_reset=\"earliest\",\n enable_auto_commit=True, # Commit messages automatically\n value_deserializer=AccountConsumer.decode_json,\n consumer_timeout_ms=2000 # Stop consuming after 2 seconds of idle\n )\n self.user_service = user_service\n self.healthy = False\n self.shutting_down = False\n self.main_thread = None #type: Thread\n\n @staticmethod\n def decode_json(message):\n \"\"\"JSON message decoder to be used in Kafka consumer.\"\"\"\n try:\n return json.loads(message.decode(\"ascii\"))\n except Exception as e:\n logger.warn(\"Failed to decode message as JSON, {}\".format(str(e)))\n\n def consume_batch(self):\n \"\"\"Consume a batch of events. The consumer will iterate until a period of\n consumer_timeout_ms is passed without new messages.\"\"\"\n for m in self.consumer:\n try:\n event = DomainEvent.map_from_json(m.value)\n if event.type is DomainEventType.CREATED:\n self.handle_create(event.data)\n elif event.type is DomainEventType.DELETED:\n self.handle_delete(event.data)\n else:\n logger.info(\"Unexpected domain event type: {}\".format(event.type))\n except Exception as e:\n logger.error(\"Received invalid data from Kafka\", e)\n\n def launch_child_threads(self):\n \"\"\"Launch consumer threads in a while loop as long as we are not shutting down. Each\n consumer thread will close after being 2 seconds being idle.\"\"\"\n logger.info(\"Main account consumer thread started\")\n\n while not self.shutting_down:\n thread = Thread(target=self.consume_batch)\n thread.start()\n thread.join()\n\n logger.info(\"Main account thread consumer stopped\")\n\n\n def start(self):\n \"\"\"\"Start the consuming by launching a main background thread that will manage\n consuming process by spawning a consumer thread one after another.\"\"\"\n topic = kafka_consumer_config[\"topic\"]\n self.consumer.subscribe(topic)\n logger.info(\"AccountConsumer subscribed to topic {}\".format(topic))\n self.main_thread = Thread(target=self.launch_child_threads)\n self.main_thread.start()\n self.healthy = True\n\n def stop(self):\n \"\"\"Stop the consumer and wait for threads to finish.\"\"\"\n self.shutting_down = True\n if self.main_thread is not None:\n self.main_thread.join()\n self.consumer.close()\n self.healthy = False\n\n def handle_create(self, data):\n try:\n user = user_from_json(data)\n self.user_service.createUser(user)\n except Exception as e:\n logger.error(\"Failed to create user from user event\", e)\n\n def handle_delete(self, data):\n try:\n user = user_from_json(data)\n self.user_service.deleteUserById(user.id)\n except Exception as e:\n logger.error(\"Failed to delete user from user event\", e)\n","sub_path":"user-service/app/account_consumer.py","file_name":"account_consumer.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"407320452","text":"#!/usr/bin/env python3\n\nfrom autotest import sp_test,mp_test,mp_test2,res_code,long_sequence_compare\nimport autotest as at\nfrom sys import argv\nfrom os import chdir\nimport sys\nfrom importlib import import_module\nfrom numbers import Number\nfrom math import isnan\nfrom collections import Sequence\nimport copy\nimport operator as op\nfrom pprint import pprint\n\nfrom aset import abset,alset\n\ntry:\n from aligncalc import calc\nexcept:\n from AlignDNA import get_alignment_score\n def calc(dna1,dna2,scores):\n return get_alignment_score(dna1,dna2,*scores)\n\n\nclass FakeException(Exception):\n pass\n\ndef diff_str(intro,exp,act):\n return \"\\n\".join([intro+\":\",\n \"expected: \"+str(exp),\n \"actual: \"+str(act)])\n\ndef import_runner(modulename, fname, args=[], kwargs={}, check_input=True,tname=''):\n module = import_module(modulename)\n func = getattr(module, fname)\n if check_input:\n args2 = copy.deepcopy(args)\n kwargs2 = copy.deepcopy(kwargs)\n res = func(*args, **kwargs)\n if check_input:\n if not (args==args2 and kwargs==kwargs2): #good enough for now\n return (\"modified\", res)\n return (None,res)\n\ndef import_runner_best(modulename, fname, args=[], kwargs={}, check_input=True,tname=''):\n code,res=import_runner(modulename, fname, args, kwargs)\n if code:\n return (code, res)\n dna1,dna2,match,mismatch,gap=args\n score,al1,al2=res\n if ''.join(al1.split('-')) != dna1:\n return (\"badalign\", str(al1)+\" is not alignment of \"+str(dna1))\n if ''.join(al2.split('-')) != dna2:\n return (\"badalign\", str(al2)+\" is not alignment of \"+str(dna2))\n if len(al1) != len(al2):\n return (\"badalign\", \"returned alignments have differnt lengths, \"+str(al1)+\", \"+str(al2))\n if calc(al1,al2,(match,mismatch,gap)) != score:\n return (\"badalign\", \"alignment has wrong score\")\n return (None,score)\n\ndef test_align(modulename=\"AlignDNA\",timeout=3):\n for name,testlist in abset.items():\n test_set(name,testlist,modulename,timeout,runner=import_runner_best)\n\n for name,testlist in alset.items():\n test_set(name,testlist,modulename,timeout)\n\ndef test_set(name, testlist, modulename,timeout=3,\n runner=import_runner, comparemethod=None):\n correct = 0\n #answers = []\n for i,(fname,args,kwargs,ans) in enumerate(testlist):\n tname = name + \"_\" + str(i)\n input = kwargs.pop(\"_input\",\"\")\n try:\n res, retval = mp_test2(runner,[modulename,fname,args,kwargs],{\"tname\":tname}, timeout=timeout)\n #ans=retval\n #answers.append((fname,args,kwargs,ans))\n #continue\n if res==\"skip\":\n continue\n if res:\n res_code(tname, res, retval)\n continue\n if retval==ans: # correct result #with no floats\n correct+=1\n continue\n else:\n #if isinstance(ans, Sequence):\n # long_sequence_compare(tname, ans, retval, contextpreview=3)\n #else:\n res_code(tname, \"wrong\",diff_str(\"Wrong result\",ans,retval))\n continue\n except at.Error as e:\n res_code(tname, e.code, e.message)\n except Exception as e:\n res_code(tname, \"testingFailed\", e)\n continue\n\n #print (name+'=',answers)\n res_code(name, str(correct))\n\nif __name__==\"__main__\":\n if len(argv)>1:\n test_align(argv[1])\n else:\n test_align()\n","sub_path":"ex5/tests_a.py","file_name":"tests_a.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"606533631","text":"import urllib.request\nimport urllib.parse\nimport urllib.error\nimport socket\nimport http.cookiejar\n\n\ndef req_baidu():\n res = urllib.request.urlopen(\"http://www.baidu.com\")\n print(res.read().decode('utf-8'))\n\n\ndef req_po():\n data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding=\"utf8\")\n print(data)\n res = urllib.request.urlopen(\"http://httpbin.org/post\",data=data)\n print(res.read())\n\n\ndef req_timeout():\n try:\n res = urllib.request.urlopen(\"http://httpbin.org/get\",timeout=0.1)\n print(res.read())\n except urllib.error.URLError as e:\n if isinstance(e.reason,socket.timeout):\n print(\"TIME OUT\")\n\n\ndef req_res():\n res = urllib.request.urlopen('https://www.python.org')\n print(type(res))\n\n\n\n\ndef req_head1():\n req = urllib.request.Request('https://python.org')\n res = urllib.request.urlopen(req)\n print(res.read().decode('utf-8'))\n\n url = \"http://httpbin.org/post\"\n headers = {\n 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',\n 'Host': 'httpbin.org'\n }\n dict = {\n 'name': 'zhaofan'\n }\n data = bytes(urllib.parse.urlencode(dict),encoding='utf-8')\n req = urllib.request.Request(url=url,data=data,headers=headers,method='POST')\n res = urllib.request.urlopen(req)\n print(res.read().decode('utf-8'))\n\n\ndef req_head2():\n url = \"http://httpbin.org/post\"\n dict = {\n 'name': 'zhaofan'\n }\n data = bytes(urllib.parse.urlencode(dict),encoding=\"utf8\")\n req = urllib.request.Request(url=url,data=data,method='POST')\n req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')\n res = urllib.request.urlopen(req)\n print(res.read().decode('utf-8'))\n\n\n# def handler():\n# proxy_handler = urllib.request.ProxyHandler({\n# 'http':'127.0.0.1:9743',\n# 'http':'127.0.0.1:9743'\n# })\n# opener = urllib.request.build_opener(proxy_handler,urllib.request.HTTPHandler)\n# res = opener.open('http://www.baidu.com')\n# print(res.read())\n\n\ndef cookie1():\n cookie = http.cookiejar.CookieJar()\n handler = urllib.request.HTTPCookieProcessor(cookie)\n opener = urllib.request.build_opener(handler)\n res = opener.open('http://www.baidu.com')\n print(res)\n for item in cookie:\n print(item.name+\"=\"+item.value)\n\n\ndef cookie2():\n cookie = http.cookiejar.MozillaCookieJar(\"cookie.txt\")\n handler = urllib.request.HTTPCookieProcessor(cookie)\n opener = urllib.request.build_opener(handler)\n res = opener.open('http://www.baidu.com')\n cookie.save(ignore_discard=True, ignore_expires=True)\n print(res)\n for item in cookie:\n print(item.name+\"=\"+item.value)\n\n\ncookie2()\n\n\n\n\n\n\n\n\n","sub_path":"reptile_pra/urllib_prac.py","file_name":"urllib_prac.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"167713561","text":"import Tkinter, socks, datetime, time, socket, ConfigParser, ast, base64, pygame\nfrom Crypto.Cipher import AES\nfrom thread import start_new_thread\n\n\nconfig = ConfigParser.RawConfigParser()\nconfig.read('OnionChat.ini')\nonions = []\n\n\nwith open(\"contacts.ini\") as fp:\n onions = [ast.literal_eval(line) for line in fp if line.strip()]\n\ntor_ip = config.get('Settings', 'tor_ip')\ntor_port = int(config.get('Settings', 'tor_port'))\nchat_port = int(config.get('Settings', 'chat_port'))\nmy_chatname = config.get('Settings', 'my_chatname')\nsecret = config.get('Settings', 'aes_key')\naes_encryption = config.getboolean('Settings', 'enable_encryption')\n\nBLOCK_SIZE = 32\nPADDING = '{'\npad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING\nEncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))\nDecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)\ncipher = AES.new(secret)\n\n\ndef onion_send(onion, str, curd):\n try:\n s = socks.socksocket();\n s.setproxy(socks.PROXY_TYPE_SOCKS5, tor_ip, tor_port);\n s.connect((onion[0], chat_port));\n if aes_encryption:\n s.send(EncodeAES(cipher, (curd + str + '\\n').encode(\"utf-8\")));\n else:\n s.send((curd + str + '\\n').encode(\"utf-8\"));\n s.close();\n except (RuntimeError, TypeError, NameError):\n pass\n\n\ndef text_send(onion,str):\n try:\n s = socks.socksocket();\n s.setproxy(socks.PROXY_TYPE_SOCKS5, tor_ip, tor_port);\n s.connect((onion[0], chat_port));\n if aes_encryption:\n s.send(EncodeAES(cipher, (str).encode(\"utf-8\")));\n else:\n s.send((str).encode(\"utf-8\"));\n s.close();\n except (RuntimeError, TypeError, NameError):\n pass\n\n\n\ndef onion_status(env):\n onlinestr = '...loading online status...'\n online = 1\n while True:\n app.labelVariable.set(onlinestr)\n onlinestr = ''\n for onion in onions:\n try:\n s = socks.socksocket();\n s.setproxy(socks.PROXY_TYPE_SOCKS5, tor_ip, tor_port);\n s.settimeout(5)\n s.connect((onion[0], chat_port));\n if online > 0:\n s.send(EncodeAES(cipher, (\"[\" + my_chatname + \" is online]\\n\").encode(\"utf-8\")));\n online = 0\n s.close();\n onlinestr += onion[1] + ' online \\n'\n except:\n pass\n\ndef onion_rev():\n serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serversocket.bind(('localhost', chat_port))\n serversocket.listen(5)\n while True:\n connection, address = serversocket.accept()\n buf = connection.recv(50000)\n if len(buf) > 0:\n start_new_thread(play_sound, ());\n if aes_encryption:\n try:\n app.T.insert(Tkinter.END, DecodeAES(cipher, (buf)))\n except (RuntimeError, TypeError, NameError, ValueError):\n app.T.insert(Tkinter.END, (buf).decode(\"utf-8\"))\n else:\n app.T.insert(Tkinter.END, buf)\n app.T.yview(Tkinter.END)\n\ndef offline():\n msg = \"[\" + my_chatname + \" is offline]\\n\"\n for onion in onions:\n text_send(onion,msg)\n app.destroy()\n\n\ndef play_sound():\n if app.sound_on:\n pygame.mixer.init()\n pygame.mixer.music.load(\"echo.wav\")\n pygame.mixer.music.play()\n while pygame.mixer.music.get_busy():\n continue\n\n\nclass simpleapp_tk(Tkinter.Tk):\n\n def __init__(self, parent):\n Tkinter.Tk.__init__(self, parent)\n self.parent = parent\n self.initialize()\n\n def initialize(self):\n self.grid( )\n self.entryVariable = Tkinter.StringVar()\n self.S = Tkinter.Scrollbar(self)\n self.T = Tkinter.Text(self) # , height=20, width=50\n self.S.config(command=self.T.yview)\n self.T.config(yscrollcommand=self.S.set)\n self.T.grid(column=0, row=0, sticky='EW')\n self.entry = Tkinter.Entry(self, textvariable=self.entryVariable)\n self.entry.grid(column=0, row=1, sticky='EW')\n self.entry.bind(\"\", self.OnPressEnter)\n self.entryVariable.set(u\"\")\n self.button = Tkinter.Button(self, text=u\"Send\",\n command=self.OnButtonClick)\n self.button.grid(column=1, row=1)\n self.labelVariable = Tkinter.StringVar()\n self.label = Tkinter.Label(self, textvariable=self.labelVariable,\n anchor=\"w\", fg=\"black\", bg=\"white\")\n self.label.grid(column=1, row=0, columnspan=2)\n self.VC = Tkinter.Checkbutton(self, text=\"Encryption\", command=self.toggle_encryption)\n self.VC.grid(column=1, row=0, sticky=\"NW\")\n self.SoundCheck = Tkinter.IntVar;\n self.SC = Tkinter.Checkbutton(self, text = \"Sound\", command=self.toggle_sound, onvalue=1, offvalue=0 )\n self.SC.grid(column=1, row=0, sticky=\"SW\")\n self.sound_on = False\n self.grid_columnconfigure(0, weight=1)\n self.resizable(False, False)\n self.update()\n self.geometry('800x415-5+40')\n self.entry.focus_set()\n\n self.protocol(\"WM_DELETE_WINDOW\", offline)\n self.SC.toggle();\n self.toggle_sound();\n if aes_encryption:\n self.VC.toggle();\n\n\n start_new_thread(onion_rev, ());\n start_new_thread(onion_status, (self.entryVariable,));\n\n def OnButtonClick(self):\n self.OnPressEnter(0)\n\n def toggle_sound(self):\n self.sound_on = not self.sound_on\n\n def toggle_encryption(self):\n global aes_encryption\n aes_encryption = not aes_encryption\n\n def OnPressEnter(self, event):\n curdate = str(datetime.datetime.fromtimestamp(time.time()).strftime('[%H:%M:%S] ')) + my_chatname + ': '\n for onion in onions:\n start_new_thread(onion_send, (onion, self.entryVariable.get(), curdate));\n self.entryVariable.set(u\"\")\n self.entry.focus_set()\n self.entry.selection_range(0, Tkinter.END)\n\n\nif __name__ == \"__main__\":\n app = simpleapp_tk(None)\n app.title('Onion Chat')\n app.mainloop()","sub_path":"src/OnionChat.pyw","file_name":"OnionChat.pyw","file_ext":"pyw","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"259853542","text":"from __future__ import annotations\n\nimport os\nfrom typing import TYPE_CHECKING\n\nimport dolfinx as df\nimport ufl\n\nif TYPE_CHECKING:\n from fenicsxconcrete.finite_element_problem.base_material import MaterialProblem\n\nfrom fenicsxconcrete.sensor_definition.base_sensor import PointSensor\nfrom fenicsxconcrete.util import project, ureg\n\n\nclass StrainSensor(PointSensor):\n \"\"\"A sensor that measures strain at a specific point\n\n Attributes:\n data: list of measured values\n time: list of time stamps\n units : pint definition of the base unit a sensor returns\n name : name of the sensor, default is class name, but can be changed\n where: location where the value is measured\n \"\"\"\n\n def measure(self, problem: MaterialProblem) -> None:\n \"\"\"\n The strain value at the defined point is added to the data list,\n as well as the time t to the time list\n\n Arguments:\n problem : FEM problem object\n t : time of measurement for time dependent problems, default is 1\n \"\"\"\n\n try:\n strain = problem.q_fields.strain\n assert strain is not None\n except AssertionError:\n raise Exception(\"Strain not defined in problem\")\n\n strain_function = project(\n strain, # stress fct from problem\n df.fem.TensorFunctionSpace(problem.experiment.mesh, problem.q_fields.plot_space_type), # tensor space\n problem.q_fields.measure,\n )\n # project stress onto visualization space\n\n # finding the cells corresponding to the point\n bb_tree = df.geometry.BoundingBoxTree(problem.experiment.mesh, problem.experiment.mesh.topology.dim)\n cells = []\n\n # Find cells whose bounding-box collide with the points\n cell_candidates = df.geometry.compute_collisions(bb_tree, [self.where])\n\n # Choose one of the cells that contains the point\n colliding_cells = df.geometry.compute_colliding_cells(problem.experiment.mesh, cell_candidates, [self.where])\n if len(colliding_cells.links(0)) > 0:\n cells.append(colliding_cells.links(0)[0])\n\n # adding correct units to stress\n strain_data = strain_function.eval([self.where], cells)\n\n self.data.append(strain_data)\n self.time.append(problem.time)\n\n def report_metadata(self) -> dict:\n \"\"\"Generates dictionary with the metadata of this sensor\"\"\"\n metadata = super().report_metadata()\n metadata[\"sensor_file\"] = os.path.splitext(os.path.basename(__file__))[0]\n return metadata\n\n @staticmethod\n def base_unit() -> ureg:\n \"\"\"Defines the base unit of this sensor\n\n Returns:\n the base unit as pint unit object\n \"\"\"\n return ureg(\"\")\n","sub_path":"src/fenicsxconcrete/sensor_definition/strain_sensor.py","file_name":"strain_sensor.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"373402222","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nimport clean_data\r\nimport helpers\r\nimport os\r\nimport pickle\r\nimport polynomial_expansion\r\nimport proj1_helpers\r\nimport re\r\n\r\n\r\ndef plot_cross_validation_lambda_accuraccy(lambdas, avg_train_error_ratios, avg_test_error_ratios):\r\n fig = plt.figure()\r\n\r\n plt.semilogx()\r\n plt.grid()\r\n\r\n plt.plot(lambdas, avg_train_error_ratios, color=\"b\", marker=\".\", label=\"Training\")\r\n plt.hold('on')\r\n plt.plot(lambdas, avg_test_error_ratios, color='r', marker=\".\", label=\"Validation\")\r\n plt.hold('off')\r\n\r\n # plt.title(\"Misclassification ratio as a function of lambda\")\r\n plt.xlabel('lambda')\r\n plt.ylabel(\"Misclassification ratio\")\r\n\r\n ax = fig.add_subplot(111)\r\n handles, labels = ax.get_legend_handles_labels()\r\n plt.legend(handles=handles, loc=\"best\")\r\n\r\n plt.show()\r\n\r\n\r\ndef read_data_lambda_grid_search(dirname, regularization_level, degree, iter_count, fold):\r\n lambdas = []\r\n lamb_wStars_dict = {}\r\n lamb_trainRatios_dict = {}\r\n lamb_testRatios_dict = {}\r\n\r\n os.chdir(dirname)\r\n for filename in os.listdir(\".\"):\r\n # regularization level match\r\n match = re.search(r\"_L(\\d)_degree\", filename)\r\n regularization_level_file = int(match.group(1))\r\n\r\n # degree match\r\n match = re.search(r\"_degree(\\d)_\", filename)\r\n degree_file = int(match.group(1))\r\n\r\n # iter match\r\n match = re.search(r\"_iter(\\d+)_\", filename)\r\n iter_count_file = int(match.group(1))\r\n\r\n # fold match\r\n match = re.search(r\"_fold(\\d)_\", filename)\r\n fold_file = int(match.group(1))\r\n\r\n if regularization_level_file == regularization_level and degree_file == degree and iter_count_file == iter_count and fold_file == fold:\r\n\r\n # extract lambda from filename\r\n match = re.search(r\"_lamb(\\d+\\.\\d+)\\.pickle\", filename)\r\n lamb = float(match.group(1))\r\n\r\n # open and read file\r\n with open(filename, \"rb\") as pickle_file:\r\n (w_stars, train_correct_ratios, test_correct_ratios) = pickle.load(pickle_file)\r\n\r\n lambdas.append(lamb)\r\n lamb_wStars_dict[lamb] = w_stars\r\n lamb_trainRatios_dict[lamb] = train_correct_ratios\r\n lamb_testRatios_dict[lamb] = test_correct_ratios\r\n\r\n lambdas = sorted(lambdas)\r\n\r\n return (lambdas, lamb_wStars_dict, lamb_trainRatios_dict, lamb_testRatios_dict)\r\n\r\n\r\ndef read_data_lambda_cross_validation(dirname):\r\n w_stars = []\r\n train_ratios = []\r\n test_ratios = []\r\n\r\n os.chdir(dirname)\r\n for filename in os.listdir(\".\"):\r\n\r\n # open and read file\r\n with open(filename, \"rb\") as pickle_file:\r\n (w_star, train_correct_ratio, test_correct_ratio) = pickle.load(pickle_file)\r\n\r\n w_stars.append(w_star)\r\n train_ratios.append(train_correct_ratio)\r\n test_ratios.append(test_correct_ratio)\r\n\r\n os.chdir(\"..\")\r\n return (w_stars, train_ratios, test_ratios)\r\n\r\n\r\n################################################################################\r\n\r\n# grid search for lambda plot\r\n(lambdas, lamb_wStars_dict, lamb_trainRatios_dict, lamb_testRatios_dict) = read_data_lambda_grid_search(\"train_clean_avg_L2_degree2_fold3_gamma0.05_iter1000/\", 2, 2, 1000, 3)\r\navg_train_correct_ratios = np.array([np.mean(lamb_trainRatios_dict[lamb]) for lamb in lambdas])\r\navg_test_correct_ratios = np.array([np.mean(lamb_testRatios_dict[lamb]) for lamb in lambdas])\r\navg_train_error_ratios = 1 - avg_train_correct_ratios\r\navg_test_error_ratios = 1 - avg_test_correct_ratios\r\n\r\nplot_cross_validation_lambda_accuraccy(lambdas, avg_train_error_ratios, avg_test_error_ratios)\r\n\r\n# # get best w_star for given lambda\r\n# (w_stars_5, train_ratios_5, test_ratios_5) = read_data_lambda_cross_validation(\"train_clean_avg_L2_degree2_fold5_gamma0.05_iter5000_lambda10.6\")\r\n# (w_stars_8, train_ratios_8, test_ratios_8) = read_data_lambda_cross_validation(\"train_clean_avg_L2_degree2_fold8_gamma0.05_iter10000_lambda10.6\")\r\n# # (w_stars_jan, train_ratios_jan, test_ratios_jan) = read_data_lambda_cross_validation(\"jan_train_clean_avg_L2_degree2_fold1_foldId0_gamma0.04_iter5000_lamb0\")\r\n# (w_stars_jan, train_ratios_jan, test_ratios_jan) = read_data_lambda_cross_validation(\"jan_train_clean_avg_L2_degree2_fold1_foldId0_gamma0.08_iter7000_lamb0\")\r\n#\r\n# ################################################################################\r\n# # submission #\r\n# ################################################################################\r\n# w_stars = w_stars_jan\r\n# print(train_ratios_jan)\r\n#\r\n# ################################################################################\r\n# # read data #\r\n# ################################################################################\r\n# DATA_TEST_PATH = \"../data/test_clean_avg.csv\"\r\n# (y, X, id) = proj1_helpers.load_csv_data(DATA_TEST_PATH, sub_sample=False)\r\n#\r\n# # y is categorical, so we want integers (-1, 1) instead of floats (-1.0, 1.0)\r\n# # Modified here instead of in load_csv_data, because we don't know if we have the\r\n# # right to change the provided functions.\r\n# y = y.astype(int)\r\n#\r\n# # The formulas used for the cost and gradients of the logistic function expect\r\n# # categories that are 0/1 for some terms to disappear in the equations.\r\n# y[np.where(y == -1)] = 0\r\n#\r\n# ################################################################################\r\n# # clean data #\r\n# ################################################################################\r\n# # one-hot coding for \"PRI_jet_num\" (column 22)\r\n# (id, y, X) = clean_data.one_hot_PRI_jet_num(id, y, X)\r\n#\r\n# ################################################################################\r\n# # standardize & polynomial expansion #\r\n# ################################################################################\r\n# degree = 2\r\n# X = polynomial_expansion.polynomial_expansion(X, degree)\r\n# (X, _, _) = helpers.standardize(X)\r\n# X = helpers.add_offset_parameter(X)\r\n#\r\n# N, D = X.shape\r\n#\r\n# ################################################################################\r\n# # predict labels #\r\n# ################################################################################\r\n# # compute labels for each w_star obtained through cross validation\r\n# y_preds = np.zeros((N, len(w_stars)))\r\n# for idx, w_star in enumerate(w_stars):\r\n# y_preds[:, idx] = proj1_helpers.predict_labels(w_star, X)\r\n#\r\n# # majority voting for best y\r\n# y_pred_final = np.zeros(N)\r\n# for i in range(N):\r\n# if np.sum(y_preds[i, :] > 0):\r\n# y_pred_final[i] = 1\r\n# else:\r\n# y_pred_final[i] = -1\r\n#\r\n# proj1_helpers.create_csv_submission(id, y_pred_final, \"submission_jan_test_clean_avg_L2_degree2_fold1_foldId0_gamma0.08_iter7000_lamb0.csv\")\r\n#\r\n# print(\"done\")\r\n","sub_path":"PCML temp/src/analysis_plot.py","file_name":"analysis_plot.py","file_ext":"py","file_size_in_byte":7133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"178407020","text":"import os\nimport sys\nimport warnings\nfrom types import SimpleNamespace, ModuleType\nfrom typing import Optional, List, Any, Dict\nfrom collections import defaultdict\n\nIMPORTED = SimpleNamespace()\nIMPORTED.executors = False\nIMPORTED.executors = False\nIMPORTED.drivers = False\nIMPORTED.hub = False\n\n\ndef import_classes(namespace: str,\n show_import_table: bool = False,\n import_once: bool = False):\n \"\"\"\n Import all or selected executors into the runtime. This is called when Jina is first imported for registering the YAML constructor beforehand. It can be also used to import third-part or external executors.\n\n :param namespace: the namespace to import\n :param show_import_table: show the import result as a table\n :param import_once: import everything only once, to avoid repeated import\n :return: the dependency tree of the imported classes under the `namespace`\n \"\"\"\n _namespace2type = {\n 'jina.executors': 'ExecutorType',\n 'jina.drivers': 'DriverType',\n 'jina.hub': 'ExecutorType'\n }\n _import_type = _namespace2type.get(namespace)\n if _import_type is None:\n raise TypeError(f'namespace: {namespace} is unrecognized')\n\n _imported_property = namespace.split('.')[-1]\n _is_imported = getattr(IMPORTED, _imported_property)\n if import_once and _is_imported:\n warnings.warn(f'{namespace} has already imported. If you want to re-imported, please set `import_once=True`',\n ImportWarning)\n return {}\n\n try:\n _modules = _get_modules(namespace)\n except ImportError as e:\n warnings.warn(f'{namespace} has no module to import. {e}', ImportWarning)\n return {}\n\n load_stat = defaultdict(list)\n bad_imports = []\n depend_tree = {}\n for _mod_name in _modules:\n try:\n bad_imports += _import_module(_mod_name, _import_type, depend_tree, load_stat)\n except Exception as ex:\n load_stat[_mod_name].append(('', False, ex))\n bad_imports.append(_mod_name)\n\n if show_import_table:\n _print_load_table(load_stat)\n else:\n _raise_bad_imports_warnings(bad_imports, namespace)\n\n setattr(IMPORTED, _imported_property, True)\n\n return depend_tree\n\n\nclass ImportExtensions:\n \"\"\"\n A context manager for wrapping extension import and fallback. It guides the user to pip install correct package by looking up extra-requirements.txt.\n\n :param required: set to True if you want to raise the ModuleNotFound error\n :param logger: when not given, built-in warnings.warn will be used\n :param help_text: the help text followed after\n :param pkg_name: the package name to find in extra_requirements.txt, when not given the ModuleNotFound exec_val will be used as the best guess\n \"\"\"\n\n def __init__(self, required: bool, logger=None,\n help_text: str = None, pkg_name: str = None, verbose: bool = True):\n \"\"\"Set constructor method.\"\"\"\n self._required = required\n self._tags = []\n self._help_text = help_text\n self._logger = logger\n self._pkg_name = pkg_name\n self._verbose = verbose\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, traceback):\n if exc_type == ModuleNotFoundError:\n missing_module = self._pkg_name or exc_val.name\n from pkg_resources import resource_filename\n with open(resource_filename('jina', '/'.join(('resources', 'extra-requirements.txt')))) as fp:\n for v in fp:\n if (v.strip()\n and not v.startswith('#')\n and v.startswith(missing_module)\n and ':' in v):\n missing_module, install_tags = v.split(':')\n self._tags.append(missing_module)\n self._tags.extend(vv.strip() for vv in install_tags.split(','))\n break\n\n if self._tags:\n req_msg = 'fallback to default behavior'\n if self._required:\n req_msg = 'and it is required'\n err_msg = f'Module \"{missing_module}\" is not installed, {req_msg}. ' \\\n f'You are trying to use an extension feature not enabled by the ' \\\n 'current installation.\\n' \\\n 'This feature is available in: '\n from .helper import colored\n err_msg += ' '.join(colored(f'[{tag}]', attrs='bold') for tag in self._tags)\n err_msg += f'\\nUse {colored(\"pip install jina[TAG]\", attrs=\"bold\")} to enable it'\n\n else:\n err_msg = f'{exc_val.msg}'\n\n if self._required:\n if self._verbose:\n if self._logger:\n self._logger.critical(err_msg)\n if self._help_text:\n self._logger.error(self._help_text)\n else:\n warnings.warn(err_msg, RuntimeWarning, stacklevel=2)\n raise exc_val\n else:\n if self._verbose:\n if self._logger:\n self._logger.warning(err_msg)\n if self._help_text:\n self._logger.info(self._help_text)\n else:\n warnings.warn(err_msg, RuntimeWarning, stacklevel=2)\n return True # suppress the error\n\n\ndef _load_contrib_module(logger=None) -> Optional[List[Any]]:\n if 'JINA_CONTRIB_MODULE_IS_LOADING' not in os.environ:\n\n contrib = os.getenv('JINA_CONTRIB_MODULE')\n os.environ['JINA_CONTRIB_MODULE_IS_LOADING'] = 'true'\n\n modules = []\n\n if contrib:\n pr = logger.info if logger else print\n pr(f'find a value in $JINA_CONTRIB_MODULE={contrib}, will load them as external modules')\n for p in contrib.split(','):\n m = PathImporter.add_modules(p)\n modules.append(m)\n pr(f'successfully registered {m} class, you can now use it via yaml.')\n else:\n modules = None\n\n return modules\n\n\nclass PathImporter:\n \"\"\"The class to import modules from paths.\"\"\"\n\n @staticmethod\n def _get_module_name(path: str, use_abspath: bool = False, use_basename: bool = True) -> str:\n module_name = os.path.dirname(os.path.abspath(path) if use_abspath else path)\n if use_basename:\n module_name = os.path.basename(module_name)\n module_name = module_name.replace('/', '.').strip('.')\n return module_name\n\n @staticmethod\n def add_modules(*paths) -> Optional[ModuleType]:\n \"\"\"\n Import modules from paths.\n\n :param paths: Paths of the modules.\n :return: The target module.\n \"\"\"\n for p in paths:\n if not os.path.exists(p):\n raise FileNotFoundError(f'cannot import module from {p}, file not exist')\n module = PathImporter._path_import(p)\n return module\n\n @staticmethod\n def _path_import(absolute_path: str) -> Optional[ModuleType]:\n import importlib.util\n try:\n # module_name = (PathImporter._get_module_name(absolute_path) or\n # PathImporter._get_module_name(absolute_path, use_abspath=True) or 'jinahub')\n\n # I dont want to trust user path based on directory structure, \"jinahub\", period\n spec = importlib.util.spec_from_file_location('jinahub', absolute_path)\n module = importlib.util.module_from_spec(spec)\n user_module_name = os.path.splitext(os.path.basename(absolute_path))[0]\n if user_module_name == '__init__':\n # __init__ can not be used as a module name\n spec_name = spec.name\n else:\n spec_name = f'{spec.name}.{user_module_name}'\n sys.modules[spec_name] = module\n spec.loader.exec_module(module)\n except Exception as ex:\n raise ImportError(f'can not import module from {absolute_path}') from ex\n return module\n\n\ndef _print_load_table(load_stat: Dict[str, List[Any]], logger=None):\n from .helper import colored\n\n load_table = []\n cached = set()\n\n for k, v in load_stat.items():\n for cls_name, import_stat, err_reason in v:\n if cls_name not in cached:\n load_table.append(\n f'{colored(\"✓\", \"green\") if import_stat else colored(\"✗\", \"red\"):<5} {cls_name if cls_name else colored(\"Module load error\", \"red\"):<25} {k:<40} {str(err_reason)}')\n cached.add(cls_name)\n if load_table:\n load_table.sort()\n load_table = ['', '%-5s %-25s %-40s %-s' % ('Load', 'Class', 'Module', 'Dependency'),\n '%-5s %-25s %-40s %-s' % ('-' * 5, '-' * 25, '-' * 40, '-' * 10)] + load_table\n pr = logger.info if logger else print\n pr('\\n'.join(load_table))\n\n\ndef _print_load_csv_table(load_stat: Dict[str, List[Any]], logger=None):\n from .helper import colored\n\n load_table = []\n for k, v in load_stat.items():\n for cls_name, import_stat, err_reason in v:\n load_table.append(\n f'{colored(\"✓\", \"green\") if import_stat else colored(\"✗\", \"red\")} {cls_name if cls_name else colored(\"Module_load_error\", \"red\")} {k} {str(err_reason)}')\n if load_table:\n pr = logger.info if logger else print\n pr('\\n'.join(load_table))\n\n\ndef _print_dep_tree_rst(fp, dep_tree, title='Executor'):\n tableview = set()\n treeview = []\n\n def _iter(d, depth):\n for k, v in d.items():\n if k != 'module':\n treeview.append(' ' * depth + f'- `{k}`')\n tableview.add(f'| `{k}` | ' + (f'`{d[\"module\"]}`' if 'module' in d else ' ') + ' |')\n _iter(v, depth + 1)\n\n _iter(dep_tree, 0)\n\n fp.write(f'# List of {len(tableview)} {title}s in Jina\\n\\n'\n f'This version of Jina includes {len(tableview)} {title}s.\\n\\n'\n f'## Inheritances in a Tree View\\n')\n fp.write('\\n'.join(treeview))\n\n fp.write(f'\\n\\n## Modules in a Table View \\n\\n| Class | Module |\\n')\n fp.write('| --- | --- |\\n')\n fp.write('\\n'.join(sorted(tableview)))\n\n\ndef _raise_bad_imports_warnings(bad_imports, namespace):\n if not bad_imports:\n return\n if namespace != 'jina.hub':\n warnings.warn(\n f'theses modules or classes can not be imported {bad_imports}. '\n f'You can use `jina check` to list all executors and drivers')\n else:\n warnings.warn(\n f'due to the missing dependencies or bad implementations, '\n f'{bad_imports} can not be imported '\n f'if you are using these executors/drivers, they wont work. '\n f'You can use `jina check` to list all executors and drivers')\n\n\ndef _get_modules(namespace):\n from setuptools import find_packages\n from pkgutil import get_loader\n\n try:\n _path = os.path.dirname(get_loader(namespace).path)\n except AttributeError as ex:\n if namespace == 'jina.hub':\n warnings.warn(f'hub submodule is not initialized. Please try \"git submodule update --init\"', ImportWarning)\n raise ImportError(f'{namespace} can not be imported. {ex}')\n\n _modules = _get_submodules(_path, namespace)\n\n for _pkg in find_packages(_path):\n _modules.add('.'.join([namespace, _pkg]))\n _pkgpath = os.path.join(_path, _pkg.replace('.', '/'))\n _modules |= _get_submodules(_pkgpath, namespace, prefix=_pkg)\n\n return _filter_modules(_modules)\n\n\ndef _get_submodules(path, namespace, prefix=None):\n from pkgutil import iter_modules\n _prefix = '.'.join([namespace, prefix]) if prefix else namespace\n modules = set()\n for _info in iter_modules([path]):\n _is_hub_module = namespace == 'jina.hub' and _info.ispkg\n _is_nonhub_module = namespace != 'jina.hub' and not _info.ispkg\n module_name = '.'.join([_prefix, _info.name])\n if _is_hub_module or _is_nonhub_module:\n modules.add(module_name)\n return modules\n\n\ndef _filter_modules(modules):\n import re\n _ignored_module_pattern = re.compile(r'\\.tests|\\.api|\\.bump_version')\n return {m for m in modules if not _ignored_module_pattern.findall(m)}\n\n\ndef _load_default_exc_config(cls_obj):\n from .executors.requests import get_default_reqs\n try:\n _request = get_default_reqs(type.mro(cls_obj))\n except ValueError as ex:\n warnings.warn(f'Please ensure a config yml is given for {cls_obj.__name__}. {ex}')\n\n\ndef _update_depend_tree(cls_obj, module_name, cur_tree):\n d = cur_tree\n for vvv in cls_obj.mro()[:-1][::-1]:\n if vvv.__name__ not in d:\n d[vvv.__name__] = {}\n d = d[vvv.__name__]\n d['module'] = module_name\n\n\ndef _import_module(module_name, import_type, depend_tree, load_stat):\n from importlib import import_module\n from .helper import colored\n bad_imports = []\n _mod_obj = import_module(module_name)\n for _attr in dir(_mod_obj):\n _cls_obj = getattr(_mod_obj, _attr)\n if _cls_obj.__class__.__name__ != import_type:\n continue\n # update the dependency tree for each class\n try:\n _update_depend_tree(_cls_obj, module_name, depend_tree)\n if _cls_obj.__class__.__name__ == 'ExecutorType':\n _load_default_exc_config(_cls_obj)\n # TODO: _success_msg is never used\n _success_msg = colored('▸', 'green').join(f'{vvv.__name__}' for vvv in _cls_obj.mro()[:-1][::-1])\n load_stat[module_name].append((_attr, True, _success_msg))\n except Exception as ex:\n load_stat[module_name].append((_attr, False, ex))\n bad_imports.append('.'.join([module_name, _attr]))\n return bad_imports\n","sub_path":"jina/importer.py","file_name":"importer.py","file_ext":"py","file_size_in_byte":13982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"227549103","text":"from django.contrib import admin\nfrom django.utils.encoding import force_text\nfrom django.utils.translation import gettext, gettext_lazy as _\n\n\ndef send_to_trash(modeladmin, request, queryset):\n \"\"\"\n Trashes all objects in a query.\n \"\"\"\n del modeladmin, request\n\n for item in queryset.all():\n item.trash()\n\n\ndef restore_from_trash(modeladmin, request, queryset):\n \"\"\"\n Restores all objects in a query.\n \"\"\"\n del modeladmin, request\n\n for item in queryset.all():\n item.restore()\n\n\nclass TrashedListFilter(admin.SimpleListFilter):\n \"\"\"\n A filter that only displays trashed model items.\n \"\"\"\n title = _('trash status')\n parameter_name = 'trashed_at'\n\n @staticmethod\n def lookups(request, modeladmin):\n del request, modeladmin\n return (\n ('available', gettext('Not in trash')),\n ('trashed', gettext('In trash')),\n )\n\n def queryset(self, request, queryset):\n if self.value() == 'available':\n return queryset.filter(trashed_at=None)\n if self.value() == 'trashed':\n return queryset.exclude(trashed_at=None)\n\n\nclass TrashableAdminMixin(admin.ModelAdmin):\n \"\"\"\n Adds trash/restore functionality to a model admin. This'll only work if the underlying model\n supports it.\n \"\"\"\n actions = [send_to_trash, restore_from_trash]\n list_filter = (TrashedListFilter,)\n","sub_path":"trashable/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"108190394","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport os\n\n\ndef plot_pipeline_step_as_subplots(in_image, out_image, in_title, out_title, out_dir, cmap_in=None, cmap_out=None):\n \"\"\"\n Helper function to plot an image processed image as subplot of input and output image to visualize the effect of transform\n applied.\n \"\"\"\n f, (axis1, axis2) = plt.subplots(1, 2, figsize=(15,10))\n axis1.imshow(in_image, cmap=cmap_in)\n axis1.set_title(in_title, fontsize=16)\n axis2.imshow(out_image, cmap=cmap_out)\n axis2.set_title(out_title, fontsize=16)\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n plt.savefig('{}/{}.jpg'.format(out_dir, out_title))\n \n# Remove distortion from images\ndef undistort(img, cameraMatrix, distortionCoeffs, image_name='', out_dir=None):\n \"\"\"\n Undistort the image using Camera calibration parameters.\n \n :returns: undistorted image\n \"\"\"\n image_size = (img.shape[1], img.shape[0])\n undist = cv2.undistort(img, cameraMatrix, distortionCoeffs, None, cameraMatrix) \n if out_dir:\n plot_pipeline_step_as_subplots(img, undist, image_name,'{}_undistorted'.format(image_name), out_dir)\n return undist\n\n# Visualize multiple color space channels\ndef get_color_channels(img, color_space = 'RGB', channel_needed = None, image_name = '', plot = False):\n \"\"\"\n Convert the input image to various color spaces: RGB, HSV and HLS\n \"\"\"\n if plot:\n fig, axs = plt.subplots(1,3, figsize=(15,10))\n fig.subplots_adjust(hspace = .2, wspace=.001)\n axs = axs.ravel()\n \n if color_space == 'RGB':\n img_R = img[:,:,0]\n img_G = img[:,:,1]\n img_B = img[:,:,2]\n if plot:\n axs[0].imshow(img_R, cmap='gray')\n axs[0].set_title('{} RGB_R'.format(image_name), fontsize=15)\n axs[1].imshow(img_G, cmap='gray')\n axs[1].set_title('{} RGB_G'.format(image_name), fontsize=15)\n axs[2].imshow(img_B, cmap='gray')\n axs[2].set_title('{} RGB_B'.format(image_name), fontsize=15)\n if channel_needed == 'R':\n return img_R\n if channel_needed == 'G':\n return img_G\n if channel_needed == 'B':\n return img_B\n \n if color_space == 'HSV':\n img_HSV = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n img_H = img_HSV[:,:,0]\n img_S = img_HSV[:,:,1]\n img_V = img_HSV[:,:,2]\n if plot:\n axs[0].imshow(img_H, cmap='gray')\n axs[0].set_title('{} HSV_H'.format(image_name), fontsize=15)\n axs[1].imshow(img_S, cmap='gray')\n axs[1].set_title('{} HSV_S'.format(image_name), fontsize=15)\n axs[2].imshow(img_V, cmap='gray')\n axs[2].set_title('{} HSV_V'.format(image_name), fontsize=15)\n if channel_needed == 'H':\n return img_H\n if channel_needed == 'S':\n return img_S\n if channel_needed == 'V':\n return img_V\n \n if color_space == 'HLS':\n img_HLS = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n img_H = img_HLS[:,:,0]\n img_L = img_HLS[:,:,1]\n img_S = img_HLS[:,:,2]\n if plot:\n axs[0].imshow(img_H, cmap='gray')\n axs[0].set_title('{} HLS_H'.format(image_name), fontsize=15)\n axs[1].imshow(img_L, cmap='gray')\n axs[1].set_title('{} HLS_L'.format(image_name), fontsize=15)\n axs[2].imshow(img_S, cmap='gray')\n axs[2].set_title('{} HLS_S'.format(image_name), fontsize=15)\n if channel_needed == 'H':\n return img_H\n if channel_needed == 'L':\n return img_L\n if channel_needed == 'S':\n return img_S\n if channel_needed is None:\n return fig\n \ndef get_binary_thresholded_image(image, image_name='', out_dir=None):\n \"\"\"\n Get a binary thresholded image that is tuned for road lane detection feature extraction.\n \n :returns: Binary thresholded image\n \"\"\"\n \n # convert to gray scale\n gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n \n height, width = gray.shape\n \n # apply sobel gradient threshold on the horizontal gradient\n sx_binary = apply_sobel_absolute(gray, 'x', 10, 200)\n \n # apply sobel gradient direction threshold so that only edges closer to vertical are detected.\n dir_binary = apply_sobel_direction(gray, thresh=(np.pi/6, np.pi/2))\n \n # combine the gradient and direction thresholds.\n dir_horiz_gradient_combined = ((sx_binary == 1) & (dir_binary == 1))\n \n # Combine R and G pixels and threshold them to detect yellow lanes perfectly\n R = get_color_channels(image, color_space = 'RGB', channel_needed = 'R')\n G = get_color_channels(image, color_space = 'RGB', channel_needed = 'G')\n R_G_threshold = 150\n R_G_condition = (R > R_G_threshold) & (G > R_G_threshold)\n \n # Get S channel and threshold it for detecting bright yellow and white lanes\n S = get_color_channels(image, color_space = 'HLS', channel_needed = 'S')\n S_threshold = (100, 255)\n S_condition = (S > S_threshold[0]) & (S <= S_threshold[1])\n \n # Get L channel and threshold it to avoid pixels which have shadows and as a result darker.\n L = get_color_channels(image, color_space = 'HLS', channel_needed = 'L')\n L_threshold = (120, 255)\n L_condition = (L > L_threshold[0]) & (L <= L_threshold[1])\n\n # combine all the thresholds from the color channels\n color_channel_combined = np.zeros_like(R)\n # A pixel should either be a yellowish or whiteish\n # And it should also have a gradient, as per our thresholds\n color_channel_combined[(R_G_condition & L_condition) & (S_condition | dir_horiz_gradient_combined)] = 1\n \n # Apply the region of interest mask\n ROI_mask = np.zeros_like(color_channel_combined)\n ROI_vertices = np.array([[0,height-1], [width/2, int(0.5*height)], [width-1, height-1]], dtype=np.int32)\n cv2.fillPoly(ROI_mask, [ROI_vertices], 1)\n thresholded = cv2.bitwise_and(color_channel_combined, ROI_mask)\n \n if out_dir:\n plot_pipeline_step_as_subplots(image, thresholded, image_name,'{}_bin_thresholded'.format(image_name), out_dir, cmap_out='gray')\n return thresholded\n\ndef apply_sobel_absolute(gray, orient='x', thresh_min=25, thresh_max=255):\n sobel = cv2.Sobel(gray, cv2.CV_64F, orient=='x', orient=='y')\n abs_sobel = np.absolute(sobel)\n scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))\n sxbinary = np.zeros_like(scaled_sobel)\n sxbinary[(scaled_sobel >= thresh_min) & (scaled_sobel <= thresh_max)] = 1\n return sxbinary\n\ndef apply_sobel_direction(gray, sobel_kernel=3, thresh=(0, np.pi/2)): \n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n abs_sobelx = np.absolute(sobelx)\n abs_sobely = np.absolute(sobely)\n grad_dir = np.arctan2(abs_sobely, abs_sobelx)\n binary_output = np.zeros_like(grad_dir)\n binary_output[(grad_dir >= thresh[0]) & (grad_dir <= thresh[1])] = 1\n return binary_output\n\n\ndef apply_warp(img, image_name='', out_dir=None):\n \"\"\"\n Apply perspective image on a binary thresholded image\n \n :returns: warped image\n \"\"\"\n image = img.copy()\n image_size = (image.shape[1], image.shape[0])\n \n offset = 0\n \n #These values for source and destination points are derived by trial and error\n source = np.float32([[490, 482],[810, 482],\n [1250, 720],[40, 720]])\n \n destination = np.float32([[0, 0], [1280, 0], \n [1250, 720],[40, 720]])\n \n M = cv2.getPerspectiveTransform(source, destination)\n M_inv = cv2.getPerspectiveTransform(destination, source)\n warped = cv2.warpPerspective(image, M, image_size)\n if out_dir:\n plot_pipeline_step_as_subplots(image, warped, '{}_thresholded'.format(image_name), '{}_warped'.format(image_name), out_dir, cmap_in='gray', cmap_out='gray')\n return (warped, M_inv)","sub_path":"util/image_process.py","file_name":"image_process.py","file_ext":"py","file_size_in_byte":8056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"422344183","text":"\n# Used in main loop\nfrom time import sleep\nimport random\n\n###################################\n# Graphics imports, constants and structures\n###################################\nfrom rgbmatrix import RGBMatrix, RGBMatrixOptions\nfrom PIL import Image, ImageDraw\n\n# this is the size of ONE of our matrixes. \nmatrix_rows = 32 \nmatrix_columns = 32 \n\n# how many matrixes stacked horizontally and vertically \nmatrix_horizontal = 5 \nmatrix_vertical = 3\n\ntotal_rows = matrix_rows * matrix_vertical\ntotal_columns = matrix_columns * matrix_horizontal\n\noptions = RGBMatrixOptions()\noptions.rows = matrix_rows \noptions.cols = matrix_columns \noptions.chain_length = matrix_horizontal\noptions.parallel = matrix_vertical \n\n#options.hardware_mapping = 'adafruit-hat-pwm' \n#options.hardware_mapping = 'adafruit-hat' # If you have an Adafruit HAT: 'adafruit-hat'\noptions.hardware_mapping = 'regular' \n\noptions.gpio_slowdown = 2\n\nmatrix = RGBMatrix(options = options)\n#bg_color = (25,25,25)\nrandomColor = random.randint(0,360)\nbg_color =\"hsl({}, 100%, 20%)\".format(randomColor)\n\n#create an instance of the image object to allow for it to be used globally in functions and main loop\ntemp_image = Image.new(\"RGB\", (total_columns,total_rows))\ntemp_draw = ImageDraw.Draw(temp_image)\n\nimageSize = 64\n\n###################################\n# Background\n###################################\ndef background():\n global temp_image\n randomColor = random.randint(0,360)\n bg_color =\"hsl({}, 100%, 50%)\".format(randomColor)\n temp_draw = ImageDraw.Draw(temp_image)\n temp_draw.rectangle((0,0,total_columns,total_rows), fill= bg_color)\n matrix.SetImage(temp_image,0,0)\n\n###################################\n# Image Setup\n###################################\ndef newImage():\n # used global keyword here to access the object image in the main loop\n global temp_image\n global imageSize\n global total_rows\n global total_columns\n\n pickImage = random.randint(1,4)\n if pickImage == 1:\n local_image = Image.open(\"./octocats/octocat-Eva256.jpg\").convert('RGB')\n elif pickImage == 2:\n local_image = Image.open(\"./octocats/octocat-Jeff256.jpg\").convert('RGB')\n elif pickImage == 3:\n local_image = Image.open(\"./octocats/octocat-Molly256.jpg\").convert('RGB') \n else:\n local_image = Image.open(\"./octocats/octocat-Sam256.jpg\").convert('RGB')\n local_image = local_image.resize((imageSize,imageSize))\n \n imageOffsetX = (total_columns - imageSize) // 2\n imageOffsetY = (total_rows - imageSize) // 2\n temp_image.paste(local_image, (imageOffsetX,imageOffsetY))\n matrix.SetImage(temp_image,0,0)\n\n###################################\n# ScreenWipe\n###################################\ndef ScreenWipe(direction):\n global temp_image\n global temp_draw\n global total_rows\n global total_columns\n wipeSpeed = .01\n\n randomColor = random.randint(0,360)\n bg_color =\"hsl({}, 100%, 50%)\".format(randomColor)\n\n #Vertical wipe\n if (direction == 1): \n for y in range (total_rows):\n temp_draw.line((0,y,total_columns,y), fill=bg_color)\n matrix.SetImage(temp_image,0,0)\n sleep(wipeSpeed)\n\n #Horizontal wipe \n elif (direction == 2):\n for x in range (total_columns):\n temp_draw.line((x,0,x,total_rows), fill=bg_color)\n matrix.SetImage(temp_image,0,0)\n sleep(wipeSpeed) \n\n #Diagonal wipe -- This currently doesn't work as desired. See issue #6\n else:\n for z in range (total_rows+total_columns):\n temp_draw.line((0,z,total_columns,z - total_columns), fill=bg_color)\n matrix.SetImage(temp_image,0,0)\n sleep(wipeSpeed/2) \n\n###################################\n# Main loop \n###################################\nbackground()\nsleep(2)\nwhile True:\n newImage()\n sleep(2)\n ScreenWipe(random.randint(1,3))\n sleep(1)\n\ntry:\n print(\"Press CTRL-C to stop\")\n while True:\n sleep(100)\nexcept KeyboardInterrupt:\n exit(0)\n\n","sub_path":"octocats.py","file_name":"octocats.py","file_ext":"py","file_size_in_byte":3854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"2091012","text":"import os\nimport pandas as pd\nfrom tqdm import tqdm\nimport math\nfrom matplotlib.cbook import boxplot_stats\nimport librosa as lb # https://librosa.github.io/librosa/\nimport soundfile as sf # https://pysoundfile.readthedocs.io/en/latest/\nimport file as fi\nimport labels as la\nimport argparse\n\n\ndef slice_data(start, end, raw_data, sample_rate):\n \"\"\"splices audio data to desired start, end timestamps\"\"\"\n max_ind = len(raw_data)\n start_ind = min(int(start * sample_rate), max_ind)\n end_ind = min(int(end * sample_rate), max_ind)\n return raw_data[start_ind: end_ind]\n\n\ndef compute_len(samp_rate=22050, time=0, acquisition_mode=0):\n \"\"\"Computes the supposed length of sliced data\n samp_size = sample size from the data\n samp_rate = sampling rate. by default since we're working on 24-bit files, we'll use 96kHz\n time = length of time for the audio file. by default we'll use the max we have which is 5.48\n acquisition_mode = either mono or stereo. 0 for mono, 1 for stereo\n \"\"\"\n if acquisition_mode == 1: # ac mode is single channel which means it's 'mono'\n comp_len = samp_rate * time\n else: # stereo\n comp_len = samp_rate * time\n\n return comp_len\n\n\ndef get_cycledf(audio_text_loc):\n \"\"\"identify all cycle information files\n creates a list (files_) containting information for each respiratory cycle for a given wav file. Each element of\n the list is a dataframe containing the filename, patient ID, start, end, crackles, wheezes, and acquisition mode\n \"\"\"\n files = [fi.split_path(s).split('.')[0] for s in fi.get_filenames(audio_text_loc, [\"txt\"])]\n files_ = []\n # create dataframe from information contained in wav file names\n for f in files:\n df = pd.read_csv(audio_text_loc + '/' + f + '.txt', sep='\\t', names=['start', 'end', 'crackles', 'wheezes'])\n df['filename'] = f\n # get filename features\n f_features = fi.tokenize_file(f)\n df['pId'] = f_features[0]\n df['ac_mode'] = f_features[3]\n\n files_.append(df)\n\n return files_\n\n\ndef mergedf(cycle_info, diagnosis):\n \"\"\"process the dataframes and merge so that we have start and end info for each slice\n first converts cycle list to a df. Then merges the diagnosis info with the cycle info so each cycle (row) contains\n the appropriate diagnosis.\n \"\"\"\n files_df = pd.concat(cycle_info)\n files_df.reset_index()\n files_df['pId'] = files_df['pId'].astype('float64')\n files_df = pd.merge(files_df, diagnosis, on='pId')\n return files_df\n\n\ndef max_length(files_df):\n files_df['len_per_slice'] = files_df['end'].sub(files_df['start'], axis=0)\n return math.ceil(boxplot_stats(files_df['len_per_slice'])[0]['whishi'])\n\n\ndef process(data_path='../data', labels_only=False):\n \"\"\"Process the raw wavs to get each slice\n INPUT: A data dir where audio files and cycle info is stored in data_path/audio_txt_files\n OUTPUTS: data_path/processed with each recording split into the respiratory cycles\n disease_labels.csv: file with patient ids and their disease diagnoses mapped by Healthy, COPD, or Other\n symptoms_labels.csv: file with respiratory cycle ids and presence of crackles and wheezes\n The function parses through each of the txt files and filenames to identify start and end for each cycle. A good\n clipping value is then calculated. Each slice from the raw audios is processed so that they are of uniform length by\n cropping/padding as appropriate. Files are then saved.\n \"\"\"\n processed_dir = os.path.join(data_path, 'processed')\n fi.make_path(processed_dir)\n\n diagnosis = la.process_diag_labels(data_path)\n # find unique labels-->we will need this later\n ds = diagnosis['diagnosis'].unique()\n\n audio_text_loc = os.path.join(data_path, 'audio_and_txt_files')\n files_df = mergedf(get_cycledf(audio_text_loc), diagnosis)\n if not labels_only:\n # determine a max length for clips\n force_max_len = max_length(files_df)\n\n # make paths for the spliced files\n for d in ds:\n path = os.path.join(processed_dir, d)\n fi.make_path(path)\n\n # for each original file we splice by timestamps, and save as well as constructing a label file for the symptoms\n i = 0 # iterator for file naming\n with open(os.path.join(processed_dir, 'symptoms_labels.csv'), \"w\") as out:\n out.write(\"ID,cycle,crackles,wheezes\\n\")\n\n for idx, row in tqdm(files_df.iterrows(), total=files_df.shape[0]):\n filename = row['filename']\n start = row['start']\n end = row['end']\n diag = row['diagnosis']\n crackles = row['crackles']\n wheezes = row['wheezes']\n if not labels_only:\n # check len and force to 6 sec if more than that\n if force_max_len < end - start:\n end = start + force_max_len\n\n # reset index for each original file\n if idx != 0:\n if files_df.iloc[idx - 1]['filename'] == filename:\n i = i + 1\n else:\n i = 0\n\n n_filename = filename + '_' + str(i) + '.wav'\n if not labels_only:\n path = os.path.join(processed_dir, diag, n_filename)\n\n aud_loc = audio_text_loc + '/' + filename + '.wav'\n data, samplingrate = lb.load(aud_loc)\n sliced_data = slice_data(start=start, end=end, raw_data=data, sample_rate=samplingrate)\n\n # pad audio if < forced_max_len\n a_len = compute_len(samp_rate=samplingrate, time=force_max_len, acquisition_mode=row['ac_mode'] == 'sc')\n padded_data = lb.util.pad_center(sliced_data, a_len)\n\n sf.write(file=path, data=padded_data, samplerate=samplingrate)\n\n cycle = n_filename.split(\".\")[0]\n files_df.loc[idx,'cycle']=cycle\n ID = cycle.split('_')[0]\n out.write(f'{ID},{cycle},{str(crackles)},{str(wheezes)}\\n')\n\n files_df=files_df[[\"pId\",\"cycle\",\"diagnosis\"]].rename(columns={\"pId\":\"ID\"})\n files_df.to_csv(os.path.join(processed_dir, 'disease_labels.csv'), index=False)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--data', default='../data', help='data path')\n parser.add_argument(\"--labels_only\", default=False, help=\"if True does not process and only creates label files.\")\n args = parser.parse_args()\n process(args.data, args.labels_only)\n","sub_path":"utils/process_lung.py","file_name":"process_lung.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"53439025","text":"import torch\nimport torch.nn as nn\nclass KNRMModel(nn.Module):\n def __init__(self,hparams,vocab):\n super().__init__()\n self.name = hparams['name']\n self.device = hparams['device']\n self.metrics = hparams['metrics']\n\n self.cdd_size = (hparams['npratio'] + 1) if hparams['npratio'] > 0 else 1\n self.batch_size = hparams['batch_size']\n self.signal_length = hparams['title_size']\n self.his_size = hparams['his_size']\n self.embedding_dim = hparams['embedding_dim']\n \n self.mus = torch.arange(-0.9,1.1,0.1,device=self.device)\n self.kernel_num = len(self.mus)\n self.sigmas = torch.tensor([0.1]*(self.kernel_num - 1) + [0.001], device=self.device)\n\n self.embedding = vocab.vectors.clone().detach().requires_grad_(True).to(self.device)\n self.CosSim = nn.CosineSimilarity(dim=-1)\n self.softmax = nn.Softmax(dim=-1)\n self.learningToRank = nn.Linear(self.his_size * self.kernel_num, 1)\n\n def _kernel_pooling(self,matrixs):\n \"\"\"\n apply kernel pooling on matrix, in order to get the relatedness from many levels\n \n Args:\n matrix: tensor of [batch_size, rows, columns]\n \n Returns:\n pooling_vectors: tensor of [batch_size, kernel_num]\n \"\"\"\n pooling_matrixs = torch.zeros(matrixs.shape[0],matrixs.shape[1],self.kernel_num,device=self.device)\n \n for k in range(self.kernel_num):\n pooling_matrixs[:,:,k] = torch.sum(torch.exp(-(matrixs - self.mus[k])**2 / (2*self.sigmas[k]**2)),dim=2)\n \n pooling_vectors = torch.sum(torch.log(torch.clamp(pooling_matrixs,min=1e-10)),dim=1)\n return pooling_vectors\n \n def _fusion(self, cdd_news_batch, his_news_batch):\n \"\"\" fuse batch of candidate news and history news into batch of |candidate|*|history| interaction matrixs, according to cosine similarity\n\n Args:\n cdd_news_batch: tensor of [batch_size, cdd_size, signal_length]\n his_news_batch: tensor of [batch_size, his_size, signal_length]\n \n Returns:\n fusion_matrixs: tensor of [batch_size, cdd_size, his_size, signal_length, signal_length]\n \"\"\"\n cdd_news_embedding = self.embedding[cdd_news_batch]\n his_news_embedding = self.embedding[his_news_batch]\n \n fusion_matrixes = torch.zeros((self.batch_size, self.cdd_size, self.his_size, self.signal_length, self.signal_length), device=self.device)\n for i in range(self.cdd_size):\n for j in range(self.signal_length):\n fusion_matrixes[:,i,:,j,:] = self.CosSim(cdd_news_embedding[:,i,j,:].unsqueeze(1).unsqueeze(2), his_news_embedding)\n\n return fusion_matrixes\n\n def _click_predictor(self, pooling_vectors):\n \"\"\" learning to rank\n Args: \n pooling_vecors: tensor of [batch_size, cdd_size, his_size * kernel_num]\n \n Returns:\n scpre: tensor of [batch_size, cdd_size, his_size]\n \"\"\"\n score = self.learningToRank(pooling_vectors)\n\n if self.cdd_size > 1:\n score = nn.functional.log_softmax(score,dim=1)\n else:\n score = torch.sigmoid(score)\n return score.squeeze()\n\n def forward(self, x):\n fusion_matrixes = self._fusion(x['candidate_title'].long().to(self.device),x['clicked_title'].long().to(self.device))\n pooling_vectors = self._kernel_pooling(fusion_matrixes.view(-1,self.signal_length,self.signal_length)).view(self.batch_size,self.cdd_size,-1)\n score = self._click_predictor(pooling_vectors)\n\n return score","sub_path":"2018202180/src/scripts/models/KNRM.py","file_name":"KNRM.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"194894843","text":"# MLT hw8 problem 15. ~ 16.\n\nfrom sys import argv\nimport numpy as np\nnp.set_printoptions(precision=6, suppress=True)\nimport matplotlib.pyplot as plt\n\n\nclass TreeNode():\n \n def __init__(self, d, theta):\n \n self.dim = d # dimension\n self.theta = theta # division point\n self.sign = 0 # direction\n self.left = None\n self.right = None\n\n\ndef readData(filename):\n \n X, Y = [], []\n with open(filename, 'r') as f:\n \n for line in f:\n *x, y = line.split()\n X += [ [float(i) for i in x] ]\n Y += [ int(y) ]\n \n return (np.array(X), np.array(Y))\n\n\ndef plotDataset(X, Y, filename, picname):\n\n plt.figure()\n for x, y in zip(X, Y):\n\n if y > 0:\n plt.plot(x[0], x[1], 'bo')\n else:\n plt.plot(x[0], x[1], 'ro')\n \n plt.grid()\n plt.xlabel('x0')\n plt.ylabel('x1')\n plt.title(picname)\n plt.savefig(filename, dpi=300)\n #plt.show()\n\n\ndef GiniIndex(Y):\n\n N = Y.shape[0]\n pos, neg = sum(Y > 0), sum(Y < 0)\n\n if N == 0 or pos == 0 or neg == 0:\n return 0.\n else:\n return 1. - (pos / N)**2 - (neg / N)**2\n\n\ndef split(X, Y):\n \n (size, D) = X.shape\n \n min_err = np.inf\n best_d, theta = 0, 0\n for d in range(D):\n\n index = np.argsort(X[:, d])\n X_sort = X[index][:, d]\n Y_sort = Y[index]\n for i in range(1, size):\n \n ly = Y_sort[:i]\n ry = Y_sort[i:]\n err = ly.shape[0] * GiniIndex(ly) + ry.shape[0] * GiniIndex(ry)\n if err < min_err:\n min_err = err\n best_d = d\n theta = (X_sort[i-1] + X_sort[i]) / 2\n\n LX = X[ np.where(X[:, best_d] < theta) ]\n LY = Y[ np.where(X[:, best_d] < theta) ]\n RX = X[ np.where(X[:, best_d] >= theta) ]\n RY = Y[ np.where(X[:, best_d] >= theta) ]\n\n return (LX, LY), (RX, RY), best_d, theta\n\ndef createTree(X, Y, depth):\n \n # termination\n if X.shape[0] == 0: return None\n\n # create tree node\n if GiniIndex(Y) == 0 or depth > 0:\n node = TreeNode(-1, -1)\n node.sign = np.sign( np.sum(Y) )\n if node.sign == 0: node.sign += 1\n return node\n else:\n (LX, LY), (RX, RY), dim, theta = split(X, Y)\n node = TreeNode(dim, theta)\n node.left = createTree(LX, LY, depth+1)\n node.right = createTree(RX, RY, depth+1)\n return node\n\n\ndef printTree(node, depth):\n \n if node == None: return\n if node.left == None and node.right == None:\n print(' ' * depth + 'leaf: %d' % node.sign)\n return\n \n print(' ' * depth + 'dim: %d, theta: %f' % (node.dim, node.theta))\n if node.left != None:\n print(' ' * depth + 'left')\n print(' ' * depth + '{')\n printTree(node.left, depth+1)\n print(' ' * depth + '}')\n if node.right != None:\n print(' ' * depth + 'right')\n print(' ' * depth + '{')\n printTree(node.right, depth+1)\n print(' ' * depth + '}')\n\n\ndef predict(node, x):\n\n if node.left == None and node.right == None: return node.sign\n \n d, t = node.dim, node.theta\n return predict(node.left, x) if x[d] < t else predict(node.right, x)\n\n\ndef predictPruneOneLeaf(node, x, leaf):\n\n if node.left == None and node.right == None: return node.sign\n \n d, t = node.dim, node.theta\n if d == leaf[0] and t == leaf[1]:\n if leaf[2] == 'prune_left':\n return predict(node.right, x)\n if leaf[2] == 'prune_right':\n return predict(node.left, x)\n else:\n return predictPruneOneLeaf(node.left, x, leaf) if x[d] < t else predictPruneOneLeaf(node.right, x, leaf)\n\n\ndef findLeaves(node, leaves):\n \n def isLeaf(node):\n return 1 if node.left == None and node.right == None else 0\n\n if isLeaf(node.left):\n leaves.append( (node.dim, node.theta, 'prune_left') )\n else:\n leaves = findLeaves(node.left, leaves)\n\n if isLeaf(node.right):\n leaves.append( (node.dim, node.theta, 'prune_right') )\n else:\n leaves = findLeaves(node.right, leaves)\n\n return leaves\n\ndef toSign(Y):\n \n result = []\n for y in Y:\n if y == 0:\n result.append(1)\n else:\n result.append(np.sign(y))\n return np.array(result)\n\n\ndef main():\n \n (X, Y) = readData('hw3_train.dat')\n N, D = X.shape[0], X.shape[1]\n print('X shape:', X.shape)\n print('Y shape:', Y.shape)\n #plotDataset(X, Y, 'train_data.png', 'Training Data Set')\n \n (Xt, Yt) = readData('hw3_test.dat')\n Nt, Dt = Xt.shape[0], Xt.shape[1]\n print('Xt shape:', Xt.shape)\n print('Yt shape:', Yt.shape)\n\n T = 30000\n Y_pred_all, Yt_pred_all = np.zeros(N), np.zeros(Nt)\n roots, Ein_g, Ein_G, Eout_G = [], [], [], []\n for i in range(T):\n print('\\rtree: %d' % (i+1), end='', flush=True)\n \n np.random.seed(i)\n idx = np.random.randint(0, N, N)\n X_sample = X[idx]\n Y_sample = Y[idx]\n \n root = createTree(X_sample, Y_sample, 0)\n\n Y_pred, Yt_pred = [], []\n for x in X: Y_pred.append( predict(root, x) )\n for x in Xt: Yt_pred.append( predict(root, x) )\n Y_pred_all += np.array(Y_pred)\n Yt_pred_all += np.array(Yt_pred)\n\n ein_g = np.sum( abs( np.array(Y_pred) - Y ) / 2 ) / N\n ein_G = np.sum( abs( toSign(Y_pred_all) - Y ) / 2 ) / N\n eout_G = np.sum( abs( toSign(Yt_pred_all) - Yt ) / 2) / Nt\n\n Ein_g.append(ein_g)\n Ein_G.append(ein_G)\n Eout_G.append(eout_G)\n print('')\n \n plt.figure()\n plt.plot(Ein_G)\n plt.xlabel('t')\n plt.ylabel('Ein(Gt)')\n plt.title('15. t v.s. Ein(Gt)')\n plt.grid(linestyle=':')\n plt.savefig('15.png', dpi=300)\n plt.show()\n\n plt.figure()\n plt.plot(Eout_G)\n plt.xlabel('t')\n plt.ylabel('Eout(Gt)')\n plt.title('16. t v.s. Eout(Gt)')\n plt.grid(linestyle=':')\n plt.savefig('16.png', dpi=300)\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"hw8/code/15~16.py","file_name":"15~16.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"309912573","text":"'''\nCreated on 2019. 11. 28.\n\n@author: chiho\n'''\nimport os\nimport json\nimport numpy as np\nimport pandas as pd\nimport glob\nimport math\n\nfrom konlpy.tag import Hannanum\nfrom konlpy.tag import Kkma\nfrom collections import Counter\nfrom pandas import DataFrame\nfrom sklearn import preprocessing\n\nhannanum = Hannanum() \nhannanum.analyze #구(Phrase) 분석\nhannanum.morphs #형태소 분석\nhannanum.nouns #명사 분석\nhannanum.pos #형태소 분석 태깅\nkkma=Kkma() \n\ndef Query_vector_genarator(st,df1,df2,index_dict):\n \n nouns=[]\n pos = kkma.pos(st)\n if len(st) > 0 :\n for keyword, type in pos:\n if type == \"NNG\" or type == \"NNP\":\n if keyword in df1.columns[1:]:\n nouns.append(keyword)\n count=Counter(nouns)\n df2 = df2.append(count,ignore_index=True)\n df2 = df2.fillna(0)\n for colname in df2.columns[1:]:\n df2[colname]=df2[colname].map(lambda y:math.log10(y+1) if y > 0.0 else y )\n df2['계약서명'] = index_dict\n df3=df1.append(df2,ignore_index = True)\n df2=df2.drop([0])\n return df3\n\n\nall_keyword_list = []\ndata_dict = {}\ndataset_json = 'resources/dataset/{}_dataset.json'.format('recommendation')\nwith open(dataset_json, \"r\", encoding='UTF-8') as f:\n str_data = f.read()\n data_dict = json.loads(str_data)\n col = [ data[0] for data in data_dict]\n print(\"col=\",col)\n df = pd.DataFrame(columns=(col),dtype=float)\n print(df)\n\ndf_c=pd.DataFrame(columns=(['계약서명']),dtype=float)\ndf_o=pd.DataFrame(columns=(df.columns),dtype=float)\n\ndf1 = pd.concat([df_c, df_o], axis=1)\ndf2=pd.DataFrame(columns=(df1.columns),dtype=float)\n\nfiles = glob.glob(\"D:/OneDrive/법률문서/법률문서 데이터/*.txt\")\n\nindex_dict={}\ncount=0\nfor i, x in enumerate(files):\n \n f = open(x, 'r', encoding='utf-8')\n lines=f.read().count(\"\\n\")\n index_dict = x.replace('\\\\','/').split('/')[-1][:-4]\n f.close()\n \n f = open(x, 'r', encoding='utf-8')\n for j in range(lines):\n st=f.readline()\n df1 = Query_vector_genarator(st,df1,df2,index_dict)\n count=count+1\n print(count, index_dict, st)\n \nprint('==========end of job=============================')\ndf1.to_csv(\"D:/OneDrive/법률문서/질의문테이블.csv\", encoding='utf-8', mode='w')\n","sub_path":"deep_learning(딥러닝)/auto_encoder_model_nlp/4. 질의문테이블작성.py","file_name":"4. 질의문테이블작성.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"371068203","text":"import os\nfrom cget.util import cmd\n\n\ndef is_boost(directory):\n return os.path.isfile(os.path.join(directory, 'bootstrap.bat')) \\\n or os.path.isfile(os.path.join(directory, 'bootstrap.sh'))\n\n\nclass Boost:\n def __init__(self, install_root=None):\n self.name = 'boost'\n self.install_root = install_root\n\n def is_fetched(self, src_dir, name):\n if name != 'boost':\n return False\n return is_boost(src_dir)\n\n def configure(self, src_dir=None, build_dir=None, options=None):\n args = [os.path.join(src_dir, 'bootstrap.bat')]\n cmd(args, cwd=src_dir)\n\n def build(self, src_dir: str = None, build_dir: str = None, options: dict = None, install: bool = True) -> object:\n b2 = os.path.join(src_dir, 'b2.exe')\n if not os.path.isfile(b2):\n self.configure(src_dir=src_dir, build_dir=build_dir, options=options)\n args = [b2] # os.path.join(src_dir, './b2'),\n args.append('--prefix=' + self.install_root)\n if build_dir is not None:\n args.append('--build-dir=' + build_dir)\n variant = options.get('config', None)\n if variant is not None:\n args.append('variant=' + variant.lower())\n generator = options.get('generator', None)\n if generator is not None:\n if generator.startswith('Visual Studio'):\n args.append('toolset=msvc')\n if generator.endswith('Win64'):\n args.append('address-model=64')\n args.append('architecture=x86')\n static = options.get('static', None)\n if static is not None:\n if static:\n args.append('link=static')\n else:\n args.append('link=shared')\n if install:\n args.append('install')\n else:\n args.append('stage')\n cmd(args, cwd=src_dir)\n\n def install(self, **kwargs):\n self.build(install=True, **kwargs)\n","sub_path":"cget/boost.py","file_name":"boost.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"598168160","text":"import json as simplejson\nimport urllib2\n\n\ndef StockPriceReturner(array):\n yql_url=YQLQueryCompiler(array)\n \n data=simplejson.loads(urllib2.urlopen(yql_url).read())\n info=[]\n \n \n if len(array) > 1:\n \n for i in data['query']['results']['quote']:\n \n info.append({'Symbol':i['Symbol'],\n 'Price': i['LastTradePriceOnly']}\n )\n else:\n \n info.append({'Symbol':data['query']['results']['quote']['Symbol'],\n 'Price': data['query']['results']['quote']['LastTradePriceOnly']\n })\n \n return info\n\n\ndef YQLQueryCompiler(stock_array):\n \n base_url=\"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22\"\n\n for i in stock_array:\n \n if stock_array.index(i)==len(stock_array)-1:\n base_url+=i+\"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=\"\n else:\n base_url+=i+\"%22%2c%22\"\n\n return base_url\n\n\ndef GetQuoteInfo(quote):\n base_url=\"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.stocks%20where%20symbol%3D%22\"+quote+\"%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=\"\n base_url2=\"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22\"+quote+\"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=\"\n \n\n data=simplejson.loads(urllib2.urlopen(base_url).read())\n data2=simplejson.loads(urllib2.urlopen(base_url2).read())\n \n \n info={'Symbol':data2['query']['results']['quote']['Symbol'],\n 'Company':data2['query']['results']['quote']['Name'],\n 'Price': data2['query']['results']['quote']['LastTradePriceOnly'],\n 'Sector':data['query']['results']['stock']['Sector'],\n 'Industry':data['query']['results']['stock']['Industry'],\n 'Exchange': data2['query']['results']['quote']['StockExchange']\n }\n return info\n\ndef HistoricalPriceRange(tick, StartDate, EndDate):\n base_url=\"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22\"+tick+\"%22%20and%20startDate%20%3D%20%22\"+str(StartDate)+\"%22%20and%20endDate%20%3D%20%22\"+str(EndDate)+\"%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=\"\n data=simplejson.loads(urllib2.urlopen(base_url).read())\n \n \n \n if StartDate==EndDate:\n \n if data['query']['results'] is not None:\n return data['query']['results']['quote']['High'], data['query']['results']['quote']['Low']\n else:\n return 'error', 'error'\n \n else:\n if data['query']['results'] is not None:\n \n \n return data['query']['results']['quote'] \n else:\n return 'error'\n \n \n \n\n\n \n \n\n","sub_path":"resources/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"395623148","text":"# Status: \"available\", \"purchased\", \"blocked\"\nimport os, json\n\noriginal = { \n #NUCLEAR ----------------------------\n 'Conhecimento atômico': {\n 'title': \"Conhecimento atômico\",\n 'price': 50,\n 'type': \"is-warning\",\n 'spec': \"Estudos necessários para entender melhor o funcionamento das partículas atômicas e subatômicas e como promover mudanças ambientalmente favoráveis.\",\n 'type_tech': \"nuclear\",\n 'status': 'available',\n 'unlock': 'Usinas nucleares',\n 'affects': ['ABATEMENT', 'PRODUCTION', 'EMISSIONS', 'CARBON_INTENSITY', 'CARBON_BACKSTOP_PRICE'],\n 'how': [1.01, 1.05, .95, .9, .9]\n },\n 'Usinas nucleares': {\n 'title': \"Usinas nucleares\",\n 'price': 350,\n 'type': \"is-warning\",\n 'spec': \"Criação de polos de usinas nucleares para produzirem mais energia com um imacto ambiental menor.\",\n 'type_tech': \"nuclear\",\n 'status': 'blocked',\n 'unlock': 'Geradores nucleares',\n 'affects': ['ABATEMENT', 'PRODUCTION', 'EMISSIONS', 'CARBON_INTENSITY', 'CARBON_BACKSTOP_PRICE'],\n 'how': [1.01, 1.05, .95, .9, .9]\n },\n 'Geradores nucleares': {\n 'title': \"Geradores nucleares\",\n 'price': 700,\n 'type': \"is-warning\",\n 'spec': \"Diminui a demanda energética de combustíveis fósseis em 20% da população ao produzir um novo gerador de energia elétrica pessoal com elementos radioativos.\",\n 'type_tech': \"nuclear\",\n 'status': 'blocked',\n 'unlock': 'Comida irradiada',\n 'affects': ['ABATEMENT', 'PRODUCTION', 'EMISSIONS', 'CARBON_INTENSITY', 'CARBON_BACKSTOP_PRICE'],\n 'how': [1.01, 1.05, .95, .9, .9]\n },\n 'Comida irradiada': {\n 'title': \"Comida irradiada\",\n 'price': 1500,\n 'type': \"is-warning\",\n 'spec': \"Produção de alimentos com o uso de irradiação na agricultura a fim de prevenir a proliferação de pragas, diminuindo o uso de agrotóxicos que liberam gases estufa.\",\n 'type_tech': \"nuclear\",\n 'status': 'blocked',\n 'affects': ['ABATEMENT', 'PRODUCTION', 'EMISSIONS', 'CARBON_INTENSITY', 'CARBON_BACKSTOP_PRICE'],\n 'how': [1.05, 1.1, .9, .8, .8]\n },\n\n # BIOLÓGICO ---------------------\n \n 'Conhecimento molecular': {\n 'title': \"Conhecimento molecular\",\n 'price': 50,\n 'type': \"is-success\",\n 'spec': \"Estudos necessários para entender melhor o funcionamento da microbiologia e como promover mudanças ambientalmente favoráveis.\",\n 'type_tech': \"biológico\",\n 'status': 'available',\n 'unlock': 'Melhor sistema de reflorestamento',\n 'affects': ['C_ATM', 'ABATEMENT'],\n 'how': [.9, 1.5]\n },\n 'Melhor sistema de reflorestamento': {\n 'title': \"Melhor sistema de reflorestamento\",\n 'price': 350,\n 'type': \"is-success\",\n 'spec': \"Aumenta a plantação de árvores no planeta Terra, fazendo com que o sequestro de carbono (CO2) aumente em 15%.\",\n 'type_tech': \"biológico\",\n 'status': 'blocked',\n 'unlock': 'Biofiltro de algas',\n 'affects': ['C_ATM', 'ABATEMENT'],\n 'how': [.9, 1.5]\n },\n 'Biofiltro de algas': {\n 'title': \"Biofiltro de algas\",\n 'price': 700,\n 'type': \"is-success\",\n 'spec': \"Biofiltros formados por microalgas aumentam a absorção de CO2 da atmosfera em um nível 100 vezes mais alto que as árvores, podendo melhorar a qualidade de vida na Terra.\",\n 'type_tech': \"biológico\",\n 'status': 'blocked',\n 'unlock': 'Árvores geneticamente modificadas',\n 'affects': ['C_ATM', 'ABATEMENT'],\n 'how': [.9, 1.5]\n },\n 'Árvores geneticamente modificadas': {\n 'title': \"Árvores geneticamente modificadas\",\n 'price': 1500,\n 'type': \"is-success\",\n 'spec': \"Elaboração, em laboratório, de árvores com DNA modificado para terem um rendimento fotossintetizante mais alto que o normal, aumentando a absorção de CO2 na atmosfera.\",\n 'type_tech': \"biológico\",\n 'status': 'blocked',\n 'affects': ['C_ATM', 'ABATEMENT'],\n 'how': [.9, 1.5]\n },\n\n # TRANSPORTE --------------------\n \n 'Conhecimento de energias renováveis': {\n 'title': \"Conhecimento de energias renováveis\",\n 'price': 50,\n 'type': \"is-error\",\n 'spec': \"Estudos necessários para fazer meios de transporte serem menos agressivos ambientalmente.\",\n 'type_tech': \"transporte\",\n 'status': 'available',\n 'unlock': 'Carro movido a motor de hidrogênio',\n 'affects': ['PRODUCTIVITY', 'ABATEMENT', 'PRODUCTION'],\n 'how': [1.1, 1.2, 1.2]\n },\n 'Carro movido a motor de hidrogênio': {\n 'title': \"Carro movido a motor de hidrogênio\",\n 'price': 350,\n 'type': \"is-error\",\n 'spec': \"Liberação do motor movido a hidrogênio a preços acessíveis para a população, reduzindo a produção de CO2.\",\n 'type_tech': \"transporte\",\n 'status': 'blocked',\n 'unlock': 'Uberdrone',\n 'affects': ['PRODUCTIVITY', 'ABATEMENT', 'PRODUCTION'],\n 'how': [1.1, 1.2, 1.2]\n },\n 'Uberdrone': {\n 'title': \"Uberdrone\",\n 'price': 700,\n 'type': \"is-error\",\n 'spec': \"Criação do app Uberdrone que permite com que cidadãos realizem corridas econômicas e mais rápidas, diminuindo o uso de carros para a locomoção.\",\n 'type_tech': \"transporte\",\n 'status': 'blocked',\n 'unlock': 'Aerobus',\n 'affects': ['PRODUCTIVITY', 'ABATEMENT', 'PRODUCTION'],\n 'how': [1.1, 1.2, 1.2]\n },\n 'Aerobus': {\n 'title': \"Aerobus\",\n 'price': 1500,\n 'type': \"is-error\",\n 'spec': \"Ônibus voadores são desenvolvidos como alternativa para o transporte público. Como possui preço acessível, permitiu o o transporte mais rápido e eficiente entre os locais para a população, diminuindo em massa o uso de ônibus terrestres.\",\n 'type_tech': \"transporte\",\n 'status': 'blocked',\n 'affects': ['PRODUCTIVITY', 'ABATEMENT', 'PRODUCTION'],\n 'how': [1.1, 1.2, 1.2]\n },\n \n # ENERGÉTICO ---------------------\n \n 'Conhecimentos sobre o fluxo energético': {\n 'title': \"Conhecimentos sobre o fluxo energético\",\n 'price': 50,\n 'type': \"is-primary\",\n 'spec': \"Estudos necessários para promover o uso energético mais eficiente e menos poluente.\",\n 'type_tech': \"energético\",\n 'status': 'available',\n 'unlock': 'Usinas eólicas',\n 'affects': ['ABATEMENT', 'PRODUCTION', 'EMISSIONS'],\n 'how': [1.1, 1.2, .85]\n },\n 'Usinas eólicas': {\n 'title': \"Usinas eólicas\",\n 'price': 350,\n 'type': \"is-primary\",\n 'spec': \"Instalação de usinas eólicas para maior produção energética.\",\n 'type_tech': \"energético\",\n 'status': 'blocked',\n 'unlock': 'Giroplacas',\n 'affects': ['PRODUCTIVITY', 'ABATEMENT', 'PRODUCTION'],\n 'how': [1.1, 1.2, 1.2]\n },\n 'Giroplacas': {\n 'title': \"Giroplacas\",\n 'price': 700,\n 'type': \"is-primary\",\n 'spec': \"Desenvolvimento de sistema de placas solares autônomas que orbitam a Terra, de forma a garantir que os raios solares ao longo do dia sejam absorvidos pelas placas solares.\",\n 'type_tech': \"energético\",\n 'status': 'blocked',\n 'unlock': 'Fazendas de armazenamento de energia',\n 'affects': ['PRODUCTIVITY', 'ABATEMENT', 'PRODUCTION'],\n 'how': [1.1, 1.2, 1.2]\n },\n 'Fazendas de armazenamento de energia': {\n 'title': \"Fazendas de armazenamento de energia\",\n 'price': 1500,\n 'type': \"is-primary\",\n 'spec': \"Armazenamento da produção energética excedente para evitar demanda desigual ao longo do dia.\",\n 'type_tech': \"energético\",\n 'status': 'blocked',\n 'affects': ['PRODUCTIVITY', 'ABATEMENT', 'PRODUCTION'],\n 'how': [1.1, 1.2, 1.2]\n },\n\n # INDUSTRIAL -----------------------\n \n 'Conhecimentos industriais': {\n 'title': \"Conhecimentos industriais\",\n 'price': 50,\n 'type': \"industry\",\n 'spec': \"Estudos necessários ara promover uma produção industrial ambientalmente melhor.\",\n 'type_tech': \"industrial\",\n 'status': 'available',\n 'unlock': 'Reciclagem otimizada',\n 'affects': ['PRODUCTION', 'EMISSIONS', 'CARBON_BACKSTOP_PRICE'],\n 'how': [1.3, 1.2, .85]\n },\n 'Reciclagem otimizada': {\n 'title': \"Reciclagem otimizada\",\n 'price': 350,\n 'type': \"industry\",\n 'spec': \"Produção industrial mais eficiente, fazendo com que a produção de lixo seja menor e ambientalmente favorável.\",\n 'type_tech': \"industrial\",\n 'status': 'blocked',\n 'unlock': 'Eficiência industrial',\n 'affects': ['PRODUCTION', 'EMISSIONS', 'CARBON_BACKSTOP_PRICE'],\n 'how': [1.3, 1.2, .85]\n },\n 'Eficiência industrial': {\n 'title': \"Eficiência industrial\",\n 'price': 700,\n 'type': \"industry\",\n 'spec': \"Aumento da eficiência da produção industrial, fazendo com que menos energia seja gasta para produzir os produtos.\",\n 'type_tech': \"industrial\",\n 'status': 'blocked',\n 'unlock': 'Catalisadores inerentes',\n 'affects': ['PRODUCTION', 'EMISSIONS', 'CARBON_BACKSTOP_PRICE'],\n 'how': [1.3, 1.2, .85]\n },\n 'Catalisadores inerentes': {\n 'title': \"Catalisadores inerentes\",\n 'price': 1500,\n 'type': \"industry\",\n 'spec': \"Veículos utilitários terão catalisadores acoplados de forma obrigatória e gratuita para diminuir a emissão dos gases estufa.\",\n 'type_tech': \"industrial\",\n 'status': 'blocked',\n 'affects': ['PRODUCTION', 'EMISSIONS', 'CARBON_BACKSTOP_PRICE'],\n 'how': [1.3, 1.2, .85]\n },\n}\n\ndata = original\n\ndef list_techs():\n return [sc for sc in data.values() if sc[\"status\"] == \"available\"]\n\n\ndef save_techs():\n path = os.path.abspath('techs.json')\n techs = data\n with open(path, 'w') as fd:\n json.dump(techs, fd)\n\ndef load_techs():\n global data\n path = os.path.abspath('techs.json')\n with open(path, 'r') as fd:\n techs = json.load(fd)\n data = techs\n\ndef buy_tech(id):\n data[id][\"status\"] = \"purchased\"\n for tech in data.values():\n if \"unlock\" in data[id]:\n if(tech[\"title\"] == data[id][\"unlock\"]):\n tech[\"status\"] = \"available\"\n return data[id]\n\ndef get_type(type):\n techs = data.values()\n techreturn = []\n for tech in techs:\n if tech['type_tech'] == type:\n techreturn.append(tech)\n return techreturn\n\n\n","sub_path":"app/science.py","file_name":"science.py","file_ext":"py","file_size_in_byte":10820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"134425155","text":"import numpy as np\nimport cv2\nimport sys\nfrom matplotlib import pyplot as plt\n\n# img = cv2.imread('logo.png',0)\n# # Initiate ORB detector\n# orb = cv2.ORB_create()\n# # find the keypoints with ORB\n# kp = orb.detect(img,None)\n# # compute the descriptors with ORB\n# kp, des = orb.compute(img, kp)\n# # draw only keypoints location,not size and orientation\n# img2 = cv2.drawKeypoints(img, kp, None, color=(0,255,0), flags=0)\n# plt.imshow(img2), plt.show()\n\nfrom os import listdir\nfrom os.path import isfile, join\n\n\nclass Application:\n def __init__(self, extractor, detector):\n self.extractor = extractor\n self.detector = detector\n\n def train_vocabulary(self, file_list, vocabulary_size):\n kmeans_trainer = cv2.BOWKMeansTrainer(vocabulary_size)\n for path_to_image in file_list:\n img = cv2.imread(path_to_image, 0)\n kp, des = self.detector.detectAndCompute(img, None)\n kmeans_trainer.add(des)\n return kmeans_trainer.cluster()\n\n def extract_features_from_image(self, file_name):\n image = cv2.imread(file_name)\n return self.extractor.compute(image, self.detector.detect(image))\n\n def extract_train_data(self, file_list, category):\n train_data, train_responses = [], []\n for path_to_file in file_list:\n train_data.extend(self.extract_features_from_image(path_to_file))\n train_responses.append(category)\n return train_data, train_responses\n\n def train_classifier(self, data, responses):\n n_trees = 200\n max_depth = 10\n model = cv2.ml.RTrees_create()\n eps = 1\n criteria = (cv2.TERM_CRITERIA_MAX_ITER, n_trees, eps)\n model.setTermCriteria(criteria)\n model.setMaxDepth(max_depth)\n model.train(np.array(data), cv2.ml.ROW_SAMPLE, np.array(responses))\n return model\n\n def predict(self, file_name):\n features = self.extract_features_from_image(file_name)\n return self.classifier.predict(features)[0]\n\n def train(self, files_array, vocabulary_size=12):\n all_categories = []\n for category in files_array:\n all_categories += category\n\n vocabulary = self.train_vocabulary(all_categories, vocabulary_size)\n self.extractor.setVocabulary(vocabulary)\n\n data = []\n responses = []\n for id in range(len(files_array)):\n data_temp, responses_temp = self.extract_train_data(files_array[id], id)\n data += data_temp\n responses += responses_temp\n\n self.classifier = self.train_classifier(data, responses)\n\n def error(self, file_list, category):\n responses = np.array([self.predict(file) for file in file_list])\n _responses = np.array([category for _ in range(len(responses))])\n return 1 - np.sum(responses == _responses) / len(responses)\n\n\ndef get_images_from_folder(folder):\n return [\"%s/%s\" % (folder, f) for f in listdir(folder) if isfile(join(folder, f))]\n\n\ndef start(folders, detector_type, voc_size, train_proportion):\n if detector_type == \"SIFT\":\n # \"Scale Invariant Feature Transform\"\n extract = cv2.xfeatures2d.SIFT_create()\n detector = cv2.xfeatures2d.SIFT_create()\n else:\n # \"Speeded up Robust Features\"\n extract = cv2.xfeatures2d.SURF_create()\n detector = cv2.xfeatures2d.SURF_create()\n flann_params = dict(algorithm=1, trees=5)\n matcher = cv2.FlannBasedMatcher(flann_params, {})\n extractor = cv2.BOWImgDescriptorExtractor(extract, matcher)\n\n train = []\n test = []\n for folder in folders:\n images = get_images_from_folder(folder)\n np.random.shuffle(images)\n\n slice = int(len(images) * train_proportion)\n train_images = images[0:slice]\n test_images = images[slice:]\n train.append(train_images)\n test.append(test_images)\n\n app = Application(extractor, detector)\n app.train(train, voc_size)\n\n total_error = 0.0\n\n for id in range(len(test)):\n print(app.error(train[id], id))\n test_error = app.error(test[id], id)\n print(test_error)\n print(\"---------\")\n total_error = total_error + test_error\n\n total_error = total_error / float(len(test))\n print(\"Total error = %f\" % total_error)\n\n\nfirstFolder = sys.argv[1]\nsecondFolder = sys.argv[2]\ndetectorType = sys.argv[3]\nvocSize = int(sys.argv[4])\ntrainProportion = float(sys.argv[5])\n\nstart([firstFolder, secondFolder], detectorType, vocSize, trainProportion)\n","sub_path":"src/four/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"449964672","text":"'''\n1)\n- Program prosi nas o imie\n- Jesli imie wystepuje w slowniku to wyswietlamy date urodzenia tej osoby\n- Jesli nie, to prosimy o podanie daty urodzin i dodajemy ta osobe do slownika\n'''\n\nurodziny = {\"ania\": \"3 czer 1990\"}\n#urodziny[\"michal\"] = \"7 kwietnia 1993\"\n#print(urodziny[\"michal\"])\n\nwhile True:\n imie = input(\"Podaj imie: \")\n if imie in urodziny:\n print(\"Urodziny: \" + urodziny[imie])\n else:\n data = input(\"Podaj date urodzenia: \")\n urodziny[imie] = data\n\n","sub_path":"zajecia3/zajecia9zad1.py","file_name":"zajecia9zad1.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"283753039","text":"# -*- coding: utf-8 -*-\n# dst_v29.py\n\nfrom plato_wp36.lightcurve import LightcurveArbitraryRaster\nfrom plato_wp36.settings import settings\n\n\ndef process_lightcurve(lc: LightcurveArbitraryRaster, lc_duration: float, search_settings: dict):\n \"\"\"\n Perform a transit search on a light curve, using the bls_kovacs code.\n\n :param lc:\n The lightcurve object containing the input lightcurve.\n :type lc:\n LightcurveArbitraryRaster\n :param lc_duration:\n The duration of the lightcurve, in units of days.\n :type lc_duration:\n float\n :param search_settings:\n Dictionary of settings which control how we search for transits.\n :type search_settings:\n dict\n :return:\n dict containing the results of the transit search.\n \"\"\"\n\n time = lc.times\n flux = lc.fluxes\n\n results = {}\n\n # Extended results to save to disk\n results_extended = results\n\n # Return results\n return results, results_extended\n","sub_path":"docker_containers/testbed/python_modules/plato_wp36/plato_wp36/tda_wrappers/dst_v29.py","file_name":"dst_v29.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"195852158","text":"import random \r\ndef ufcc():\r\n\tdef creat_fighter():\r\n\t\tperson = {\"Сила\": 100, \"Выносливость\": 1000}\r\n\t\tperson[\"Имя\"] = input(\"Введи имя, боец \")\r\n\t\tchoose = input(\"\"\"\r\n1- прирост к силе\r\n2-прирост к выносливости\r\n3.кидать снежок \r\n4.Бросить на прогиб\r\n\t\t\t\"\"\")\r\n\t\tif choose == 1 :\r\n\t\t\tperson[\"Сила\"] = random.randint(10,100)\r\n\t\telif choose == 2 :\r\n\t\t\tperson[\"Выносливость\"] = random.randint(400,500)\r\n\t\telif choose == 3 :\r\n\t\t\tperson[\"Сила\"] = 1000\r\n\t\telse:\r\n\t\t\tperson[\"Сила\"] = random.randint(10,500)\r\n\r\n\t\treturn person\r\n\r\n\tdef attack(attacker, defender):\r\n\t\tprint(\"Игрок\", attacker[\"Имя\"], \"Нанес\", attacker[\"Сила\"], \"урона\")\r\n\t\tdefender[\"Выносливость\"] -= attacker[\"Сила\"]\r\n\r\n\tperson1 = creat_fighter()\r\n\tperson2 = creat_fighter()\r\n\r\n\tprint(person1)\r\n\tprint(person2)\r\n\r\n\twhile True:\r\n\t\tattack(person1,person2)\r\n\t\tattack(person2,person1)\r\n\t\tprint(\"У игрока\", person1[\"Имя\"], \"осталось\", person1[\"Выносливость\"])\r\n\t\tprint(\"У игрока\", person2[\"Имя\"], \"осталось\", person2[\"Выносливость\"])\r\n\t\tinput()\r\n\t\tif person1[\"Выносливость\"] <= 0:\r\n\t\t\tprint( person1[\"Имя\"], \"Ты проиграл\")\r\n\t\t\tbreak\r\n\t\telif person1[\"Выносливость\"] == person2[\"Выносливость\"]:\r\n\t\t\tprint(\"У вас ничья\")\r\n\t\telif person2[\"Выносливость\"] <= 0 :\r\n\t\t\tprint(person2[\"Имя\"], \"Ты проиграл\")\r\n\t\t\tbreak","sub_path":"ufc.py","file_name":"ufc.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"315724214","text":"from email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nimport smtplib\nimport time\n\nimport cv2 \nimport face_recognition\n\nyuz = r\"C:\\Users\\HH\\Desktop\\python\\output\\yuz.png\"\nhakan = r\"C:\\Users\\HH\\Desktop\\python\\data\\hakan.png\"\n\ndef cropFaceFromCamera():\n camera = cv2.VideoCapture(0) \n counter=0\n \n while True:\n ret, img = camera.read()\n \n face_locations = face_recognition.face_locations(img)\n \n \n for face_location in face_locations:\n top, right, bottom, left = face_location\n face = img[top:bottom, left:right]\n cv2.imwrite(yuz, face)\n counter +=1\n \n if counter != 0:\n break \n \n cv2.imshow('img',img)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break \n \n # Close the window \n camera.release() \n # De-allocate any associated memory usage \n cv2.destroyAllWindows() \n \n\ndef gmail(filename):\n time.sleep(8)\n \n fromaddr = \"from@gmail.com\"\n toaddr = \"to@gmail.com\"\n \n msg = MIMEMultipart()\n msg['From'] = fromaddr\n msg['To'] = toaddr\n msg['Subject'] = \"\"\n \n \n body = \"Test mail\"\n msg.attach(MIMEText(body, 'plain'))\n filename = filename\n attachment = open(filename,\"rb\")\n \n part = MIMEBase('application', 'octet-stream')\n part.set_payload((attachment).read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', f\"attachment; filename= {filename}\" )\n \n msg.attach(part)\n \n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.starttls()\n server.login(fromaddr, \"password\")\n text = msg.as_string()\n server.sendmail(fromaddr, toaddr, text)\n server.quit()\n \ndef faceMatches():\n hakan_image = face_recognition.load_image_file(hakan)\n hakan_encode = face_recognition.face_encodings(hakan_image)[0]\n\n current_image = face_recognition.load_image_file(yuz)\n current_encode = face_recognition.face_encodings(current_image,num_jitters=10)[0]\n\n result = face_recognition.compare_faces([hakan_encode],current_encode)\n\n if result[0] == True:\n print(\"eşleşti:) \")\n gmail(yuz)\n else:\n print(\"yohhh : \")\n gmail(yuz)\n\n\ndef showFaces():\n old = cv2.imread(hakan)\n current = cv2.imread(yuz)\n while True:\n cv2.imshow('old',old)\n cv2.imshow('current',current)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break \n\n\n\ncropFaceFromCamera()\nshowFaces()\ntry:\n faceMatches()\nexcept:\n cropFaceFromCamera()\n faceMatches()\n\n","sub_path":"Projects/#1CameraFaceToGmail.py","file_name":"#1CameraFaceToGmail.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"324581297","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom puppies import Shelter, Base, Puppy, engine\n# from flask.ext.sqlalchemy import SQLAlchemy\n\nfrom random import randint\nimport random\n\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\n\nsession = DBSession()\n\ntry:\n\n for row in session.query(Shelter.id).\\\n order_by(Shelter.name):\n session.query(Shelter.id).\\\n filter(Shelter.id == row.id).\\\n update({'current_occupancy': 0,\n 'maximum_capacity': randint(0, 10)})\n session.commit()\nexcept:\n session.rollback()\n raise\n","sub_path":"Problem_Set_1/data_init_shelter_capacity.py","file_name":"data_init_shelter_capacity.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"474242672","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport math\nimport copy\nimport itertools\n\n\ndef get_maximums(numbers):\n\treturn [max(elem) for elem in numbers]\n\ndef join_integers(numbers):\n\t# methode plusieurs lignes\n\t# result = \"\"\n\t# for elem in numbers:\n\t# \tresult += str(elem)\n\t# return int(result)\n\t# methode une ligne\n\treturn int(\"\".join([str(elem) for elem in numbers]))\n\ndef generate_prime_numbers(limit):\n\tpremiers = []\n\tnombres = [i for i in range(2, limit+1)]\n\twhile len(nombres) != 0:\n\t\tpremiers.append(nombres[0])\n\t# facon longue\n\t# \tnombres_2 = []\n\t# \tfor elem in nombres:\n\t# \t\tif elem % nombres[0] != 0:\n\t# \t\t\tnombres_2.append(elem)\n\t# \tnombres = nombres_2\n\t# facon 1 ligne\n\t\tnombres = [elem for elem in nombres if elem % nombres[0] != 0]\n\treturn premiers\n\ndef combine_strings_and_numbers(strings, num_combinations, excluded_multiples):\n\tresult = []\n# generer une liste de nombre allant de 1 A num_combinaisons (inclu) (None pour le premeir veu dire on exclu rien)\n\tfor i in range(1, num_combinations+1):\n# pour chaque entier dans la liste de nombre\n# #pour chaque string dans strings\n\t\tfor string in strings:\n\t\t\tif excluded_multiples is None or i % excluded_multiples != 0:\n\t\t\t\tresult.append(string + str(i))\n\n\treturn result\nif __name__ == \"__main__\":\n\tprint(get_maximums([[1,2,3], [6,5,4], [10,11,12], [8,9,7]]))\n\tprint(\"\")\n\tprint(join_integers([111, 222, 333]))\n\tprint(join_integers([69, 420]))\n\tprint(\"\")\n\tprint(generate_prime_numbers(17))\n\tprint(\"\")\n\tprint(combine_strings_and_numbers([\"A\", \"B\"], 2, None))\n\tprint(combine_strings_and_numbers([\"A\", \"B\"], 5, 2))\n","sub_path":"exercice.py","file_name":"exercice.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"65225820","text":"import pandas as pd\nimport os.path as osp\nfrom .utils import InterpolatingMap as itp_map\nfrom .utils import get_resource\n\ndef get_resource_config(config):\n if config['experiment'] == 'XENON1T':\n resource_config = {\n 'photon_area_distribution': 'XENON1T_spe_distributions.csv',\n 's1_light_yield_map': 'XENON1T_s1_xyz_ly_kr83m_SR1_pax-680_fdc-3d_v0.json',\n 's1_pattern_map': 'XENON1T_s1_xyz_patterns_interp_corrected_MCv2.1.0.json.gz',\n 's2_light_yield_map': 'XENON1T_s2_xy_ly_SR1_v2.2.json',\n 's2_pattern_map': 'XENON1T_s2_xy_patterns_top_corrected_MCv2.1.0.json.gz',\n 's2_per_pmt_params': 'Kr83m_Ddriven_per_pmt_params_dataframe.csv',\n 'ele_ap_cdfs': 'ele_after_pulse.npy',\n 'ele_ap_pdfs': 'x1t_se_afterpulse_delaytime.pkl.gz',\n 'photon_ap_cdfs': 'x1t_pmt_afterpulse_config.pkl.gz',\n 'noise_file': 'x1t_noise_170203_0850_00_small.npz',\n }\n if config['experiment'] == 'XENONnT':\n resource_config = {\n 'photon_area_distribution': 'XENON1T_spe_distributions.csv',\n 's1_light_yield_map': 'XENONnT_s1_xyz_ly_kr83m_SR1_pax-680_fdc-3d_v0.json',\n 's1_pattern_map': 'XENONnT_s1_xyz_patterns_interp_corrected_MCv2.1.0.json.gz',\n 's2_light_yield_map': 'XENONnT_s2_xy_ly_SR1_v2.2.json',\n 's2_pattern_map': 'XENONnT_s2_xy_patterns_top_corrected_MCv2.1.0.json.gz',\n 's2_per_pmt_params': 'Kr83m_Ddriven_per_pmt_params_dataframe.csv',\n 'ele_ap_cdfs': 'ele_after_pulse.npy',\n 'ele_ap_pdfs': 'xnt_se_afterpulse_delaytime.pkl.gz',\n 'photon_ap_cdfs': 'xnt_pmt_afterpulse_config.pkl.gz',\n 'noise_file': 'x1t_noise_170203_0850_00_small.npz',\n }\n\n for k in resource_config:\n resource_config[k] = osp.join('https://raw.githubusercontent.com/XENONnT/strax_auxiliary_files/'\n 'master/fax_files', resource_config[k])\n\n return resource_config\n\nclass Resource(object):\n # The private nested inner class __Resource would only be instantiate once \n\n class __Resource(object):\n\n def __init__(self, config={}):\n self.config = get_resource_config(config)\n\n # Pulse\n self.photon_area_distribution = get_resource(self.config['photon_area_distribution'], fmt='csv')\n\n # S1\n self.s1_light_yield_map = itp_map(self.config['s1_light_yield_map'], fmt='json')\n self.s1_pattern_map = itp_map(self.config['s1_pattern_map'], fmt='json.gz')\n\n # S2\n self.s2_light_yield_map = itp_map(self.config['s2_light_yield_map'], fmt='json')\n if config['experiment']=='XENON1T':\n self.s2_per_pmt_params = get_resource(self.config['s2_per_pmt_params'], fmt='csv')\n if config['experiment']=='XENONnT':\n self.s2_per_pmt_params = itp_map(self.config['s2_pattern_map'], fmt='json.gz')\n # Electron After Pulses\n # self.uniform_to_ele_ap = get_resource(self.config['ele_ap_cdfs'], fmt='npy')\n\n # Electron After Pulses compressed, haven't figure out how pkl.gz works\n self.uniform_to_ele_ap = get_resource(self.config['ele_ap_pdfs'], fmt='pkl.gz')\n\n # Photon After Pulses\n self.uniform_to_pmt_ap = get_resource(self.config['photon_ap_cdfs'], fmt='pkl.gz')\n\n # Noise sample\n self.noise_data = get_resource(self.config['noise_file'], fmt='npy')['arr_0'].flatten()\n\n self.config.update(config)\n instance = None\n \n def __init__(self, config={}):\n self.config = config\n if not Resource.instance:\n Resource.instance = Resource.__Resource(config)\n \n def __getattr__(self, name):\n return getattr(self.instance, name)\n","sub_path":"WFSim/wfsim/load_resource.py","file_name":"load_resource.py","file_ext":"py","file_size_in_byte":3842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"196426615","text":"\"\"\" Functions that read efficiently files stored on disk \"\"\"\n\nimport os\nimport re\nfrom typing import Iterator, List\n\nimport numpy as np\nfrom tqdm import tqdm as tq\n\n\ndef read_embeddings_local(local_embeddings_path: str, stack_input: int = 1, verbose=True) -> Iterator[np.ndarray]:\n \"\"\"\n Iterate over embeddings arrays saved on disk.\n It is possible to iterate over batchs of files and yield stacked embeddings arrays.\n\n Parameters\n ----------\n local_embeddings_path : str\n Path on local disk of the embedding in numpy format.\n stack_input : int (default 1)\n Number of arrays that should be stacked at each iterations.\n This parameter is useful when working with many small files.\n verbose : bool\n Print detailed informations if set to True\n\n Returns\n -------\n embeddings_iterator : Iterator[np.ndarray]\n An iterator over batchs of stacked embedding arrays.\n \"\"\"\n return read_arrays_local(local_embeddings_path, stack_input=stack_input, verbose=verbose)\n\n\ndef read_arrays_local(\n local_path: str, reg_exp_pattern: str = r\".+\\.npy\", stack_input: int = 1, verbose=True\n) -> Iterator[np.ndarray]:\n \"\"\"\n Iterate over numpy array files that match the reg ex pattern and yield their content.\n It is possible to iterate over the stacked content of several arrays.\n\n Parameters\n ----------\n local_embeddings_path : str\n Path on local disk of arrays in numpy format.\n stack_input : int (default 1)\n Number of arrays that should be stacked at each iterations.\n This parameter is useful when working with many small files.\n verbose : bool\n Print detailed informations if set to True\n\n Returns\n -------\n arrays_iterator : Iterator[np.ndarray]\n An iterator over batchs of stacked arrays.\n \"\"\"\n\n assert stack_input > 0\n\n reg_exp = re.compile(reg_exp_pattern)\n\n filenames = os.walk(local_path).__next__()[2]\n filenames = [filename for filename in filenames if reg_exp.match(filename)]\n filenames.sort()\n embeddings_stack: List[np.ndarray] = []\n\n iterator = enumerate(filenames)\n if verbose:\n iterator = tq(list(iterator))\n\n for file_number, file_name in iterator:\n\n if embeddings_stack and (file_number % stack_input == 0):\n yield np.concatenate(embeddings_stack)\n embeddings_stack = []\n\n try:\n embeddings_stack.append(np.load(f\"{local_path}/{file_name}\"))\n except Exception as e: # pylint: disable=broad-except\n print(e)\n\n if embeddings_stack:\n yield np.concatenate(embeddings_stack).astype(np.float32)\n","sub_path":"autofaiss/datasets/readers/local_iterators.py","file_name":"local_iterators.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"271553649","text":"import numpy as np\nimport pandas as pd\nfrom expt_settings.configs import ExperimentConfig\nimport os\nimport wget\nimport pyunpack\nfrom pandas import DataFrame, Series, Timestamp, Index\nfrom numpy import ndarray\n\n\n# General functions for data downloading & aggregation.\ndef download_from_url(url: str, output_path: str):\n \"\"\"Downloads a file froma url.\"\"\"\n\n print('Pulling data from {} to {}'.format(url, output_path))\n wget.download(url, output_path)\n print('done')\n\n\ndef unzip(zip_path: str, output_file: str, data_folder: str):\n \"\"\"Unzips files and checks successful completion.\"\"\"\n\n print('Unzipping file: {}'.format(zip_path))\n pyunpack.Archive(zip_path).extractall(data_folder)\n\n # Checks if unzip was successful\n if not os.path.exists(output_file):\n raise ValueError(\n 'Error in unzipping process! {} not found.'.format(output_file))\n\n\ndef download_and_unzip(url: str, zip_path: str, csv_path: str, data_folder: str):\n \"\"\"Downloads and unzips an online csv file.\n Args:\n url: Web address\n zip_path: Path to download zip file\n csv_path: Expected path to csv file\n data_folder: Folder in which data is stored.\n \"\"\"\n\n download_from_url(url, zip_path)\n\n unzip(zip_path, csv_path, data_folder)\n\n print('Done.')\n\n\ndef download_electricity(config: ExperimentConfig) -> str:\n \"\"\"Downloads electricity dataset from UCI repository.\"\"\"\n\n url: str = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00321/LD2011_2014.txt.zip'\n\n data_folder: str = config.data_folder\n csv_path: str = os.path.join(data_folder, url.split('/')[-1].replace('.zip', ''))\n zip_path: str = csv_path + '.zip'\n if os.path.exists(csv_path):\n return csv_path\n else:\n download_and_unzip(url, zip_path, csv_path, data_folder)\n\n return csv_path\n\n\ndef preprocess_electricty(csv_path: str, config: ExperimentConfig):\n if os.path.exists(config.data_csv_path):\n print(f'File already preprocessed in {config.data_csv_path}')\n else:\n print('Aggregating to hourly data')\n\n df: DataFrame = pd.read_csv(csv_path, index_col=0, sep=';', decimal=',')\n df.index = pd.to_datetime(df.index)\n df.sort_index(inplace=True)\n\n # Used to determine the start and end dates of a series\n output = df.resample('1h').mean().replace(0., np.nan)\n\n earliest_time: Timestamp = output.index.min()\n\n df_list = []\n for label in output:\n print('Processing {}'.format(label))\n srs: Series = output[label]\n\n start_date: Timestamp = min(srs.fillna(method='ffill').dropna().index)\n end_date: Timestamp = max(srs.fillna(method='bfill').dropna().index)\n\n active_range: ndarray = (srs.index >= start_date) & (srs.index <= end_date)\n srs: Series = srs[active_range].fillna(0.)\n\n tmp: DataFrame = pd.DataFrame({'power_usage': srs})\n date: Series = tmp.index\n tmp['t']: Series = (date - earliest_time).seconds / 60 / 60 + (\n date - earliest_time).days * 24\n tmp['days_from_start']: Series = (date - earliest_time).days\n tmp['categorical_id']: Series = label\n tmp['date']: Series = date\n tmp['id']: Series = label\n tmp['hour']: Series = date.hour\n tmp['day']: Series = date.day\n tmp['day_of_week']: Series = date.dayofweek\n tmp['month']: Series = date.month\n\n df_list.append(tmp)\n\n output: DataFrame = pd.concat(df_list, axis=0, join='outer').reset_index(drop=True)\n\n output['categorical_id']: Series = output['id'].copy()\n output['hours_from_start']: Series = output['t']\n output['categorical_day_of_week']: Series = output['day_of_week'].copy()\n output['categorical_hour']: Series = output['hour'].copy()\n\n # Filter to match range used by other academic papers\n output: DataFrame = output[(output['days_from_start'] >= 1096)\n & (output['days_from_start'] < 1346)].copy()\n\n output.to_csv(config.data_csv_path)\n print(f'Saved in {config.data_csv_path}')\n print('Done.')\n\n\nif __name__ == \"__main__\":\n expt_config = ExperimentConfig('electricity', './outputs/data/electricity')\n csv_path: str = download_electricity(expt_config)\n preprocess_electricty(csv_path, expt_config)\n","sub_path":"script_download_data.py","file_name":"script_download_data.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"319983733","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\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/topp/build/opencore/options.py\n# Compiled at: 2007-09-27 10:29:31\n\"\"\" options for this script -- topp.build.opencore \"\"\"\n\ndef add_options(parser):\n parser.add_option('--create-site', dest='create_site', action='store_true', default=False, help='create openplans site and customizations')\n parser.add_context_option('--zope-port', dest='zope_port', help='Zope HTTP server port number.', metavar='ZOPE-PORT')\n parser.add_context_option('--zeo-port', dest='zeo_port', help='The port the ZEO server will listen on.', metavar='ZEO-PORT')\n parser.add_context_option('--debug-mode', dest='debug_mode', default='${zope/debug_mode}', help='Run Zope in debug mode? (on/off, default defined by the distribution settings)', metavar='DEBUG-MODE')\n parser.add_context_option('--with-zope', dest='zope_source', directory=True, default='${srcdir}/${zope/package}', help='Location of an existing Zope source checkout (must have write access?)', metavar='/path/to/Zope-source-checkout')\n parser.add_context_option('--with-products', dest='products', directory=True, default='${deploydir}/src/${opencore/package}', help='Location of an existing Products bundle (will be symlinked in)', metavar='/path/to/products-bundle-checkout')\n parser.add_context_option('--with-python', dest='python', help='Location of the python you want to use', metavar='/path/to/python')","sub_path":"pycfiles/topp.build.opencore-0.5.1-py2.4/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"621407904","text":"import requests\nimport datetime as dt\nfrom pprint import pprint\n\n\nclass FlightData:\n # This class is responsible for structuring the flight data.\n def __init__(self):\n self.parameters = {\n \"apikey\": self.api_key,\n \"fly_from\": self.fly_from,\n \"fly_to\": self.fly_to,\n \"date_from\": self.date_from,\n \"date_to\": self.date_to,\n \"nights_in_dst_from\": self.nights_in_dst_from,\n \"nights_in_dst_to\": self.nights_in_dst_to,\n \"flight_type\": self.flight_type,\n \"max_stopovers\": self.max_stopovers,\n \"sort\": self.sort,\n \"limit\": self.limit,\n \"curr\": self.curr,\n \"fly_days_type\": \"departure\",\n \"ret_fly_days_type\": \"departure\"\n }\n self.api_key = \"\"\n self.fly_from = \"LON\"\n self.fly_to = \"\"\n self.date_from = (dt.date.today() + dt.timedelta(days=1)).strftime(\"%d/%m/%Y\"),\n self.date_to = (dt.date.today() + dt.timedelta(days=180)).strftime(\"%d/%m/%Y\")\n self.flight_type = \"round\"\n self.max_stopovers = 0 # indicates direct flight\n self.nights_in_dst_from = 7\n self.nights_in_dst_to = 28\n self.sort = \"price\"\n self.curr = \"GBP\"\n self.limit = 10\n self.list_of_data = []\n\n self.flight_url = \"https://tequila-api.kiwi.com/v2/search\"\n\n def flight_data(self, destination_list):\n for destination in destination_list:\n self.parameters[\"fly_to\"] = destination\n try:\n flight_response = requests.get(self.flight_url, params=self.parameters)\n except IndexError:\n print(\"Data not available\")\n return None\n except:\n print(\"No Flights\")\n return None\n else:\n\n data = flight_response.json()[\"data\"][0]\n city_From = data[\"cityFrom\"]\n city_Code_From = data[\"cityCodeFrom\"]\n city_TO = data[\"cityTo\"]\n city_Code_TO = data[\"cityCodeTo\"]\n\n price = data[\"price\"]\n departure_date = data[\"local_departure\"].split(\"T\")[0]\n arrival_date = data[\"route\"][1][\"local_departure\"].split(\"T\")[0]\n city_dict = {\"city_TO\": city_TO, \"price\": price, \"city_From\": city_From,\n \"city_Code_From\": city_Code_From,\n \"city_Code_TO\": city_Code_TO, \"departure_date\": departure_date,\n \"arrival_date\": arrival_date}\n self.list_of_data.append(city_dict)\n return self.list_of_data\n","sub_path":"flight_data.py","file_name":"flight_data.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"508533746","text":"# Shell Sort Algorithm\r\n\r\ndef shellsort(list):\r\n interval = len(list) // 2\r\n while interval > 0:\r\n for index in range(interval, len(list)):\r\n current_element = list[index]\r\n pos = index\r\n while pos >= interval and current_element < list[pos - interval]:\r\n list[pos] = list[pos - interval]\r\n pos -= interval\r\n list[pos] = current_element\r\n interval = interval // 2\r\n\r\nlist = [9, 8, 3, 7, 5, 6, 4, 1]\r\nshellsort(list)\r\nprint(list)\r\n","sub_path":"014-shell-sort.py","file_name":"014-shell-sort.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"241841015","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\nmsg_enum = {\n 200: \"执行成功\",\n 201: \"执行失败\",\n 202: \"接口不存在\",\n 203: \"缺少必要的参数\",\n 204: \"授权码不正确\",\n 300: \"本书不存在\",\n 301: \"章节不存在\",\n 302: \"手机号码格式不正确\",\n 303: \"验证码不正确\",\n 304: \"短信发送失败\",\n 305: \"数据不存在\",\n 306: \"参数不正确\",\n 500: \"不启用SDK广告\",\n 601: \"已点赞\",\n 602: \"内容含有敏感信息,发送失败\",\n}\n\n\ndef messages_status(code):\n data = {\"code\": code, \"messages\": \"\"}\n if code in msg_enum:\n data[\"messages\"] = msg_enum[code]\n return data\n","sub_path":"test-flask/config/mycode.py","file_name":"mycode.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"31775104","text":"import time\nimport boto3\nimport os\nimport shutil\nfrom pathlib import Path\n\ncurrent_path = Path(os.path.dirname(os.path.realpath(__file__)))\n\n\ndef operator_session():\n\n client = boto3.client(\"sts\")\n\n role_to_assume = f\"arn:aws:iam::288342028542:role/operator\"\n response = client.assume_role(\n RoleArn=role_to_assume, RoleSessionName=\"assumed_role\"\n )\n\n session = boto3.Session(\n aws_access_key_id=response[\"Credentials\"][\"AccessKeyId\"],\n aws_secret_access_key=response[\"Credentials\"][\"SecretAccessKey\"],\n aws_session_token=response[\"Credentials\"][\"SessionToken\"],\n )\n\n return session\n\n\ndef get_list_of_files(bucket_name, s3, local_data_path):\n resp = s3.list_objects_v2(Bucket=bucket_name)\n files_in_bucket = []\n\n for obj in resp[\"Contents\"]:\n file_and_folder = obj[\"Key\"]\n folder = file_and_folder.split(\"/\")[0]\n file = file_and_folder.split(\"/\")[1]\n dl_file_location = str(local_data_path) + \"/\" + file\n if folder == \"anon\" and file.endswith(\".csv\"):\n s3.download_file(bucket_name, file_and_folder, dl_file_location)\n print(file_and_folder)\n files_in_bucket.append(file_and_folder)\n\n print(f\"Total files returned: {len(files_in_bucket)}\")\n return files_in_bucket\n\n\ndef clear_folder(folder):\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print(\"Failed to delete %s. Reason: %s\" % (file_path, e))\n\n\ndef main():\n csv_dir_suffix = os.getenv(\"CSV_DIR_SUFFIX\")\n bucket = \"casrec-migration-development\"\n s3_session = operator_session()\n s3 = s3_session.client(\"s3\")\n local_data_path = current_path / csv_dir_suffix\n clear_folder(local_data_path)\n\n get_list_of_files(bucket, s3, local_data_path)\n\n\nif __name__ == \"__main__\":\n t = time.process_time()\n main()\n print(f\"Total time: {round(time.process_time() - t, 2)}\")\n","sub_path":"migration_steps/load_s3/synchronise_s3.py","file_name":"synchronise_s3.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"66132724","text":"import os, json\nfrom awscli.testutils import aws\nfrom functools import wraps\n\nDEFAULT_PROFILE='user_session'\nDEFAULT_REGION='us-east-2'\n\n\ndef get_account_id():\n response = aws_command(['sts','get-caller-identity'])\n return kindly_find(response, ['Account'])\n\ndef aws_command(fields, raw=False, profile=DEFAULT_PROFILE):\n if profile is not None:\n fields += ['--profile', profile]\n\n result = aws(' '.join(fields), env_vars=os.environ)\n\n if result.rc != 0:\n raise Exception(result.stderr)\n if raw:\n return result.stdout.strip()\n else:\n return result.json\n\ndef stringify(resource):\n return '\"'+json.dumps(resource).replace('\\\\', \"\\\\\\\\\").replace(\"\\\"\", \"\\\\\\\"\")+'\"'\n\ndef kindly_find(full_hash, keys):\n reference = full_hash\n for key in keys:\n if present(key, reference):\n reference = reference[key]\n else:\n return ''\n return reference\n\ndef present(key, reference):\n return key in reference or isinstance(key, int) and key < len(reference)\n\ndef cache_result(original_function):\n @wraps(original_function)\n def wrapper(decorated_class, *args, **kwargs):\n key_name = original_function.__name__.strip('_')\n if key_name not in decorated_class._cache:\n decorated_class._cache[key_name] = original_function(decorated_class, *args, **kwargs)\n\n return decorated_class._cache[key_name]\n\n return wrapper","sub_path":"lib/aws/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"107516849","text":"import numpy as np\nfrom typing import List, Optional, Tuple\n\nfrom snc.agents.activity_rate_to_mpc_actions.action_mpc_policy import ActionMPCPolicy\nimport snc.agents.agents_utils as agents_utils\nimport snc.agents.hedgehog.policies.policy_utils as policy_utils\nimport snc.utils.snc_types as types\n\n\nclass FeedbackStationaryFeasibleMpcPolicy(ActionMPCPolicy):\n # TODO: Allow to choose actions deterministically, e.g., for a resource take the action with\n # largest rate.\n def __init__(self,\n physical_constituency_matrix: types.ConstituencyMatrix,\n buffer_processing_matrix: types.BufferMatrix,\n mpc_seed: Optional[int] = None) -> None:\n \"\"\"\n Obtain feasible binary actions from activity rates with feedback on how many actions have\n been performed so far for a given horizon. The actions are drawn from a probability\n distribution that aims to match the activity rates after some horizon. The feedback allows\n to adjust the distribution so that underperformed activities are emphasised. Feasible\n actions refer to those that drain nonempty buffers. In the case that some action is\n infeasible, then the corresponding resource performs other activity.\n\n :param physical_constituency_matrix: Constituency matrix from environment. We assume it has\n orthogonal rows.\n :param buffer_processing_matrix: Buffer processing matrix from environment.\n :return: None.\n \"\"\"\n # Ensure that constituency_matrix has a single one per column.\n assert agents_utils.has_orthogonal_rows(physical_constituency_matrix), \\\n \"Physical constituency matrix must have orthogonal rows.\"\n super().__init__(physical_constituency_matrix, mpc_seed)\n\n self.buffer_processing_matrix = buffer_processing_matrix\n\n self.activities_per_resource, self.num_activities_per_resource \\\n = self.get_ind_activities_per_resource(physical_constituency_matrix)\n\n @staticmethod\n def get_ind_activities_per_resource(physical_constituency_matrix: types.ConstituencyMatrix) -> \\\n Tuple[List[List[int]], List[int]]:\n \"\"\"\n Return the index of activities per resource and the total number of activities per resource.\n\n :param physical_constituency_matrix: Constituency matrix from environment. We assume it has\n orthogonal rows.\n :return: (activities_per_resource, num_activities_per_resource):\n - activities_per_resource: List of lists of activities per resource.\n - num_activities_per_resource: List of number of activities per resource.\n \"\"\"\n assert agents_utils.has_orthogonal_rows(physical_constituency_matrix), \\\n \"Physical constituency matrix must have orthogonal rows.\"\n\n activities_per_resource = [] # type: List[List[int]]\n num_activities_per_resource = [] # type: List[int]\n\n for c in physical_constituency_matrix:\n activities_c = np.nonzero(c)[0]\n assert activities_c.size > 0\n\n activities_per_resource += [activities_c.tolist()]\n num_activities_per_resource += [activities_c.size]\n\n return activities_per_resource, num_activities_per_resource\n\n @staticmethod\n def does_activity_j_drain_any_currently_empty_buffer(\n state: types.StateSpace, j: int, buffer_processing_matrix: types.BufferMatrix) -> bool:\n \"\"\"\n Check if activity j drains an empty buffer.\n\n :param state: Current state.\n :param j: Index activity.\n :param buffer_processing_matrix: Buffer processing matrix.\n :return: True if activity j drains an empty buffer, or False otherwise.\n \"\"\"\n empty_buffers = np.where(state < 1)[0].tolist()\n if not empty_buffers:\n return False\n else:\n it_drains_empty_buffer = False\n for b in empty_buffers:\n if j in policy_utils.get_index_activities_that_can_drain_buffer(\n b, buffer_processing_matrix).tolist():\n it_drains_empty_buffer = True\n return it_drains_empty_buffer\n\n @staticmethod\n def get_activities_drain_currently_empty_buffers(\n state: types.StateSpace, buffer_processing_matrix: types.BufferMatrix) -> List[int]:\n \"\"\"\n Return list of activities that will attempt to drain empty buffers.\n\n :param state: Current state.\n :param buffer_processing_matrix: Buffer processing matrix.\n :return: List of indexes of activities draining empty buffers.\n \"\"\"\n act_drain_empty_buffers = [] # type: List[int]\n num_activities = buffer_processing_matrix.shape[1]\n for j in range(num_activities):\n if FeedbackStationaryFeasibleMpcPolicy.does_activity_j_drain_any_currently_empty_buffer(\n state, j, buffer_processing_matrix):\n act_drain_empty_buffers += [j]\n return act_drain_empty_buffers\n\n @staticmethod\n def get_valid_actions(act_s: List[int], act_drain_empty: List[int]):\n \"\"\"\n For a given list of activities of some resource, return only those activities that don't\n drain empty buffers.\n This is actually a generic function that takes two lists as input, and returns the elements\n of the first argument that are not in the second argument.\n\n :param act_s: List of activities of the s-th resource.\n :param act_drain_empty: List of activities that don't drain empty buffers.\n\n \"\"\"\n return [x for x in act_s if x not in act_drain_empty] # List of valid actions.\n\n @staticmethod\n def reallocate_activity_j(j: int, activity_rates: types.ActionSpace,\n act_s: List[int], act_drain_empty: List[int]):\n \"\"\"\n Adjust the activity rates by reallocating the activity rate of action j, which drains an\n empty buffer, to other actions that belong to the same resource but don't drain any empty\n buffer.\n\n :param j: Index of the activity whose rate we want to reallocate.\n :param activity_rates: Vector of activity rates.\n :param act_s: List of actions of the s-th resource.\n :param act_drain_empty: List of not valid actions, which drain empty buffers.\n :return: new_activity_rates: Vector of activity rates where the mass of j has been evenly\n added to other activities of the same resource.\n \"\"\"\n assert j in act_drain_empty, f\"Only reallocate activity j={j} if it drains an empty buffer.\"\n assert j in act_s, f\"Something is wrong: action j={j} should belong to act_s=[{act_s}].\"\n\n new_activity_rates = activity_rates.copy()\n valid_act_s = FeedbackStationaryFeasibleMpcPolicy.get_valid_actions(act_s, act_drain_empty)\n if valid_act_s:\n new_activity_rates[valid_act_s] += activity_rates[j] / len(valid_act_s)\n new_activity_rates[j] = 0\n return new_activity_rates\n\n @staticmethod\n def clip_to_simplex_and_normalise_feedback_rates(sum_actions: types.ActionSpace,\n activities_per_resource: List[List[int]],\n sum_actions_per_resource: np.ndarray,\n num_steps_to_recompute_policy: int) \\\n -> np.ndarray:\n \"\"\"\n Returns rates for remaining activities, with entries given by the number of times each\n activity has to be performed normalised by the sum of rates for the resource to which the\n activity belongs.\n\n :param sum_actions: Vector with number of times that each action has to be executed in\n the remaining number of steps given by `num_steps_to_recompute_policy`.\n :param activities_per_resource: List of lists of activities per resource.\n :param sum_actions_per_resource: Sum of number of times all the activities that belong to\n each resource have to be performed.\n :param num_steps_to_recompute_policy: Remaining number of steps before recomputing the\n policy.\n :return: Weighting diagonal matrix.\n \"\"\"\n rate_remain_act = np.zeros((sum_actions.shape[0], 1))\n for i, s in enumerate(activities_per_resource):\n if sum_actions_per_resource[i] > 0:\n for j in s:\n rate_remain_act[j] = sum_actions[j] / num_steps_to_recompute_policy\n rate_remain_act[j] = np.clip(rate_remain_act[j], 0, 1)\n assert np.all(0 <= rate_remain_act) and np.all(rate_remain_act <= 1)\n return rate_remain_act\n\n def choose_action_from_rate_distribution(self, num_activities, rates):\n return self.np_random.choice(num_activities, 1, p=rates)[0]\n\n def generate_actions_with_feedback(self, sum_actions: types.ActionSpace,\n state: types.StateSpace,\n num_steps_to_recompute_policy: int,\n tol: float = 1e-7):\n \"\"\"\n Return a single action vector with the following features:\n - It never works on an empty buffer.\n - It is drawn from a distribution obtained as follows:\n i) First convert remaining actions to activity rates, clip the negative values (i.e.\n actions that have been performed more often than required) to zero, and normalised\n the number of remaining actions for each activity by the total remaining number of\n remaining actions of the resource it belongs to.\n d[i] = 0 if sum_actions[i] <= 0, and\n d[i] = sum_actions[i] / [C @ sum_actions]_{s}, for all i such that C_{s,i} = 1.\n ii) For any action i that serves an empty buffer, we reallocate d[i] to the rest of\n activities of the same resource that drain nonempty buffers. Let us say that\n valid_activities is the set of activities that don't drain an empty buffer. Then:\n d[i] = 0, if i not in valid_activities\n d[j] = d[j] + sum_{i not in valid_activities} d[i] / |valid_activities|\n iii) For each resource s:\n 1) [C @ d]_s in {0, 1} (this is always feasible if the rows of C are orthogonal),\n 2) [C @ d]_s = 0 if and only if [C @ sum_actions]_s <= 0.\n\n :param state: Current state, needed to check if some buffers are empty.\n :param sum_actions: Vector with number of times that each action has to be executed in\n the remaining number of steps given by `num_steps_to_recompute_policy`.\n :param num_steps_to_recompute_policy: Remaining number of steps before recomputing the\n policy.\n :param tol: Tolerance to check inequalities.\n :return: action: Binary action vector satisfying feasibility constraints.\n \"\"\"\n action = np.zeros_like(sum_actions) # Initialise action vector to be returned.\n\n # Compute sum_actions_per_resource.\n sum_actions_per_resource = self.constituency_matrix @ sum_actions\n # If [C @ sum_actions]_s > 0, then the s-th resource shouldn't idle.\n nonidling = sum_actions_per_resource > tol\n\n # Obtain rates for remaining activities: d.\n rate_remain_act = self.clip_to_simplex_and_normalise_feedback_rates(\n sum_actions, self.activities_per_resource, sum_actions_per_resource,\n num_steps_to_recompute_policy)\n\n act_drain_empty_buffers = self.get_activities_drain_currently_empty_buffers(\n state, self.buffer_processing_matrix)\n\n for s in range(self.num_resources):\n if nonidling[s]: # if [C @ sum_actions]_s > 0\n act_s = self.activities_per_resource[s]\n\n for j in act_s:\n if j in act_drain_empty_buffers: # Reallocate rate to other activities: d.\n rate_remain_act = self.reallocate_activity_j(\n j, rate_remain_act, act_s, act_drain_empty_buffers)\n\n # Normalise per resource so that: [C @ d]_s = 1.\n rate_remain_act[act_s] /= np.sum(rate_remain_act[act_s])\n # TODO the line above produces NAN that should instead be a 0\n # Choose one valid action for resource s, such that [C @ action]_s = 1.\n valid_act = self.get_valid_actions(act_s, act_drain_empty_buffers)\n if valid_act:\n j = self.choose_action_from_rate_distribution(\n self.num_activities_per_resource[s],\n np.squeeze(rate_remain_act[act_s], axis=1))\n action[act_s[j]] = 1\n assert 1 - tol < self.constituency_matrix[s] @ action < 1 + tol, \\\n \"Constraint C @ rate_remain_act <= 1 does not hold.\"\n return action\n\n def obtain_actions(self, **kwargs) -> types.ActionProcess:\n \"\"\"\n This method implements the abstract method from super class `ActionMPCPolicy`.\n It first gathers the feedback information namely the number of times each activity has to\n be performed (i.e. 'sum_actions') and the current state ('state'). Then, it calls its own\n method to return a single action vector.\n\n :return: actions: binary indicator matrix with number of rows equal to the number of\n non-idling activities (i.e. num of columns of the constituency matrix), and number of\n columns equal to number of time steps to perform MPC.\n \"\"\"\n assert 'mpc_variables' in kwargs, \"Ensure MPC variables dict is passed\"\n assert 'sum_actions' in kwargs[\"mpc_variables\"], \\\n \"Number of times each activity has to be performed ('sum_actions') is required to be \" \\\n \"passed as parameter.\"\n assert 'state' in kwargs, \"Current state ('state') is required to be passed as parameter.\"\n\n actions = self.generate_actions_with_feedback(kwargs[\"mpc_variables\"]['sum_actions'],\n kwargs['state'],\n kwargs['num_steps_to_recompute_policy'])\n return actions\n","sub_path":"src/snc/agents/activity_rate_to_mpc_actions/feedback_stationary_feasible_mpc_policy.py","file_name":"feedback_stationary_feasible_mpc_policy.py","file_ext":"py","file_size_in_byte":14361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"90435028","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\n\nimport pprint\n\nfrom utils import has_cuda\n\nclass DataEngine(object):\n\n\tclasses = ('plane', 'car', 'bird', 'cat', 'deer', 'dog',\n\t\t\t'frog', 'horse', 'ship', 'truck')\n\n\tdef __init__(self, args):\n\t\tsuper(DataEngine, self).__init__()\n\t\tself.batch_size_cuda = args.batch_size_cuda\n\t\tself.batch_size_cpu = args.batch_size_cpu\n\t\tself.num_workers = args.num_workers\n\t\tself.load()\n\n\tdef _transforms(self):\n\t\t# Mean and standard deviation of train dataset\n\t\tmean = (0.4914, 0.4822, 0.4465)\n\t\tstd = (0.2023, 0.1994, 0.2010)\n\t\t# mean = (0.5, 0.5, 0.5)\n\t\t# std = (0.5, 0.5, 0.5)\n\n\t\t# Data Transformations\n\t\ttrain_transform = transforms.Compose(\n\t\t [transforms.RandomCrop(32, padding=4),\n\t\t transforms.RandomHorizontalFlip(),\n\t\t transforms.ToTensor(),\n\t\t transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\n\t\t transforms.RandomErasing(0.25)])\n\t\t\n\t\ttest_transform = transforms.Compose(\n\t\t [transforms.ToTensor(),\n\t\t transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\n\t\treturn train_transform, test_transform\n\n\tdef _dataset(self):\n\t\t# Get data transforms\n\t\ttrain_transform, test_transform = self._transforms()\n\n\t\t# Dataset and Creating Train/Test Split\n\t\ttrain_set = torchvision.datasets.CIFAR10(root='./data', train=True,\n\t\t download=True, transform=train_transform)\n\t\ttest_set = torchvision.datasets.CIFAR10(root='./data', train=False,\n\t\t download=True, transform=test_transform)\n\t\treturn train_set, test_set\n\n\tdef load(self):\n\t\t# Get Train and Test Data\n\t\ttrain_set, test_set = self._dataset()\n\n\t\t# Dataloader Arguments & Test/Train Dataloaders\n\t\tdataloader_args = dict(\n\t\t\tshuffle= True,\n\t\t\tbatch_size= self.batch_size_cpu)\n\t\tif has_cuda():\n\t\t\tdataloader_args.update(\n\t\t\t\tbatch_size= self.batch_size_cuda,\n\t\t\t\tnum_workers= self.num_workers,\n\t\t\t\tpin_memory= True)\n\n\t\tself.train_loader = torch.utils.data.DataLoader(train_set, **dataloader_args)\n\t\tself.test_loader = torch.utils.data.DataLoader(test_set, **dataloader_args)\n\n","sub_path":"S8/data/data_engine.py","file_name":"data_engine.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"540069418","text":"import collections\nimport concurrent.futures\n\nimport dateutil.parser\nimport pymongo\nimport get_object\n\nclient = pymongo.MongoClient()\ndb = client.get_database('aviezer')\npages = db.get_collection('pages')\nposts = db.get_collection('posts')\npages.create_index('id', unique=True)\nposts.create_index('id', unique=True)\nposts.create_index('created_time', unique=True)\n\n\nx = posts.find()\nb = x[0]['created_time'].split('t')[0]\ny = x[0]['created_time']\nprint(y)\n\n\n\ndef show_post_date(date):\n message =[]\n [message.append((post['message'], post['created_time'].split('T')[0], post['created_time'].split('T')[1])) for post\n in posts.find() if 'message' in post if (post['created_time'].split('T'))[0] == date]\n sorted_by_second = sorted(message, key=lambda tup: tup[2])\n for data in sorted_by_second:\n print(data)\n\n\n\n\nshow_post_date(\"2016-04-15\")\n","sub_path":"Desktop/10x/22.5/show_posts.py","file_name":"show_posts.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"125224954","text":"\n# -*- coding: utf-8 -*-\n\"\"\"\n Author: kun.wang\n Create: 2015-06-11\n\nusing: PySide\n\"\"\"\n\n# import os\nimport sys\nimport PySide.QtCore as QtCore\nimport PySide.QtGui as QtGui\n\n\nclass FlatNavButton(QtGui.QWidget):\n clicked = QtCore.Signal(str)\n focus_color = QtGui.QColor(255, 255, 255, 100)\n active_color = QtGui.QColor(150, 150, 200)\n\n def __init__(self, name, title, parent=None):\n super(FlatNavButton, self).__init__(parent)\n self.name = name\n self.__title = title\n self.__mouse_in = False\n self.__active = False\n self.label = QtGui.QLabel(self.__title, self)\n self.label.setStyleSheet(\n \"font-size: 15px;\"\n \"margin-left: 20px;\"\n \"margin-right: 10px;\"\n \"margin-top: 5px;\"\n \"margin-bottom: 5px;\"\n \"color: lightgrey\"\n )\n self.setMinimumHeight(40)\n\n self.__layout = QtGui.QHBoxLayout()\n self.__layout.setContentsMargins(0, 0, 0, 0)\n self.setLayout(self.__layout)\n self.__layout.addWidget(self.label)\n\n def mouseReleaseEvent(self, event):\n self.clicked.emit(self.name)\n\n def paintEvent(self, event):\n painter = QtGui.QPainter(self)\n if self.__mouse_in:\n painter.fillRect(self.rect(), FlatNavButton.focus_color)\n if self.__active:\n painter.fillRect(0, 0, 10, self.height(), FlatNavButton.active_color)\n\n def enterEvent(self, event):\n self.__mouse_in = True\n self.repaint()\n\n def leaveEvent(self, event):\n self.__mouse_in = False\n self.repaint()\n\n def resizeEvent(self, event):\n self.label.resize(self.width(), self.height())\n\n def set_active(self, active):\n self.__active = active\n\n\nclass FlatVNavBar(QtGui.QWidget):\n status_changed = QtCore.Signal(str)\n\n def __init__(self, parent=None):\n super(FlatVNavBar, self).__init__(parent)\n self.max_width = 70\n self.button_width = 100\n self.setMinimumWidth(self.max_width)\n self.resize(self.max_width, 500)\n\n self.bg_color = QtGui.QColor(100, 100, 130)\n\n self.main_layout = QtGui.QVBoxLayout()\n self.main_layout.setContentsMargins(0, 0, 0, 0)\n self.main_layout.setSpacing(0)\n self.setLayout(self.main_layout)\n\n self.buttons = dict()\n\n def paintEvent(self, event):\n painter = QtGui.QPainter(self)\n # draw background\n painter.fillRect(self.rect(), self.bg_color)\n\n def on_status_changed(self, nav):\n self.change_active(nav)\n self.status_changed.emit(nav)\n\n def change_active(self, nav):\n for key in self.buttons.keys():\n self.buttons[key].set_active(False)\n self.buttons[key].repaint()\n self.buttons[nav].set_active(True)\n self.buttons[nav].repaint()\n\n def add_button(self, name, title):\n button = FlatNavButton(name, title)\n button.clicked.connect(self.on_status_changed)\n self.buttons[name] = button\n self.main_layout.addWidget(button)\n\n def add_stretch(self):\n self.main_layout.addStretch()\n\n def add_spacing(self, spacing):\n self.main_layout.addSpacing(spacing)\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n a = FlatVNavBar()\n a.add_button('home', 'Home')\n a.add_button('home1', 'Home1')\n a.add_button('home2', 'Home2')\n a.add_button('home3', 'Home3')\n a.add_button('home4', 'Home4')\n a.add_button('home5', 'Home5')\n a.add_button('home6', 'Home6')\n a.add_button('home7', 'Home7')\n\n a.change_active('home')\n a.resize(60, 700)\n a.show()\n sys.exit(app.exec_())\n","sub_path":"OpenCGPipeline/HoneyMongo/honey_gui/base_ui/flat_navbar.py","file_name":"flat_navbar.py","file_ext":"py","file_size_in_byte":3660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"625672295","text":"# -*- coding: utf-8 -*-\n\n\"\"\" Main. \"\"\"\nimport logging\nimport re\nimport os\nimport sys\nimport datetime\nfrom functools import partial\n\nfrom riana.project import ReadDirectory\nfrom riana.peptides import ReadPercolator\nfrom riana.spectra import Mzml\n\nfrom riana import integrate, params, __version__\n\nimport tqdm\nimport pandas as pd\n\n\ndef runriana(args):\n \"\"\"\n Improved process to integrate for isotope abundance analysis.\n Idea is to loop through the mzML only once - get all the peptides to be integrated first\n Find all the spectrum ID - m/z combinations to be integrated, then integrate them sequentially\n\n :param args: Arguments from command line\n :return:\n\n \"\"\"\n\n # Get timestamp for out files\n now = datetime.datetime.now()\n directory_to_write = os.path.join(args.out, 'riana_' + now.strftime('%Y%m%d%H%M%S'))\n os.makedirs(directory_to_write, exist_ok=True)\n\n main_log = logging.getLogger('riana')\n main_log.setLevel(logging.DEBUG)\n\n # create file handler which logs even debug messages\n fh = logging.FileHandler(os.path.join(directory_to_write, 'riana.log'))\n fh.setLevel(logging.INFO)\n\n # create console handler with a higher log level\n ch = logging.StreamHandler()\n ch.setLevel(logging.ERROR)\n\n # create formatter and add it to the handlers\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n\n # add the handlers to the logger\n main_log.addHandler(fh)\n main_log.addHandler(ch)\n\n main_log.info(args)\n main_log.info(__version__)\n\n # Handle command line arguments\n unique_pep = args.unique\n\n # lysine_filter = args.lysine # Does lysine peptides only (for Liverpool aa labeling data\n # try:\n # lysine_filter = int(lysine_filter)\n # if lysine_filter not in [1, 2, 3]:\n # lysine_filter = 0\n #\n # except TypeError or ValueError:\n # lysine_filter = 0\n\n #\n # Convert the to-do isotopomer list option into a list of integers\n #\n iso_to_do = []\n\n for char in args.iso.split(','):\n\n try:\n char = int(char)\n\n # Only doing down to mz + 12.\n if char <= 12:\n iso_to_do.append(int(char))\n\n except ValueError or TypeError:\n pass\n\n if not iso_to_do:\n sys.exit('Error: Invalid isotopomer list given.')\n\n iso_to_do = list(set(iso_to_do))\n iso_to_do.sort()\n\n\n #\n # Percolator q value cutoff for peptides and proteins\n #\n if args.qvalue:\n\n try:\n qcutoff = float(args.qvalue)\n\n except ValueError or TypeError:\n main_log.warning('Invalid Q value given - using default value.')\n qcutoff = float(1e-2)\n\n #\n # Retention time cutoff peptides and proteins\n #\n if args.rtime:\n\n try:\n rt_tolerance = float(args.rtime)\n\n except ValueError or TypeError:\n main_log.warning('Invalid retention time tolerance given - using default value.')\n rt_tolerance = float(1.0)\n else:\n rt_tolerance = float(1.0)\n\n #\n # MS1 mass tolerance for integration\n #\n if args.masstolerance:\n try:\n mass_tolerance = float(args.masstolerance) * 1e-6\n\n except ValueError or TypeError:\n main_log.warning('Invalid mass tolerance given - using default value.')\n mass_tolerance = float(100) * 1e-6\n else:\n mass_tolerance = float(100) * 1e-6\n\n #\n # Multi-threading\n #\n if args.thread:\n try:\n num_threads = max(os.cpu_count()*4, int(args.thread))\n\n except ValueError or TypeError:\n print('Invalid thread count. Using default.')\n num_threads = os.cpu_count()*4\n\n else:\n num_threads = os.cpu_count()*4\n\n #\n # Inclusion lists\n #\n # if args.amrt:\n # input_type = 'AMRT' #\"lipid\"\n # else:\n # input_type = 'Percolator'\n\n dir_loc = args.dir\n assert os.path.isdir(dir_loc), '[error] project directory not valid'\n\n # This is the directory that holds the entire project\n project = ReadDirectory(dir_loc)\n\n # Get the master peptide ID list\n # if input_type == 'Percolator':\n mzid = ReadPercolator(project, directory_to_write)\n mzid.read_all_project_psms()\n mzid.make_master_match_list(# lysine_filter=0,\n peptide_q=qcutoff,\n unique_only=unique_pep,\n min_fraction=params.min_fraction_mar)\n\n # elif input_type == 'AMRT':\n # raise Exception('AMRT temporarily not supported while we work on Match Between Runs')\n # sys.exit()\n\n # 2020-02-27 Need to rewrite ReadLipid module to be like ReadPercolator (reading all IDs in project at once)\n '''\n elif mol_type == 'lipid':\n # Get a master lipid id list\n for sample in tqdm.tqdm(samples, desc='Processing Sample'):\n\n sample_loc = os.path.join(project.path, sample)\n try:\n mzid = ReadLipid(sample_loc)\n #mzid.get_mzid_indices()\n\n except OSError as e:\n sys.exit('Failed to load am_rt file. ' + str(e.errno))\n '''\n\n # Each subdirectory is a sample\n samples = project.samples\n\n for current_sample in tqdm.tqdm(samples, desc='Processing Sample', total=len(samples)):\n\n sample_loc = os.path.join(project.path, current_sample, 'mzml')\n\n mzid.get_current_sample_psms(current_sample=current_sample)\n mzid.get_current_sample_mzid_indices()\n\n mzml_files = [f for f in os.listdir(sample_loc) if re.match('^.*.mzML', f)]\n\n # Sort the mzML files by names\n # Note this may create a problem if the OS Percolator runs on has natural sorting (xxxx_2 before xxxx_10)\n # But we will ignore for now\n mzml_files.sort()\n\n # Throw an error if there is no mzML file in the mzml directory\n assert len(mzml_files) != 0, '[error] no mzml files in the specified directory'\n # Check that the number of mzMLs in the mzML folder is the same as the maximum of the ID file's file_idx column.\n # Note this will break if the last fraction does not contain at least some ID, but we will ignore for now.\n assert len(mzml_files) == max(mzid.indices) + 1, '[error] number of mzml files not matching id list'\n\n #\n # Read the mzml files\n #\n\n # For each file index (fraction), open the mzML file, and create a subset Percolator ID dataframe\n for idx in mzid.indices:\n\n # Verbosity 0 progress message\n main_log.info('Doing mzml: {0} ({1} of {2})'.format(\n mzml_files[idx],\n str(idx + 1),\n str(len(mzid.indices))))\n\n # Make a subset dataframe with the current file index (fraction) being considered\n mzid.get_current_fraction_psms(idx)\n mzid.filter_current_fraction_psms(# lysine_filter=0,\n peptide_q=qcutoff,\n unique_only=unique_pep,\n use_soft_threshold=True,\n match_across_runs=True)\n\n try:\n mzml = Mzml(os.path.join(sample_loc, mzml_files[idx]))\n except OSError as e:\n sys.exit('[error] failed to load fraction mzml file. ' + str(e.errno))\n\n # #\n # # read the spectra into dictionary and also create MS1/MS2 indices\n # #\n mzml.parse_mzml()\n\n #\n # get peak intensity for each isotopomer in each spectrum ID in each peptide\n #\n # peaks.get_isotopes_from_amrt_multiwrapper(num_thread=num_thread)\n\n loop_ = range(len(mzid.curr_frac_filtered_id_df))\n\n integrate_one_partial = partial(integrate.integrate_one,\n id_=mzid.curr_frac_filtered_id_df.copy(),\n iso_to_do=iso_to_do,\n mzml=mzml,\n rt_tolerance=rt_tolerance,\n mass_tolerance=mass_tolerance,\n deuterium_mass_defect=args.deuterium,\n )\n\n # Single threaded loop\n # '''\n # results = []\n # for i in loop_:\n # print(i)\n # results += integrate_one_partial(i)\n # '''\n\n\n # For parellization, use concurrent.futures instead of multiprocessing for higher speed\n # '''\n from concurrent import futures\n with futures.ThreadPoolExecutor(max_workers=num_threads) as ex:\n result = list(tqdm.tqdm(ex.map(integrate_one_partial, loop_),\n total=max(loop_),\n desc='Integrating Peaks in Current Sample'))\n # '''\n\n #\n # Convert the output_table into a data frame\n #\n df_columns = ['ID', 'pep_id'] + ['m' + str(iso) for iso in iso_to_do]\n result_df = pd.DataFrame(result, columns=df_columns)\n id_result_df = pd.merge(mzid.curr_frac_filtered_id_df, result_df, on='pep_id', how='left')\n\n # Create subdirectory if not exists\n os.makedirs(os.path.join(directory_to_write, current_sample), exist_ok=True)\n save_path = os.path.join(directory_to_write, current_sample, mzml_files[idx] + '_riana.txt')\n id_result_df.to_csv(save_path, sep='\\t')\n\n # Make the soft-threshold data frame. These are the peptides that are ID'ed at 10 times the q-value\n # as the cut-off in this fraction up to q < 0.1, but has q >= q-value cutoff, and furthermore has been\n # consistently identified in the other samples at the same fraction (median fraction) at the q-value cutoff\n\n return sys.exit(os.EX_OK)\n\n\n#\n# Code for running main with parsed arguments from command line\n#\ndef main():\n\n import argparse\n\n parser = argparse.ArgumentParser(description='Riana integrates the relative abundance of'\n 'isotopomers')\n\n parser.add_argument('dir', help='path to folders containing the mzml and search files (see documentation)')\n\n parser.add_argument('-i', '--iso', help='isotopes to do, separated by commas, e.g., 0,1,2,3,4,5 [default: 0,6]',\n default='0,6')\n\n parser.add_argument('-d', '--deuterium', action='store_true', help='use mass defect for deuterium.')\n\n parser.add_argument('-u', '--unique', action='store_true', help='integrate unique peptides only')\n\n # parser.add_argument('--amrt', action='store_true', help='integrate an inclusion list of AM-RTs',\n # default=False)\n\n # parser.add_argument('-k', '--lysine',\n # help='lysine mode, 0=No filter, 1=1 K, 2=1 or more K, 3=KK only [default = 0]',\n # type=int,\n # choices=[0, 1, 2, 3],\n # default=0)\n\n # parser.add_argument('--matchbetweenruns', action='store_true', help='attempt to match between runs',\n # default=False)\n\n parser.add_argument('-q', '--qvalue',\n help='integrate only peptides with q value below this threshold[default: 1e-2]',\n type=float,\n default=1e-2)\n\n parser.add_argument('-r', '--rtime', help='retention time (in minutes, both directions) tolerance for integration',\n type=float,\n default=1.0)\n\n parser.add_argument('-m', '--masstolerance', help='mass tolerance in ppm for integration [default 50 ppm]',\n type=float,\n default=50)\n\n parser.add_argument('-t', '--thread', help='number of threads for concurrency; leave as 0 for auto (default = 0)',\n type=int,\n default=0)\n\n parser.add_argument('-o', '--out', help='prefix of the output directory [default: riana_out]',\n default='out')\n\n parser.add_argument('-v', '--version', action='version',\n version='%(prog)s {version}'.format(version=__version__))\n\n parser.set_defaults(func=runriana)\n\n # Print help message if no arguments are given\n import sys\n if len(sys.argv[1:]) == 0:\n parser.print_help()\n parser.exit()\n\n #gc.enable()\n #gc.set_debug(gc.DEBUG_LEAK)\n\n # Parse all the arguments\n args = parser.parse_args()\n\n # Run the function in the argument\n args.func(args)\n","sub_path":"riana/riana.py","file_name":"riana.py","file_ext":"py","file_size_in_byte":12897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"22919918","text":"__author__ = 'kawakami_note'\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn import tree\n\ndata = pd.read_csv('data/wakati.csv')\nx_train, x_test = np.split(data['text'], 200)\ny_train, y_test = np.split(data['class'], 200)\n\nprint(x_train)\nprint(x_test)\nprint(y_train)\nprint(y_test)\n\nclassifier = tree.DecisionTreeClassifier()\nclassifier = classifier.fit(data['text'], data['class'])","sub_path":"sandbox/decision_tree_practice.py","file_name":"decision_tree_practice.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"468409262","text":"#!/usr/bin/env python\n\n\"\"\"\nA utility script to assemble downloaded segments into a valid video file.\n\nUsage Example:\npython assemble.py 'downloaded/johndoe_17849164549199999_1486300000.json' \\\n-o 'downloaded/downloads_johndoe_17849164549199999_1486300000/' \\\n-c 'downloaded/johndoe_17849164549199999_1486300000_comments.json' \\\n-f 'downloaded/johndoe_17849164549199999_1486300000.mp4'\n\n\"\"\"\n\nimport os\nimport shutil\nimport argparse\nimport re\nimport logging\nimport glob\nimport subprocess\nimport json\nfrom .utils import Formatter\nfrom .download import generate_srt\n\n\ndef _get_file_index(filename):\n \"\"\" Extract the numbered index in filename for sorting \"\"\"\n mobj = re.match(r'.+\\-(?P[0-9]+)\\.[a-z]+', filename)\n if mobj:\n return int(mobj.group('idx'))\n return -1\n\n\nlogger = logging.getLogger(__file__)\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nformatter = Formatter()\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\n\ndef main():\n\n parser = argparse.ArgumentParser(description='Manually assemble video from download folder.')\n parser.add_argument('broadcast_json_file')\n parser.add_argument('-o', dest='output_dir', required=True,\n help='Folder containing the downloaded segments.')\n parser.add_argument('-f', dest='output_filename', required=True,\n help='File path for the generated video.')\n parser.add_argument('-c', dest='comments_json_file',\n help='File path to the comments json file.')\n parser.add_argument('-cleanup', action='store_true', help='Clean up output_dir and temp files')\n parser.add_argument('-openwhendone', action='store_true', help='Open final generated file')\n parser.add_argument('-v', dest='verbose', action='store_true', help='Turn on verbose debug')\n parser.add_argument('-log', dest='log_file_path', help='Log to file specified.')\n args = parser.parse_args()\n\n if args.verbose:\n logger.setLevel(logging.DEBUG)\n else:\n logger.setLevel(logging.INFO)\n\n if args.log_file_path:\n file_handler = logging.FileHandler(args.log_file_path)\n formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n\n if not os.path.exists(args.output_dir):\n raise ValueError('Output dir does not exist: %s' % args.output_dir)\n if not os.path.isfile(args.broadcast_json_file):\n raise ValueError('broadcast json file does not exist: %s' % args.broadcast_json_file)\n\n with open(args.broadcast_json_file) as info_file:\n broadcast_info = json.load(info_file)\n\n stream_id = str(broadcast_info['id'])\n download_start_time = broadcast_info['published_time'] + (\n broadcast_info['delay'] if broadcast_info['delay'] > 0 else 0)\n\n audio_stream = os.path.join(args.output_dir, 'assembled_source_%s_m4a.tmp' % stream_id)\n video_stream = os.path.join(args.output_dir, 'assembled_source_%s_mp4.tmp' % stream_id)\n\n with open(audio_stream, 'wb') as outfile:\n logger.info('Assembling audio stream... %s' % audio_stream)\n files = list(filter(\n os.path.isfile,\n glob.glob(os.path.join(args.output_dir, '%s-*.m4a' % stream_id))))\n files = sorted(files, key=lambda x: _get_file_index(x))\n for f in files:\n with open(f, 'rb') as readfile:\n try:\n shutil.copyfileobj(readfile, outfile)\n except IOError as e:\n logger.error('Error processing %s' % f)\n logger.error(e)\n raise e\n\n with open(video_stream, 'wb') as outfile:\n logger.info('Assembling video stream... %s' % video_stream)\n files = list(filter(\n os.path.isfile,\n glob.glob(os.path.join(args.output_dir, '%s-*.m4v' % stream_id))))\n files = sorted(files, key=lambda x: _get_file_index(x))\n for f in files:\n with open(f, 'rb') as readfile:\n try:\n shutil.copyfileobj(readfile, outfile)\n except IOError as e:\n logger.error('Error processing %s' % f)\n logger.error(e)\n raise e\n\n assert os.path.isfile(audio_stream)\n assert os.path.isfile(video_stream)\n\n ffmpeg_binary = os.getenv('FFMPEG_BINARY', 'ffmpeg')\n cmd = [\n ffmpeg_binary, '-loglevel', 'panic',\n '-i', audio_stream,\n '-i', video_stream,\n '-c:v', 'copy', '-c:a', 'copy', args.output_filename]\n logger.info('Executing: \"%s\"' % ' '.join(cmd))\n exit_code = subprocess.call(cmd)\n\n assert not exit_code, 'ffmpeg exited with the code: %s' % exit_code\n assert os.path.isfile(args.output_filename), '%s not generated.' % args.output_filename\n\n logger.info('---------------------------------------------')\n logger.info('Generated file: %s' % args.output_filename)\n logger.info('---------------------------------------------')\n\n if args.comments_json_file:\n # convert json to srt\n if not os.path.isfile(args.comments_json_file):\n raise ValueError('Cannot load comments json files: %s' % args.comments_json_file)\n filename_segments = args.output_filename.split('.')\n filename_segments[-1] = 'srt'\n srt_file = '.'.join(filename_segments)\n\n with open(args.comments_json_file) as cj:\n comments_info = json.load(cj)\n\n comments = comments_info.get('comments', [])\n generate_srt(\n comments, download_start_time, srt_file,\n comments_delay=comments_info.get('initial_buffered_duration', 10.0))\n\n assert os.path.isfile(srt_file), '%s not generated.' % srt_file\n logger.info('Comments written to: %s' % srt_file)\n\n if args.cleanup and not exit_code:\n logger.debug('Cleaning up files...')\n for f in glob.glob(os.path.join(args.output_dir, '%s-*.*' % stream_id)):\n os.remove(f)\n os.remove(audio_stream)\n os.remove(video_stream)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"livestream_dl/assemble.py","file_name":"assemble.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"587690696","text":"from common.vectorize import *\nfrom AbstractModel import AbstractModel\n\nPARAM_PERIOD = 'period'\n\nclass SeasonalityByAverageModel(AbstractModel):\n \"\"\"\n Simple Seasonality model.\n The value on x is the average of its previous period.\n F(x) = Average(x - period * t) t = [1, )\n \"\"\"\n def __init__(self, params):\n self.params = params\n self.name = 'Seasonality model by simple average'\n self.checkParams()\n self.period = params[PARAM_PERIOD]\n self.averageSeaon = []\n self.sampe = None\n\n def checkParams(self):\n assert PARAM_PERIOD in self.params, 'Need a period param'\n\n def train(self, data):\n self.data = data[:]\n period = self.period\n length = len(self.data)\n repeatCount = len(self.data) / period\n\n self.averageSeaon = [0] * period\n for i in xrange(repeatCount):\n self.averageSeaon = vectorAdd(self.averageSeaon,\n self.data[(length - (i + 1) * period) : (length - i * period)])\n self.averageSeaon = vectorMultiply(self.averageSeaon, 1.0 / repeatCount)\n\n def forecast(self, nAhead):\n \"\"\"\n Forecast nAhead future values.\n \"\"\"\n assert len(self.averageSeaon) > 0, 'This model hasn\\'t been trained'\n forecastValues = self.averageSeaon * (int(nAhead / self.period) + 1)\n forecastValues = forecastValues[:nAhead]\n return forecastValues\n\n def test(self, data):\n length = len(data)\n forecastValues = self.forecast(length)\n self.computeSAMPE(data, forecastValues)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"forecast/SeasonalityByAverageModel.py","file_name":"SeasonalityByAverageModel.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"494064194","text":"import numpy as np\nimport lda\nimport lda.datasets\n\ntitles = lda.datasets.load_reuters_titles() # 原始的文本资料,长度是395\nvocab = lda.datasets.load_reuters_vocab() # 字典,tuple类型,长度是4258.\n\nx = lda.datasets.load_reuters() # 加载的one-hot形式的文本资料,是一个(395,4258)的矩阵\nprint(x)\nexit()\nmodel = lda.LDA(n_topics=20, n_iter=1500, random_state=1) # 设置topic的数量是20,定义模型\nmodel.fit(x) # 训练模型\n\ntopic_word = model.topic_word_ # topic到word的模型,(20,4258)的权重矩阵\n\nn_top_words = 8\n\nfor i, topic_dist in enumerate(topic_word):\n topic_words = np.array(vocab)[np.argsort(\n topic_dist)][:-(n_top_words + 1):-1] # 找到topic对应的前8个最重要的单词\n print('Topic {}: {}'.format(i, ' '.join(topic_words)))\n\ndoc_topic = model.doc_topic_ # doc到topic的权重矩阵(395,20)\nfor i in range(10):\n print(\"{} (top topic: {})\".format(\n titles[i], doc_topic[i].argmax())) # 输出每个文本对应的topic\n","sub_path":"topic mining/lad_test.py","file_name":"lad_test.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"109659440","text":"import datetime\n\nimport factory\nfrom django.test import TestCase\nfrom django.urls import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom article.models import Article\nfrom user_auth.models import User\n\n\nclass UserFactory(factory.DjangoModelFactory):\n class Meta:\n model = User\n\n username = factory.Sequence(lambda n: 'john%s' % n)\n email = factory.LazyAttribute(lambda o: '%s@example.com' % o.username)\n role = factory.Faker(\n 'random_element', elements=[x[0] for x in User.ROLE_CHOICES]\n )\n\n\nclass ArticleFactory(factory.DjangoModelFactory):\n class Meta:\n model = Article\n\n title = factory.Sequence(lambda n: 'qqq%s' % n)\n content = u'ddffffgtrrdd tgrjmhmjhge fgrnghngege'\n author = factory.SubFactory(UserFactory)\n publication_date = factory.LazyFunction(datetime.datetime.now)\n\n\nclass TestArticleAPI(TestCase):\n def setUp(self):\n self.article = ArticleFactory()\n self.user = UserFactory()\n self.user.password = 'password'\n self.user.save()\n self.client = APIClient()\n\n def test_get_articles_not_logged(self):\n response = self.client.get(reverse(\"articles-list\"))\n self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)\n\n def test_get_articles_logged(self):\n self.client.force_authenticate(user=self.user)\n response = self.client.get(reverse(\"articles-list\"))\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n\n def test_add_article(self):\n self.client.force_authenticate(user=self.user)\n articles_before = Article.objects.count()\n data = {\"title\": \"lol\",\n \"content\": \"lol\",\n }\n response = self.client.post(reverse(\"articles-list\"), data=data)\n articles_after = Article.objects.count()\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertTrue(articles_after - articles_before == 1)\n\n def test_delete_article(self):\n self.client.force_authenticate(user=self.user)\n articles_before = Article.objects.count()\n data = {\"title\": \"loll\",\n \"content\": \"loll\",\n }\n self.client.post(reverse(\"articles-list\"), data=data)\n item_id = Article.objects.get(title=data[\"title\"]).id\n response = self.client.delete(reverse(\"articles-detail\", args=[item_id, ]))\n self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)\n articles_after = Article.objects.count()\n self.assertTrue(articles_after - articles_before == 0)\n\n\n def test_update_article(self):\n self.client.force_authenticate(user=self.user)\n data = {\"title\": \"loll\",\n \"content\": \"loll\",\n }\n resp = self.client.post(reverse(\"articles-list\"), data=data)\n item_id = Article.objects.get(title=data[\"title\"]).id\n data_patch = {\"content\": \"updated\"}\n self.assertFalse(resp.data[\"content\"] == data_patch[\"content\"])\n response = self.client.patch(reverse(\"articles-detail\", args=[item_id, ]), data=data_patch)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data[\"content\"], data_patch[\"content\"])\n\n\nclass TestCommentsAPI(TestCase):\n def setUp(self):\n self.article = ArticleFactory()\n self.user = UserFactory()\n self.user.password = 'password'\n self.user.save()\n self.client = APIClient()\n\n def test_get_comments(self):\n pass","sub_path":"blog/article/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"593901608","text":"from django.urls import path\n\nfrom . import views\n\n\napp_name = 'schedule'\nurlpatterns = [\n path('', views.IView.as_view(), name=\"index\"),\n path('month/', views.MonthCalendar.as_view(), name='month'),\n path('month///', views.MonthCalendar.as_view(), name='month'),\n path('week/', views.WeekCalendar.as_view(), name='week'),\n path('week////', views.WeekCalendar.as_view(), name='week'),\n path('week_with_schedule/', views.WeekWithScheduleCalendar.as_view(), name='week_with_schedule'),\n path('week_with_schedule////',views.WeekWithScheduleCalendar.as_view(),name='week_with_schedule'),\n path('month_with_schedule/',views.MonthWithScheduleCalendar.as_view(), name='month_with_schedule'),\n path('month_with_schedule///',views.MonthWithScheduleCalendar.as_view(), name='month_with_schedule'),\n path('mycalendar/', views.MyCalendar.as_view(), name='mycalendar'),\n path('mycalendar////', views.MyCalendar.as_view(), name='mycalendar'),\n\n path('today_schedule/',views.MyCalendarDetail.as_view(),name=\"today_schedule\"),\n path('today_schedule///',views.MyCalendarDetail.as_view(),name=\"today_schedule\"),\n path('create_schedule/',views.createschedule,name='create_schedule'),\n path('create_schedule///',views.createschedule,name='create_schedule'),\n path('create_schedule//',views.createschedule,name='create_schedule'),\n path('edit_schedule////',views.EditSchedule.as_view(),name='edit_schedule'),\n path('delete_schedule/////',views.DeleteSchedule.as_view(),name=\"delete_schedule\"),\n\n\n\n path('select_group/',views.selectGroup,name=\"select_group\"),\n path('select_group///',views.selectGroup,name=\"select_group\"),\n path('select_group/',views.selectGroup,name=\"select_group\"),\n path('select_group//',views.selectGroup,name=\"select_group\"),\n path('select_group/////',views.selectGroup,name=\"select_group\"),\n path('group_calendar_detail////',views.GroupCalendarDetail,name=\"group_calendar_detail\"),\n path('group_calendar_detail//',views.GroupCalendarDetail,name=\"group_calendar_detail\"),\n path('group_calendar_detail//////',views.GroupCalendarDetail,name=\"group_calendar_detail\"),\n path('add_firends/',views.addFriends,name=\"add_friends\"),\n path('add_firends//',views.addFriends,name=\"add_friends\"),\n path('create_group/',views.createGroup,name='create_group'),\n path('delete_group/',views.deleteGroup,name='delete_group'),\n path('delete_group//',views.deleteGroup,name='delete_group'),\n path('display_member//',views.display_member,name=\"display_member\"),\n path('nukeru_group//',views.nukeru_group,name=\"nukeru_group\"),\n path('list_group/',views.listGroup,name=\"list_group\"),\n path('comfirm/',views.comfirm,name=\"comfirm\"),\n path('comfirm_member//',views.comfirm_member,name=\"comfirm_member\"),\n path('input_excel',views.input_excel,name=\"input_excel\"),\n #path('output_excel',views.output_excel,name=\"output_excel\"),\n path('username_input',views.username_input,name=\"username_input\"),\n path('username_input_nickname',views.username_input_nickname,name=\"username_input_nickname\"),\n path('chenge_nickname',views.chenge_nickname,name=\"chenge_nickname\"),\n]\n","sub_path":"management_schedule/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"555107373","text":"import hashlib\r\nimport os\r\n\r\ndef read_and_hash(file_path: str, single_segment_size: int=512,\r\n hash_func=hashlib.sha1, first_segment=False):\r\n \"\"\"\r\n This function reads one or multiple segments of a file and hashes them.\r\n It returns a single segment has for further comparison.\r\n Or yields a segment hash for potential duplicates.\r\n \r\n Attributes:\r\n -----------\r\n file_path: str\r\n path-like object, the full path of the file to be read.\r\n \r\n single_segment_size: int\r\n the size in bytes of a segment to be read fist. Files of the same size,\r\n having the same hash of this first segment are considered as potential duplicates.\r\n \r\n hash_func: object\r\n reference to the object of the hashing function.\r\n \r\n first_segment: bool\r\n when true, only the first segment of the file is read and hashed.\r\n \r\n Returns:\r\n -------\r\n hashed_object.digest()\r\n The digest of the first segment.\r\n \r\n Yields:\r\n ------\r\n hashed_object.update(segment)\r\n The updated with a next segment digest for the file.\r\n \"\"\"\r\n \r\n hashed_object = hash_func()\r\n with open(file_path, \"rb\") as f:\r\n if first_segment:\r\n read_first_segment = f.read(single_segment_size)\r\n hashed_object.update(read_first_segment)\r\n else:\r\n full_file = f.read(os.path.getsize(file_path))\r\n hashed_object.update(full_file)\r\n \r\n return hashed_object.hexdigest()","sub_path":"read_and_hash.py","file_name":"read_and_hash.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"23587336","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 24 23:26:19 2019\r\n\r\n@author: zakir\r\n\"\"\"\r\nfrom PIL import Image,ImageEnhance, ImageFilter\r\nimport os\r\n\r\n#Change type\r\n\r\nfor item in os.listdir():\r\n if item.endswith(\".jpg\"):\r\n img=Image.open(item)\r\n fileName,extention=os.path.splitext(item)\r\n img.save(f\"{fileName}.pdf\")\r\n img.save(f\"{fileName}.png\")\r\n\r\n#Change size\r\nfor item in os.listdir(): \r\n if item.endswith(\".png\"): \r\n image_size=(20,20)\r\n img1=Image.open(item)\r\n img1.thumbnail(image_size)\r\n fileName,extention=os.path.splitext(item)\r\n img1.save(f\"{fileName}.png\")\r\n\r\n\r\n#------------------- Sharpness -------------\r\n\r\nimg3=Image.open(\"bird3.jpg\")\r\nenhancer=ImageEnhance.Sharpness(img3)\r\nenhancer.enhance(3).save(\"new_bird3_Sharpness.jpg\")\r\n\r\n#--------------------- Color -------------\r\nimg4=Image.open(\"bird3.jpg\")\r\ncEnhancer=ImageEnhance.Color(img4)\r\ncEnhancer.enhance(5).save(\"new_bird3_Color.jpg\")\r\n\r\n#--------------- Brightness --------------\r\nimg5=Image.open(\"bird3.jpg\")\r\nbEnhancer=ImageEnhance.Brightness(img5)\r\nbEnhancer.enhance(6).save(\"new_bird3_Brightness.jpg\")\r\n\r\n#-------------- Contrast ---------------\r\nimg6=Image.open(\"bird3.jpg\")\r\nconEnhancer=ImageEnhance.Contrast(img6)\r\nconEnhancer.enhance(6).save(\"new_bird3_Brightness.jpg\")\r\n\r\n#---------------- GaussianBlur ---------------\r\nimg7=Image.open(\"bird3.jpg\")\r\nimg7.filter(ImageFilter.GaussianBlur(radius=4)).save(\"new_bird3_GaussianBlur.jpg\")\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"77. image_editing_practice.py","file_name":"77. image_editing_practice.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"126801367","text":"# -*- coding: utf8 -*-\n\"\"\"\nLongest Common Prefix\n=====================\n\nWrite a function to find the longest common prefix string amongst an array of strings.\n\nLongest common prefix for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2.\n\nAs an example, longest common prefix of \"abcdefgh\" and \"abcefgh\" is \"abc\".\n\nGiven the array of strings, you need to find the longest S which is the prefix of ALL the strings in the array.\n\nExample:\n\nGiven the array as:\n\n[\n \"abcdefgh\",\n \"aefghijk\",\n \"abcefgh\"\n]\nThe answer would be “a”.\n\nSolution\n--------\n\nUse character by character approach to find the first position in strings at which different characters appear in string array.\n\nTime complexity O(N*M)\n\"\"\"\n\nfrom __future__ import print_function\n\n\ndef lcp(strings):\n min_len = min(len(s) for s in strings)\n\n i = 0\n while i < min_len:\n c = strings[0][i]\n if not all(s[i]==c for s in strings):\n break\n i += 1\n\n return strings[0][:i]\n\n\nprint(lcp([\n \"abcdefgh\",\n \"abfghijk\",\n \"abcefgh\"\n]))\n","sub_path":"InterviewBit/Strings/LongestCommonPrefix.py","file_name":"LongestCommonPrefix.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"150793169","text":"# ENTENDO O FOR GABRIEL\n# for = para\n# for item in serie_ de_qualquer_coisa\n# for pega um item que pode ser qualquer nome/ coisa para percorrer qualquer tipo de conjunto\n\n# Pode-se ser utilizado em \n# 1- strings\n# 2- listas\n# 3- tuplas\n# 4- elementos de dicionarios\n# 5- arquivos\n\n# Machine Learning é iteração = repetir processos para treinamento\ntupla01 = (2,5,6,7,8)\nfor i in tupla01:\n print(i)\n\n# Usando com dicionario\ndicionario01 = [\"coisa01\",\"coisa02\",\"coisa03\",\"coisa04\"]\nfor n in dicionario01:\n print(n)\n\n# Usar com com range\nfor numero in range(0,100):\n print(numero)\n\n# Verificando se os números são pares em um conjunto\nfor numero in range(0,20):\n if numero % 2 == 0:\n print(numero)\n\n# range pode ser usado range(inicio, fim, condição)\n# quero uma lista de x a y pulando o z por exemplo\n\nfor numero in range(0, 10, 3):\n print(numero)\n\n# Podemos usar em uma string\nfrase = \"O rato roeu a roupa do rei de roma\"\nfor caractere in frase:\n print(caractere)\n","sub_path":"Py_DSA_LV02/004_loop_for.py","file_name":"004_loop_for.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"338258441","text":"class MhsTif(object):\r\n def __init__(self, nama, nim, kota, uangsaku):\r\n self.nama = nama\r\n self.nim = nim\r\n self.kotaTinggal = kota\r\n self.uangSaku = uangsaku\r\n\r\n\r\nclass buatArray(object):\r\n internalData = 11 * [None]\r\n\r\n def __getitem__(self, item):\r\n return self.internalData[item]\r\n\r\n def __setitem__(self, key, value):\r\n self.internalData[key] = value\r\n\r\n def siapaTerkecil(self):\r\n terkecil = self[0].uangSaku\r\n d = []\r\n for i in self:\r\n if i.uangSaku <= terkecil:\r\n terkecil = i.uangSaku\r\n for i in self:\r\n if terkecil == i.uangSaku:\r\n d.append((i.nama, i.nim, i.kotaTinggal, i.uangSaku))\r\n return d\r\n\r\nc = buatArray()\r\nc[0] = MhsTif(\"Ika\", 10, \"Sukoharjo\", 240000)\r\nc[1] = MhsTif(\"Budi\", 51, \"Sragen\", 230000)\r\nc[2] = MhsTif(\"Ahmad\", 2, \"Surakarta\", 250000)\r\nc[3] = MhsTif(\"Chandra\", 18, \"Surakarta\", 235000)\r\nc[4] = MhsTif(\"Eka\", 4, \"Boyolali\", 240000)\r\nc[5] = MhsTif(\"Fandi\", 31, \"Salatiga\", 250000)\r\nc[6] = MhsTif(\"Deni\", 13, \"Klaten\", 245000)\r\nc[7] = MhsTif(\"Galuh\", 5, \"Wonogiri\", 245000)\r\nc[8] = MhsTif(\"Janto\", 23, \"Klaten\", 245000)\r\nc[9] = MhsTif(\"Hasan\", 64, \"Karanganyar\", 270000)\r\nc[10] = MhsTif(\"Khalid\", 29, \"Purwodadi\", 265000)\r\n","sub_path":"Modul_4/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"579793841","text":"''' ---------------------------------------------------\n\nPATH 제공, 스크립트:\nrelative path를 하드코드로 가지고 있다가 런타임에\nabsolute path로 변경하여 Dictionary 형태로 제공한다\n(Path.get()으로 absolute path를 제공)\n\n0. init 시 PATH 존재 여부 확인하여 에러 출력\n1. relative 기준은 이 스크립트 위치\n2. key는 대소문자 구별 없음\n\n--------------------------------------------------- '''\n\nimport os\nimport interfaceUtils as utils\n\nclass _Path():\n __DIC = { }\n\n def __init__(self):\n self.__append('label', '..\\\\..\\\\data\\\\LABEL.txt') # 라벨 종류를 나타내는 LABEL.txt의 상대 경로 추가\n self.__append('train', '..\\\\..\\\\data\\\\train') # train set이 저장되어 있는 폴더의 상대 경로 추가\n self.__append('test', '..\\\\..\\\\data\\\\test') # test set이 저장되어 있는 폴더의 상대 경로 추가\n self.__append('data', '..\\\\..\\\\data')\n self.__append('weight', '..\\\\weight') # weight파일이 저장되어 있는 폴더의 상대 경로 추가\n self.__append('img', '..\\\\img')\n self.__append('temp', '..\\\\..\\\\data\\\\temp') # kinectProgram이 촬영한 손, 위치가 저장되어 있는 temp폴더의 상대 경로 추가\n\n # Change relative to absolute\n for key in self.__DIC:\n self.__DIC[key] = self.__relToAb(self.__DIC[key])\n\n self.ifNoDirThanMakeDir('data')\n self.ifNoDirThanMakeDir('train')\n self.ifNoDirThanMakeDir('test')\n self.ifNoDirThanMakeDir('weight')\n self.ifNoDirThanMakeDir('img')\n self.ifNoDirThanMakeDir('temp')\n\n # Error File/Folder is not exist\n for key in self.__DIC:\n # Path 미존재\n if (os.path.exists(self.__DIC[key]) == False):\n utils.showError('{0} 파일/폴더를 찾을 수 없습니다.'.format(self.__DIC[key]))\n #else:\n #print(key + \": OK\")\n\n def __relToAb(self, rel):\n dirpath = os.path.dirname(os.path.realpath(__file__)) # 상대 경로를 절대 경로로 바꿔주기 위해 현재 파일의 절대 경로를 dirpath에 저장\n return dirpath + \"\\\\\" + rel\n\n def __append(self, key, val):\n self.__DIC[key.upper()] = val # key를 대문자로 변경후 key에 대한 value 설정\n\n def get(self, key):\n return self.__DIC[key.upper()]\n\n def ifNoDirThanMakeDir(self, key): # key에 해당하는 경로가 존재하지 않을 경우 디렉토리를 생성\n path = self.get(key)\n if not os.path.exists(path):\n os.mkdir(path)\n\nPath = _Path()","sub_path":"Project_DNN/scripts/Path.py","file_name":"Path.py","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"236693370","text":"'''Experiment with blend num_subdivision_operations parameter. \n \n default num_subdivision_operations = 1\n\n Blend num_subdivision_operations : 0\n Blend: Num nodes: 12074\n Blend: Num cells: 24144\n\n Blend num_subdivision_operations : 1\n Blend: Num nodes: 22340\n Blend: Num cells: 44676\n\n Blend num_subdivision_operations : 2\n Blend: Num nodes: 199108\n Blend: Num cells: 398212\n\n A larger num_subdivision_operations value increases the number of polygons substantually. \n\n'''\nimport os\nfrom pathlib import Path\nimport sv\nimport sys\nimport vtk\n\n## Set some directory paths. \nscript_path = Path(os.path.realpath(__file__)).parent\nparent_path = Path(os.path.realpath(__file__)).parent.parent\ndata_path = parent_path / 'data'\n\ntry:\n sys.path.insert(1, str(parent_path / 'graphics'))\n import graphics as gr\nexcept:\n print(\"Can't find the new-api-tests/graphics package.\")\n\n## Initialize graphics.\n#\nwin_width = 500\nwin_height = 500\nrenderer, renderer_window = gr.init_graphics(win_width, win_height)\n\n## Create blend options.\noptions = sv.geometry.BlendOptions()\nprint(\"\\n\\nOptions values: \")\n[ print(\" {0:s}:{1:s}\".format(key,str(value))) for (key, value) in sorted(options.get_values().items()) ]\nprint(\"\\n\\n\")\n#\n\n## Read in a model.\nfile_name = str(data_path / 'geometry' / 'demo-no-blend.vtp')\n#file_name = str(data_path / 'geometry' / 'two-cyls.vtp')\nreader = vtk.vtkXMLPolyDataReader()\nreader.SetFileName(file_name) \nreader.Update()\nmodel = reader.GetOutput()\nprint(\"Model: \")\nprint(\" Num cells: {0:d}\".format(model.GetNumberOfCells()))\n\n## Set faces to blend.\nblend_radius = 1.0\nprint(\"Blend radius: {0:f}\".format(blend_radius))\n\nif \"two-cyls.vtp\" in file_name:\n blend_faces = [ { 'radius': blend_radius, 'face1':1, 'face2':2 } ]\nelif \"demo-no-blend.vtp\" in file_name:\n blend_faces = [ { 'radius': blend_radius, 'face1':1, 'face2':2 } ]\n\n## Perform the blend operation.\n#\nnum_subdivision_operations_list = \\\n[ \n (0, [0.0,0.0,1.0]), \n (1, [0.0,1.0,0.0]), \n (2, [1.0,0.0,0.0]) \n]\n\nfor i,entry in enumerate(num_subdivision_operations_list):\n num_subdivision_operations = entry[0]\n color = entry[1]\n print(\"Blend num_subdivision_operations : {0:g}\".format(num_subdivision_operations))\n options.num_subdivision_operations = num_subdivision_operations \n blend = sv.geometry.local_blend(surface=model, faces=blend_faces, options=options)\n print(\" Blend: Num nodes: {0:d}\".format(blend.GetNumberOfPoints()))\n print(\" Blend: Num cells: {0:d}\".format(blend.GetNumberOfCells()))\n if i == 2:\n gr.add_geometry(renderer, blend, color=color, wire=True)\n else:\n gr.add_geometry(renderer, blend, color=color, wire=False)\n\n ## Write the blended surface.\n file_name = str(script_path / str(\"blend-numsubbdiv-\" + str(i) + \".vtp\"))\n writer = vtk.vtkXMLPolyDataWriter()\n writer.SetFileName(file_name)\n writer.SetInputData(blend)\n writer.Update()\n writer.Write()\n\n## Show geometry.\ngr.display(renderer_window)\n\n","sub_path":"new-api-tests/geometry/blend-numsubdiv.py","file_name":"blend-numsubdiv.py","file_ext":"py","file_size_in_byte":3007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"575965439","text":"# Call in this directory with python3 and arcPro after logging into ArcPro account\n# ex: \"C:\\Program Files\\ArcGIS\\Pro\\bin\\Python\\envs\\arcgispro-py3\\python.exe\" \"F:\\model_review\\mobi-app-data-uploader\\py\\automateDicingData.py\" \"F:\\model_review\\mobi-app-data-uploader\\data\"\n\nimport arcpy\nfrom arcpy import env\nimport os\nimport sys\nimport traceback\nimport time\nimport datetime\nimport shutil\nfrom zipfile import ZipFile\n\nif len(sys.argv) > 1:\n dataPath = sys.argv[1]\n if len(sys.argv) > 2:\n max_vertices = sys.argv[2]\n else:\n max_vertices = 10000\nelse:\n os.chdir(os.path.dirname(__file__))\n dataPath = '../data'\n max_vertices = 10000\n\nif os.path.exists(dataPath) and os.path.isdir(dataPath):\n start_ts = time.time()\n start_sttime = datetime.datetime.fromtimestamp(\n start_ts).strftime('%Y%m%d_%H%M')\n log = os.path.join(dataPath, 'Log_' + start_sttime + '.txt')\n with open(log, 'a') as logfile:\n logfile.write('Start log at ' + start_sttime + '\\n')\nelse:\n print('ERROR: Datapath not found: ' + dataPath)\n exit()\n\n\ndef log_except_hook(*exc_info):\n text = ''.join(traceback.format_exception(*exc_info))\n printlog('ERROR: Unhandled exception: ' + text)\n\n\nsys.excepthook = log_except_hook\n\n\ndef printlog(text):\n print(text)\n ts = time.time()\n sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')\n with open(log, 'a') as logfile:\n logfile.write(sttime + text + '\\n')\n\n\ndef get_all_file_paths(directory):\n # initializing empty file paths list\n file_paths = []\n\n # crawling through directory and subdirectories\n for root, directories, files in os.walk(directory):\n for filename in files:\n # join the two strings in order to form the full filepath.\n filepath = os.path.join(root, filename)\n file_paths.append(filepath)\n\n # returning all file paths\n return file_paths\n# end get_all_file_paths\n\n\ndef main():\n for f in os.listdir(dataPath):\n if os.path.isdir(os.path.join(dataPath, f)):\n # For each data/\n printlog('Processing Species Folder: ' + f)\n try:\n for sf in os.listdir(os.path.join(dataPath, f)):\n if sf.endswith('.zip') and not sf.startswith('old'):\n # Make backup of zipped gdb\n newSpeciesZip = os.path.join(dataPath, f, sf)\n oldSpeciesZip = os.path.join(dataPath, f, 'old-' + sf)\n zipcnt = 1\n while (os.path.exists(oldSpeciesZip)):\n oldSpeciesZip = os.path.join(\n dataPath, f, 'old' + str(zipcnt) + '-' + sf)\n zipcnt = zipcnt + 1\n printlog('Backing up zip: ' + oldSpeciesZip)\n os.rename(newSpeciesZip, oldSpeciesZip)\n\n # open feature layer in it\n newGdbPath = newSpeciesZip.replace('.zip', '')\n\n # clear gdb if it exists\n if os.path.exists(newGdbPath):\n printlog('Deleting: ' + newGdbPath)\n arcpy.Delete_management(newGdbPath)\n\n # Unzip it\n printlog('Unzipping: ' + newSpeciesZip)\n with ZipFile(oldSpeciesZip) as toUnzip:\n toUnzip.extractall(os.path.join(dataPath, f))\n\n # check for expected gdb\n if os.path.exists(newGdbPath):\n env.workspace = newGdbPath\n featureClasses = arcpy.ListFeatureClasses()\n for fc in featureClasses:\n # backup the layer in case dice fails\n oldFeatureClass = 'old_' + fc\n\n printlog('Backing up layer: ' + fc)\n arcpy.CopyFeatures_management(\n fc, oldFeatureClass)\n # clear the current\n arcpy.Delete_management(fc)\n\n row_count = arcpy.GetCount_management(\n oldFeatureClass)\n printlog('Original Feature Count: ' +\n str(row_count))\n\n printlog(\n 'Checking for bad geometries in: ' + fc)\n checkGeomPath = os.path.join(\n dataPath, f, fc + '_checkGeom.csv')\n\n if os.path.exists(checkGeomPath):\n printlog('Deleting: ' + checkGeomPath)\n os.remove(checkGeomPath)\n os.remove(os.path.join(\n dataPath, f, fc + '_checkGeom.txt.xml'))\n\n printlog('Look for geom errors in: ' +\n checkGeomPath)\n arcpy.CheckGeometry_management(\n oldFeatureClass, checkGeomPath)\n\n printlog(\n 'Repairing any potentially bad geometries in: ' + fc)\n arcpy.RepairGeometry_management(\n oldFeatureClass)\n\n printlog('Dicing layer: ' + fc)\n # Dice it with 10K vertices making it new fc\n arcpy.Dice_management(\n oldFeatureClass, fc, max_vertices)\n\n # Clear the backup once to this point\n printlog(\n 'Dicing successful, deleting backup layer')\n arcpy.Delete_management(oldFeatureClass)\n\n row_count = arcpy.GetCount_management(fc)\n printlog('New Feature Count: ' +\n str(row_count))\n\n printlog('Rezipping: ' + newSpeciesZip)\n with ZipFile(newSpeciesZip, 'w') as toZip:\n file_paths = get_all_file_paths(newGdbPath)\n zipbasedir = os.path.dirname(newGdbPath)\n for file in file_paths:\n toZip.write(\n file, file.replace(zipbasedir, ''))\n\n printlog('Deleting: ' + newGdbPath)\n arcpy.Delete_management(newGdbPath)\n printlog('---------')\n else:\n printlog(\n 'ERROR: Zip did not contain expected gdb. Skipping to next folder.')\n except:\n exc_type, exc_value, exc_traceback = sys.exc_info()\n text = ''.join(traceback.format_exception(\n exc_type, exc_value, exc_traceback))\n printlog(\n 'ERROR: Unexpected exception while processing %s.\\nSkipping to next folder.\\nYou will need to rename old-.zip to .zip if you want to process this folder again.\\nException: %s' % (f, text))\n printlog('---------')\n printlog('Finished!')\n# end main\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"py/automateDicingData.py","file_name":"automateDicingData.py","file_ext":"py","file_size_in_byte":7709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"290835326","text":"#!/usr/bin/env python3\n#\n# This is a plot of the function\n# f(x) = Integral [exp(-x-y) * (x+y)^N G(y | mu sigma) dy]\n# where G is a Gaussian for y of mean=mu and std dev=sigma\n# with y>0\n#\n# It is plotted betwee x1 and x2\n#\n# CC 6 Feb 2019\n#--------------------------------\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport ccHistStuff as cc\n\n# The function that multiplies the Gaussian\ndef ff(x,y,N):\n return np.exp(-x-y) * (x+y)**N\n\n# parameters from problem\nN = 5\nmu = 3\nsigma = 0.5\nx1 = -3.\nx2 = 15.\nnpoints = 100 # number of points in x to plot\nntoy = 1000 # for MC integration of y\ndx = (x2-x1)/100\nxar = np.linspace(x1, x2, npoints) # the points in x to plot\n\n# init random number\nnp.random.seed(1234567)\n\n# an array for f(x) initialized to zero\nfar = np.zeros(npoints)\ni = 0\nfor x in xar:\n y = np.random.normal(mu, sigma, ntoy) # pick y\n y = y[ y> 0 ] # require y>0\n thisN = len(y) # how many \"usable\" y's do we really have? \n ftoy = ff(x, y, N) \n far[i] = (1./thisN) * ftoy.sum()\n i = i + 1\n\n# now the plot\nfig, ax = plt.subplots()\nax.plot(xar, far)\nax.set_xlim(x1,x2)\nax.set_ylim(0)\nax.grid(True, which='both')\nfig.show()\ninput(\"blah to continue\")\n","sub_path":"Campagnari-0000-hw4/poissonPosterior.py","file_name":"poissonPosterior.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"241389749","text":"#!/bin/python\n\n# DEP:\n# 1. PIL\n# 2. libwebp\n\nfrom optparse import OptionParser\nimport os, os.path\nimport logging\nfrom PIL import Image\nimport sys\nimport shutil\n\nCOUNT = 0\n\n# Decompress a WebP file to an image file, from google.\nDWEBP = \"E:\\\\opt\\\\libwebp-0.4.2-windows-x64\\\\bin\\\\dwebp.exe\"\n\n# store some info in readme.txt\nREADMETXT = \"readme.txt\"\n\ndef xlog(str):\n logger = logging.getLogger(__name__)\n logger.info( str )\n\ndef xfail(code):\n err = []\n prefix = \"error code %s : \" % code\n err.append('cmd line option `--dir` must be given. see error.log for more detail\")') #1\n err.append('...') #2\n err.append('move html to txt, and into sub dir. see error.log for more detail') #3\n print(prefix + err[code])\n sys.exit(code)\n\n#http://python-forum.org/viewtopic.php?f=6&t=6352\ndef walk_depth(root, max_depth):\n # some initial setup for getting the depth\n root = os.path.normpath(root)\n depth_offset = root.count(os.sep) - 1\n\n for root, dirs, files in os.walk(root, topdown=True):\n # get current depth to determine if we need to stop\n depth = root.count(os.sep) - depth_offset\n yield root, dirs, files, depth\n if depth >= max_depth:\n # modify dirs so we don't go any deeper\n dirs[:] = []\n\n# get file path extension\n# input : \"c:\\\\a\\\\b\\\\abc.jpg\"\n# output : \".jpg\"\ndef getpathext(filename):\n return os.path.splitext(filename)[1].lower()\n\n# get file path root\n# input : \"c:\\\\a\\\\b\\\\abc.jpg\"\n# ouput : \"c:\\\\a\\\\b\\\\abc\"\ndef getpathroot(filename):\n return os.path.splitext(filename)[0]\n\ndef is_image(fullpath):\n try:\n im = Image.open(fullpath)\n except:\n xlog(\"file is not a image : \" + fullpath)\n return False\n else:\n return im.format.lower()\n\ndef preprocessing(filename, fullpath):\n # convert webp to png.\n if getpathext(filename) == \".webp\":\n cmd = DWEBP + ' ' + getpathroot(fullpath) + '.webp -o ' + getpathroot(fullpath) + '.png'\n xlog(\"cmd line : %s\" % cmd)\n try:\n ret_code = os.system(cmd)\n except:\n xlog(\"Something is wrong when changing webp format : \" + filename)\n else:\n if ret_code != 0:\n xlog(\"Something is wrong when changing webp format : \" + filename)\n #print(\"error code 2\")\n #sys.exit(2)\n xlog(\"File is webp format, success to change format to png : \" + filename)\n\n \n \n # file w/o extension, check for image format\n if getpathext(filename) == '':\n fileformat = is_image(fullpath)\n if fileformat:\n newpath = getpathroot(fullpath) + \".\" + fileformat\n xlog(\"[preprocessing] give file a extension, from \" + fullpath + \" to \" + newpath)\n shutil.copy2(fullpath, newpath)\n\ndef is_good_pic(filename, fullpath):\n # file type must image\n if getpathext(filename) not in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:\n return False\n \n # file size must not zero\n if os.path.getsize(fullpath) == 0:\n return False\n \n try:\n #@fixme: file type must be a image.\n im = Image.open(fullpath)\n except:\n xlog(\"file is not a image : \" + fullpath)\n else:\n if im.size[0] < 300:\n return False\n if im.size[1] < 300:\n return False\n \n # go though test above, this file is a good image\n return True\n\ndef counter():\n global COUNT\n COUNT+=1\n\ndef initlog(log_file_path):\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.INFO)\n\n # create a file handler\n handler = logging.FileHandler(log_file_path, 'w+')\n handler.setLevel(logging.INFO)\n\n # create a logging format\n\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n\n # add the handlers to the logger\n\n logger.addHandler(handler)\n\n #logger.info('Hello baby')\n return logger\n\ndef initcmd():\n parser = OptionParser()\n parser.add_option(\"-d\", \"--dir\", dest=\"xdir\",\n help=\"dir\")\n\n (options, args) = parser.parse_args()\n\n if options.xdir is None:\n parser.error(\"`--dir` must be given\")\n xfail(1)\n return options\n\ndef main():\n global COUNT\n\n options = initcmd()\n \n DIR = options.xdir\n \n initlog(DIR + os.path.sep + 'del.log')\n xlog( \"processing root dir is : \" + DIR )\n \n # loop depth must be 2\n #for root, _, files in os.walk(DIR):\n for root, _, files, depth in walk_depth(DIR, 2):\n if depth == 1:\n continue\n \n # loop every files in depth 2.\n for f in files:\n fullpath = os.path.join(root, f)\n xlog(\"processing files in depth2 dir : \" + fullpath)\n \n preprocessing(f, fullpath)\n \n if is_good_pic(f, fullpath):\n continue\n elif f == READMETXT:\n # store some info in this file.\n continue\n else:\n counter()\n xlog(\"remove file : \" + f)\n os.remove(fullpath)\n\n # backup html page\n for file in os.listdir(DIR):\n fullpath = os.path.join(DIR, file)\n if getpathext(file) != \".html\" and getpathext(file) != \".htm\":\n continue\n newpath = os.path.join(DIR, getpathroot(file) + \"_files\", READMETXT)\n xlog(\"[main] move html to txt, and into sub dir : from %s to %s\" % (fullpath, newpath))\n try:\n shutil.move(fullpath, newpath)\n except:\n xfail(3)\n \n \n xlog(\"removed files count : \" + str(COUNT))\n xlog(\"= END =\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"del.py","file_name":"del.py","file_ext":"py","file_size_in_byte":5702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"482462317","text":"#参考https://www.cnblogs.com/lfri/p/10542797.html\n#使用selenium,获取html元素\n#模拟登陆台州学院教务系统,\n# 进入个人课表查询页面\n# 选择学年、学期,提交查询\n\n# 模拟登陆台州学院教务系统\nfrom selenium.webdriver.support.select import Select\nfrom selenium import webdriver\nfrom time import sleep\n\noption=webdriver.ChromeOptions()\ndriver=webdriver.Chrome(options=option)\ndriver.get(\"http://www.jwglxt.tzc.edu.cn/jwglxt/xtgl/login_slogin.html\") # 进入台州学院教务登陆页面\nsleep(1)\nele_user=driver.find_element_by_id('yhm') #查找元素\nele_pwd=driver.find_element_by_id('mm')\nele_submit=driver.find_element_by_id('dl')\nele_user.send_keys('1998013')\nele_pwd.send_keys('Zhang5221')\nele_submit.click()\nsleep(1)\n# 获取当前页面url\ncurrentPageUrl = driver.current_url\nprint(\"当前页面的url是:\", currentPageUrl)\n\n# 进入个人课表查询页面\ndriver.get(\"http://www.jwglxt.tzc.edu.cn/jwglxt/kbcx/jskbcx_cxJskbcxIndex.html?gnmkdm=N2150&layout=default&su=1998013\")\n\ntext_ele = driver.find_element_by_id(\"xnm_chosen\") # 定位学年下拉框\ntext_ele.click() # 点击展开学年下拉列表\nsleep(1)\njs = \"document.getElementById('xnm').style.display='block'\" #修改学年下拉列表元素的isDisplayed()值为true\ndriver.execute_script(js)\nselect_ele = driver.find_element_by_id(\"xnm\") # 定位学年下拉框\n\n# Select(select_ele).select_by_index(2) # 选中选项-3间(索引从0开始)\n# Select(select_ele).select_by_value(3) # 选中选项-3间,value=3\n# Select(select_ele).select_by_visible_text(\"2018-2019\") # 选中-3间,文本\"3间\"\n# # 获取选中的选项\n# for select in Select(select_ele).all_selected_options:\n# print(\"选中选项:\", select.text)\n\nfor select in Select(select_ele).options:# 获取所有下拉列表选项\n if '2019-' in select.text:\n Select(select_ele).select_by_visible_text(select.text)\nsleep(1)\n\njs = \"document.getElementById('xqm').style.display='block'\" #修改学年下拉列表元素的isDisplayed()值为true\ndriver.execute_script(js)\nselect_ele = driver.find_element_by_id(\"xqm\") # 定位学期下拉框\nSelect(select_ele).select_by_visible_text(\"1\") # 选中-3间,文本\"3间\"\nsleep(1)\n\nBtn=driver.find_element_by_id('search_go') #查找查询元素\nBtn.click()\n","sub_path":"selenium_tzc_jwc.py","file_name":"selenium_tzc_jwc.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"545944341","text":"\"\"\"\nThe frontend module\n - deal with graphic output\n - define a Pyglet window for drawing and create sprites from images\n\"\"\"\n\nimport pyglet\n\n# define the board and size of tiles:\nTILE_WIDTH = 64\nTILE_HEIGHT = 64\nWINDOW_WIDTH = 12*TILE_WIDTH\nWINDOW_HEIGHT = 12*TILE_HEIGHT\n\ndef init_window(WINDOW_WIDTH, WINDOW_HEIGHT):\n \"\"\"\n create a pyglet window for graphic output\n \"\"\"\n window = pyglet.window.Window(WINDOW_WIDTH, WINDOW_HEIGHT)\n return window\n\n\ndef load_images(state, TILE_WIDTH, TILE_HEIGHT):\n \"\"\"\n return list of images\n\n input needed - loaded data fron JSON, dictionary state, size of tiles\n \"\"\"\n\n images = []\n for layer in state.board:\n img = sprite(state.board[layer], TILE_WIDTH, TILE_HEIGHT)\n # print(state.board[layer])\n images.extend(img)\n return images\n\n\ndef load_robots(state, TILE_WIDTH, TILE_HEIGHT):\n \"\"\"\n return sprites of robots\n\n input needed - dictionary state, size of tiles\n \"\"\"\n robots = sprite(state.robots, TILE_WIDTH, TILE_HEIGHT)\n return robots\n\n\ndef sprite(img_dict, TILE_WIDTH, TILE_HEIGHT):\n \"\"\"\n return list of sprites of items\n\n input needed - dictionary img_dict, size of tiles\n \"\"\"\n list = []\n for coordinate, value in img_dict.items():\n rotation = value.rotation\n path = value.path\n if path != 0:\n x, y = coordinate\n img = pyglet.image.load(path)\n img.anchor_x = img.width//2\n img.anchor_y = img.height//2\n tile_x = x*TILE_WIDTH\n tile_y = y*TILE_HEIGHT\n img = pyglet.sprite.Sprite(img, x=img.anchor_x+tile_x, y=img.anchor_y+tile_y)\n img.rotation = rotation\n list.append(img)\n return list\n\n\ndef draw_board(images, robots):\n \"\"\"\n draw the images of tiles into map\n \"\"\"\n images.extend(robots)\n for tile in images:\n tile.draw()\n","sub_path":"frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"202564771","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''\nCreated on 2015年11月18日\n\n@author: dxw\n'''\nimport struct\nfrom DDDProxy.baseServer import sockConnect, socketBufferMaxLenght\nimport json\nimport hashlib\nfrom DDDProxy import log\n\n\n\nclass symmetryConnect(sockConnect):\n\t\"\"\"\n\t@type remoteConnect: remoteServerConnect\n\t\"\"\"\n\n\toptCloseSymmetryConnect = -1\n\n\toptSymmetryPing = -2\n\toptSymmetryPingResponse = -3\n\n\toptCloseForceSymmetryConnect = -4\n\n\t\n\tdef __init__(self,server):\n\t\tsockConnect.__init__(self, server)\n\t\tself.symmetryConnectId = 0\n\t\tself._symmetryConnectSendPendingCache = []\n\t\tself._requestRemove = False\n\t\tself.symmetryConnectManager = None\n\t\tself.waitSymmetryPingResponse = False\n\t\t\n\t\tself._symmetryPingLenght = 0\n\t\t\n#--------\n\n\n\tdef pauseSendAndRecv(self):\n\t\treturn self.waitSymmetryPingResponse\n\n\tdef onRecv(self, data):\n\t\tsockConnect.onRecv(self, data)\n\t\tself.sendDataToSymmetryConnect(data)\n\t\t\n\t\tself._symmetryPingLenght += len(data)\n\t\tif(self._symmetryPingLenght>1024*100):\n\t\t\tself._symmetryPingLenght = 0\n\t\t\tself.waitSymmetryPingResponse = True\n\t\t\tself.sendOptToSymmetryConnect(symmetryConnect.optSymmetryPing)\n\t\t\n\tdef onClose(self):\n\t\tself.sendOptToSymmetryConnect(symmetryConnect.optCloseSymmetryConnect)\n\t\tself._requestRemove = True\n\t\n#--------\n\tdef onSymmetryConnectServerClose(self):\n\t\tself.close()\n\tdef onSymmetryConnectData(self,data):\n\t\tpass\n\tdef onSymmetryConnectOpt(self,opt):\n\t\tif opt == symmetryConnect.optCloseSymmetryConnect:\n\t\t\tself.close()\n\t\telif opt == symmetryConnect.optSymmetryPing:\n\t\t\tself.sendOptToSymmetryConnect(symmetryConnect.optSymmetryPingResponse)\n\t\telif opt == symmetryConnect.optSymmetryPingResponse:\n\t\t\tself.waitSymmetryPingResponse = False\n\t\telif opt == symmetryConnect.optCloseForceSymmetryConnect:\n\t\t\tself.shutdown()\n\t\t\tself.onClose()\n\t\t\tlog.log(2,self,\"<<< optCloseForceSymmetryConnect, close\")\n\t\t\n\tdef sendOptToSymmetryConnect(self,opt):\n\t\tif self._requestRemove:\n\t\t\treturn\n\t\toptData = symmetryConnectServerHandler.optChunk(self.symmetryConnectId, opt)\n\t\tif type(optData) != str:\n\t\t\tlog.log(3,\"data not is str\")\n\t\tself._symmetryConnectSendPendingCache.append(optData)\n\tdef sendDataToSymmetryConnect(self,data):\n\t\tif self._requestRemove:\n\t\t\treturn\n\t\t\n\t\t\t\n\t\tif type(data) != str:\n\t\t\tlog.log(3,\"data not is str\")\n\t\tfor part in symmetryConnectServerHandler.dataChunk(self.symmetryConnectId, data):\n\t\t\tif type(part) != str:\n\t\t\t\tlog.log(3,\"part not is str\")\n\t\t\tself._symmetryConnectSendPendingCache.append(part)\n\n#--------------- for symmetryConnectServerHandler\n\tdef symmetryConnectSendPending(self):\n\t\treturn len(self._symmetryConnectSendPendingCache)\n\tdef getSymmetryConnectSendData(self):\n\t\treturn self._symmetryConnectSendPendingCache.pop(0)\n\tdef requestRemove(self):\n\t\treturn self._requestRemove\n\t\nclass symmetryConnectServerHandler(sockConnect):\n\n\tserverToServerJsonMessageConnectId = -1\n\t\n\tdef __init__(self, server, *args, **kwargs):\n\t\tsockConnect.__init__(self, server, *args, **kwargs)\n\t\tself.symmetryConnectList = {}\n\t\tself._symmetryConnectMessageBuffer = \"\"\n\t\tself.symmetryConnectIdLoop = 0\n\t\n\tdef getSendPending(self):\n\t\tif sockConnect.getSendPending(self) < socketBufferMaxLenght:\n\t\t\tfor symmetryConnectId,v in self.symmetryConnectList.items():\n\t\t\t\tif v.symmetryConnectSendPending():\n\t\t\t\t\tdata = v.getSymmetryConnectSendData()\n\t\t\t\t\tself.send(data)\n\t\t\t\telif v.requestRemove():\n\t\t\t\t\tdel self.symmetryConnectList[symmetryConnectId]\n\t\t\t\t\t\n\t\treturn sockConnect.getSendPending(self)\n\tdef onSend(self, data):\n\t\tsockConnect.onSend(self, data)\n# \t\tprint \"\"\n\n# ------------- \n\n\tdef onServerToServerMessage(self,serverMessage):\n\t\tpass\n\n# -------------\t\t\n\tdef onClose(self):\n\t\tfor _,connect in self.symmetryConnectList.items():\n\t\t\tconnect.onSymmetryConnectServerClose()\n\n\t@staticmethod\n\tdef optChunk(symmetryConnectId,opt):\n\t\tif opt >=0:\n\t\t\traise Exception(\"opt must < 0\")\n\t\treturn struct.pack(\"i\", symmetryConnectId)+struct.pack(\"h\", opt) +\"\\n\"\n\n\t@staticmethod\n\tdef dataChunk(symmetryConnectId,data):\n\t\tl = len(data)\n\t\tif l > 32767: #分块\n\t\t\tyield symmetryConnectServerHandler.dataChunk(symmetryConnectId, data[:32767])\n\t\t\tyield symmetryConnectServerHandler.dataChunk(symmetryConnectId, data[32767:])\n\t\telse:\n\t\t\tyield struct.pack(\"i\", symmetryConnectId)+struct.pack(\"h\", l) +data+\"\\n\"\n\t\n\t\n\t_headSize = struct.calcsize(\"ih\")\n\tdef onRecv(self,data):\n\t\tsockConnect.onRecv(self, data)\n\t\tself._symmetryConnectMessageBuffer += data\n\t\twhile True:\n\t\t\tbufferLen = len(self._symmetryConnectMessageBuffer)\n\t\t\t_headSize = symmetryConnectServerHandler._headSize\n\t\t\tif bufferLen >= _headSize:\n\t\t\t\tsymmetryConnectId,dataSize = struct.unpack(\"ih\",self._symmetryConnectMessageBuffer[:_headSize])\n\t\t\t\tif dataSize>=0:\n\t\t\t\t\tendIndex = dataSize+_headSize\n\t\t\t\t\tif bufferLen > endIndex:\n\t\t\t\t\t\tdataMessage = self._symmetryConnectMessageBuffer[_headSize:endIndex]\n\t\t\t\t\t\tself._symmetryConnectMessageBuffer = self._symmetryConnectMessageBuffer[endIndex+1:]\n\t\t\t\t\t\tself._onRecvData(symmetryConnectId, dataMessage)\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tself._symmetryConnectMessageBuffer = self._symmetryConnectMessageBuffer[_headSize+1:]\n\t\t\t\t\tself._onRecvOpt(symmetryConnectId, dataSize)\n\t\t\telse:\n\t\t\t\tbreak\n\t\n\tdef _onRecvData(self,symmetryConnectId,data):\n# \t\tprint \"<_onRecvData \",symmetryConnectId,\" ----------\\n\",data,\"\\n------------->\"\n\t\tif symmetryConnectId == symmetryConnectServerHandler.serverToServerJsonMessageConnectId:\n\t\t\ttry:\n\t\t\t\tserverMessage = json.loads(data)\n\t\t\t\tself.onServerToServerMessage(serverMessage)\n\t\t\texcept:\n\t\t\t\tpass\n\t\telse:\n\t\t\tconnect = self.getSymmetryConnect(symmetryConnectId)\n\t\t\tif connect:\n\t\t\t\tconnect.onSymmetryConnectData(data)\n\n\tdef _onRecvOpt(self,symmetryConnectId,opt):\n# \t\tprint \"<_onRecvOpt \",symmetryConnectId,\" ------\",opt,\"--------->\"\n\t\tif symmetryConnectId == symmetryConnectServerHandler.serverToServerJsonMessageConnectId:\n\t\t\tpass\n\t\telse:\n\t\t\tconnect = self.getSymmetryConnect(symmetryConnectId)\n\t\t\tif connect:\n\t\t\t\tconnect.onSymmetryConnectOpt(opt)\n\tdef getSymmetryConnect(self,symmetryConnectId):\n\t\treturn self.symmetryConnectList[symmetryConnectId] if symmetryConnectId in self.symmetryConnectList else None\n# -----------\n\tdef sendOpt(self,symmetryConnectId,opt):\n\t\tself.send(self.optChunk(symmetryConnectId, opt))\n\tdef sendData(self,symmetryConnectId,data):\n\t\tfor d in self.dataChunk(symmetryConnectId, data):\n\t\t\tself.send(d)\n\tdef addSymmetryConnect(self,connect,connectId):\n\t\tconnect.symmetryConnectId = connectId\n\t\tconnect.symmetryConnectManager = self\n\t\tself.symmetryConnectList[connectId] = connect\n\t\t\n\tdef makeSymmetryConnectId(self):\n\t\tself.symmetryConnectIdLoop += 1\n\t\treturn self.symmetryConnectIdLoop\n\n\tdef authMake(self,auth,timenum):\n\t\treturn {\n\t\t\t\"time\":timenum,\n\t\t\t\"password\":hashlib.md5(\"%s_%d\" % (auth, timenum)).hexdigest()\n\t\t\t}\n","sub_path":"DDDProxy/symmetryConnectServerHandler.py","file_name":"symmetryConnectServerHandler.py","file_ext":"py","file_size_in_byte":6757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"23134075","text":"import pygame\nfrom settings import Settings\nfrom player import Player\n\n\nclass Game(Settings):\n def __init__(self, player1_name=\"Player1\", player2_name=\"Player2\"):\n self.player1 = Player(player1_name, self.player1_color, 1, self.queen1_color)\n self.player2 = Player(player2_name, self.player2_color, 2, self.queen2_color)\n self.game_over = False\n self.turn = True\n pygame.init()\n self.font = pygame.font.SysFont('Arial', 25)\n self.winner_font = pygame.font.SysFont('Arial', 45)\n self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))\n pygame.display.set_caption('Warcaby')\n self.screen.fill(self.background_color)\n self._draw_table()\n self._draw_pieces()\n\n def _draw_table(self):\n for column in range(0, 8):\n for row in range(0, 8):\n if (row % 2 == 0 and column % 2 == 0) or (row % 2 == 1 and column % 2 == 1):\n pygame.draw.rect(self.screen, self.color1,\n pygame.Rect(row * self.tile_width, column * self.tile_height, self.tile_width,\n self.tile_height))\n pygame.display.flip()\n else:\n pygame.draw.rect(self.screen, self.color2,\n pygame.Rect(row * self.tile_width, column * self.tile_height, self.tile_width,\n self.tile_height))\n pygame.display.flip()\n\n def _draw_pieces(self):\n for column in range(0, 3):\n for row in range(0, 8):\n if (row % 2 != 0 and column % 2 == 0) or (row % 2 == 0 and column % 2 != 0):\n pygame.draw.circle(self.screen, self.player2_color,\n (self.piece_center[0] * (2 * row + 1), self.piece_center[1] * (2 * column + 1)),\n self.piece_radius) # draw player2 pieces\n pygame.display.flip()\n else:\n pygame.draw.circle(self.screen, self.player1_color,\n (self.piece_center[0] * (2 * row + 1), self.piece_center[1] * (2 * column + 11)),\n self.piece_radius) # draw player1 pieces\n pygame.display.flip()\n\n def reset_tile(self, position, color, *args):\n if len(args) > 0:\n for arg in args:\n for pos in arg:\n pygame.draw.rect(self.screen, color,\n pygame.Rect(pos[0] * self.tile_width, pos[1] * self.tile_height,\n self.tile_width, self.tile_height))\n pygame.display.flip()\n else:\n pygame.draw.rect(self.screen, color, pygame.Rect(position[0] * self.tile_width, position[1] * self.tile_height,\n self.tile_width, self.tile_height))\n pygame.display.flip()\n\n def move_piece(self, new_position, current_position, value=1):\n self.reset_tile(current_position, self.color2)\n player = self.player1 if value == 1 else self.player2\n color = (0, 0, 0)\n for piece in player.pieces_list:\n if piece.position == current_position:\n if piece.queen:\n color = player.queen_color\n else:\n color = player.color\n pygame.draw.circle(self.screen, color, (self.piece_center[0] * (2 * new_position[0] + 1),\n self.piece_center[1] * (2 * new_position[1] + 1)), self.piece_radius)\n pygame.display.flip()\n self.update_piece(new_position, current_position, player.value)\n\n def update_piece(self, new_position, current_position, player=1):\n turn = self.player1 if player == 1 else self.player2\n for piece in turn.pieces_list:\n if piece.position == current_position:\n piece.position = new_position\n\n def get_tile(self, pos):\n # pos[0] -> x-axis pos[1] -> y-axis\n row = pos[0] // self.tile_width\n column = pos[1] // self.tile_height\n return row, column\n\n def color_tile(self, pos, color=(255, 22, 33)):\n row, column = pos[0], pos[1]\n pygame.draw.rect(self.screen, color,\n pygame.Rect(row * self.tile_width, column * self.tile_height, self.tile_width,\n self.tile_height))\n pygame.display.flip()\n\n def find_moves(self, pos, player=1):\n moves = []\n north_east = (pos[0]+1, pos[1]-1)\n north_west = (pos[0]-1, pos[1]-1)\n south_east = (pos[0]+1, pos[1]+1)\n south_west = (pos[0]-1, pos[1]+1)\n\n if player == 1:\n if (north_east not in self.player1 and north_east not in self.player2) and north_east[0] < 8 and north_east[1] >= 0:\n moves.append(north_east)\n if (north_west not in self.player1 and north_west not in self.player2) and north_west[0] >= 0 and north_west[1] >= 0:\n moves.append(north_west)\n else:\n if (south_east not in self.player2 and south_east not in self.player1) and south_east[0] < 8 and south_east[1] < 8:\n moves.append(south_east)\n if (south_west not in self.player2 and south_west not in self.player1) and south_west[0] >= 0 and south_west[1] < 8:\n moves.append(south_west)\n moves += self.find_kills(pos, player)\n gamer = self.player1 if player == 1 else self.player2\n for piece in gamer.pieces_list:\n if piece.position == pos and piece.queen:\n moves += self.find_queen_moves(pos, player)\n break\n return moves\n\n def find_kills(self, pos, value=1):\n kills = []\n north_east_short = (pos[0] + 1, pos[1] - 1)\n north_west_short = (pos[0] - 1, pos[1] - 1)\n south_east_short = (pos[0] + 1, pos[1] + 1)\n south_west_short = (pos[0] - 1, pos[1] + 1)\n north_east = (pos[0] + 2, pos[1] - 2)\n north_west = (pos[0] - 2, pos[1] - 2)\n south_east = (pos[0] + 2, pos[1] + 2)\n south_west = (pos[0] - 2, pos[1] + 2)\n\n player = self.player1 if value == 1 else self.player2\n opponent = self.player2 if value == 1 else self.player1\n\n if (north_east_short in opponent and north_east not in player and north_east not in opponent)\\\n and north_east[0] < 8 and north_east[1] >= 0:\n kills.append(north_east)\n if (north_west_short in opponent and north_west not in player and north_west not in opponent)\\\n and north_west[0] >= 0 and north_west[1] >= 0:\n kills.append(north_west)\n if (south_east_short in opponent and south_east not in player and south_east not in opponent)\\\n and south_east[0] < 8 and south_east[1] < 8:\n kills.append(south_east)\n if (south_west_short in opponent and south_west not in player and south_west not in opponent)\\\n and south_west[0] >= 0 and south_west[1] < 8:\n kills.append(south_west)\n return kills\n\n def find_queen_moves(self, pos, value=1):\n player = self.player1 if value == 1 else self.player2\n opponent = self.player2 if value == 1 else self.player1\n moves = []\n find_obstacle_enemy = False\n i = 1 #index\n\n # South-East direction\n while 8 > pos[0] + i >= 0 and 8 > pos[1] + i >= 0:\n if (pos[0] + i, pos[1] + i) in player:\n break\n elif (pos[0] + i, pos[1] + i) in opponent:\n if (pos[0] + i + 1, pos[1] + i + 1) in opponent:\n break\n else:\n moves.append((pos[0] + i + 1, pos[1] + i + 1))\n i += 1\n else:\n moves.append((pos[0] + i, pos[1] + i))\n i += 1\n i = 1\n # South-West direction\n while 8 > pos[0] - i >= 0 and 8 > pos[1] + i >= 0:\n if (pos[0] - i, pos[1] + i) in player:\n break\n elif (pos[0] - i, pos[1] + i) in opponent:\n if (pos[0] - i - 1, pos[1] + i + 1) in opponent:\n break\n else:\n moves.append((pos[0] - i - 1, pos[1] + i + 1))\n i += 1\n else:\n moves.append((pos[0] - i, pos[1] + i))\n i += 1\n i = 1\n # North-East direction\n while 8 > pos[0] + i >= 0 and 8 > pos[1] - i >= 0:\n if (pos[0] + i, pos[1] - i) in player:\n break\n elif (pos[0] + i, pos[1] - i) in opponent:\n if (pos[0] + i + 1, pos[1] - i - 1) in opponent:\n break\n else:\n moves.append((pos[0] + i + 1, pos[1] - i - 1))\n i += 1\n else:\n moves.append((pos[0] + i, pos[1] - i))\n i += 1\n i = 1\n # North-West direction\n while 8 > pos[0] - i >= 0 and 8 > pos[1] - i >= 0:\n if (pos[0] - i, pos[1] - i) in player:\n break\n elif (pos[0] - i, pos[1] - i) in opponent:\n if (pos[0] - i - 1, pos[1] - i - 1) in opponent:\n break\n else:\n moves.append((pos[0] - i - 1, pos[1] - i - 1))\n i += 1\n else:\n moves.append((pos[0] - i, pos[1] - i))\n i += 1\n return moves\n\n def is_kill(self, after_pos, before_pos, value=1):\n if abs(after_pos[0] - before_pos[0]) == 2:\n return True\n player = self.player1 if value == 1 else self.player2\n opponent = self.player2 if value == 1 else self.player1\n\n # if lower than 0 then north else south\n first_destination = after_pos[1] - before_pos[1]\n\n # if lower than 0 then west else east\n second_destination = after_pos[0] - before_pos[0]\n\n for piece in player.pieces_list:\n if piece.position == after_pos and piece.queen:\n for i, tile in enumerate(range(1, (abs(before_pos[0] - after_pos[0])))):\n if first_destination < 0:\n if second_destination > 0:\n if (before_pos[0] + i, before_pos[1] - i) in opponent:\n return True\n else:\n if (before_pos[0] - i, before_pos[1] - i) in opponent:\n return True\n else:\n if second_destination > 0:\n if (before_pos[0] + i, before_pos[1] + i) in opponent:\n return True\n else:\n if (before_pos[0] - i, before_pos[1] + i) in opponent:\n return True\n return False\n\n def display_moves(self, moves):\n for move in moves:\n self.color_tile(move, self.move_color)\n\n def draw_turn_rect(self, value=1):\n player = self.player1 if value == 1 else self.player2\n pygame.draw.rect(self.screen, player.color,\n pygame.Rect(8.5 * self.tile_width, 4 * self.tile_height, self.tile_width * 2,\n self.tile_height))\n pygame.display.flip()\n self.screen.blit(self.font.render(player.name, True, self.color1),\n (8.6 * self.tile_width + 10, 4.3 * self.tile_height))\n pygame.display.update()\n\n def draw_winner_rect(self, value=1):\n player = self.player1 if value == 1 else self.player2\n pygame.draw.rect(self.screen, player.color,\n pygame.Rect(0, 2 * self.tile_height, self.screen_width,\n 4 * self.tile_height))\n pygame.display.flip()\n self.screen.blit(self.winner_font.render(f\"{player.name} WINS!!!\", True, self.color1),\n (self.screen_width // 4, self.screen_height // 2))\n pygame.display.update()\n\n def is_queen(self, pos, value=1):\n player = self.player1 if value == 1 else self.player2\n if player.value == 1:\n if pos[1] == 0:\n return True\n else:\n if pos[1] == 7:\n return True\n return False\n\n def promote_to_queen(self, pos, value=1, next_jump = False):\n player = self.player1 if value == 1 else self.player2\n for piece in player.pieces_list:\n if piece.position == pos:\n piece.queen = True\n if next_jump:\n pygame.draw.circle(self.screen, player.queen_color, (self.piece_center[0] * (2 * pos[0] + 1),\n self.piece_center[1] * (2 * pos[1] + 1)),\n self.piece_radius)\n pygame.display.flip()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":13096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"491173245","text":"\"\"\"\n(c) 2013 LinkedIn Corp. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\");?you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software?distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\"\"\"\n\nfrom .soap_request import M, T, DISTINGUISHED_IDS\n\nimport sys\nif sys.version_info[0] == 3:\n unicode = str\n basestring = str\n\n\ndef get_mail_items(folder_id='inbox', format=u\"Default\", query=None, max_entries=1000):\n \"\"\"\n :param str format: IdOnly or Default or AllProperties\n - see `doc `_\n :param str query: advanced query, example: `HasAttachments:true Subject:'Message with Attachments' Kind:email`\n - see `doc `_\n :param max_entries: defaults to 1000 as exchange won't return more under default settings\n \"\"\"\n # http://msdn.microsoft.com/en-us/library/aa566107%28v=exchg.140%29.aspx FindItem operation\n # http://msdn.microsoft.com/en-us/library/aa566370%28v=exchg.140%29.aspx FindItem XML\n # http://msdn.microsoft.com/en-us/library/office/dn579420%28v=exchg.150%29.aspx FindItem + AQS\n xml_fid = T.DistinguishedFolderId(Id=folder_id) if folder_id in DISTINGUISHED_IDS else T.FolderId(Id=folder_id)\n root = M.FindItem(\n {u'Traversal': u'Shallow'},\n M.ItemShape(\n T.BaseShape(format),\n T.AdditionalProperties(\n T.FieldURI(FieldURI=u'item:Subject'),\n T.FieldURI(FieldURI=u'item:DateTimeReceived'),\n T.FieldURI(FieldURI=u'item:Size'),\n T.FieldURI(FieldURI=u'item:Importance'),\n # T.FieldURI(FieldURI=u'item:Attachments'),\n T.FieldURI(FieldURI=u'message:IsRead'),\n )\n ),\n # \n # \n M.IndexedPageItemView(MaxEntriesReturned=unicode(max_entries), Offset=\"0\", BasePoint=\"Beginning\"),\n M.SortOrder(\n T.FieldOrder(\n T.FieldURI(FieldURI=u'item:DateTimeReceived'),\n Order=u'Descending'\n )\n ),\n M.ParentFolderIds(xml_fid),\n M.QueryString(query) if query else ' '\n )\n return root\n\n\ndef get_attachment(aid):\n \"\"\"\n The GetAttachment operation is used to retrieve existing attachments on items in the Exchange store.\n See `doc `\n \n Can raise FailedExchangeException: Exchange Fault (ErrorInvalidIdNotAnItemAttachmentId) from Exchange server\n \"\"\"\n root = M.GetAttachment(\n M.AttachmentShape(),\n M.AttachmentIds(\n T.AttachmentId(Id=aid)\n )\n )\n return root\n\n\n","sub_path":"pyexchange/exchange2010/soap_request_mail.py","file_name":"soap_request_mail.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"2390634","text":"\"\"\"\n Copyright (C) 2021 Intel Corporation\n SPDX-License-Identifier: BSD-3-Clause\n\"\"\"\n\n\nimport io\nimport wave\nfrom threading import Thread, RLock\nfrom speech_library.speech_manager import SpeechManager\nfrom multiprocessing import freeze_support\nimport numpy as np\nimport scipy.io.wavfile as sv\nfrom zmq_integration_lib import InputPortWithEvents, OutputPort\nimport _config as config\n\nlog = config.get_logger()\n\n\ndef pusher(manager, port):\n Final = False\n data = \"\"\n while not Final:\n data, Final = manager.get_result()\n log.info(\"in thread: data [ {} ] final [ {} ]\".format(data.decode(), Final))\n port.push(bytes(pretty(data), encoding=\"utf-8\"), \"FINAL\")\n\n\ndef pretty(text):\n text_ = text.decode()\n return \" \".join(text_.replace(\"\", \" \").split()).lower()\n\n\ndef main():\n freeze_support()\n log.info(\"Kaldi ASR\")\n\n # Set Input and Output Ports\n ipp = config.get_inputport()\n log.info(\"Main: Input port set\")\n\n Outport = config.get_outputport()\n log.info(\"Main: Output port set\")\n\n manager = SpeechManager()\n config_file = \"/app/src/model/speech_lib.cfg\"\n manager.initialize(config_file)\n log.info(\"Main: Speech Manager Initialized\")\n try:\n for data, event in ipp.data_and_event_generator():\n if event == \"pcm\":\n process_pcm_data(data, manager, Outport)\n continue\n except Exception as msg:\n log.info(\"Received Exception %s\", msg)\n\n\n# This function expects the data as, bytes read from a wave file.\n# bitrate,16000:mono channel and pcmle encoded\ndef process_pcm_data(data, manager, Outport):\n\n wave_data = data\n out = io.BytesIO()\n data_ = np.frombuffer(data, dtype=np.int16)\n sv.write(out, 16000, data_)\n\n def buffer_generator(file):\n with wave.open(file, \"rb\") as f:\n frames_per_buffer = 160\n frames = f.readframes(frames_per_buffer)\n while frames:\n yield frames\n frames = f.readframes(frames_per_buffer)\n\n for d in buffer_generator(out):\n try:\n manager.push_data(d, finish_processing=False)\n r, r1 = manager.get_result()\n text = pretty(r)\n if text is not None:\n Outport.push(bytes(text, encoding=\"utf-8\"), \"INTERMEDIATE\")\n except Exception as msg:\n log.error(\"Exception %s\", msg)\n manager.push_data(b\"\", finish_processing=True)\n t = Thread(target=pusher, args=(manager, Outport), daemon=True)\n t.start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"asr_kaldi/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"80919070","text":"from django.shortcuts import render, render_to_response\nfrom . import models\n\n# Create your views here.\n\n\"\"\"基础数据\"\"\"\ndef BasicData(request):\n\treturn render(request, 'BasicData.html')\n\ndef Manager(request):\n\t\"\"\"管理人员\"\"\"\n\tif request.method == \"POST\":\n\t\tif request.POST['delete'] == \"True\":\n\t\t\tnumber = request.POST['number']\n\t\t\tmodels.Manager.objects.filter(number=number).delete()\n\t\telse:\n\t\t\tname = request.POST['name']\n\t\t\tnumber = request.POST['number']\n\t\t\tsex = request.POST['sex']\n\t\t\tphone_number = request.POST['phone_number']\n\t\t\tposition = request.POST['position']\n\t\t\taddress = request.POST['address']\n\t\t\tremarks = request.POST['remarks']\n\t\t\t\n\t\t\tmodels.Manager.objects.create(name = name, number = number, sex = sex, phone_number = phone_number, \n\t\t\t\tposition = position, address=\n\t\t\t\taddress, remarks = remarks)\n\tmanagers = models.Manager.objects.all()\n\treturn render_to_response('BasicData/Manager.html',{'managers':managers})\n\ndef BreedingPigHouseSetting(request):\n\t\"\"\"种猪舍设置\"\"\"\n\tif request.method == \"POST\":\n\t\tsex = request.POST['sex']\n\t\tcolumn = request.POST['column']\n\t\tbreeder = request.POST['breeder']\n\t\tremarks = request.POST['remarks']\n\t\tmodels.BreedingPigHouseSetting.objects.create(sex = sex,column = column,breeder = breeder,remarks = remarks,)\n\tBreedingPigHouseSettings = models.BreedingPigHouseSetting.objects.all()\n\treturn render_to_response('BasicData/BreedingPigHouseSetting.html',{'BreedingPigHouseSettings':BreedingPigHouseSettings})\n\ndef CustomerInfo(request):\n\t\"\"\"客户资料\"\"\"\n\tif request.method == \"POST\":\n\t\tnumber = request.POST['number']\n\t\tcategory = request.POST['category']\n\t\tclient = request.POST['client']\n\t\tlinkman = request.POST['linkman']\n\t\tphone_number = request.POST['phone_number']\n\t\taddress = request.POST['address']\n\t\tremarks = request.POST['remarks']\n\t\tmodels.CustomerInfo.objects.create(number = number,category = category,client = client,linkman = linkman,phone_number = phone_number,address = address,remarks = remarks,)\n\tCustomerInfos = models.CustomerInfo.objects.all()\n\treturn render_to_response('BasicData/CustomerInfo.html',{'CustomerInfos':CustomerInfos})\n\ndef LivePigHouseSetting(request):\n\t\"\"\"生猪舍设置\"\"\"\n\tif request.method == \"POST\":\n\t\tsex = request.POST['sex']\n\t\tcolumn = request.POST['column']\n\t\tbreeder = request.POST['breeder']\n\t\tremarks = request.POST['remarks']\n\t\tmodels.LivePigHouseSetting.objects.create(sex = sex,column = column,breeder = breeder,remarks = remarks,)\n\tLivePigHouseSettings = models.LivePigHouseSetting.objects.all()\n\treturn render_to_response('BasicData/LivePigHouseSetting.html',{'LivePigHouseSettings':LivePigHouseSettings})\n\ndef PigletHealthCareSetting(request):\n\t\"\"\"仔猪保健免疫设置\"\"\"\n\tif request.method == \"POST\":\n\t\tnumber = request.POST['number']\n\t\tname = request.POST['name']\n\t\tdays = request.POST['days']\n\t\tamount = request.POST['amount']\n\t\tmodels.PigletHealthCareSetting.objects.create(number = number,name = name,days = days,amount = amount,)\n\tPigletHealthCareSettings = models.PigletHealthCareSetting.objects.all()\n\treturn render_to_response('BasicData/PigletHealthCareSetting.html',{'PigletHealthCareSettings':PigletHealthCareSettings})\n\ndef SowHealthCareSetting(request):\n\t\"\"\"母猪保健免疫设置\"\"\"\n\tif request.method == \"POST\":\n\t\tnumber = request.POST['number']\n\t\tname = request.POST['name']\n\t\tcategory = request.POST['category']\n\t\tdays = request.POST['days']\n\t\tamount = request.POST['amount']\n\t\tmodels.SowHealthCareSetting.objects.create(number = number,name = name,category = category,days = days,amount = amount,)\n\tSowHealthCareSettings = models.SowHealthCareSetting.objects.all()\n\treturn render_to_response('BasicData/SowHealthCareSetting.html',{'SowHealthCareSettings':SowHealthCareSettings})","sub_path":"BasicData/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"651488263","text":"import math\r\nimport random\r\nclass part_a:\r\n def __init__(self):\r\n self.x_minimum = 0\r\n self.x_maximum = 2\r\n self.num_steps = 1000000\r\n self.num_points = 1000000\r\n\r\n def function(self,x):\r\n return math.sqrt((math.cos(x) ** 2) + 1)\r\n\r\n def perform_experiment(self):\r\n y_minmum = self.function(self.x_minimum)\r\n y_maximum = y_minmum\r\n\r\n for i in range(self.num_steps):\r\n x = random.randint(0,2) \r\n y = self.function(x)\r\n\r\n if y < y_minmum: \r\n y_minmum = y\r\n if y > y_maximum: \r\n y_maximum = y\r\n\r\n rect_area = (self.x_maximum - self.x_minimum) * (y_maximum - y_minmum)\r\n\r\n under_curve = 0\r\n\r\n for j in range(self.num_points):\r\n x = random.randint(0,2) \r\n y = random.randint(y_minmum,y_maximum) \r\n if self.function(x) > 0 and y > 0 and y <= self.function(x):\r\n under_curve += 1\r\n if self.function(x) < 0 and y < 0 and y >= self.function(x):\r\n under_curve += 1\r\n\r\n arera_under_the_curve = rect_area * float(under_curve) / self.num_points\r\n \r\n return arera_under_the_curve\r\nobj = part_a()\r\n\r\nprint (\" Area under the curve = \" + str(obj.perform_experiment()))\r\n","sub_path":"ddqn_version_1/tekken-automte.py","file_name":"tekken-automte.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"577896345","text":"import json\nimport logging\n\nfrom bs4 import BeautifulSoup\nfrom decimal import Decimal\n\nfrom storescraper.product import Product\nfrom storescraper.store import Store\nfrom storescraper.utils import session_with_proxy, html_to_markdown\nfrom storescraper.categories import STORAGE_DRIVE, SOLID_STATE_DRIVE, \\\n MOTHERBOARD, PROCESSOR, CPU_COOLER, RAM, VIDEO_CARD, POWER_SUPPLY, \\\n COMPUTER_CASE, MOUSE, MONITOR, TABLET, NOTEBOOK\n\n\nclass SupermexDigital(Store):\n @classmethod\n def categories(cls):\n return [\n STORAGE_DRIVE,\n SOLID_STATE_DRIVE,\n MOTHERBOARD,\n PROCESSOR,\n CPU_COOLER,\n RAM,\n VIDEO_CARD,\n POWER_SUPPLY,\n COMPUTER_CASE,\n MOUSE,\n MONITOR,\n TABLET,\n NOTEBOOK,\n ]\n\n @classmethod\n def discover_urls_for_category(cls, category, extra_args=None):\n url_extensions = [\n ['almacenamiento-interno/disco-mecanico', STORAGE_DRIVE],\n ['almacenamiento-interno/disco-solido', SOLID_STATE_DRIVE],\n ['almacenamiento-interno/m2', SOLID_STATE_DRIVE],\n ['tarjetas-madre', MOTHERBOARD],\n ['procesadores', PROCESSOR],\n ['sistema-de-enfriamiento', CPU_COOLER],\n ['memoria-ram', RAM],\n ['tarjeta-de-video', VIDEO_CARD],\n ['fuente', POWER_SUPPLY],\n ['gabinetes', COMPUTER_CASE],\n ['mouse', MOUSE],\n ['monitores', MONITOR],\n ['tablet', TABLET],\n ['laptop', NOTEBOOK],\n\n ]\n\n base_url = 'https://www.supermexdigital.mx/collections/{}?page={}'\n\n product_urls = []\n session = session_with_proxy(extra_args)\n\n for url_extension, local_category in url_extensions:\n if local_category != category:\n continue\n\n page = 1\n\n while True:\n url = base_url.format(url_extension, page)\n print(url)\n\n if page >= 15:\n raise Exception('Page overflow: ' + url)\n\n soup = BeautifulSoup(session.get(url).text, 'html.parser')\n\n product_container = soup.find('div', 'productgrid--items')\n products = product_container.findAll('div', 'productitem')\n\n if not products:\n if page == 1:\n logging.warning('Empty category: ' + url)\n break\n\n for product in products:\n product_url = 'https://www.supermexdigital.mx{}'\\\n .format(product.find('a')['href'])\n product_urls.append(product_url)\n\n page += 1\n\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n print(url)\n session = session_with_proxy(extra_args)\n\n page_source = session.get(url).text\n soup = BeautifulSoup(page_source, 'html.parser')\n\n data = json.loads(\n soup.find('script', {'data-section-id': 'static-product'}).text)\n\n variants = data['product']['variants']\n\n picture_urls = soup.findAll('figure', 'product-gallery--image')\n picture_urls = ['https:{}'.format(i.find('img')['src'])\n for i in picture_urls]\n description = html_to_markdown(\n str(soup.find('div', 'product-description')))\n\n products = []\n\n for product in variants:\n name = product['name']\n sku = product['sku']\n stock = product['inventory_quantity']\n price = Decimal(product['price']/100)\n\n products.append(\n Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n stock,\n price,\n price,\n 'MXN',\n sku=sku,\n picture_urls=picture_urls,\n description=description,\n )\n )\n\n return products\n","sub_path":"storescraper/stores/supermex_digital.py","file_name":"supermex_digital.py","file_ext":"py","file_size_in_byte":4194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"26663474","text":"# -*- coding: utf-8 -*-\n# Copyright 2014 Objectif Libre\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#\n# @author: Stéphane Albert\n#\nimport datetime\n\nfrom ceilometerclient import client as cclient\n\nfrom cloudkitty import collector\n\n\nclass CeilometerCollector(collector.BaseCollector):\n def __init__(self, **kwargs):\n super(CeilometerCollector, self).__init__(**kwargs)\n\n self._resource_cache = {}\n\n def _connect(self):\n \"\"\"Initialize connection to the Ceilometer endpoint.\"\"\"\n self._conn = cclient.get_client('2', os_username=self.user,\n os_password=self.password,\n os_auth_url=self.keystone_url,\n os_tenant_name=self.tenant,\n os_region_name=self.region)\n\n def gen_filter(self, op='eq', **kwargs):\n \"\"\"Generate ceilometer filter from kwargs.\"\"\"\n q_filter = []\n for kwarg in kwargs:\n q_filter.append({'field': kwarg, 'op': op, 'value': kwargs[kwarg]})\n return q_filter\n\n def prepend_filter(self, prepend, **kwargs):\n \"\"\"Filter composer.\"\"\"\n q_filter = {}\n for kwarg in kwargs:\n q_filter[prepend + kwarg] = kwargs[kwarg]\n return q_filter\n\n def user_metadata_filter(self, op='eq', **kwargs):\n \"\"\"Create user_metadata filter from kwargs.\"\"\"\n user_filter = {}\n for kwarg in kwargs:\n field = kwarg\n # Auto replace of . to _ to match ceilometer behaviour\n if '.' in field:\n field = field.replace('.', '_')\n user_filter[field] = kwargs[kwarg]\n user_filter = self.prepend_filter('user_metadata.', **user_filter)\n return self.metadata_filter(op, **user_filter)\n\n def metadata_filter(self, op='eq', **kwargs):\n \"\"\"Create metadata filter from kwargs.\"\"\"\n meta_filter = self.prepend_filter('metadata.', **kwargs)\n return self.gen_filter(op, **meta_filter)\n\n def get_active_instances(self, start, end=None, project_id=None,\n q_filter=None):\n \"\"\"Instance that were active during the timespan.\"\"\"\n start_iso = datetime.datetime.fromtimestamp(start).isoformat()\n req_filter = self.gen_filter(op='ge', timestamp=start_iso)\n if project_id:\n req_filter.extend(self.gen_filter(project=project_id))\n if end:\n end_iso = datetime.datetime.fromtimestamp(end).isoformat()\n req_filter.extend(self.gen_filter(op='le', timestamp=end_iso))\n if isinstance(q_filter, list):\n req_filter.extend(q_filter)\n elif q_filter:\n req_filter.append(q_filter)\n instance_stats = self._conn.statistics.list(meter_name='instance',\n period=0, q=req_filter,\n groupby=['resource_id'])\n return [instance.groupby['resource_id'] for instance in instance_stats]\n\n def get_compute(self, start, end=None, project_id=None, q_filter=None):\n active_instances = self.get_active_instances(start, end, project_id,\n q_filter)\n compute_data = []\n volume_data = {'unit': 'instance', 'qty': 1}\n for instance in active_instances:\n instance_data = {}\n instance_data['desc'] = self.get_resource_detail(instance)\n instance_data['desc']['instance_id'] = instance\n instance_data['vol'] = volume_data\n compute_data.append(instance_data)\n\n data = {}\n data['compute'] = compute_data\n return data\n\n def _strip_compute(self, data):\n res_data = {}\n res_data['name'] = data.metadata.get('display_name')\n res_data['flavor'] = data.metadata.get('flavor.name')\n res_data['vcpus'] = data.metadata.get('vcpus')\n res_data['memory'] = data.metadata.get('memory_mb')\n res_data['image_id'] = data.metadata.get('image.id')\n res_data['availability_zone'] = (\n data.metadata.get('OS-EXT-AZ.availability_zone')\n )\n\n res_data['project_id'] = data.project_id\n res_data['user_id'] = data.user_id\n\n res_data['metadata'] = {}\n for field in data.metadata:\n if field.startswith('user_metadata'):\n res_data['metadata'][field[14:]] = data.metadata[field]\n\n return res_data\n\n def strip_resource_data(self, res_data, res_type='compute'):\n if res_type == 'compute':\n return self._strip_compute(res_data)\n\n def get_resource_detail(self, resource_id):\n if resource_id not in self._resource_cache:\n resource = self._conn.resources.get(resource_id)\n resource = self.strip_resource_data(resource)\n self._resource_cache[resource_id] = resource\n return self._resource_cache[resource_id]\n","sub_path":"cloudkitty/collector/ceilometer.py","file_name":"ceilometer.py","file_ext":"py","file_size_in_byte":5512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"213006098","text":"\"\"\" Aqara Gateway remote \"\"\"\nimport logging\n\nfrom homeassistant.helpers.entity import ToggleEntity\nfrom homeassistant.helpers.debounce import Debouncer\n\nfrom . import DOMAIN, GatewayGenericDevice\nfrom .core.gateway import Gateway\nfrom .core.utils import Utils\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_entry(hass, config_entry, async_add_entities):\n \"\"\" setup config entry \"\"\"\n def setup(gateway: Gateway, device: dict, attr: str):\n async_add_entities([GatewayRemote(hass, gateway, device, attr)])\n\n aqara_gateway: Gateway = hass.data[DOMAIN][config_entry.entry_id]\n aqara_gateway.add_setup('remote', setup)\n\n\nclass GatewayRemote(GatewayGenericDevice, ToggleEntity):\n \"\"\" Gateway Remote \"\"\"\n _state = False\n\n def __init__(\n self,\n hass,\n gateway,\n device,\n attr,\n ):\n \"\"\"Initialize the Gateway Remote.\"\"\"\n self.hass = hass\n self.async_refresh_toggle = None\n super().__init__(gateway, device, attr)\n\n async def async_added_to_hass(self):\n \"\"\" add to home assistant \"\"\"\n self.async_refresh_toggle = Debouncer(\n self.hass,\n _LOGGER,\n cooldown=60,\n immediate=True,\n function=self._async_refresh_toggle,\n )\n await super().async_added_to_hass()\n\n async def _async_refresh_toggle(self):\n \"\"\"Set instance object and trigger an entity state update.\"\"\"\n self.async_write_ha_state()\n\n @property\n def is_on(self):\n \"\"\" in on \"\"\"\n return self._state\n\n @property\n def icon(self):\n \"\"\" return icon \"\"\"\n return 'mdi:zigbee'\n\n async def async_turn_on(self, **kwargs):\n \"\"\"Turn the remote on.\"\"\"\n self._state = True\n self.gateway.send(\n self.device, {'did': 'lumi.0', 'paring': 60})\n self.async_write_ha_state()\n self._state = False\n await self.async_refresh_toggle.async_call()\n\n async def async_turn_off(self, **kwargs):\n \"\"\"Turn the remote off.\"\"\"\n self._state = False\n self.gateway.send(\n self.device, {'did': 'lumi.0', 'paring': 0})\n self.async_write_ha_state()\n self.async_refresh_toggle.async_cancel()\n\n async def async_send_command(self, command, **kwargs):\n \"\"\" send command \"\"\"\n for cmd in command:\n args = cmd.split(' ')\n cmd = args[0]\n\n # for testing purposes\n if cmd == 'remove':\n did: str = kwargs['device']\n self.gateway.send(\n self.device, {'did': 'lumi.0', 'removed_did': did})\n Utils.remove_device(self.hass, did)\n elif cmd == 'paring':\n self._state = True\n self.gateway.send(\n self.device, {'did': 'lumi.0', 'paring': 60})\n self.async_write_ha_state()\n self._state = False\n await self.async_refresh_toggle.async_call()\n","sub_path":"custom_components/aqara_gateway/remote.py","file_name":"remote.py","file_ext":"py","file_size_in_byte":3037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"219214533","text":"import os\nimport logging\nimport pickle\nfrom typing import Callable, Dict\nimport matplotlib.pyplot as plt\nfrom scipy.stats import t\n\nfrom omegaconf import OmegaConf, DictConfig\n\nlog = logging.getLogger(__name__)\n\n\nfrom torch.utils.tensorboard import SummaryWriter\nimport hydra\nfrom torch.optim import *\n\nfrom src.fed_zoo import *\nfrom src.utils import *\nfrom src.centralized.centralized import Centralized as Centralizer\n\ndef reduce_results(results, reducer: Callable[[list],list], factor=1) -> Dict[str, list]:\n dev={\"loss\": [], \"accuracy\": []}\n #for each element in loss and accuracy, compute stddev of values\n rounds=len(results[0][\"loss\"])\n for r in range(rounds):\n accuracy_r = []\n loss_r = []\n for it in range(len(results)):\n loss_r.append(results[it][\"loss\"][r])\n accuracy_r.append(results[it][\"accuracy\"][r])\n dev[\"loss\"].append(factor*reducer(loss_r))\n dev[\"accuracy\"].append(factor*reducer(accuracy_r))\n return dev\n\ndef create_model(cfg: DictConfig, writer):\n if not cfg.centralized:\n return eval(cfg.fed.classname)(modelClassname=cfg.model.classname,\n optimizer=eval(cfg.optim.classname),\n optimizer_args=cfg.optim.args,\n num_clients=cfg.K,\n batchsize=cfg.B,\n fraction=cfg.C,\n local_epoch=cfg.E,\n device=cfg.device,\n writer=writer,\n dataset=cfg.dataset,\n alpha=cfg.alpha,\n max_iter_dirichlet = cfg.max_iter_dirichlet,\n rebalance = cfg.rebalance,\n additionalParams=cfg.fed.params\n )\n else:\n return Centralizer(modelClassname=cfg.model.classname,\n optimizer=eval(cfg.optim.classname),\n optimizer_args=cfg.optim.args,\n batchsize=cfg.B,\n device=cfg.device,\n writer=writer,\n dataset=cfg.dataset)\n\n\ndef check_arguments(cfg: DictConfig):\n if cfg.fit_iterations < 1:\n raise ValueError(\"At least one fitting iteration is required\")\n if cfg.n_round < 1:\n raise ValueError(\"At least one round of the algorithm is required\")\n\ndef train_fit(cfg: DictConfig, writer):\n check_arguments(cfg)\n results = [] #list of dictionaries containing the result for each iteration\n for iteration in range(cfg.fit_iterations):\n log.info(f\"Iteration: {iteration+1}/{cfg.fit_iterations}\")\n model = create_model(cfg, writer)\n if type(model) == FedSeq:\n with open(os.path.join(cfg.savedir, f\"examples_superclients.pkl\"), \"wb\") as f:\n pickle.dump(model.examples_superclients(), f)\n f.close()\n model.fit(cfg.n_round)\n results.append(model.result)\n\n \n with open(os.path.join(cfg.savedir, f\"result_iteration{iteration}.pkl\"), \"wb\") as f:\n pickle.dump(model.result, f)\n f.close()\n return results\n\ndef compute_final_result(results, method):\n if method == \"mean\":\n return reduce_results(results, np.mean)\n else:\n raise NotImplementedError\n\ndef savepickle(obj, path):\n with open(path, \"wb\") as f:\n pickle.dump(obj, f)\n f.close()\n\n\n@hydra.main(config_path=\"config\", config_name=\"config\")\ndef main(cfg: DictConfig):\n os.chdir(cfg.root)\n seed_everything(cfg.seed)\n log.info(\"\\n\" + OmegaConf.to_yaml(cfg))\n writer = SummaryWriter(log_dir=os.path.join(cfg.savedir, \"tf\"))\n \n\n #list of dictionaries {\"loss\": [], \"accuracy\": [], \"time_elapsed\": []}\n results = train_fit(cfg, writer)\n final_result = compute_final_result(results, cfg.output_result)\n savepickle(final_result, os.path.join(cfg.savedir, \"final_result.pkl\"))\n\n #dev is a dictionary {\"loss\": [], \"accuracy\": [], \"time_elapsed\": []} with std deviation for each round\n if cfg.fit_iterations >= 2:\n factor = t.ppf(cfg.confidence + (1-cfg.confidence)/2, cfg.fit_iterations-1)/np.sqrt(cfg.fit_iterations)\n dev = reduce_results(results, lambda x: np.std(x, ddof=1), factor)\n savepickle(dev, os.path.join(cfg.savedir, \"deviations.pkl\"))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"472972634","text":"import click\nfrom virl.api import VIRLServer\nfrom subprocess import call\nfrom virl import helpers\nfrom virl.cli.views.console import console_table\nimport platform\n\n\n@click.command()\n@click.argument('node', nargs=-1)\n@click.option('--display/--none',\n default='False',\n help='Display Console information')\ndef console(node, display, **kwargs):\n \"\"\"\n console for node\n \"\"\"\n server = VIRLServer()\n\n if len(node) == 2:\n # we received env and node name\n env = node[0]\n running = helpers.check_sim_running(env)\n node = node[1]\n elif display:\n # only displaying output\n env = 'default'\n running = helpers.check_sim_running(env)\n node = None\n\n elif len(node) == 1:\n # assume default env\n env = 'default'\n running = helpers.check_sim_running(env)\n node = node[0]\n else:\n # node was not specified, display usage\n exit(call(['virl', 'console', '--help']))\n\n if running:\n\n sim_name = running\n\n resp = server.get_node_console(sim_name, node=node)\n if node:\n click.secho(\"Attempting to connect to console \"\n \"of {}\".format(node))\n try:\n ip, port = resp.json()[node].split(':')\n\n # use user specified telnet command\n if 'VIRL_CONSOLE_COMMAND' in server.config:\n cmd = server.config['VIRL_CONSOLE_COMMAND']\n cmd = cmd.format(host=ip, port=port)\n print(\"Calling user specified command: {}\".format(cmd))\n exit(call(cmd.split()))\n\n # someone still uses windows\n elif platform.system() == \"Windows\":\n with helpers.disable_file_system_redirection():\n exit(call(['telnet', ip, port]))\n\n # why is shit so complicated?\n else:\n exit(call(['telnet', ip, port]))\n except AttributeError:\n click.secho(\"Could not find console info for \"\n \"{}:{}\".format(env, node), fg=\"red\")\n except KeyError:\n click.secho(\"Unknown node {}:{}\".format(env, node), fg=\"red\")\n else:\n # defaults to displaying table\n console_table(resp.json())\n","sub_path":"virl/cli/console/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"292597726","text":"import requests\nimport json\nimport time\n\nx_auth_token = '205b8aee07671127f2c9883586d62ebdd3f089d23caad41c85971d96b6de89149dbd53320b6c44c6d115b9ba647d517f659fb0fc28e95d720b4b8eeb'\n\nheader = {'x-auth-token': x_auth_token}\n\nurl = \"https://stg-api.lapelu.com.ar/api/employee\"\n\nresponse = requests.get(url, headers=header)\n\nif response.status_code == 200:\n print('Ok')\nelse:\n print('El status code no es 200')\n\nresponse_json = json.loads(response.text)\n\ntime.sleep(1)\n\nresponse1 = response_json['result']\nresponse2 = response_json['data']['employees'][0]['id']\nresponse3 = response_json['data']['employees'][0]['locations'][0]['id']\nresponse4 = response_json['data']['employees'][0]['name']\nresponse5 = response_json['data']['employees'][0]['locations'][0]['name']\nresponse6 = response_json['data']['employees'][0]['locations'][0]['brand']['id']\nresponse7 = response_json['data']['employees'][0]['locations'][0]['brand']['name']\n\ndef chequear_datos(respuesta, dato, resultado, mensaje):\n assert type(respuesta) == dato and respuesta == resultado, mensaje\n\n\nchequear_datos(response1, bool, True, 'El resultado no es el esperado')\nchequear_datos(response2, int, 265, 'El resultado no es el esperado')\nchequear_datos(response3, int, 12, 'El resultado no es el esperado')\nchequear_datos(response4, str, 'Andres Sosa', 'El resultado no es el esperado')\nchequear_datos(response5, str, 'ETTIOS', 'El resultado no es el esperado')\nchequear_datos(response6, int, 11, 'El resultado no es el esperado')\nchequear_datos(response7, str, 'ETTIOS', 'El resultado no es el esperado')\n\n","sub_path":"Api_get_la_pelu.py","file_name":"Api_get_la_pelu.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"203294215","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n#将gz文件解压为xml文件,并由dom或sax解析,最后写入csv文件\n#最新修改为读入指定个文件,解析后写入一个文件,总体来看效率提升不明显,改用cStringIO后还是不明显。\n#先改成函数调用结构,主程序和parser之前通过传递参数进行通信,避免采用全局变量带来的复杂化。\n#加入改用内存文件的sax_parser函数,运行时间为DOM方式的大约1/6,速度提升明显。\n#后续考虑多线程以及协程\n\n#导入相关模块\nimport os,gzip,time,cStringIO\nfrom os.path import join, splitext, abspath\n\n#指定每次处理多少个文件\npaser_num = -1\n#指定输入输出文件路径\ninput_path = '/tmcdata/mro2csv/input31/'\noutput_path = '/tmcdata/mro2csv/output31/'\nos.chdir(input_path)\n\n#DOM解析函数,输入gz文件,输出解析后的字符串和处理行数\ndef dom_parser(gz):\n\timport gzip,cStringIO\n\timport xml.dom.minidom\n\t\n\tvs_cnt = 0\n\tstr_s = ''\n\tfile_io = cStringIO.StringIO()\n\txm = gzip.open(gz,'rb')\n\tprint(\"已读入:%s.\\n解析中:\" % (os.path.abspath(gz)))\n\tdoc = xml.dom.minidom.parseString(xm.read())\n\tbulkPmMrDataFile = doc.documentElement\n\t#读入子元素\n\tenbs = bulkPmMrDataFile.getElementsByTagName(\"eNB\")\n\tmeasurements = enbs[0].getElementsByTagName(\"measurement\")\n\tobjects = measurements[0].getElementsByTagName(\"object\")\n\t#写入csv文件\n\tfor object in objects:\n\t\tvs = object.getElementsByTagName(\"v\")\n\t\tvs_cnt += len(vs)\n\t\tfor v in vs:\n\t\t\tfile_io.write(enbs[0].getAttribute(\"id\")+' '+object.getAttribute(\"id\")+' '+\\\n\t\t\tobject.getAttribute(\"MmeUeS1apId\")+' '+object.getAttribute(\"MmeGroupId\")+' '+object.getAttribute(\"MmeCode\")+' '+\\\n\t\t\tobject.getAttribute(\"TimeStamp\")+' '+v.childNodes[0].data+'\\n') #获取文本值\n\tstr_s = (((file_io.getvalue().replace(' \\n','\\r\\n')).replace(' ',',')).replace('T',' ')).replace('NIL','')\n\txm.close()\n\tfile_io.close()\n\treturn (str_s,vs_cnt)\n\ndef sax_parser(gz):\n\timport os,gzip,cStringIO\n\tfrom xml.parsers.expat import ParserCreate\n\n\t#变量声明\n\td_eNB = {}\n\td_obj = {}\n\ts = ''\n\tglobal flag \n\tflag = False\n\tfile_io = cStringIO.StringIO()\n\t\n\t#Sax解析类\n\tclass DefaultSaxHandler(object):\n\t\t#处理开始标签\n\t\tdef start_element(self, name, attrs):\n\t\t\tglobal d_eNB\n\t\t\tglobal d_obj\n\t\t\tglobal vs_cnt\n\t\t\tif name == 'eNB':\n\t\t\t\td_eNB = attrs\n\t\t\telif name == 'object':\n\t\t\t\td_obj = attrs\n\t\t\telif name == 'v':\n\t\t\t\tfile_io.write(d_eNB['id']+' '+ d_obj['id']+' '+d_obj['MmeUeS1apId']+' '+d_obj['MmeGroupId']+' '+d_obj['MmeCode']+' '+d_obj['TimeStamp']+' ')\n\t\t\t\tvs_cnt += 1\n\t\t\telse:\n\t\t\t\tpass\n\t\t#处理中间文本\n\t\tdef char_data(self, text):\n\t\t\tglobal d_eNB\n\t\t\tglobal d_obj\n\t\t\tglobal flag\n\t\t\tif text[0:1].isnumeric():\n\t\t\t\tfile_io.write(text)\n\t\t\telif text[0:17] == 'MR.LteScPlrULQci1':\n\t\t\t\tflag = True\n\t\t\t\t#print(text,flag)\n\t\t\telse:\n\t\t\t\tpass\n\t\t#处理结束标签\n\t\tdef end_element(self, name):\n\t\t\tglobal d_eNB\n\t\t\tglobal d_obj\n\t\t\tif name == 'v':\n\t\t\t\tfile_io.write('\\n')\n\t\t\telse:\n\t\t\t\tpass\n\t\n\t#Sax解析调用\n\thandler = DefaultSaxHandler()\n\tparser = ParserCreate()\n\tparser.StartElementHandler = handler.start_element\n\tparser.EndElementHandler = handler.end_element\n\tparser.CharacterDataHandler = handler.char_data\n\tvs_cnt = 0\n\tstr_s = ''\n\txm = gzip.open(gz,'rb')\n\tprint(\"已读入:%s.\\n解析中:\" % (os.path.abspath(gz)))\n\tfor line in xm.readlines():\n\t\tparser.Parse(line) #解析xml文件内容\n\t\tif flag:\n\t\t\tbreak\n\tstr_s = file_io.getvalue().replace(' \\n','\\r\\n').replace(' ',',').replace('T',' ').replace('NIL','')\t#写入解析后内容\n\txm.close()\n\tfile_io.close()\n\treturn (str_s,vs_cnt)\n\ndef ET_parser(gz):\n\timport os,gzip,cStringIO\n\timport xml.etree.cElementTree as ET\n\n\tvs_cnt = 0\n\tstr_s = ''\n\tfile_io = cStringIO.StringIO()\n\txm = gzip.open(gz,'rb')\n\tprint(\"已读入:%s.\\n解析中:\" % (os.path.abspath(gz)))\n\ttree = ET.ElementTree(file=xm)\n\troot = tree.getroot()\n\tfor elem in root[1][0].findall('object'):\n\t\t\tfor v in elem.findall('v'):\n\t\t\t\t\tfile_io.write(root[1].attrib['id']+' '+elem.attrib['TimeStamp']+' '+elem.attrib['MmeCode']+' '+elem.attrib['id']+' '+ elem.attrib['MmeUeS1apId']+' '+ elem.attrib['MmeGroupId']+' '+ v.text+'\\n')\n\t\t\tvs_cnt += 1\n\tstr_s = file_io.getvalue().replace(' \\n','\\r\\n').replace(' ',',').replace('T',' ').replace('NIL','')\t#写入解析后内容\n\txm.close()\n\tfile_io.close()\n\treturn (str_s,vs_cnt)\n\t\ndef ET_parser_iter(gz):\n\timport os,gzip,cStringIO\n\timport xml.etree.cElementTree as ET\n\n\tvs_cnt = 0\n\tstr_s = ''\n\tfile_io = cStringIO.StringIO()\n\txm = gzip.open(gz,'rb')\n\tprint(\"已读入:%s.\\n解析中:\" % (os.path.abspath(gz)))\n\td_eNB = {}\n\td_obj = {}\n\ti = 0\n\tfor event,elem in ET.iterparse(xm,events=('start','end')):\n\t\tif i >= 2:\n\t\t\tbreak\t\t\n\t\telif event == 'start':\n\t\t\tif elem.tag == 'eNB':\n\t\t\t\td_eNB = elem.attrib\n\t\t\telif elem.tag == 'object':\n\t\t\t\td_obj = elem.attrib\n\t\telif event == 'end' and elem.tag == 'smr':\n\t\t\ti += 1\n\t\telif event == 'end' and elem.tag == 'v':\n\t\t\tfile_io.write(d_eNB['id']+' '+d_obj['TimeStamp']+' '+d_obj['MmeCode']+' '+d_obj['id']+' '+ d_obj['MmeUeS1apId']+' '+ d_obj['MmeGroupId']+' '+str(elem.text)+'\\n')\n\t\t\tvs_cnt += 1\n\t\telem.clear()\n\tstr_s = file_io.getvalue().replace(' \\n','\\r\\n').replace(' ',',').replace('T',' ').replace('NIL','')\t#写入解析后内容\n\txm.close()\n\tfile_io.close()\n\treturn (str_s,vs_cnt)\n\ndef lxml_parser_TitleTarget(gz):\n\tfrom lxml import etree\n\tclass TitleTarget(object):\n\t\tdef __init__(self):\n\t\t\tself.text = []\n\t\t\tself.is_v = False\n\t\t\tself.eNB = {}\n\t\t\tself.obj = {}\n\t\t\tself.vs_cnt = 0\n\t\t\tself.i = 0\n\t\tdef start(self, tag, attrib):\n\t\t\tif tag == 'eNB':\n\t\t\t\tself.eNB = attrib\n\t\t\telif tag == 'smr':\n\t\t\t\tself.i += 1\n\t\t\telif tag == 'object':\n\t\t\t\tself.obj = attrib\n\t\t\telif tag == 'v':\n\t\t\t\tself.is_v = True\n\t\tdef end(self, tag):\n\t\t\tself.is_v = False\n\t\tdef data(self, data):\n\t\t\tif self.is_v and self.i < 2:\n\t\t\t\tself.text.append(self.eNB['id']+' ')\n\t\t\t\tself.text.append(self.obj['id']+' ')\n\t\t\t\tself.text.append(self.obj['MmeUeS1apId']+' ')\n\t\t\t\tself.text.append(self.obj['MmeGroupId']+' ')\n\t\t\t\tself.text.append(self.obj['MmeCode']+' ')\n\t\t\t\tself.text.append(self.obj['TimeStamp']+' ')\n\t\t\t\tself.text.append(data.strip())\n\t\t\t\tself.text.append('\\n')\n\t\t\t\tself.vs_cnt += 1\n\t\tdef close(self):\n\t\t\treturn(''.join(self.text).rstrip('\\n').replace(' ',',').replace('T',' ').replace('NIL',''),self.vs_cnt)\n\tprint(\"已读入:%s.\\n解析中:\" % (os.path.abspath(gz)))\n\tparser = etree.XMLParser(target = TitleTarget())\n\treturn etree.parse(gz, parser)\n\ndef lxml_parser_iter(gz):\n\timport os,gzip,cStringIO\n\tfrom lxml import etree\n\tvs_cnt = 0\n\tstr_s = ''\n\tfile_io = cStringIO.StringIO()\n\txm = gzip.open(gz,'rb')\n\tprint(\"已读入:%s.\\n解析中:\" % (os.path.abspath(gz)))\n\td_eNB = {}\n\td_obj = {}\n\ts_data = ''\n\ti = 0\n\tfor event,elem in etree.iterparse(xm,events=(\"start\",\"end\")):\n\t\tif i >= 2:\n\t\t\tbreak\t\t\n\t\telif event == 'start' and elem.tag == 'eNB':\n\t\t\td_eNB = elem.attrib\n\t\t\t#print(d_eNB,d_eNB['id'])\n\t\telif event == 'start' and elem.tag == 'object':\n\t\t\td_obj = elem.attrib\n\t\t\t#print(d_obj,d_obj['id'])\n\t\telif event == 'end' and elem.tag == 'smr':\n\t\t\ti += 1\n\t\telif event == 'end' and elem.tag == 'v':\n\t\t\ts_data = elem.text\n\t\t\tvs_cnt += 1\n\t\tfile_io.write(d_eNB.get('id','0')+' '+d_obj.get('TimeStamp','0')+' '+d_obj.get('MmeCode','0')+' '+d_obj.get('id','0')+' '+ d_obj.get('MmeUeS1apId','0')+' '+ d_obj.get('MmeGroupId','0')+' '+str(s_data)+'\\n')\n\t\telem.clear()\n\tstr_s = file_io.getvalue().replace(' \\n','\\r\\n').replace(' ',',').replace('T',' ').replace('NIL','')\t#写入解析后内容\n\txm.close()\n\tfile_io.close()\n\treturn (str_s,vs_cnt)\n\n#定义空列表,用于放入gz路径文件名\ngzs = []\nvs_cnt = 0\n#读入文件名到列表gzs\ngzs = [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.gz']\n#检查并纠正paser_num设置\nif paser_num < 0 or paser_num >= len(gzs):\n\tpaser_num = len(gzs)\n\nprint(\"*\"*50)\nprint(\"\\\n程序处理启动。\\\n\\n输入目录为:%s。\\\n\\n输出目录为:%s。\\\n\\n输入目录下.gz文件个数为:%d,本次处理其中的%d个。\" % (input_path,output_path,len(gzs),paser_num))\nprint(\"*\"*50)\n\n#截短gzs\ngzs = gzs[0:paser_num]\noutput = cStringIO.StringIO()\nstart_time = time.time()\ngz_cnt = 0\nfor gz in gzs:\n\tcnt = 0\n\tstr_s = ''\n\tgz_cnt += 1\n\tprint(\"文件计数:%d/%d.\" % (gz_cnt,paser_num))\n\t#str_s,cnt = dom_parser(gz)\n\t#str_s,cnt = sax_parser(gz)\n\t#str_s,cnt = ET_parser(gz)\n\t#str_s,cnt = ET_parser_iter(gz)\n\t#str_s,cnt = lxml_parser_TitleTarget(gz)\n\tstr_s,cnt = lxml_parser_iter(gz)\n\toutput.write(str_s)\n\tvs_cnt += cnt\nwith open(os.path.join(output_path,'mro_0001.csv'),'w') as t:\t\t#生成csv文件以写入数据\n\tt.write(output.getvalue())\t#写入解析后内容\n\tprint(\"VS行计数:%d,运行时间:%f,每秒处理行数:%d。\\n已写入:%s。\\n\" % (vs_cnt, time.time()-start_time, vs_cnt/(time.time()-start_time), os.path.abspath(t.name)))\noutput.close()\n\t#try:\n\t\t#os.remove(gz)\n\t\t#print(\"已删除:%s.\\n\" % os.path.abspath(gz))\n\t#except:\n\t\t#print(\"文件删除失败:%s.\\n\" % os.path.abspath(gz))\n\nprint(\"*\"*50)\nprint(\"程序处理结束。\")\n","sub_path":"linux/os_walk_dom_parser_func.py","file_name":"os_walk_dom_parser_func.py","file_ext":"py","file_size_in_byte":9035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"19049591","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom rest_framework import routers\nfrom users.models import UserSerializer, UserViewSet\nfrom track.models import AlbumSerializer, AlbumViewSet, GenreSerializer, GenreViewSet, TrackSerializer,TrackiewSet,AlbumGenreSerializer,AlbumGenreViewset\n\nadmin.autodiscover();\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet)\nrouter.register(r'genes', GenreViewSet)\nrouter.register(r'albums', AlbumViewSet)\nrouter.register(r'tracks', TrackiewSet)\nrouter.register(r'album-genre-mapping',AlbumGenreViewset)\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'musicsite.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^', include(router.urls)),\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\n)\n","sub_path":"musicsite/musicsite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"469294084","text":"import socket\nimport struct\nfrom utils.save_load import dumps, loads\n\n\ndef send_msg(sock, msg):\n msg_pickled = dumps(msg)\n sock.sendall(struct.pack(\">I\", len(msg_pickled)))\n sock.sendall(msg_pickled)\n # print(\"Sent \", msg, \" to \", sock.getpeername())\n\n\ndef recv_msg(sock):\n msg_len = struct.unpack(\">I\", sock.recv(4))[0]\n msg = sock.recv(msg_len, socket.MSG_WAITALL)\n msg = loads(msg)\n # print(\"Received\", msg, \"from\", sock.getpeername())\n return msg\n\n\ndef recv_msg_async(sock, ret: list, index):\n msg_len = struct.unpack(\">I\", sock.recv(4))[0]\n msg = sock.recv(msg_len, socket.MSG_WAITALL)\n msg = loads(msg)\n # print(\"Received\", msg, \"from\", sock.getpeername())\n ret[index] = msg\n","sub_path":"utils/messaging.py","file_name":"messaging.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"548962880","text":"# -*- coding: utf-8 -*-\n\n# __author__ = 'zhutong'\n\nfrom struct import unpack\nfrom time import timezone\n\nimport pandas as pd\n\n\ndef read_gen(rrd_filename, last=0):\n with open(rrd_filename, 'rb') as f:\n _id, size = unpack('2I', f.read(8))\n if last > size or last < 1:\n last = size\n start = _id - last\n if start < 1:\n start += size\n f.seek(start * 16)\n try:\n data = unpack('4I', f.read(16)) # get data\n if data[0] == 0: # 0 means never updated\n raise\n yield data # else this is the oldest data\n for i in xrange(last - 1):\n yield unpack('4I', f.read(16))\n except:\n f.seek(16)\n for i in xrange(1, _id):\n yield unpack('4I', f.read(16))\n\n\ndef get_df(rrd_filname):\n U, M, B = 'Unicast', 'Multicast', 'Broadcast'\n times = []\n datas = []\n for d in read_gen(rrd_filname):\n times.append(d[0])\n datas.append(d[1:])\n times = pd.to_datetime(times, unit='s')\n df = pd.DataFrame(datas, times, columns=[U, M, B])\n return df\n","sub_path":"tools/zrrdreader.py","file_name":"zrrdreader.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"331063951","text":"import smbus\nimport math\nimport time\n\n# Power management registers\npower_mgmt_1 = 0x6b\npower_mgmt_2 = 0x6c\n\ngyro_scale = 131.0\naccel_scale = 16384.0\nx_error=2.0\ny_error=5.0\n\naddress = 0x68 # This is the address value read via the i2cdetect command\n\ndef read_all():\n raw_gyro_data = bus.read_i2c_block_data(address, 0x43, 6)\n raw_accel_data = bus.read_i2c_block_data(address, 0x3b, 6)\n\n gyro_scaled_x = twos_compliment((raw_gyro_data[0] << 8) + raw_gyro_data[1]) / gyro_scale\n gyro_scaled_y = twos_compliment((raw_gyro_data[2] << 8) + raw_gyro_data[3]) / gyro_scale\n gyro_scaled_z = twos_compliment((raw_gyro_data[4] << 8) + raw_gyro_data[5]) / gyro_scale\n\n accel_scaled_x = twos_compliment((raw_accel_data[0] << 8) + raw_accel_data[1]) / accel_scale\n accel_scaled_y = twos_compliment((raw_accel_data[2] << 8) + raw_accel_data[3]) / accel_scale\n accel_scaled_z = twos_compliment((raw_accel_data[4] << 8) + raw_accel_data[5]) / accel_scale\n\n return (gyro_scaled_x, gyro_scaled_y, gyro_scaled_z, accel_scaled_x, accel_scaled_y, accel_scaled_z)\n \ndef twos_compliment(val):\n if (val >= 0x8000):\n return -((65535 - val) + 1)\n else:\n return val\n\ndef dist(a, b):\n return math.sqrt((a * a) + (b * b))\n\n\ndef get_y_rotation(x,y,z):\n radians = math.atan2(x, dist(y,z))\n return -math.degrees(radians)\n\ndef get_x_rotation(x,y,z):\n radians = math.atan2(y, dist(x,z))\n return math.degrees(radians)\n\nbus = smbus.SMBus(1) # or bus = smbus.SMBus(0) for Revision 1 boards\n\n# Now wake the 6050 up as it starts in sleep mode\nbus.write_byte_data(address, power_mgmt_1, 0)\n\nnow = time.time()\n\nk = 0.85\nk1 = 1 - k\n\ndtime = 0\n\n(gyro_scaled_x, gyro_scaled_y, gyro_scaled_z, accel_scaled_x, accel_scaled_y, accel_scaled_z) = read_all()\n\nlast_x = get_x_rotation(accel_scaled_x, accel_scaled_y, accel_scaled_z)\nlast_y = get_y_rotation(accel_scaled_x, accel_scaled_y, accel_scaled_z)\n\n#for calibration----\nx_error=2.0\ny_error=5.0\nangvelerrorz=gyro_scaled_z\n\n#for calibration----\n\n\nwhile 1:\n \n \n (gyro_scaled_x, gyro_scaled_y, gyro_scaled_z, accel_scaled_x, accel_scaled_y, accel_scaled_z) = read_all()\n \n rotation_x = get_x_rotation(accel_scaled_x, accel_scaled_y, accel_scaled_z)\n rotation_y = get_y_rotation(accel_scaled_x, accel_scaled_y, accel_scaled_z)\n\n dtime=time.time()-now\n\n now=time.time()\n \n last_x=(k*(last_x+(gyro_scaled_x*dtime)))+(k1*rotation_x)\n last_y=(k*(last_y+(gyro_scaled_x*dtime)))+(k1*rotation_y)\n\n angle_x=last_x\n angle_y=last_y\n\n linacc_x=accel_scaled_x-(math.sin(math.radians(angle_x)))\n linacc_y=accel_scaled_y-(math.sin(math.radians(angle_y)))\n angularVelocity_z=gyro_scaled_z-angvelerrorz\n\n print (round(angle_x),round(angle_y),round(linacc_x),round(linacc_y),round(angularVelocity_z))\n \n","sub_path":"Quadcopter_project_iiest/mpu6050/working modules/alloutputmpu.py","file_name":"alloutputmpu.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"559649185","text":"import torch\r\nimport torch.nn as nn\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\n\r\n# 如果有GPU,则使用GPU加速\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n# 定义初始化神经网络的权重——标准正态分布\r\ndef weights_init_uniform(m):\r\n classname = m.__class__.__name__\r\n # for every Linear layer in a model..\r\n if classname.find('Linear') != -1:\r\n # apply a uniform distribution to the weights and a bias=0\r\n m.weight.data.uniform_(0.0, 1.0)\r\n m.bias.data.fill_(0)\r\n\r\n# 超参数的设置\r\nnum_epochs = 100\r\nbatch_size = 100\r\nlearning_rate = 0.001\r\n\r\n# Cifar10 Dataset 数据集\r\ntrain_dataset = torchvision.datasets.CIFAR10(root='./cifar10', #指定数据集的目录\r\n train=True, transform=transforms.Compose([transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406],\r\n [0.229, 0.224, 0.225])]),download=True)\r\ntest_dataset = torchvision.datasets.CIFAR10(root='./cifar10',\r\n train=False,\r\n transform=transforms.Compose([transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406],\r\n [0.229, 0.224, 0.225])]),download=True)\r\n\r\n# Data loader\r\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\r\n batch_size=batch_size,\r\n shuffle=True) #shuffle:在每个Epoch中打乱数据\r\n\r\ntest_loader = torch.utils.data.DataLoader(dataset=test_dataset,\r\n batch_size=batch_size,\r\n shuffle=False)\r\n\r\n# 两个有400个线性修正激活单元的隐藏层的大网络——student\r\nclass NeuralNet_stu(nn.Module):\r\n def __init__(self):\r\n super(NeuralNet_stu, self).__init__()\r\n self.fc1 = nn.Linear(32*32*3, 400) # 输入层->隐藏层1\r\n self.fc2 = nn.Linear(400, 400) # 隐藏层1->隐藏层2\r\n self.fc3 = nn.Linear(400, 10) # 隐藏层2->输出层\r\n def forward(self, x):\r\n out = self.fc1(x)\r\n out = self.fc2(out)\r\n out = self.fc3(out)\r\n return out\r\n\r\n# 如果有GPU,则使用GPU加速\r\nmodel = NeuralNet_stu().apply(weights_init_uniform).to(device)\r\n# 交叉熵和随机梯度下降优化器\r\ncriterion = nn.CrossEntropyLoss()\r\n# Adam自带变化的学习率,所以就没有用SGD,懒得动态更改学习率了\r\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\r\n\r\n# 训练模型\r\ntotal_step = len(train_loader)\r\nfor epoch in range(num_epochs):\r\n for i, (images, labels) in enumerate(train_loader):\r\n # 将变量添加到GPU里面,如果有加速\r\n images = images.reshape(-1, 32 * 32 *3).to(device)\r\n labels = labels.to(device)\r\n # 前馈计算Loss\r\n outputs = model(images)\r\n loss = criterion(outputs, labels)\r\n # 反馈计算梯度\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n # 输出loss\r\n if (i + 1) % 100 == 0:\r\n print('Epoch [{}/{}], Step [{}/{}], Loss: {:.8f}'\r\n .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))\r\n\r\n\r\n# 测试模型\r\nwith torch.no_grad():\r\n correct = 0\r\n total = 0\r\n for images, labels in test_loader:\r\n images = images.reshape(-1, 32 * 32*3).to(device)\r\n labels = labels.to(device)\r\n outputs = model(images)\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += labels.size(0)\r\n correct += (predicted == labels).sum().item()\r\n\r\n print('Accuracy of the network on the 10000 test images: {} %'.format(100 * correct / total))\r\n\r\n\r\n\r\n","sub_path":"models/CIFAR_FC_StuNet.py","file_name":"CIFAR_FC_StuNet.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"163870483","text":"from flask import Flask,render_template,url_for,request,redirect\napp = Flask(__name__)\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlite_setup import Base,MenuItem,Restaurant\n\nengine = create_engine('sqlite:///restaurantmenu.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n# This is testing\n@app.route('/items')\ndef Helloworld():\n restaurant = session.query(Restaurant).first()\n items = session.query(MenuItem).filter_by(restaurant_id = restaurant.id)\n output = ''\n for i in items:\n output += i.name\n output += ''\n output += ''\n return output\n\n@app.route('/restaurant//')\ndef FindRestaurantMenuByID(restaurant_id):\n restaurant = session.query(Restaurant).filter_by(id = restaurant_id).one()\n items = session.query(MenuItem).filter_by(restaurant_id = restaurant.id)\n return render_template('menu.html',restaurant = restaurant,items = items)\n\n\n#Task 1: Create route for newMenuItem function here\n@app.route('/restaurant//new/', methods = ['GET','POST'])\ndef newMenuItem(restaurant_id):\n if(request.method == 'POST'):\n newItem = MenuItem(name = request.form['name'],restaurant_id = restaurant_id )\n session.add(newItem)\n session.commit()\n return redirect(url_for('FindRestaurantMenuByID',restaurant_id = restaurant_id))\n else:\n return render_template('newmenuitem.html',restaurant_id = restaurant_id)\n \n\n#Task 2: Create route for editMenuItem function here\n@app.route('/restaurant///edit', methods = ['GET', 'POST'])\ndef editMenuItem(restaurant_id, MenuID):\n editedItem = session.query(MenuItem).filter_by(id = MenuID).one()\n if request.method == 'POST':\n if request.form['name']:\n editedItem.name = request.form['name']\n session.add(editedItem)\n session.commit()\n return redirect(url_for('FindRestaurantMenuByID', restaurant_id = restaurant_id))\n else:\n \n #USE THE RENDER_TEMPLATE FUNCTION BELOW TO SEE THE VARIABLES YOU SHOULD USE IN YOUR EDITMENUITEM TEMPLATE\n return render_template('editmenuitem.html', restaurant_id = restaurant_id, MenuID = MenuID, item = editedItem)\n \n#Task 3: Create a route for deleteMenuItem function here\n@app.route('/restaurant///delete/')\ndef deleteMenuItem(restaurant_id, MenuID):\n return \"page to delete a new menu item. Task 3 complete!\"\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host = '0.0.0.0', port = 5000)","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"72631492","text":"from sympy import *\nfrom sympy.printing import print_ccode\nfrom math import pi\n\na, b, c, d, e, x = symbols('a b c d e x')\n\nsine = (a*x**2 + b*x + c + d*x**-1 + e*x**-2)\nsine_d = diff(sine, x)\nsine_i = integrate(sine, x)\n\nthe_system = [\n sine_i.subs(x, pi) - sine_i.subs(x, -pi/2) - 1,\n sine_d.subs(x, pi) + 1,\n sine_d.subs(x, pi / 2),\n\tsine.subs(x, pi) - 0,\n sine.subs(x, pi / 2) - 1\n]\n\nres = solve(the_system, (a, b, c, d, e))\n\nfor var, exp in res.items():\n print(var, exp)\n","sub_path":"exp/cpp_sine/sin_model/sin_model_complex.py","file_name":"sin_model_complex.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"488431194","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"Usage:\nimages.py [options]\nimages.py scrap [options]\nimages.py features [options]\nimages.py references [options]\nimages.py visualize [options]\n\n\nOptions:\n--uri= Only process this serie, defaults to process all\n\n* main: do 'scrap', 'features' and 'references'\n* scrap: Get images from IMDB character's page given a list of urls and character's names\n (following the format of `characters.txt` described in CONTRIBUTING.md)\n* features: Then extracts features off theses images.\n* references: Then cluster image features, tag clusters based on image caption\n and compute average embedding for (labelled) cluster to keep as reference\n* visualize: same as 'references' but saves figure with cropped faces\n\"\"\"\n\nimport json\nfrom pathlib import Path\n\n# Dependencies\nfrom docopt import docopt\nfrom image_features import *\nfrom image_scraping import main as scrap\n\nimport Plumcot as PC\n\n# Hyperparameters\n\n## core\nN_COL = 5 # the CHARACTERS file should have 5 columns, separated by SEPARATOR\nSEPARATOR = \",\"\n\nDATA_PATH = Path(PC.__file__).parent / \"data\"\nIMAGE_FORMAT = \"jpg\"\n\n## web\nIMDB_URL = \"https://www.imdb.com\"\nTHUMBNAIL_CLASS = \"titlecharacters-image-grid__thumbnail-link\"\nIMAGE_CLASS = \"pswp__img\"\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n uri = args['--uri']\n main = not (args['scrap'] or args['features'] or args['references'] or args[\n 'visualize'])\n with open(os.path.join(DATA_PATH, \"series.txt\")) as file:\n series = file.readlines()\n for serie in series:\n SERIE_URI, _, SERIE_IMDB_URL, _, _ = serie.split(\",\")\n if SERIE_URI != uri and uri is not None:\n continue\n if SERIE_IMDB_URL == '': # film -> open episode:\n SERIE_IMDB_URL = np.loadtxt(\n os.path.join(DATA_PATH, SERIE_URI, 'episodes.txt'), dtype=str,\n delimiter=SEPARATOR)[:, 2]\n else: # only one but turn it to a list so we can iterate it\n SERIE_IMDB_URL = [SERIE_IMDB_URL]\n CHARACTERS_PATH = os.path.join(DATA_PATH, SERIE_URI, 'characters.txt')\n IMAGE_PATH = Path(DATA_PATH, SERIE_URI, 'images')\n if args['scrap'] or main:\n scrap(SERIE_URI, SERIE_IMDB_URL, IMAGE_PATH, CHARACTERS_PATH, N_COL,\n SEPARATOR, IMAGE_FORMAT)\n if args['features'] or main:\n with open(os.path.join(IMAGE_PATH, \"images.json\"), \"r\") as file:\n image_jsons = json.load(file)\n image_jsons = compute_features(image_jsons, MODEL_NAME, DLIB_LANDMARKS,\n DLIB_EMBEDDING)\n with open(os.path.join(IMAGE_PATH, \"images.json\"), \"w\") as file:\n json.dump(image_jsons, file)\n if args['references'] or main:\n with open(os.path.join(IMAGE_PATH, \"images.json\"), \"r\") as file:\n image_jsons = json.load(file)\n image_jsons = compute_references(image_jsons, IMAGE_PATH,\n CLUSTERING_THRESHOLD,\n CLUSTERING_METHOD, KEEP_IMAGE_TYPES,\n keep_faces=False)\n with open(os.path.join(IMAGE_PATH, \"images.json\"), \"w\") as file:\n json.dump(image_jsons, file)\n if args['visualize'] or main:\n with open(os.path.join(IMAGE_PATH, \"images.json\"), \"r\") as file:\n image_jsons = json.load(file)\n image_jsons = compute_references(image_jsons, IMAGE_PATH,\n CLUSTERING_THRESHOLD,\n CLUSTERING_METHOD, KEEP_IMAGE_TYPES,\n keep_faces=True)\n with open(os.path.join(IMAGE_PATH, \"images.json\"), \"w\") as file:\n json.dump(image_jsons, file)\n","sub_path":"scripts/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":3879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"505886486","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 26 19:15:16 2015\n\nWrite an algorithm to bring all non-zero elements to the left of the array and \nreturns the number of non-zero elements\n\n@author: mac\n\"\"\"\n\n'''\n========= O(2n) =========\n'''\n# Function which pushes all zeros to end of an array.\ndef pushZerosToEnd(arr,n):\n count = 0; #Count of non-zero elements\n \n # Traverse the array. If element encountered is non-zero, then\n # replace the element at index 'count' with this element\n for i in range(n):\n if arr[i] != 0:\n count+=1 # here count is incremented\n arr[count-1] = arr[i]\n print (arr)\n noncount=count\n ## Now all non-zero elements have been shifted to front and 'count' is\n # set as index of first 0. Make all elements 0 from count to end.\n while (count < n):\n count+=1\n arr[count-1] = 0\n print (arr)\n return noncount\n\n\n\n \n# Driver program to test above function\ndef main():\n \n #=========\n arr = [1, 0, 2, 0, 0, 3, 4,0,9]\n n = len(arr)\n print(pushZerosToEnd(arr, n))\n print( \"Array with all zeros at end : \",arr)\n \nmain()\n\n\n'''\n========= O(n) =========\n'''\ndef move_nonzero_to_left(lst):\n nonzero_count = 0\n for index, value in enumerate(lst):\n if value:\n if index != nonzero_count:\n lst[nonzero_count], lst[index] = value, 0\n nonzero_count += 1\n print(lst)\n return nonzero_count, lst\n\n\n# Test checking that it works\n\nprint(move_nonzero_to_left([0,0,0,1]))\n\nimport unittest\n\nclass TestCase(unittest.TestCase):\n\n def test_move_nonzero_to_left(self):\n counter, lst = move_nonzero_to_left([ 1, 0, 2, 0, 0, 3, 4, 0,9 ])\n self.assertEqual(counter, 5)\n self.assertEqual(lst, [1, 2, 3, 4, 9, 0, 0, 0, 0] )\n print (counter)\nunittest.main()\n","sub_path":"Interview_MoveAllZeroesToEndOfArray.py","file_name":"Interview_MoveAllZeroesToEndOfArray.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"38530958","text":"#coding:utf-8\n__author__ = 'jmh081701'\nimport json\nfrom matplotlib import pyplot as plt\nimport numpy as np\nwith open(r\"data.file\") as fp:\n ipid_sequences=json.load(fp)\ncolor=['r','black','b','g','q']\nfor i in range(len(ipid_sequences)):\n each=ipid_sequences[i]\n print(len(each))\n each=np.array(each)\n plt.scatter(each[:,1],each[:,0],marker=\"+\")\nplt.xlabel(\"relative arrive time(s)\")\nplt.ylabel(\"tcp source port (1)\")\nplt.ylim(1024,70000)\n\nplt.show()\nexit(0)\n'''\nwith open(\"..\\\\CaptureEstimator\\\\CaptureEstimator\\\\sample_entropy.data\") as fp:\n sample_entroy=json.load(fp)\n\nwith open(\"..\\\\CaptureEstimator\\\\CaptureEstimator\\\\benchmark_entropy.data\") as fp:\n benchmark=json.load(fp)\nx=[]\ny=[]\nfor i in range(len(benchmark)-1):\n x.append(i)\n y.append(abs(sample_entroy[i]-benchmark[i]))\n#plt.plot(x,sample_entroy,label=\"sample entropy\")\n#plt.plot(x,benchmark,label=\"benchmark entropy\")\nplt.subplot(2,1,1)\nplt.plot(x,y,label=\"abs(sample entropy-benchmark)\")\nplt.legend(loc=\"upper center\")\n\nplt.subplot(2,1,2)\nplt.hist(y,bins=256,histtype=\"barstacked\",label=\"histogram\")\n\nplt.show()\n'''","sub_path":"tool/data_visible.py","file_name":"data_visible.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"629991135","text":"import os\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nfrom copy import deepcopy\nfrom math import floor, sqrt\nfrom typing import Iterator, List, Optional, Tuple, cast\nfrom urllib.parse import urlparse\n\nimport numpy as np\nimport rasterio\nfrom numpy.ma import MaskedArray\nfrom rasterio.io import DatasetReader, DatasetWriter\nfrom rasterio.vrt import WarpedVRT\nfrom rasterio.warp import transform_bounds\nfrom rasterio.windows import Window, bounds, from_bounds, union\nfrom retrying import retry\n\nfrom gfw_pixetl import get_module_logger\nfrom gfw_pixetl.decorators import SubprocessKilledError, lazy_property, processify\nfrom gfw_pixetl.errors import retry_if_rasterio_io_error\nfrom gfw_pixetl.grids import Grid\nfrom gfw_pixetl.layers import RasterSrcLayer\nfrom gfw_pixetl.models.named_tuples import InputBandElement\nfrom gfw_pixetl.models.types import Bounds\nfrom gfw_pixetl.settings.gdal import GDAL_ENV\nfrom gfw_pixetl.settings.globals import GLOBALS\nfrom gfw_pixetl.sources import RasterSource\nfrom gfw_pixetl.tiles import Tile\nfrom gfw_pixetl.utils import (\n available_memory_per_process_bytes,\n available_memory_per_process_mb,\n get_co_workers,\n snapped_window,\n)\nfrom gfw_pixetl.utils.aws import download_s3\nfrom gfw_pixetl.utils.gdal import create_multiband_vrt, create_vrt, just_copy_geotiff\nfrom gfw_pixetl.utils.google import download_gcs\nfrom gfw_pixetl.utils.path import create_dir, from_vsi\nfrom gfw_pixetl.utils.utils import create_empty_file, enumerate_bands, fetch_metadata\n\nLOGGER = get_module_logger(__name__)\n\nWindows = Tuple[Window, Window]\n\n\nclass RasterSrcTile(Tile):\n def __init__(self, tile_id: str, grid: Grid, layer: RasterSrcLayer) -> None:\n super().__init__(tile_id, grid, layer)\n self.layer: RasterSrcLayer = layer\n\n @lazy_property\n def src(self) -> RasterSource:\n LOGGER.debug(f\"Finding input files for tile {self.tile_id}\")\n\n input_bands: List[List[InputBandElement]] = list()\n for i, band in enumerate(self.layer.input_bands):\n input_elements: List[InputBandElement] = list()\n for f in band:\n if self.dst[self.default_format].geom.intersects(\n f.geometry\n ) and not self.dst[self.default_format].geom.touches(f.geometry):\n LOGGER.debug(\n f\"Adding {f.uri} to input files for tile {self.tile_id}\"\n )\n\n if self.layer.process_locally:\n uri = self._download_source_file(f.uri)\n input_file = InputBandElement(\n uri=uri, geometry=f.geometry, band=f.band\n )\n else:\n input_file = InputBandElement(\n uri=f.uri, geometry=f.geometry, band=f.band\n )\n\n input_elements.append(input_file)\n if band and not input_elements:\n LOGGER.debug(\n f\"No input files found for tile {self.tile_id} \"\n f\"in band {i}, padding VRT with empty file\"\n )\n # But we need to know the profile of the tile's siblings in this band.\n _, profile = fetch_metadata(band[0].uri)\n empty_file_uri = create_empty_file(self.work_dir, profile)\n empty_file_element = InputBandElement(\n geometry=None, band=band[0].band, uri=empty_file_uri\n )\n input_elements.append(empty_file_element)\n input_bands.append(input_elements)\n\n if all([item.geometry is None for sublist in input_bands for item in sublist]):\n raise Exception(\n f\"Did not find any intersecting files for tile {self.tile_id}\"\n )\n\n return RasterSource(\n create_multiband_vrt(input_bands, vrt=self.tile_id + \".vrt\")\n )\n\n def _download_source_file(self, remote_file: str) -> str:\n \"\"\"Download remote files.\"\"\"\n\n download_constructor = {\"gs\": download_gcs, \"s3\": download_s3}\n\n path = from_vsi(remote_file)\n parts = urlparse(path)\n\n local_file = os.path.join(self.work_dir, \"input\", parts.netloc, parts.path[1:])\n create_dir(os.path.dirname(local_file))\n\n LOGGER.debug(\n f\"Downloading remote file {remote_file} to {local_file} using {parts.scheme}\"\n )\n download_constructor[parts.scheme](\n bucket=parts.netloc, key=parts.path[1:], dst=local_file\n )\n\n return local_file\n\n @lazy_property\n def intersecting_window(self) -> Window:\n dst_left, dst_bottom, dst_right, dst_top = self.dst[self.default_format].bounds\n\n src_left, src_bottom, src_right, src_top = self.src.reproject_bounds(\n self.grid.crs\n )\n\n left = max(dst_left, src_left)\n bottom = max(dst_bottom, src_bottom)\n right = min(dst_right, src_right)\n top = min(dst_top, src_top)\n\n LOGGER.debug(\n f\"Final bounds for window for tile {self.tile_id}: \"\n f\"Left: {left} Bottom: {bottom} Right: {right} Top: {top}\"\n )\n\n try:\n window: Window = rasterio.windows.from_bounds(\n left,\n bottom,\n right,\n top,\n transform=self.dst[self.default_format].transform,\n )\n except rasterio.errors.WindowError:\n LOGGER.error(\n f\"WindowError encountered for tile {self.tile_id} with \"\n f\"transform {self.dst[self.default_format].transform} \"\n f\"SRC bounds {src_left, src_bottom, src_right, src_top} \"\n f\"and DST bounds {dst_left, dst_bottom, dst_right, dst_top}\"\n )\n raise\n\n return snapped_window(window)\n\n def within(self) -> bool:\n \"\"\"Check if target tile extent intersects with source extent.\"\"\"\n return (\n # must intersect, but we don't want geometries that only share an exterior point\n self.dst[self.default_format].geom.intersects(self.layer.geom)\n and not self.dst[self.default_format].geom.touches(self.layer.geom)\n )\n\n def transform(self) -> bool:\n \"\"\"Write input data to output tile.\"\"\"\n LOGGER.debug(f\"Transform tile {self.tile_id}\")\n\n try:\n has_data: bool = self._process_windows()\n\n # creating gdal-geotiff and computing stats here\n # instead of in a separate stage to assure we don't run out of memory\n # the transform stage uses all available memory for concurrent processes.\n # Having another stage which needs a lot of memory might cause the process to crash\n if has_data:\n self.postprocessing()\n\n except SubprocessKilledError as e:\n LOGGER.exception(e)\n self.status = \"failed - subprocess was killed\"\n has_data = True\n except Exception as e:\n LOGGER.exception(e)\n self.status = \"failed\"\n has_data = True\n\n return has_data\n\n def _src_to_vrt(self) -> Tuple[DatasetReader, WarpedVRT]:\n chunk_size = (self._block_byte_size() * self._max_blocks(),)\n with rasterio.Env(\n **GDAL_ENV,\n VSI_CACHE_SIZE=chunk_size, # Cache size for current file.\n CPL_VSIL_CURL_CHUNK_SIZE=chunk_size, # Chunk size for partial downloads\n ):\n src: DatasetReader = rasterio.open(self.src.uri)\n\n transform, width, height = self._vrt_transform(\n *self.src.reproject_bounds(self.grid.crs)\n )\n vrt = WarpedVRT(\n src,\n crs=self.dst[self.default_format].crs,\n transform=transform,\n width=width,\n height=height,\n warp_mem_limit=available_memory_per_process_mb(),\n resampling=self.layer.resampling,\n )\n\n return src, vrt\n\n def _process_windows(self) -> bool:\n\n # In case we have more workers than cores we can further subdivide the read process.\n # In that case we will need to write the windows into separate files\n # and merging them into one file at the end of the write process\n co_workers: int = get_co_workers()\n if co_workers >= 2:\n has_data: bool = self._process_windows_parallel(co_workers)\n\n # Otherwise we just read the entire image in one process\n # and write directly to target file.\n else:\n has_data = self._process_windows_sequential()\n\n return has_data\n\n def _process_windows_parallel(self, co_workers) -> bool:\n \"\"\"Process windows in parallel and write output into separate files.\n\n Create VRT of output files and copy results into final GTIFF\n \"\"\"\n LOGGER.info(f\"Processing tile {self.tile_id} with {co_workers} co_workers\")\n\n has_data = False\n out_files: List[str] = list()\n\n with ProcessPoolExecutor(max_workers=co_workers) as executor:\n future_to_window = {\n executor.submit(self._parallel_transform, window): window\n for window in self.windows()\n }\n for future in as_completed(future_to_window):\n out_file = future.result()\n if out_file is not None:\n out_files.append(out_file)\n\n if out_files:\n # merge all data into one VRT and copy to target file\n vrt_name: str = os.path.join(self.tmp_dir, f\"{self.tile_id}.vrt\")\n create_vrt(out_files, extent=self.bounds, vrt=vrt_name)\n just_copy_geotiff(\n vrt_name,\n self.local_dst[self.default_format].uri,\n self.dst[self.default_format].profile,\n )\n # Clean up tmp files\n for f in out_files:\n LOGGER.debug(f\"Delete temporary file {f}\")\n os.remove(f)\n has_data = True\n\n return has_data\n\n def _process_windows_sequential(self) -> bool:\n \"\"\"Read one window after another and update target file.\"\"\"\n LOGGER.info(f\"Processing tile {self.tile_id} with a single worker\")\n\n src: DatasetReader\n vrt: WarpedVRT\n\n src, vrt = self._src_to_vrt()\n out_files = list()\n try:\n for window in self.windows():\n out_files.append(self._processified_transform(vrt, window))\n finally:\n vrt.close()\n src.close()\n\n has_data = any(value is not None for value in out_files)\n\n return has_data\n\n def _parallel_transform(self, window) -> Optional[str]:\n \"\"\"When transforming in parallel, we need to read SRC and create VRT in\n every process.\"\"\"\n src: DatasetReader\n vrt: WarpedVRT\n\n src, vrt = self._src_to_vrt()\n\n try:\n out_file: Optional[str] = self._processified_transform(vrt, window, True)\n finally:\n vrt.close()\n src.close()\n\n return out_file\n\n @processify\n def _processified_transform(\n self, vrt: WarpedVRT, window: Window, write_to_seperate_files=False\n ) -> Optional[str]:\n \"\"\"Wrapper to run _transform in a separate process.\n\n This will make sure that memory gets completely cleared once a\n window is processed. Without this, we might experience memory\n leakage, in particular for float data types.\n \"\"\"\n return self._transform(vrt, window, write_to_seperate_files)\n\n def _transform(\n self, vrt: WarpedVRT, window: Window, write_to_seperate_files=False\n ) -> Optional[str]:\n \"\"\"Read windows from input VRT, reproject, resample, transform and\n write to destination.\"\"\"\n masked_array: MaskedArray = self._read_window(vrt, window)\n LOGGER.debug(\n f\"Masked Array size for tile {self.tile_id} when read: {masked_array.nbytes / 1000000} MB\"\n )\n if self._block_has_data(masked_array):\n LOGGER.debug(f\"{window} of tile {self.tile_id} has data - continue\")\n masked_array = self._calc(masked_array, window)\n LOGGER.debug(\n f\"Masked Array size for tile {self.tile_id} after calc: {masked_array.nbytes / 1000000} MB\"\n )\n array: np.ndarray = self._set_dtype(masked_array, window)\n LOGGER.debug(\n f\"Array size for tile {self.tile_id} after set dtype: {masked_array.nbytes / 1000000} MB\"\n )\n del masked_array\n out_file: Optional[str] = self._write_window(\n array, window, write_to_seperate_files\n )\n del array\n\n else:\n LOGGER.debug(f\"{window} of tile {self.tile_id} has no data - skip\")\n del masked_array\n out_file = None\n return out_file\n\n def windows(self) -> List[Window]:\n \"\"\"Creates local output file and returns list of size optimized windows\n to process.\"\"\"\n LOGGER.debug(f\"Create local output file for tile {self.tile_id}\")\n with rasterio.Env(**GDAL_ENV):\n with rasterio.open(\n self.get_local_dst_uri(self.default_format),\n \"w\",\n **self.dst[self.default_format].profile,\n ) as dst:\n windows = [window for window in self._windows(dst)]\n self.set_local_dst(self.default_format)\n\n return windows\n\n def _windows(self, dst: DatasetWriter) -> Iterator[Window]:\n \"\"\"Divides raster source into larger windows which will still fit into\n memory.\"\"\"\n\n block_count: int = int(sqrt(self._max_blocks()))\n x_blocks: int = int(dst.width / dst.block_shapes[0][0])\n y_blocks: int = int(dst.height / dst.block_shapes[0][1])\n\n for i in range(0, x_blocks, block_count):\n for j in range(0, y_blocks, block_count):\n max_i = min(i + block_count, x_blocks)\n max_j = min(j + block_count, y_blocks)\n window = self._union_blocks(dst, i, j, max_i, max_j)\n try:\n yield snapped_window(window.intersection(self.intersecting_window))\n except rasterio.errors.WindowError as e:\n e_str = str(e)\n if \"Bounds and transform are inconsistent\" in e_str:\n # FIXME: This check was introduced recently in rasterio\n # Figure out what it means to fail, and fix the window\n # generating code in this function\n LOGGER.warning(\n f\"Bogus window generated for tile {self.tile_id}! \"\n f\"i: {i} j: {j} max_i: {max_i} max_j: {max_j} window: {window}\"\n )\n elif \"Intersection is empty Window\" in e_str:\n # Seems harmless to skip empty windows we generate\n continue\n elif \"windows do not intersect\" in e_str:\n # Hmm, should this happen? Log for further investigation\n LOGGER.warning(\n f\"Non-intersecting windows generated for tile {self.tile_id}! \"\n f\"i: {i} j: {j} max_i: {max_i} max_j: {max_j} window: {window}\"\n )\n else:\n raise\n\n def _block_has_data(self, band_arrays: MaskedArray) -> bool:\n \"\"\"Check if current block has any data.\"\"\"\n size = 0\n for i, masked_array in enumerate(band_arrays):\n msk = np.invert(masked_array.mask.astype(bool))\n data_pixels = msk[msk].size\n size += data_pixels\n LOGGER.debug(\n f\"Block of tile {self.tile_id}, band {i+1} has {data_pixels} data pixels\"\n )\n return band_arrays.shape[1] > 0 and band_arrays.shape[2] > 0 and size != 0\n\n def _calc(self, array: MaskedArray, dst_window: Window) -> MaskedArray:\n \"\"\"Apply user defined calculation on array.\"\"\"\n if self.layer.calc:\n # Assign a variable name to each band\n band_names = \", \".join(enumerate_bands(len(array)))\n funcstr = (\n f\"def f({band_names}) -> MaskedArray:\\n return {self.layer.calc}\"\n )\n LOGGER.debug(\n f\"Apply function {funcstr} on block {dst_window} of tile {self.tile_id}\"\n )\n exec(funcstr, globals())\n array = f(*array) # type: ignore # noqa: F821\n\n # assign band index\n if len(array.shape) == 2:\n array = array.reshape(1, *array.shape)\n else:\n if array.shape[0] != self.dst[self.default_format].profile[\"count\"]:\n raise RuntimeError(\n \"Output band count does not match desired count. Calc function must be wrong.\"\n )\n else:\n LOGGER.debug(\n f\"No user defined formula provided. Skip calculating values for {dst_window} of tile {self.tile_id}\"\n )\n return array\n\n def _max_blocks(self) -> int:\n \"\"\"Calculate the maximum amount of blocks we can fit into memory,\n making sure that blocks can always fill a squared extent.\n\n We can only use a fraction of the available memory per process\n per block b/c we might have multiple copies of the array at the\n same time. Using a divisor of 8 leads to max memory usage of\n about 75%.\n \"\"\"\n\n # Adjust divisor to band count\n divisor = GLOBALS.divisor\n\n # Float data types seem to need more memory.\n if np.issubdtype(\n self.dst[self.default_format].dtype, np.floating\n ) or np.issubdtype(self.src.dtype, np.floating):\n divisor *= 2\n LOGGER.debug(\"Divisor doubled for float data\")\n\n # Float64s require even more?\n if (\n self.dst[self.default_format].dtype == np.dtype(\"float64\")\n ) or self.src.dtype == np.dtype(\"float64\"):\n divisor *= 2\n LOGGER.debug(\"Divisor doubled again for float64 data\")\n\n # Multiple layers need more memory\n divisor *= self.layer.band_count\n\n # Decrease block size if we have co-workers.\n # This way we can process more blocks in parallel.\n co_workers = get_co_workers()\n if co_workers >= 2:\n divisor *= co_workers\n LOGGER.debug(\"Divisor multiplied for multiple workers\")\n\n # further reduce block size in case we need to perform additional computations\n if self.layer.calc is not None:\n divisor **= 2\n LOGGER.debug(\"Divisor squared for calc operations\")\n\n LOGGER.debug(f\"Divisor set to {divisor} for tile {self.tile_id}\")\n\n block_byte_size: int = self._block_byte_size()\n memory_per_process: float = available_memory_per_process_bytes() / divisor\n\n # make sure we get a number whose sqrt is a whole number\n max_blocks: int = max(1, floor(sqrt(memory_per_process / block_byte_size)) ** 2)\n\n LOGGER.debug(\n f\"Maximum number of blocks for tile {self.tile_id} to read at once: {max_blocks}. \"\n f\"Expected max chunk size: {max_blocks * block_byte_size} B.\"\n )\n\n return max_blocks\n\n def _block_byte_size(self):\n\n shape = (\n len(self.layer.input_bands),\n self.dst[self.default_format].blockxsize,\n self.dst[self.default_format].blockysize,\n )\n\n dst_block_byte_size = np.zeros(\n shape, dtype=self.dst[self.default_format].dtype\n ).nbytes\n src_block_byte_size = np.zeros(shape, dtype=self.src.dtype).nbytes\n max_block_byte_size = max(dst_block_byte_size, src_block_byte_size)\n LOGGER.debug(f\"Block byte size is {max_block_byte_size/ 1000000} MB\")\n\n return max_block_byte_size\n\n @retry(\n retry_on_exception=retry_if_rasterio_io_error,\n stop_max_attempt_number=7,\n wait_exponential_multiplier=1000,\n wait_exponential_max=300000,\n ) # Wait 2^x * 1000 ms between retries by to 300 sec, then 300 sec afterwards.\n def _read_window(self, vrt: WarpedVRT, dst_window: Window) -> MaskedArray:\n \"\"\"Read window of input raster.\"\"\"\n dst_bounds: Bounds = bounds(dst_window, self.dst[self.default_format].transform)\n window = vrt.window(*dst_bounds)\n\n src_bounds = transform_bounds(\n self.dst[self.default_format].crs, self.src.crs, *dst_bounds\n )\n\n LOGGER.debug(\n f\"Read {dst_window} for Tile {self.tile_id} - this corresponds to bounds {src_bounds} in source\"\n )\n\n shape = (\n len(self.layer.input_bands),\n int(round(dst_window.height)),\n int(round(dst_window.width)),\n )\n\n try:\n return vrt.read(\n window=window,\n out_shape=shape,\n masked=True,\n )\n except rasterio.RasterioIOError as e:\n if \"Access window out of range\" in str(e) and (\n shape[1] == 1 or shape[2] == 1\n ):\n LOGGER.warning(\n f\"Access window out of range while reading {dst_window} for Tile {self.tile_id}. \"\n \"This is most likely due to subpixel misalignment. \"\n \"Returning empty array instead.\"\n )\n return np.ma.array(\n data=np.zeros(shape=shape), mask=np.ones(shape=shape)\n )\n\n else:\n LOGGER.warning(\n f\"RasterioIO error while reading {dst_window} for Tile {self.tile_id}. \"\n \"Will make attempt to retry.\"\n )\n raise\n\n def _reproject_dst_window(self, dst_window: Window) -> Window:\n \"\"\"Reproject window into same projection as source raster.\"\"\"\n\n dst_bounds: Bounds = bounds(\n window=dst_window,\n transform=self.dst[self.default_format].transform,\n height=self.grid.blockysize,\n width=self.grid.blockxsize,\n )\n src_bounds: Bounds = transform_bounds(\n self.dst[self.default_format].crs, self.src.crs, *dst_bounds\n )\n\n src_window: Window = from_bounds(*src_bounds, transform=self.src.transform)\n LOGGER.debug(\n f\"Source window for {dst_window} of tile {self.tile_id} is {src_window}\"\n )\n return src_window\n\n def _set_dtype(self, array: MaskedArray, dst_window) -> np.ndarray:\n \"\"\"Update data type to desired output datatype Update nodata value to\n desired nodata value (current no data values will be updated and any\n values which already has new no data value will stay as is)\"\"\"\n if self.dst[self.default_format].nodata is None:\n LOGGER.debug(f\"Set datatype for {dst_window} of tile {self.tile_id}\")\n array = array.data.astype(self.dst[self.default_format].dtype)\n elif isinstance(self.dst[self.default_format].nodata, list):\n LOGGER.debug(\n f\"Set datatype for entire array and no data value for each band for {dst_window} of tile {self.tile_id}\"\n )\n # make mypy happy. not sure why the isinstance check above alone doesn't do it\n nodata_list = cast(list, self.dst[self.default_format].nodata)\n array = np.array(\n [np.ma.filled(array[i], nodata) for i, nodata in enumerate(nodata_list)]\n ).astype(self.dst[self.default_format].dtype)\n\n else:\n LOGGER.debug(\n f\"Set datatype and no data value for {dst_window} of tile {self.tile_id}\"\n )\n array = np.ma.filled(array, self.dst[self.default_format].nodata).astype(\n self.dst[self.default_format].dtype\n )\n\n return array\n\n def _vrt_transform(\n self, west: float, south: float, east: float, north: float\n ) -> Tuple[rasterio.Affine, float, float]:\n \"\"\"Compute Affine transformation, width and height for WarpedVRT using\n output CRS and pixel size.\"\"\"\n\n LOGGER.debug(f\"Output Bounds {west, south, east, north}\")\n north, west = self.grid.snap_coordinates(north, west)\n south, east = self.grid.snap_coordinates(south, east)\n\n transform: rasterio.Affine = rasterio.transform.from_origin(\n west, north, self.grid.xres, self.grid.yres\n )\n width = round((east - west) / self.grid.xres)\n height = round((north - south) / self.grid.yres)\n\n LOGGER.debug(f\"Output Affine and dimensions {transform}, {width}, {height}\")\n return transform, width, height\n\n @staticmethod\n def _union_blocks(\n dst: DatasetWriter, min_i: int, min_j: int, max_i: int, max_j: int\n ) -> Window:\n \"\"\"Loops over selected blocks of data source and merges their windows\n into one.\"\"\"\n windows: List[Window] = list()\n\n for i in range(min_i, max_i):\n for j in range(min_j, max_j):\n windows.append(dst.block_window(1, i, j))\n return union(*windows)\n\n def _write_window(\n self, array: np.ndarray, dst_window: Window, write_to_separate_files: bool\n ) -> str:\n if write_to_separate_files:\n out_file: str = self._write_window_to_separate_file(array, dst_window)\n else:\n out_file = self._write_window_to_shared_file(array, dst_window)\n return out_file\n\n def _write_window_to_shared_file(\n self, array: np.ndarray, dst_window: Window\n ) -> str:\n \"\"\"Write blocks into output raster.\"\"\"\n with rasterio.Env(**GDAL_ENV):\n with rasterio.open(\n self.local_dst[self.default_format].uri,\n \"r+\",\n **self.dst[self.default_format].profile,\n ) as dst:\n LOGGER.debug(f\"Write {dst_window} of tile {self.tile_id}\")\n dst.write(array, window=dst_window)\n del array\n return self.local_dst[self.default_format].uri\n\n def _write_window_to_separate_file(\n self, array: np.ndarray, dst_window: Window\n ) -> str:\n\n file_name = f\"{self.tile_id}_{dst_window.col_off}_{dst_window.row_off}.tif\"\n file_path = os.path.join(self.tmp_dir, file_name)\n\n profile = deepcopy(self.dst[self.default_format].profile)\n transform = rasterio.windows.transform(dst_window, profile[\"transform\"])\n profile.update(\n width=dst_window.width, height=dst_window.height, transform=transform\n )\n\n with rasterio.Env(**GDAL_ENV):\n with rasterio.open(\n file_path,\n \"w\",\n **profile,\n ) as dst:\n LOGGER.debug(\n f\"Write {dst_window} of tile {self.tile_id} to separate file {file_path}\"\n )\n dst.write(array)\n del array\n return file_path\n","sub_path":"gfw_pixetl/tiles/raster_src_tile.py","file_name":"raster_src_tile.py","file_ext":"py","file_size_in_byte":27293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"256297176","text":"class Solution(object):\n\n def removeDuplicates(self, nums):\n \"\"\"\n 从排序数组中删除重复项\n 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。\n 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。\n :type nums: List[int]\n :rtype: int\n \"\"\"\n d = {}\n for i, elem in enumerate(nums):\n d[elem] = i \n nums[:] = sorted(list(d.keys()))\n \n def maxProfit(self, prices):\n \"\"\"\n 买卖股票的最佳时机 II\n 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。\n 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。\n :type prices: List[int]\n :rtype: int\n \"\"\"\n m = 0\n for i in range(len(prices)-1):\n delta = prices[i+1] - prices[i]\n if delta > 0:\n m += delta\n return m\n\n def rotate(self, nums, k):\n \"\"\"\n 旋转数组\n 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数\n :type nums: List[int]\n :type k: int\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n l = len(nums)\n k = k % l if l else 0\n if k == 0:\n pass\n else:\n nums[:] = nums[-k:] + nums[:-k]\n # print(nums)\n \n def containsDuplicate(self, nums):\n \"\"\"\n 存在重复\n 给定一个整数数组,判断是否存在重复元素。\n 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n return len(list(set(nums))) != len(nums)\n \n def singleNumber(self, nums):\n \"\"\"\n 只出现一次的数字\n 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。\n :type nums: List[int]\n :rtype: int\n \"\"\"\n nums = sorted(nums)\n i = 0\n single = nums[0]\n isSingle = True\n while i < (len(nums)-1):\n while nums[i+1] == single:\n i += 1\n isSingle = False\n if isSingle:\n return single\n else:\n i = i+1\n single = nums[i]\n isSingle = True\n return single\n\n def intersect(self, nums1, nums2):\n \"\"\"\n 两个数组的交集 II\n 给定两个数组,编写一个函数来计算它们的交集。\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n s = set(nums1) & set(nums2)\n l = {}\n r = {}\n for n in nums1:\n if n in s:\n l[n] = l.get(n, 0) + 1\n for n in nums2:\n if n in s:\n r[n] = r.get(n, 0) + 1\n result = []\n for key in l:\n min = l[key] if l[key] < r[key] else r[key]\n result.extend([key for i in range(min)])\n return result\n\n def plusOne(self, digits):\n \"\"\"\n 加一\n 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。\n 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。\n 你可以假设除了整数 0 之外,这个整数不会以零开头。\n :Input [1,2,3]\n :Output [1,2,4]\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n l = len(digits)\n digits.reverse()\n i = 0\n while i <= l:\n if digits[i] < 9:\n digits[i] += 1\n digits.reverse()\n return digits\n elif i < l and digits[i] == 9:\n digits[i] = 0\n i += 1\n if i == l:\n digits.append(0)\n return list(digits)\n \n def moveZeroes(self, nums):\n \"\"\"\n 移动零\n 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。\n :Input [0,1,0,3,12]\n :Output [1,3,12,0,0]\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n c = []\n count = 0\n for i in nums:\n if i == 0:\n count += 1\n else:\n c.append(i)\n c.extend([0 for i in range(count)])\n nums[:] = c[:]\n\n def twoSum(self, nums, target):\n \"\"\"\n 两数之和\n 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。\n 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n nums_dict = {}\n for i,a in enumerate(nums):\n if a in nums_dict:\n return [nums_dict[a], i]\n else:\n nums_dict[target-a] = i","sub_path":"juniorAlgorithm/array.py","file_name":"array.py","file_ext":"py","file_size_in_byte":5409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"378961367","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 25 22:30:59 2019\n\n@author: Jean\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\n#Load Spacy packages\nimport spacy\nfrom spacy.lang.en.stop_words import STOP_WORDS\nnlp = spacy.load(\"en_core_web_sm\")\nimport string\nfrom spacy.lang.en import English\n\nfrom sklearn.base import TransformerMixin \nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import train_test_split\n\n\n\n\n\n\ndf = pd.read_json(\"Sarcasm_Headlines_Dataset.json\",lines=True)\npred_data = pd.read_json(\"Sarcasm_Headlines_Dataset_v2.json\",lines=True)\n\nX =df.headline\ny = df.is_sarcastic\n\nstopwords = list(STOP_WORDS)\n\n# Ponctuations if string model\npunctuations = string.punctuation\n\n# Creating spacy parser\nparser = English()\n\n#Spacy tokeniZation function\ndef spacy_tokenizer(sentence):\n mytokens = parser(sentence)\n mytokens = [ word.lemma_.lower().strip() if word.lemma_ != \"-PRON-\" else word.lower_ for word in mytokens ]\n mytokens = [ word for word in mytokens if word not in stopwords and word not in punctuations ]\n return mytokens\n\n#spacy_tokenizer('')\n#Costum transformer using spacy\nclass predictors(TransformerMixin):\n def transform(self, X, **transform_params):\n return [clean_text(text) for text in X]\n def fit(self, X, y=None, **fit_params):\n return self\n def get_params(self, deep=True):\n return {}\n \n \n#Function to clean text\ndef clean_text(text):\n return text.strip().lower()\n\n# Vectorization\nvectorizer = TfidfVectorizer(tokenizer = spacy_tokenizer, ngram_range=(1,1))\n\n# Pipeline\npipe = Pipeline([(\"cleaner\", predictors()),\n ('vectorizer', vectorizer),])\n \nX=pipe.fit_transform(X)\ny = y.values\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n\n#importing the keras libaries and packages\nimport keras\nfrom keras.models import Sequential # for initialising our ANN\nfrom keras.layers import Dense #use to create the layers in our ANN\nfrom keras.layers import Dropout #if we have overfitting\n\n#Initialising the ANN\nclassifier = Sequential()\n\n#Adding the input layer and the first hidden layer with dropout\nclassifier.add(Dense(units=6, kernel_initializer= 'uniform', activation ='relu', input_dim=19445))\nclassifier.add(Dropout(p = 0.1)) #if we still have overfitting we can increase the value of p\n\n#Adding the second hidden layer with dropout\nclassifier.add(Dense(units=6, kernel_initializer= 'uniform', activation ='relu'))\nclassifier.add(Dropout(p = 0.1)) #\n\n#Adding the output layer\nclassifier.add(Dense(units=1, kernel_initializer= 'uniform', activation ='sigmoid')) #choose softmax function if more than two classes\n\n#Compiling the ANN by adding stochastic Gradient Descent (we choose Adam one)\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\n\n# Fitting th ANN to the Training set\nclassifier.fit(X_train, y_train,batch_size = 10, epochs= 100)\n\n# Predicting the Test set results\ny_pred = classifier.predict(X_test)\ny_pred = (y_pred > 0.5)\n\n# Making the Confusion Matrix\nfrom sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_test, y_pred)","sub_path":"sd.py","file_name":"sd.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"72023693","text":"# -*- coding: utf-8 -*-\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nclass Graph():\n \n def __init__(self, route):\n self.route = route\n \n def __lshift__(self, other):\n '''Merging two objects'''\n postfix = other.route.split('/')[-1].split('.')[0]\n other.data = other.data.rename(columns={i: i+'_'+postfix for i in other.data.columns})\n self.data = pd.concat((self.data, other.data), axis=1)\n \n \n def plot(self, col, names, xlab='', ylab='', xscale=None, yscale=None, figsize=(20,10), grid=True, colors=['green', 'violet'], \n linewidth=4.0, alpha=0.5, fontsize=24, ylabel='left', xtickslabels=[0], ytickslabels=[0], zeroline=0, \n location='best', legend_font=0, x_axis=[], handlelength=None, save=None):\n '''\n Function plots several dos on one figure\n ----------\n data : list of DataFrames \n col : list of columns that should be plot in respective DataFrame\n names : list of names for each plot\n xlab, ylab : signature of axis :: should be str\n yscale (xscale) : scale on the ordinat (absciss) axis :: tuple\n colors : list with colors for each curves\n alpha : coefficient intensity for filling under curves\n '''\n# plt.style.use('dark_background')\n plt.figure(figsize=figsize)\n if grid:\n plt.grid('grey', linestyle='--', linewidth=0.5)\n if ylabel == 'right':\n plt.tick_params(axis='y', labelleft='off', labelright='on', labelsize=fontsize-2)\n else:\n plt.tick_params(axis='y', labelleft='on', labelright='off', labelsize=fontsize-2)\n plt.ylabel(ylab, fontsize=fontsize)\n if len(xlab) > 0:\n plt.xlabel(xlab, fontsize=fontsize)\n plt.tick_params(axis='x', labelsize=fontsize-2)\n else:\n plt.xticks(fontsize=0)\n l = len(col)\n \n cns = self.data.columns\n \n if len(x_axis) == 0:\n x_axis = [cns[0]] * l\n \n \n for i in range(l):\n plt.plot(self.data[x_axis[i]], self.data[col[i]], colors[i], linewidth=linewidth)\n plt.fill_between(self.data[x_axis[i]], self.data[col[i]], color=colors[i], alpha=alpha)\n# if xscale:\n# plt.xlim(xscale)\n# # Вычисление верхней границы оси ординат\n# cor = 1.1 * self.data[col[i]][self.data[cns[0]] < xscale[1]][self.data[cns[0]] > xscale[0]].max()\n# if cor > ylim:\n# ylim = cor\n# plt.ylim(0, ylim)\n if legend_font == -1: legend_font = fontsize\n plt.legend(names, loc=location, fontsize=legend_font, handlelength=handlelength)\n \n if len(ytickslabels) == 0:\n plt.yticks(fontsize=0)\n else:\n plt.yticks(ytickslabels)\n \n if len(xtickslabels) == 0:\n plt.xticks(fontsize=0)\n \n if zeroline:\n plt.plot(self.data[cns[0]], np.zeros(len(self.data[cns[0]])), 'black', lw =0.5)\n plt.xlim(min(self.data[cns[0]]), max(self.data[cns[0]]))\n \n if xscale:\n plt.xlim(xscale)\n \n if yscale:\n plt.ylim(yscale)\n \n if save:\n plt.savefig(save, dpi=512)\n plt.close()\n\n##################################################\n##################################################\nclass Xas(Graph):\n def __init__(self, route):\n self.route = route\n self.data = self._convert()\n \n def get_columns(self):\n return self.data.columns\n \n def _convert(self):\n _file = [i.strip() for i in open(self.route)]\n s, gamma = [float(i.split(' ')[-1]) for i in _file[:2]]\n data = [map(float, i.split()) for i in _file[2:]]\n df = pd.DataFrame(data, columns=['Energy', 'Intensity'] + ['y' + str(i) for i in range(2, len(data[0]))])\n return df\n \n##################################################\n##################################################\nclass Optic(Graph):\n \n def __init__(self, route):\n '''\n route :: route to file\n '''\n self.route = route\n self.data = self._convert()\n \n def get_columns(self):\n '''\n Return columns names of your DataFrame\n '''\n return self.data.columns\n \n def _convert(self):\n f = open(self.route, 'r')\n _title = [next(f).split() for _ in range(3)]\n title = [_title[1][1]] + _title[1][3:]\n data = [map(float, line.split()) for line in f]\n df = pd.DataFrame(data=data, columns=title)\n return df\n\n##################################################\n##################################################\nclass Dos(Graph):\n def __init__(self, route, name, num):\n '''\n route :: route to file\n name :: name of *dos?ev file\n num :: number of *.dos?ev files\n '''\n self.route = route\n self.num = num \n self.name = name\n self.data = self._merge()\n \n def get_columns(self):\n '''\n Return columns names of your DataFrame\n '''\n return list(self.data.columns)\n \n def convert_dos(self, route):\n '''\n Mapping dos-file в DataFrame\n '''\n f = open(route)\n _title = [next(f).strip() for _ in range(3)] \n title = _title[2][1:].replace('-', '_').replace(':', '_').split()\n title = [title[i] if not title[i][0].isdigit() else title[i][2:] + title[i][0:1] for i in range(len(title))]\n data = [map(float, line.split()) for line in f]\n df = pd.DataFrame(data=data, columns=title)\n return df\n\n def _merge(self):\n '''\n Collect all DataFrame into big one\n '''\n routes_dos = [self.route + '/' + self.name + '.dos' + str(i) + 'ev' for i in range(1, self.num + 1)]\n dfs = [self.convert_dos(i) for i in routes_dos]\n data = dfs[0]\n for i in range(self.num):\n data = pd.merge(data, dfs[i])\n return data\n \n##################################################\n##################################################","sub_path":"example/plot_wien2k.py","file_name":"plot_wien2k.py","file_ext":"py","file_size_in_byte":6284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"613994580","text":"import requests\nfrom pymongo import MongoClient\nimport ftplib\nimport time\n\ndef get_pol_state(dic):\n if dic['disabled']==1:\n return 'Disabled'\n elif dic['delisted']==1:\n return 'Delisted'\n elif dic['frozen']==1:\n return 'Frozen'\n else:\n return 'Active'\n\ndef to_html(data):\n f=open('C:\\\\Users\\\\Home\\\\Documents\\\\TradeBotv2\\\\results\\\\index.html','w')\n header='''\n \n Cryto Coins Data (DEV) \n \n \n \n \n \n Crypto coins consolidated list
\n Сontains consolidated information from cryptoid.info and poloniex public API. Last update %s \n Click the header to sort
'''%(time.ctime(time.time()))\n \n f.write(header)\n title='''
\n \n \n Name \n Tag \n Difficulty \n Algorithm \n Trading on Poloniex \n Capitalization(In BTC) \n '''\n f.write(title)\n for i in data:\n if i[0]!='Verium':\n if i[4] is not False:\n str2=(''+i[0]+' '+i[1]+' '+str(i[2])+' '+i[3]+' '+str(i[4])+' '+str(round(i[5],8))+' ')\n f.write(str2)\n else:\n str1=(''+i[0]+' '+i[1]+' '+str(i[2])+' '+i[3]+' '+'No Trading'+' '+str(round(i[5],8))+' ')\n f.write(str1)\n f.write('
')\n \ndef get_coin():\n url='http://chainz.cryptoid.info/explorer/api.dws?q=summary'\n client = MongoClient()\n db=client.pol\n coins=db.coins\n response = requests.get(url)\n raw_coins=response.json()\n for i in raw_coins.keys():\n coins.insert_one({'tag':i,'algorithm':raw_coins[i]['PoW'],'difficulty24':raw_coins[i]['diff'],'supply':raw_coins[i]['supply'],'btcprice':raw_coins[i]['ticker'].get('btc',0),'name':raw_coins[i]['name']})\n\n\ndef init_pol_pairs():\n client = MongoClient()\n db=client.pol\n pairs=db.curinces\n url='https://poloniex.com/public?command=returnCurrencies'\n res=requests.get(url)\n raw_pairs=res.json()\n for i in raw_pairs.keys():\n pairs.insert_one({'tag':i.lower(),'state':get_pol_state(raw_pairs[i])})\n \ndef build_top():\n data=[]\n client = MongoClient()\n db=client.pol\n coins=db.coins\n curinces=db.curinces\n pipeline=[{\"$project\":{\"name\":1,\"tag\":1,\"algorithm\":1,'difficulty24':1,'market_cap':{ '$multiply': [ \"$difficulty24\", \"$btcprice\" ] }}},\n {\"$sort\":{\"difficulty24\":1}}]\n raw=coins.aggregate(pipeline)\n for i in raw:\n m=curinces.find_one({'tag': i['tag']})\n if type(m) is dict:\n data.append([i['name'],i['tag'],i['difficulty24'],i['algorithm'],m['state'],i['market_cap']])\n else:\n data.append([i['name'],i['tag'],i['difficulty24'],i['algorithm'],False,i['market_cap']])\n return data\n \n#get_coin()\n#init_pol_pairs()\ndt=build_top()\nto_html(dt)\n\n \n \n","sub_path":"clist.py","file_name":"clist.py","file_ext":"py","file_size_in_byte":3442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"125451964","text":"import genomepy\nimport os\nimport pytest\n\nfrom stat import S_IREAD, S_IRGRP, S_IROTH\nfrom genomepy.provider import ProviderBase\n\n\n# to ignore file changes\n# git update-index --assume-unchanged tests/data/small_genome.fa.gz\n# to recheck file changes\n# git update-index --no-assume-unchanged tests/data/small_genome.fa.gz\ndef test_genome__init__(genome=\"tests/data/small_genome.fa.gz\"):\n # no fasta file\n with pytest.raises(FileNotFoundError):\n genomepy.Genome(\"empty\", \"tests/data/genome\")\n\n # genome dir not found\n with pytest.raises(FileNotFoundError):\n genomepy.Genome(\"unknown\", \"unknown\")\n\n readme = \"tests/data/README.txt\"\n if os.path.exists(readme):\n os.unlink(readme)\n\n g = genomepy.Genome(genome)\n assert g.genomes_dir == genomepy.utils.get_genomes_dir(None, False)\n assert g.name == \"small_genome\"\n assert g.filename == os.path.abspath(genome)\n assert g.genome_dir == os.path.dirname(g.filename)\n assert os.path.exists(g.index_file)\n assert os.path.exists(g.sizes_file)\n assert os.path.exists(g.gaps_file)\n assert isinstance(g.sizes, dict)\n assert isinstance(g.gaps, dict)\n assert g.annotation_gtf_file is None\n assert g.annotation_bed_file is None\n assert g.tax_id == g.assembly_accession == \"na\"\n assert isinstance(g.plugin, dict)\n\n\ndef test__parse_name(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome) # unimportant\n\n # name\n name = g._parse_name(\"test\")\n assert name == \"test\"\n\n # file\n name = g._parse_name(\"/home/genomepy/genomes/test2.fa\")\n assert name == \"test2\"\n\n # url\n name = g._parse_name(\"http://ftp.xenbase.org/pub/Genomics/JGI/Xentr9.1/XT9_1.fa.gz\")\n assert name == \"XT9_1\"\n\n\ndef test__parse_filename(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome) # unimportant\n\n # file path\n filename = g._parse_filename(genome)\n assert filename == os.path.abspath(genome)\n\n # folder path\n filename = g._parse_filename(os.path.dirname(genome))\n assert filename == os.path.abspath(genome)\n\n # name of genome in genomes_dir\n os.mkdir(\"tests/data/small_genome\")\n with open(\"tests/data/small_genome/small_genome.fa.gz\", \"w\") as fa:\n fa.write(\"test\")\n g.genomes_dir = \"tests/data/\"\n filename = g._parse_filename(os.path.basename(genome))\n assert filename == \"tests/data/small_genome/small_genome.fa.gz\"\n genomepy.utils.rm_rf(\"tests/data/small_genome\")\n\n # genome not found\n with pytest.raises(FileNotFoundError):\n g._parse_filename(\"does not exist\")\n\n\ndef test_check_annotation_file(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # does not exist\n gtf = g.check_annotation_file(\"gtf\")\n assert gtf is None\n\n # does exist\n path = \"tests/data/small_genome.annotation.test.gz\"\n with open(path, \"w\") as fa:\n fa.write(\"test\")\n test = g.check_annotation_file(\"test\")\n assert test == os.path.abspath(path)\n os.unlink(path)\n\n\ndef test__update_provider(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # can't parse url\n metadata = {}\n g._update_provider(metadata)\n assert metadata.get(\"provider\") == \"Unknown\"\n\n # can parse url\n metadata = {\n \"genome url\": \"https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/146/465/\"\n \"GCF_000146465.1_ASM14646v1/GCF_000146465.1_ASM14646v1_genomic.fna.gz\"\n }\n g._update_provider(metadata)\n assert metadata.get(\"provider\") == \"NCBI\"\n\n\ndef test__update_tax_id(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # genome not found\n metadata = {}\n g._update_tax_id(metadata)\n assert metadata[\"tax_id\"] == \"na\"\n\n # genome found\n metadata = {}\n provider = ProviderBase.create(\"NCBI\")\n genome = provider.genomes.get(\"ASM14646v1\")\n\n g._update_tax_id(metadata, provider, genome)\n assert metadata[\"tax_id\"] == \"58839\"\n\n\ndef test__update_assembly_accession(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # genome not found\n metadata = {}\n g._update_assembly_accession(metadata)\n assert metadata[\"assembly_accession\"] == \"na\"\n\n # genome found\n metadata = {}\n provider = ProviderBase.create(\"NCBI\")\n genome = provider.genomes.get(\"ASM14646v1\")\n\n g._update_assembly_accession(metadata, provider, genome)\n assert metadata[\"assembly_accession\"] == \"GCA_000146465.1\"\n\n\ndef test__update_metadata(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n metadata = {\"provider\": \"NCBI\", \"original name\": \"ASM14646v1\"}\n g._update_metadata(metadata)\n assert metadata[\"tax_id\"] == \"58839\"\n assert metadata[\"assembly_accession\"] == \"GCA_000146465.1\"\n\n\ndef test__read_metadata(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n\n # no readme found\n readme = g.readme_file\n if os.path.exists(readme):\n os.unlink(readme)\n metadata = g._read_metadata()\n assert metadata[\"provider\"] == \"na\"\n\n # no overwrites to metadata\n with open(readme, \"w\") as f:\n f.writelines(\"provider: not_really_NCBI\\n\")\n f.writelines(\"tax_id: not_really_58839\\n\")\n f.writelines(\"assembly_accession: not_really_GCA_000146465.1\\n\")\n metadata = g._read_metadata()\n assert metadata[\"provider\"] == \"not_really_NCBI\"\n\n # updates to metadata dict and file\n with open(readme, \"w\") as f:\n f.writelines(\n \"genome url: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/\"\n \"146/465/GCF_000146465.1_ASM14646v1/\"\n \"GCF_000146465.1_ASM14646v1_genomic.fna.gz\\n\"\n )\n f.writelines(\"tax_id: not_really_58839\\n\")\n f.writelines(\"assembly_accession: not_really_GCA_000146465.1\\n\")\n metadata1 = g._read_metadata()\n assert metadata1[\"provider\"] == \"NCBI\"\n metadata2, _ = genomepy.utils.read_readme(readme)\n assert metadata2[\"provider\"] == \"NCBI\"\n\n # no writing permission to file\n with open(readme, \"w\") as f:\n f.writelines(\n \"genome url: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/000/\"\n \"146/465/GCF_000146465.1_ASM14646v1/\"\n \"GCF_000146465.1_ASM14646v1_genomic.fna.gz\\n\"\n )\n os.chmod(readme, S_IREAD | S_IRGRP | S_IROTH)\n metadata1 = g._read_metadata()\n assert metadata1[\"provider\"] == \"na\"\n os.unlink(readme)\n\n\ndef test__bed_to_seqs(\n genome=\"tests/data/small_genome.fa.gz\", track=\"tests/data/regions.bed\"\n):\n g = genomepy.Genome(genome)\n\n # extract sequences marked in regions.bed from small_genome.fa.gz\n seqs = g._bed_to_seqs(track=track, stranded=False, extend_up=0, extend_down=0)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20 gene_a\", \"chrII:20-30 gene_b\"][i]\n assert seq.seq == [\"CCCACACACC\", \"TCCTCCAAGC\"][i]\n\n # second sequence is on the negative strand\n seqs = g._bed_to_seqs(track=track, stranded=True, extend_up=0, extend_down=0)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20 gene_a\", \"chrII:20-30 gene_b\"][i]\n # original: \"CCCACACACC\", \"TCCTCCAAGC\"\n assert seq.seq == [\"CCCACACACC\", \"GCTTGGAGGA\"][i]\n\n # extend by varying amounts\n seqs = g._bed_to_seqs(track=track, stranded=True, extend_up=1, extend_down=2)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20 gene_a\", \"chrII:20-30 gene_b\"][i]\n # original: \"CCCACACACC\", \"GCTTGGAGGA\"\n assert seq.seq == [\"ACCCACACACCCA\", \"GGCTTGGAGGAGA\"][i]\n\n\ndef test__region_to_seq(genome=\"tests/data/small_genome.fa.gz\", region=\"chrI:10-20\"):\n g = genomepy.Genome(genome)\n\n # extract sequences marked in track from small_genome.fa.gz\n seq = g._region_to_seq(region=region, extend_up=0, extend_down=0)\n assert seq == \"CCCACACACC\"\n\n # extend by varying amounts\n seq = g._region_to_seq(region=region, extend_up=1, extend_down=2)\n # original: \"CCCACACACC\"\n assert seq == \"ACCCACACACCCA\"\n\n\ndef test__regions_to_seqs(\n genome=\"tests/data/small_genome.fa.gz\", track=\"tests/data/regions.txt\"\n):\n g = genomepy.Genome(genome)\n\n # extract sequences marked in regions.bed from small_genome.fa.gz\n seqs = g._regions_to_seqs(track=track, extend_up=0, extend_down=0)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20\", \"chrII:20-30\"][i]\n assert seq.seq == [\"CCCACACACC\", \"TCCTCCAAGC\"][i]\n\n # extend by varying amounts\n seqs = g._regions_to_seqs(track=track, extend_up=1, extend_down=2)\n for i, seq in enumerate(seqs):\n assert seq.name == [\"chrI:10-20\", \"chrII:20-30\"][i]\n # original: \"CCCACACACC\", \"TCCTCCAAGC\"\n assert seq.seq == [\"ACCCACACACCCA\", \"CTCCTCCAAGCCC\"][i]\n\n\ndef test_get_track_type():\n tracks = [\n ((\"chr1:10-20\", \"chr2:10-20\"), \"interval\"),\n ([\"chr1:10-20\", \"chr2:10-20\"], \"interval\"),\n (\"tests/data/regions.txt\", \"interval\"),\n (\"tests/data/regions.bed\", \"bed\"),\n (\"tests/data/regions2.bed\", \"bed\"),\n ]\n\n for track, track_type in tracks:\n result = genomepy.Genome.get_track_type(track)\n assert result == track_type\n\n\ndef test_track2fasta(genome=\"tests/data/small_genome.fa.gz\"):\n tracks = [\n (\"tests/data/regions.txt\", \"interval\"),\n (\"tests/data/regions.bed\", \"bed\"),\n ]\n g = genomepy.Genome(genome)\n\n for i, track in enumerate(tracks):\n seq = g.track2fasta(\n track=track[0],\n fastafile=None,\n stranded=False,\n extend_up=i,\n extend_down=i + 1,\n )\n\n # default sequence: CCCACACACC\n if i == 0: # extend up +0, down -1\n assert seq[0].seq == \"CCCACACACCC\"\n assert seq[1].seq == \"TCCTCCAAGCC\"\n else: # extend up +1, down -4\n assert seq[0].seq == \"ACCCACACACCCA\"\n assert seq[1].seq == \"CTCCTCCAAGCCC\"\n\n\ndef test_sizes(genome=\"tests/data/gap.fa\"):\n g = genomepy.Genome(genome)\n assert list(g.sizes.keys()) == [\"chr1\", \"chr2\", \"chr3\"]\n assert all(isinstance(g.sizes[chrom], int) for chrom in g.sizes.keys())\n assert g.sizes[\"chr1\"] == 28\n\n # does not overwrite user-set sizes\n g.sizes = {\"asd\": 1}\n assert g.sizes == {\"asd\": 1}\n\n # repopulates empty dicts\n g.sizes = {}\n assert list(g.sizes.keys()) == [\"chr1\", \"chr2\", \"chr3\"]\n\n\ndef test_gaps(genome=\"tests/data/gap.fa\"):\n g = genomepy.Genome(genome)\n assert list(g.gaps.keys()) == [\"chr1\", \"chr3\"]\n\n # does not overwrite user-set gaps\n g.gaps = {\"asd\": 1}\n assert g.gaps == {\"asd\": 1}\n\n # repopulates empty dicts\n g.gaps = {}\n assert list(g.gaps.keys()) == [\"chr1\", \"chr3\"]\n\n\ndef test__weighted_selection(n=2):\n tuples = [(1, \"one\"), (2, \"two\"), (3, \"three\")]\n ws = genomepy.Genome._weighted_selection(tuples, n)\n\n assert len(ws) == n\n assert isinstance(ws[0], str)\n assert tuples[0][1] in ws or tuples[1][1] in ws or tuples[2][1] in ws\n\n\ndef test_get_random_sequences(genome=\"tests/data/small_genome.fa.gz\"):\n g = genomepy.Genome(genome)\n n = 2\n length = 200 # default\n chroms = [\"chrI\", \"chrII\"]\n max_n = 0.1 # default\n rs = g.get_random_sequences(n=n, length=length, chroms=chroms, max_n=max_n)\n\n # check that the output has the right length, content, types, and sequence length\n assert len(rs) == n\n for i in range(n):\n assert rs[i][0] in chroms\n assert (\n isinstance(rs[i][0], str)\n and isinstance(rs[i][1], int)\n and isinstance(rs[i][2], int)\n )\n assert rs[i][2] - rs[i][1] == length\n\n # check that the max Ns are lower than the expected cutoff\n rs = g.get_random_sequences(n=1, chroms=chroms, outtype=\"string\")\n assert str(g.track2fasta(rs[0])[0].seq).upper().count(\"N\") <= length * max_n\n\n\ndef test_delete_test_files():\n for genome in [\n \"tests/data/small_genome.\",\n \"tests/data/gap.\",\n ]:\n for ext in [\"fa.fai\", \"fa.sizes\", \"gaps.bed\", \"fa.gz.fai\", \"fa.gz.sizes\"]:\n file = genome + ext\n if os.path.exists(file):\n os.unlink(file)\n","sub_path":"tests/04_genome_test.py","file_name":"04_genome_test.py","file_ext":"py","file_size_in_byte":12123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"271849232","text":"# coding=utf-8\nfrom setuptools import find_packages, setup\n\n\ndef get_version(filename):\n import ast\n version = None\n with open(filename) as f:\n for line in f:\n if line.startswith('__version__'):\n version = ast.parse(line).body[0].value.s\n break\n else:\n raise ValueError('No version found in %r.' % filename)\n if version is None:\n raise ValueError(filename)\n return version\n\n\nversion = get_version(filename='src/duckietown_mplan/__init__.py')\n\nsetup(name='duckietown_mplan',\n description='A versatile lane following algorithm for obstacle avoidance',\n version=version,\n download_url='http://github.com/duckietown/duckietown-mplan/tarball/%s' % version,\n package_dir={'': 'src'},\n packages=find_packages('src'),\n install_requires=[\n\n ],\n\n tests_require=[\n 'comptests',\n 'jupyter',\n 'nbconvert',\n ],\n\n # This avoids creating the egg file, which is a zip file, which makes our data\n # inaccessible by dir_from_package_name()\n zip_safe=False,\n\n # without this, the stuff is included but not installed\n include_package_data=True,\n\n entry_points={\n 'console_scripts': [\n 'dt-mplan-cli = duckietown_mplan.cli:cli_main',\n ]\n },\n classifiers=[\n # How mature is this project? Common values are\n # 3 - Alpha\n # 4 - Beta\n # 5 - Production/Stable\n 'Development Status :: 3 - Alpha',\n\n # Specify the Python versions you support here. In particular, ensure\n # that you indicate whether you support Python 2, Python 3 or both.\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n ],\n )\n","sub_path":"lib-mplan/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"510914153","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nimport os\nimport sys\nsys.path.append(os.path.dirname(__file__))\nfrom course_summary_widget import CourseSummaryWidget\n\nclass GradeSection(QWidget):\n\n #\n # This is the widget that goes in the tab container\n #\n\n def __init__(self, courses):\n super().__init__()\n self.courses = courses\n self.verticalLayout = QVBoxLayout()\n self.courseWidgets = []\n self.initialize_ui(courses)\n self.setLayout(self.verticalLayout)\n\n def initialize_ui(self, courses):\n '''Updates the display with all of the courses and grades.'''\n self.gradeLayout = QVBoxLayout()\n textWidget = QLabel(\" COURSE GRADE\")\n font = QFont()\n font.setBold(True)\n textWidget.setFont(font)\n self.gradeLayout.addWidget(textWidget)\n for course in courses:\n textWidget = CourseSummaryWidget(course)\n self.courseWidgets.append(textWidget)\n horizontalLayout = QHBoxLayout()\n horizontalLayout.addWidget(textWidget)\n horizontalLayout.addStretch()\n self.gradeLayout.addLayout(horizontalLayout)\n self.verticalLayout.addLayout(self.gradeLayout)\n self.setContentsMargins(4,0,0,0)\n self.setWindowTitle(\" GradeGeek™ \")","sub_path":"Source/grade_tab_section_page.py","file_name":"grade_tab_section_page.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"468977851","text":"# features\n# longo?\n# perna curta?\n# faz auau?\n\nfrom sklearn.svm import LinearSVC\nfrom sklearn.metrics import accuracy_score\n\nporco1 = [0, 1, 0]\nporco2 = [0, 1, 1]\nporco3 = [1, 1, 0]\n\ncachorro1 = [0, 1, 1]\ncachorro2 = [1, 0, 1]\ncachorro3 = [1, 1, 1]\n\ntreino_x = [porco1, porco2, porco3, cachorro1, cachorro2, cachorro3]\ntreino_y = [1, 1, 1, 0, 0, 0]\n\nmodel = LinearSVC()\nmodel.fit(treino_x, treino_y)\n\nmisterio1 = [1, 1, 1]\nmisterio2 = [1, 1, 0]\nmisterio3 = [0, 1, 1]\n\nteste_y = [0, 1, 0]\n\nteste_x = [misterio1, misterio2, misterio3]\nprevisoes = model.predict(teste_x)\n\ntaxa_de_acerto = accuracy_score(teste_y, previsoes)\nprint(\"Taxa de acerto\", taxa_de_acerto * 100)\n","sub_path":"exemplo_001.py","file_name":"exemplo_001.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"40078830","text":"'''\n\tspecfit.py - Definition of class for fitting linear combination of spectra.\n'''\n\n######################################################################\n\nimport os\nimport numpy as np\nfrom astropy.io import fits as pyfits\nfrom astropysics import spec\nimport scipy.ndimage.filters\nimport scipy.interpolate\nimport logging\nimport scipy.constants\nfrom scipy.optimize import leastsq\n\n_c_kms = scipy.constants.c / 1.e3 # Speed of light in km s^-1\nDF = -8.0\n\n\nclass SpecFit():\n ##################################################################\n\n def __init__(self, nspec):\n\n '''\nInitialize class.\n Input:\n nspec = Number of spectra that composes the observed spectra\n '''\n\n # number of componentes\n self.nspec = nspec\n\n # Store template spectra and scale factor\n self.template = [[]] * nspec\n self.templateNames = [[]] * nspec\n self.templateScale = [[]] * nspec\n self.specgrid = [[]] * nspec\n\n # velocity for each component\n self.vel = np.zeros(nspec)+1.\n\n # scale factor for each component\n self.scale = [[]] * nspec\n # self.mcscale = pm.Uniform(\"scale\", 0, 1, size=nspec)\n\n # template selected for each component\n self.ntemp = np.zeros(nspec, dtype=int)\n\n # template grid dimensions for each component\n self.grid_ndim = np.zeros(nspec, dtype=int)\n\n # Grids\n self.Grid = [[]] * nspec\n\n # store the observed spectra\n self.ospec = None\n\n self._autoprop = False\n\n ##################################################################\n\n def setAutoProp(self, value):\n self._autoprop = value\n\n ##################################################################\n\n def loadNextGenTemplate(self, ncomp, filename):\n '''\nLoads template spectra from a list of files (in filename), for\ncomponent ncomp.\n '''\n\n splist = np.loadtxt(filename, unpack=True, usecols=(0,),\n dtype='S', ndmin=1)\n\n self.template[ncomp] = [0] * len(splist)\n self.templateScale[ncomp] = [1] * len(splist)\n\n logging.debug('Loading template spectra for component %i from %s[%i]' % (ncomp, filename, len(splist)))\n\n for i in range(len(splist)):\n logging.debug('Reading %s' % (splist[i]))\n sp = np.loadtxt(splist[i], unpack=True, usecols=(0, 1),\n converters={0: lambda s: float(s.replace('D', 'e')),\n 1: lambda s: float(s.replace('D', 'e'))})\n asort = sp[0].argsort()\n self.template[ncomp][i] = spec.Spectrum(sp[0][asort],\n 10 ** (sp[1][asort]) + 8.0)\n\n return 0\n\n ##################################################################\n\n def loadPickleTemplate(self, ncomp, filename):\n '''\nLoads template spectra from a list of files (in filename), for\ncomponent ncomp.\n '''\n\n splist = np.loadtxt(filename, unpack=True,\n dtype='S', ndmin=2)\n if splist.shape[0] < self.grid_ndim[ncomp]:\n raise IOError('Grid dimensions is not consistent with expected. Expecting %i got %i.' % (\n self.grid_ndim[ncomp], splist.shape[0]))\n\n self.template[ncomp] = [0] * len(splist[0])\n self.templateNames[ncomp] = [0] * len(splist[0])\n self.templateScale[ncomp] = [1] * len(splist[0]) # np.zeros(len(splist))+1.0\n\n if self.grid_ndim[ncomp] > 0:\n grid = splist[1:self.grid_ndim[ncomp] + 1]\n gdim = np.zeros(self.grid_ndim[ncomp], dtype=np.int)\n for i in range(len(grid)):\n gdim[i] = len(np.unique(grid[i]))\n index = np.arange(len(splist[0])).reshape(gdim)\n self.Grid[ncomp] = index\n\n logging.debug('Loading template spectra for component %i from %s[%i]' % (ncomp, filename, len(splist)))\n\n for i in range(len(splist[0])):\n logging.debug('Reading %s' % (splist[0][i]))\n sp = np.load(splist[0][i])\n self.template[ncomp][i] = spec.Spectrum(sp[0], sp[1])\n self.templateNames[ncomp][i] = splist[0][i]\n\n return 0\n\n ##################################################################\n\n def loadCoelhoTemplate(self, ncomp, filename):\n '''\n Loads template spectra from a list of files (in filename), for\n component ncomp.\n '''\n\n splist = np.loadtxt(filename, unpack=True,\n dtype='S', ndmin=2)\n if splist.shape[0] < self.grid_ndim[ncomp]:\n raise IOError('Grid dimensions is not consistent with expected. Expecting %i got %i.' % (\n self.grid_ndim[ncomp], splist.shape[0]))\n\n self.template[ncomp] = [0] * len(splist[0])\n self.templateNames[ncomp] = [0] * len(splist[0])\n self.templateScale[ncomp] = [1] * len(splist[0])\n\n if self.grid_ndim[ncomp] > 0:\n grid = splist[1:self.grid_ndim[ncomp] + 1]\n index = np.arange(len(splist[0])).reshape((len(np.unique(grid[0])), len(np.unique(grid[1]))))\n self.Grid[ncomp] = index\n\n logging.debug('Loading template spectra for component %i from %s[%i]' % (ncomp, filename, len(splist)))\n\n notFound = 0\n for i in range(len(splist[0])):\n\n logging.debug('Reading %s' % (splist[0][i]))\n if os.path.exists(splist[0][i]):\n hdu = pyfits.open(splist[0][i])\n wave = hdu[0].header['CRVAL1'] + np.arange(len(hdu[0].data)) * hdu[0].header['CDELT1']\n self.template[ncomp][i] = spec.Spectrum(wave, hdu[0].data)\n self.templateNames[ncomp][i] = splist[0][i]\n else:\n logging.warning('Could not find template %s. %i/%i' % (splist[0][i], notFound, len(splist[0])))\n notFound += 1\n self.template[ncomp][i] = self.template[ncomp][i - 1]\n self.templateNames[ncomp][i] = splist[0][i] + \"NOTFOUND\"\n\n # sp = np.load(splist[0][i])\n if notFound > len(splist[0]) / 2:\n raise IOError('More than 50% of template spectra could not be loaded')\n\n return 0\n\n ##################################################################\n\n def loadPickle(self, filename, linearize=True):\n '''\nLoads observed spectra from numpy pickle file.\n '''\n\n logging.debug('Loading observed spectra for from %s' % (filename))\n\n sp = np.load(filename)\n\n self.ospec = spec.Spectrum(sp[0], sp[1])\n\n if linearize and not self.ospec.isLinear():\n logging.debug('Linearizing observed spectra')\n self.ospec.linearize()\n logging.debug('Done')\n\n return 0\n\n ##################################################################\n\n def loadtxtSpec(self, filename):\n '''\nLoad the observed spectra.\n '''\n\n logging.debug('Loading observed spectra for from %s' % (filename))\n\n sp = np.loadtxt(filename, unpack=True, usecols=(0, 1),\n converters={0: lambda s: float(s.replace('D', 'e')),\n 1: lambda s: float(s.replace('D', 'e'))})\n\n self.ospec = spec.Spectrum(sp[0], sp[1])\n\n return 0\n\n ##################################################################\n\n def loadSDSSFits(self, filename, linearize=False):\n '''\nLoad the observed spectra.\n '''\n\n logging.debug('Loading observed spectra for from %s' % (filename))\n\n sp = pyfits.open(filename)\n\n mask = np.bitwise_and(sp[1].data['and_mask'] == 0,\n sp[1].data['or_mask'] == 0)\n\n self.ospec = spec.Spectrum(x=10 ** (sp[1].data['loglam'][mask]),\n flux=sp[1].data['flux'][mask],\n ivar=sp[1].data['ivar'][mask])\n\n '''\n if linearize and not self.ospec.isLinear():\n logging.debug('Linearizing observed spectra')\n self.ospec.linearize()\n logging.debug('Done')\n '''\n\n return 0\n\n ##################################################################\n\n def gridSpec(self, ncomp=0):\n '''\n Resample and grid template spectrum.\n :return:\n '''\n\n # Use first spectrum as reference\n refspec = self.template[ncomp][0]\n\n specgrid = np.zeros((len(self.template[ncomp]), len(refspec.flux)))\n\n for i in range(len(specgrid)):\n specgrid[i] += self.template[ncomp][i].resample(refspec.x, replace=False)[1] * \\\n self.templateScale[ncomp][i]\n\n self.specgrid[ncomp] = specgrid\n self.scale[ncomp] = np.zeros(len(specgrid)).reshape(len(specgrid), -1) + 1. / len(specgrid)\n\n ##################################################################\n\n def chi2(self, p):\n '''\nCalculate chi-square of the data against model.\n '''\n\n for i in range(self.nspec):\n logging.debug('%f / %f' % (p[i], p[i + 1]))\n self.scale[i] = p[i * 2]\n self.vel[i] = p[i * 2 + 1]\n\n model = self.modelSpec()\n\n # c2 = np.mean( (self.ospec.flux - model.flux )**2.0 / self.ospec.flux)\n c2 = self.ospec.flux - model.flux\n return c2\n\n ##################################################################\n\n def modelSpec(self):\n '''\nCalculate model spectra.\n '''\n\n # _model = self.template[0][self.ntemp[0]]\n\n # logging.debug('Building model spectra')\n\n dopCor = np.sqrt((1.0 + self.vel[0] / _c_kms) / (1. - self.vel[0] / _c_kms))\n scale = self.scale[0][self.ntemp[0]] * self.templateScale[0][self.ntemp[0]]\n\n # print dopCor, scale, len(self.template[0][self.ntemp[0]].x), len(self.template[0][self.ntemp[0]].flux)\n # _model = MySpectrum(self.template[0][self.ntemp[0]].x * dopCor,\n # self.template[0][self.ntemp[0]].flux * scale)\n\n _model = MySpectrum(*MySpectrum(self.template[0][self.ntemp[0]].x * dopCor,\n self.template[0][self.ntemp[0]].flux * scale).myResample(self.ospec.x, replace=False))\n\n # logging.debug('Applying instrument signature')\n\n # kernel = self.obsRes()/np.mean(_model.x[1:]-_model.x[:-1])\n\n # _model.flux = scipy.ndimage.filters.gaussian_filter(_model.flux,kernel)\n\n\n for i in range(1, self.nspec):\n dopCor = np.sqrt((1.0 + self.vel[i] / _c_kms) / (1. - self.vel[i] / _c_kms))\n scale = self.scale[i][self.ntemp[i]] * self.templateScale[i][self.ntemp[i]]\n # print dopCor, scale, len(self.template[i][self.ntemp[i]].x), len(self.template[i][self.ntemp[i]].flux)\n # tmp = MySpectrum(self.template[i][self.ntemp[i]].x * dopCor,\n # self.template[i][self.ntemp[i]].flux * scale)\n\n # logging.debug('Applying instrument signature')\n\n # kernel = self.obsRes()/np.mean(tmp.x[1:]-tmp.x[:-1])\n\n # tmp.flux = scipy.ndimage.filters.gaussian_filter(tmp.flux,kernel)\n\n tmp = MySpectrum(*MySpectrum(self.template[i][self.ntemp[i]].x * dopCor,\n self.template[i][self.ntemp[i]].flux * scale).myResample(self.ospec.x, replace=False))\n\n _model.flux += tmp.flux\n\n '''\n if not _model.isLinear():\n logging.warning('Data must be linearized...')\n\n '''\n # kernel = self.obsRes()/tmp.getDx()/2./np.pi\n\n # _model.flux = scipy.ndimage.filters.gaussian_filter(_model.flux,kernel)\n\n # logging.debug('Resampling model spectra')\n # _model = MySpectrum(*_model.myResample(self.ospec.x, replace=False))\n if self._autoprop:\n mflux = np.mean(_model.flux)\n oflux = np.mean(self.ospec.flux)\n _model.flux *= (oflux / mflux)\n return _model\n\n ##################################################################\n\n def modelSpecThreadSafe(self, vel, scale, ntemp):\n '''\nCalculate model spectra.\n '''\n\n # _model = self.template[0][self.ntemp[0]]\n\n logging.debug('Building model spectra')\n\n dopCor = np.sqrt((1.0 + vel[0] / _c_kms) / (1. - vel[0] / _c_kms))\n scale = scale[0] * self.templateScale[0][ntemp[0]]\n\n _model = MySpectrum(self.template[0][ntemp[0]].x * dopCor,\n self.template[0][ntemp[0]].flux * scale)\n\n # logging.debug('Applying instrument signature')\n\n # kernel = self.obsRes()/np.mean(_model.x[1:]-_model.x[:-1])\n\n # _model.flux = scipy.ndimage.filters.gaussian_filter(_model.flux,kernel)\n\n\n for i in range(1, self.nspec):\n dopCor = np.sqrt((1.0 + vel[i] / _c_kms) / (1. - vel[i] / _c_kms))\n scale = scale[i] * self.templateScale[i][ntemp[i]]\n\n tmp = MySpectrum(self.template[i][ntemp[i]].x * dopCor,\n self.template[i][ntemp[i]].flux * scale)\n\n # logging.debug('Applying instrument signature')\n\n # kernel = self.obsRes()/np.mean(tmp.x[1:]-tmp.x[:-1])\n\n # tmp.flux = scipy.ndimage.filters.gaussian_filter(tmp.flux,kernel)\n\n tmp = MySpectrum(*tmp.resample(_model.x, replace=False))\n\n _model.flux += tmp.flux\n\n '''\n if not _model.isLinear():\n logging.warning('Data must be linearized...')\n\n '''\n # kernel = self.obsRes()/tmp.getDx()/2./np.pi\n\n # _model.flux = scipy.ndimage.filters.gaussian_filter(_model.flux,kernel)\n\n logging.debug('Resampling model spectra')\n _model = MySpectrum(*_model.myResample(self.ospec.x, replace=False))\n return _model\n\n ##################################################################\n\n def normTemplate(self, ncomp, w0, w1):\n '''\nNormalize spectra against data in the wavelenght regions\n '''\n\n for i in range(len(self.template[ncomp])):\n maskt = np.bitwise_and(self.template[ncomp][i].x > w0,\n self.template[ncomp][i].x < w1)\n mask0 = np.bitwise_and(self.ospec.x > w0,\n self.ospec.x < w1)\n\n scale = np.mean(self.ospec.flux[mask0]) / np.mean(self.template[ncomp][i].flux[maskt])\n\n self.templateScale[ncomp][i] = scale\n # self.template[ncomp][i].flux *= scale\n\n ##################################################################\n\n def gaussian_filter(self, ncomp, kernel):\n\n for i in range(len(self.template[ncomp])):\n if not self.template[ncomp][i].isLinear():\n logging.warning('Spectra must be linearized for gaussian filter...')\n\n self.template[ncomp][i].flux = scipy.ndimage.filters.gaussian_filter(self.template[ncomp][i].flux, kernel)\n\n ##################################################################\n\n def obsRes(self):\n return self.ospec.getDx()\n\n ##################################################################\n\n def preprocTemplate(self):\n '''\nPre-process all template spectra to have aproximate coordinates as\nthose of the observed spectrum and linearize the spectrum.\n '''\n\n logging.debug('Preprocessing all template spectra. Spectra will be trimmed and linearized')\n\n ores = self.obsRes()\n\n xmin = np.max([self.template[0][0].x[0], self.ospec.x[0] - 100.0 * ores])\n xmax = np.min([self.template[0][0].x[-1], self.ospec.x[-1] + 100.0 * ores])\n\n for i in range(self.nspec):\n for j in range(len(self.template[i])):\n # t_res = np.mean(self.template[i][j].x[1:]-self.template[i][j].x[:-1])\n # newx = np.arange(xmin,xmax,t_res)\n # self.template[i][j] = spec.Spectrum(*self.template[i][j].resample(newx,replace=False))\n\n self.template[i][j].linearize(lower=xmin, upper=xmax)\n\n tmp_spres = np.mean(self.template[i][j].x[1:] - self.template[i][j].x[:-1])\n logging.debug('Template spres = %f' % (tmp_spres))\n logging.debug('Data spres = %f' % (ores))\n\n if tmp_spres < ores / 10.:\n logging.debug('Template spectroscopic resolution too high! Resampling...')\n newx = np.arange(xmin, xmax, ores / 10.)\n self.template[i][j] = spec.Spectrum(*self.template[i][j].resample(newx, replace=False))\n\n ##################################################################\n\n def saveTemplates2Pickle(self, ncomp, filename):\n\n splist = np.loadtxt(filename, unpack=True, usecols=(0,),\n dtype='S', ndmin=1)\n\n logging.debug('Saving template spectra to pickle file...')\n\n for ntemp in range(len(self.template[ncomp])):\n logging.debug(splist[ntemp])\n sp = np.array([self.template[ncomp][ntemp].x,\n self.template[ncomp][ntemp].flux])\n np.save(splist[ntemp], sp)\n\n ##################################################################\n\n def suitableScale(self):\n '''\nFind a suitable scale values for all spectra.\n '''\n\n logging.debug('Looking for suitable scale in all spectra. Will choose the larger value.')\n\n obsmean = np.mean(self.ospec.flux)\n maxscale = 0.\n minscale = obsmean\n\n for i in range(len(self.template)):\n for j in range(len(self.template[i])):\n maskt = np.bitwise_and(self.template[i][j].x > self.ospec.x[0],\n self.template[i][j].x < self.ospec.x[-1])\n\n nscale = obsmean / np.mean(self.template[i][j].flux[maskt]) / self.templateScale[i][j]\n\n if maxscale < nscale:\n maxscale = nscale\n if minscale > nscale:\n minscale = nscale\n\n return maxscale, minscale\n\n ##################################################################\n\n def fit(self):\n '''\nFit spectra with least square fit.\n '''\n\n def score(p, x, y):\n for i in range(self.nspec):\n # self.vel[i] = p[i*self.nspec]\n # self.scale[i][self.ntemp[i]] = p[i*self.nspec+1]\n self.vel[i] = 0.\n self.scale[i][self.ntemp[i]] = p[i]\n\n return y-self.modelSpec().flux\n\n # pres, flag = leastsq(score, [self.vel[0], self.scale[0][self.ntemp[0]],\n # self.vel[1], self.scale[1][self.ntemp[1]]],\n # args=(self.ospec.x, self.ospec.flux))\n pres, flag = leastsq(score, [self.scale[0][self.ntemp[0]],\n self.scale[1][self.ntemp[1]]],\n args=(self.ospec.x, self.ospec.flux))\n\n return pres\n\n\n\n######################################################################\n\nclass MySpectrum(spec.Spectrum):\n def __init__(self, x, flux, err=None, ivar=None,\n unit='wl', name='', copy=True, sort=True):\n spec.Spectrum.__init__(self, x=x, flux=flux, err=err, ivar=ivar,\n unit=unit, name=name, copy=copy, sort=sort)\n\n ##################################################################\n\n def myResample(self, newx, replace=False):\n '''\n kernel = np.mean(newx[1:]-newx[:-1])/np.mean(self.x[1:]-self.x[:-1])\n\n dx = self.x[1:]-self.x[:-1]\n\n newy = scipy.ndimage.filters.gaussian_filter(self.flux,np.float(kernel))\n tck = scipy.interpolate.splrep(self.x,newy)\n newy2 =scipy.interpolate.splev(newx,tck)\n '''\n\n kernel = np.median(newx[1:] - newx[:-1]) / np.median(self.x[1:] - self.x[:-1]) #*4.0 #/2./np.pi\n\n newflux = scipy.ndimage.filters.gaussian_filter1d(self.flux, kernel)\n\n tck = scipy.interpolate.splrep(self.x, newflux)\n\n return newx, scipy.interpolate.splev(newx, tck)\n\n '''\n newy = np.zeros(len(newx))\n\n for i in range(len(newx)):\n xini = 0\n xend = 0\n\n if i == 0:\n xini = newx[i]-(newx[i+1]-newx[i])/2.\n else:\n xini = newx[i]-(newx[i]-newx[i-1])/2.\n\n if i == len(newx)-1:\n xend = newx[i]+(newx[i]-newx[i-1])/2.\n else:\n xend = newx[i]+(newx[i+1]-newx[i])/2.\n\n mask = np.bitwise_and(self.x > xini, self.x < xend)\n\n #newy[i] = np.sum( dx[mask[:-1]] * self.flux[mask] )\n newy[i] = np.mean(self.flux[mask])\n #print newx[i],newy[i],newy2[i],xini,xend, (xend-xini) , np.mean(self.flux[mask]),(xend-xini) * np.mean(self.flux[mask])\n #print self.x[mask],self.flux[mask],dx[mask[:-1]]\n\n\n\n return newx,newy #scipy.interpolate.splev(newx,tck)\n'''\n\n ##################################################################\n\n######################################################################\n","sub_path":"specfit/lib/specfit.py","file_name":"specfit.py","file_ext":"py","file_size_in_byte":21017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"387396563","text":"# -*- coding: utf-8 -*-\n\"\"\"Constants module.\"\"\"\n\nfrom typing import Any, Callable, Dict, List, Mapping, NamedTuple, Optional, Sequence # noqa: F401\n\nfrom xml.etree import ElementTree as ET\n\n\nNS = {\n 'soap_envelope': 'http://schemas.xmlsoap.org/soap/envelope/',\n 'device': 'urn:schemas-upnp-org:device-1-0',\n 'service': 'urn:schemas-upnp-org:service-1-0',\n 'event': 'urn:schemas-upnp-org:event-1-0',\n 'control': 'urn:schemas-upnp-org:control-1-0',\n}\n\nSTATE_VARIABLE_TYPE_MAPPING = {\n 'ui1': int,\n 'ui2': int,\n 'ui4': int,\n 'i1': int,\n 'i2': int,\n 'i4': int,\n 'int': int,\n 'r4': float,\n 'r8': float,\n 'number': float,\n 'fixed.14.4': float,\n 'float': float,\n 'char': str,\n 'string': str,\n 'boolean': bool,\n 'bin.base64': str,\n 'bin.hex': str,\n 'uri': str,\n 'uuid': str,\n} # type: Dict[str, Callable[[str], Any]]\n\nDeviceInfo = NamedTuple('DeviceInfo', [\n ('device_type', str),\n ('friendly_name', str),\n ('manufacturer', str),\n ('model_name', str),\n ('model_number', Optional[str]),\n ('model_description', Optional[str]),\n ('udn', str),\n ('url', str),\n ('xml', ET.Element),\n])\n\nServiceInfo = NamedTuple('ServiceInfo', [\n ('service_id', str),\n ('service_type', str),\n ('control_url', str),\n ('event_sub_url', str),\n ('scpd_url', str),\n ('xml', ET.Element),\n])\n\nActionArgumentInfo = NamedTuple('ActionArgumentInfo', [\n ('name', str),\n ('direction', str),\n ('state_variable_name', str),\n ('xml', ET.Element),\n])\n\nActionInfo = NamedTuple('ActionInfo', [\n ('name', str),\n ('arguments', Sequence[ActionArgumentInfo]),\n ('xml', ET.Element),\n])\n\nStateVariableTypeInfo = NamedTuple('StateVariableTypeInfo', [\n ('data_type', str),\n ('data_type_python', Callable[[str], Any]),\n ('default_value', Optional[str]),\n ('allowed_value_range', Mapping[str, Optional[str]]),\n ('allowed_values', Optional[List[str]]),\n ('xml', ET.Element),\n])\n\nStateVariableInfo = NamedTuple('StateVariableInfo', [\n ('name', str),\n ('send_events', bool),\n ('type_info', StateVariableTypeInfo),\n ('xml', ET.Element),\n])\n","sub_path":"async_upnp_client/const.py","file_name":"const.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"455470305","text":"from configparser import ConfigParser\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom os.path import abspath, dirname, isfile, join as pjoin\nfrom os import environ\n\n\n_inis = [\n pjoin(dirname(abspath(__file__)), 'config', 'config.ini'),\n pjoin(dirname(abspath(__file__)), 'config', 'agent-profile', environ.get('AGENT_PROFILE') + '.ini')\n]\n\ndef init_config():\n global _inis\n if cache.get('config') == None:\n if all(isfile(ini) for ini in _inis):\n parser = ConfigParser()\n for ini in _inis: \n parser.read(ini)\n cache.set(\n 'config',\n {s: dict(parser[s].items()) for s in parser.sections()})\n else:\n raise FileNotFoundError('Configuration file(s) mission; check {}'.format(_inis))\n return cache.get('config')\n","sub_path":"service_wrapper_project/wrapper_api/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"548991050","text":"import os\r\nimport random\r\nimport sys\r\n\r\n\r\ndef base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):\r\n base36 = ''\r\n sign = ''\r\n if number < 0:\r\n sign = '-'\r\n number = -number\r\n if 0 <= number < len(alphabet):\r\n return sign + alphabet[number]\r\n while number != 0:\r\n number, i = divmod(number, len(alphabet))\r\n base36 = alphabet[i] + base36\r\n return sign + base36\r\n\r\ndef generateKey():\r\n lengthOfKey = input(\"How many caracters you want to have in your key ?\")\r\n keyCache = \"\"\r\n for key in range(lengthOfKey): \r\n keyCache += random.choice('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')\r\n return keyCache\r\n\r\n\r\ndef KeyParser(EncryptedKey):\r\n x1 = 0\r\n x2 = 0\r\n for value in range(len(EncryptedKey)):\r\n if value%2 == 0:\r\n x1 += int(EncryptedKey[value], 36)\r\n else:\r\n x2 += int(EncryptedKey[value], 36)\r\n return x1, x2\r\n\r\n\r\ndef main():\r\n choice = input(\r\n 'Do you want to decrypt or encrypt, choose \"1\" for decrypt and \"2\" for encrypt')\r\n if (choice != '1') and (choice != '2'):\r\n print(\"You didn't choose between 1 or 2...\")\r\n main()\r\n else:\r\n if choice == '1':\r\n method = 'decrypt'\r\n if choice == '2':\r\n method = 'encrypt'\r\n baseNumber = input('In which base do you want to {0} ?', format(method))\r\n print('What do you want to ' + method)\r\n textinput = input()\r\n arrayToProcess = []\r\n arrayWord = list(textinput)\r\n if method == 'encrypt':\r\n for i in range(len(arrayWord)):\r\n randomnessLenght = False\r\n lenCount = 0\r\n while(randomnessLenght != True):\r\n if random.random() > 0.5:\r\n lenCount += 1\r\n else:\r\n randomnessLenght = True\r\n charactersToArray = \"\"\r\n for ArrayMake in range(lenCount):\r\n charactersToArray += arrayWord[i]\r\n i += 1\r\n arrayToProcess.append([charactersToArray,obfuscateCount,lenCount])\r\n EncryptedKey = input(\"Tell the key you want to use for encrypting, if you want to generate a random key just press ENTER. (Enter Only AlphaNumerical Caracters, Minimum 2 caracters.)\")\r\n if EncryptedKey == \"\":\r\n EncryptedKey = generateKey()\r\n x1, x2 = KeyParser(EncryptedKey)\r\n messageEncrypted = \"\"\r\n specificLastHeader = \"\"\r\n for index, ArrayInstruction in enumerate(arrayToProcess):\r\n StartCodon = (x1 * x2 + pow(index, 2)) / pow(index, 2) # check base taille\r\n EndCodon = (x1 * x2 + pow(index + ArrayInstruction[2], 2)) / pow(index + ArrayInstruction[2], 2) # check base taille\r\n messageEncrypted += base36encode(StartCodon)\r\n for iterationToTranslate in range(ArrayInstruction[2]):\r\n MessagerAdderFirstPart = (pow((index + iterationToTranslate), 2) / (pow(index + ArrayInstruction[2], 2) + pow(index, 2)))\r\n MessagerAdderLastPart = (1 / (1 + pow((index + iterationToTranslate), 2)))\r\n DecimalValueMessageToAdd = (StartCodon * EndCodon + MessagerAdderFirstPart) * MessagerAdderLastPart\r\n messageEncrypted += base36encode(DecimalValueMessageToAdd)\r\n # check la base\r\n messageEncrypted += base36encode(EndCodon)\r\n if method == 'decrypt':\r\n print(\"Incomming\")\r\n \r\n # base à completer avec OPCODE au debut specififier ligne et Nombre de fois du maximum\r\n\r\n\r\nmain()\r\n","sub_path":"main.1.py","file_name":"main.1.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"490065836","text":"import os\nimport re\nimport flask\nimport json\nfrom indexd.errors import AuthError, AuthzError\nfrom indexd.errors import UserError\nfrom indexd.index.errors import NoRecordFound as IndexNoRecordFound\nfrom indexd.errors import IndexdUnexpectedError\nfrom indexd.utils import reverse_url\n\nblueprint = flask.Blueprint(\"drs\", __name__)\n\nblueprint.config = dict()\nblueprint.index_driver = None\nblueprint.service_info = {}\n\n\n@blueprint.route(\"/ga4gh/drs/v1/service-info\", methods=[\"GET\"])\ndef get_drs_service_info():\n \"\"\"\n Returns DRS compliant service information\n \"\"\"\n\n reverse_domain_name = reverse_url(url=os.environ[\"HOSTNAME\"])\n\n ret = {\n \"id\": reverse_domain_name,\n \"name\": \"DRS System\",\n \"version\": \"1.0.3\",\n \"type\": {\n \"group\": \"org.ga4gh\",\n \"artifact\": \"drs\",\n \"version\": \"1.0.3\",\n },\n \"organization\": {\n \"name\": \"CTDS\",\n \"url\": \"https://\" + os.environ[\"HOSTNAME\"],\n },\n }\n\n if blueprint.service_info:\n for key, value in blueprint.service_info.items():\n if key in ret:\n if isinstance(value, dict):\n for inner_key, inner_value in value.items():\n ret[key][inner_key] = inner_value\n else:\n ret[key] = value\n\n return flask.jsonify(ret), 200\n\n\n@blueprint.route(\"/ga4gh/drs/v1/objects/\", methods=[\"GET\"])\ndef get_drs_object(object_id):\n \"\"\"\n Returns a specific DRSobject with object_id\n \"\"\"\n expand = True if flask.request.args.get(\"expand\") == \"true\" else False\n\n ret = blueprint.index_driver.get_with_nonstrict_prefix(object_id)\n\n data = indexd_to_drs(ret, expand=expand)\n\n return flask.jsonify(data), 200\n\n\n@blueprint.route(\"/ga4gh/drs/v1/objects\", methods=[\"GET\"])\ndef list_drs_records():\n limit = flask.request.args.get(\"limit\")\n start = flask.request.args.get(\"start\")\n page = flask.request.args.get(\"page\")\n\n form = flask.request.args.get(\"form\")\n\n try:\n limit = 100 if limit is None else int(limit)\n except ValueError as err:\n raise UserError(\"limit must be an integer\")\n\n if limit < 0 or limit > 1024:\n raise UserError(\"limit must be between 0 and 1024\")\n\n if page is not None:\n try:\n page = int(page)\n except ValueError as err:\n raise UserError(\"page must be an integer\")\n\n if form == \"bundle\":\n records = blueprint.index_driver.get_bundle_list(\n start=start, limit=limit, page=page\n )\n elif form == \"object\":\n records = blueprint.index_driver.ids(start=start, limit=limit, page=page)\n else:\n records = blueprint.index_driver.get_bundle_and_object_list(\n start=start, limit=limit, page=page\n )\n ret = {\n \"drs_objects\": [indexd_to_drs(record, True) for record in records],\n }\n\n return flask.jsonify(ret), 200\n\n\ndef create_drs_uri(did):\n \"\"\"\n Return ga4gh-compilant drs format uri\n\n Args:\n did(str): did of drs object\n \"\"\"\n\n default_prefix = blueprint.index_driver.config.get(\"DEFAULT_PREFIX\")\n\n if not default_prefix:\n # For env without DEFAULT_PREFIX, uri will not be drs compliant\n accession = did\n self_uri = \"drs://{}\".format(accession)\n else:\n accession = (\n did.replace(default_prefix, \"\", 1).replace(\"/\", \"\", 1).replace(\":\", \"\", 1)\n )\n\n self_uri = \"drs://{}:{}\".format(\n default_prefix.replace(\"/\", \"\", 1).replace(\":\", \"\", 1), accession\n )\n\n return self_uri\n\n\ndef indexd_to_drs(record, expand=False):\n \"\"\"\n Convert record to ga4gh-compilant format\n\n Args:\n record(dict): json object record\n expand(bool): show contents of the descendants\n \"\"\"\n\n did = (\n record[\"id\"]\n if \"id\" in record\n else record[\"did\"]\n if \"did\" in record\n else record[\"bundle_id\"]\n )\n\n self_uri = create_drs_uri(did)\n\n name = record[\"file_name\"] if \"file_name\" in record else record[\"name\"]\n\n index_created_time = (\n record[\"created_date\"] if \"created_date\" in record else record[\"created_time\"]\n )\n\n version = (\n record[\"version\"]\n if \"version\" in record\n else record[\"rev\"]\n if \"rev\" in record\n else \"\"\n )\n\n index_updated_time = (\n record[\"updated_date\"] if \"updated_date\" in record else record[\"updated_time\"]\n )\n\n content_created_date = record.get(\"content_created_date\", \"\")\n\n content_updated_date = record.get(\"content_updated_date\", \"\")\n\n form = record[\"form\"] if \"form\" in record else \"bundle\"\n\n description = record[\"description\"] if \"description\" in record else None\n\n alias = (\n record[\"alias\"]\n if \"alias\" in record\n else json.loads(record[\"aliases\"])\n if \"aliases\" in record\n else []\n )\n\n drs_object = {\n \"id\": did,\n \"mime_type\": \"application/json\",\n \"name\": name,\n \"index_created_time\": index_created_time,\n \"index_updated_time\": index_updated_time,\n \"created_time\": content_created_date,\n \"updated_time\": content_updated_date,\n \"size\": record[\"size\"],\n \"aliases\": alias,\n \"self_uri\": self_uri,\n \"version\": version,\n \"form\": form,\n \"checksums\": [],\n \"description\": description,\n }\n\n if \"description\" in record:\n drs_object[\"description\"] = record[\"description\"]\n\n if \"bundle_data\" in record:\n drs_object[\"contents\"] = []\n for bundle in record[\"bundle_data\"]:\n bundle_object = bundle_to_drs(bundle, expand=expand, is_content=True)\n if not expand:\n bundle_object.pop(\"contents\", None)\n drs_object[\"contents\"].append(bundle_object)\n\n # access_methods mapping\n if \"urls\" in record:\n drs_object[\"access_methods\"] = []\n for location in record[\"urls\"]:\n location_type = location.split(\":\")[\n 0\n ] # (s3, gs, ftp, gsiftp, globus, htsget, https, file)\n\n drs_object[\"access_methods\"].append(\n {\n \"type\": location_type,\n \"access_url\": {\"url\": location},\n \"access_id\": location_type,\n \"region\": \"\",\n }\n )\n\n # parse out checksums\n drs_object[\"checksums\"] = parse_checksums(record, drs_object)\n\n return drs_object\n\n\ndef bundle_to_drs(record, expand=False, is_content=False):\n \"\"\"\n record(dict): json object record\n expand(bool): show contents of the descendants\n is_content: is an expanded content in a bundle\n \"\"\"\n\n did = (\n record[\"id\"]\n if \"id\" in record\n else record[\"did\"]\n if \"did\" in record\n else record[\"bundle_id\"]\n )\n\n drs_uri = create_drs_uri(did)\n\n name = record[\"file_name\"] if \"file_name\" in record else record[\"name\"]\n\n drs_object = {\n \"id\": did,\n \"name\": name,\n \"drs_uri\": drs_uri,\n \"contents\": [],\n }\n\n contents = (\n record[\"contents\"]\n if \"contents\" in record\n else record[\"bundle_data\"]\n if \"bundle_data\" in record\n else []\n )\n\n if not expand and isinstance(contents, list):\n for content in contents:\n if isinstance(content, dict):\n content.pop(\"contents\", None)\n\n drs_object[\"contents\"] = contents\n\n if not is_content:\n # Show these only if its the leading bundle\n description = record[\"description\"] if \"description\" in record else \"\"\n aliases = (\n record[\"alias\"]\n if \"alias\" in record\n else json.loads(record[\"aliases\"])\n if \"aliases\" in record\n else []\n )\n version = (\n record[\"version\"]\n if \"version\" in record\n else record[\"rev\"]\n if \"rev\" in record\n else \"\"\n )\n # version = record[\"version\"] if \"version\" in record else \"\"\n drs_object[\"checksums\"] = parse_checksums(record, drs_object)\n\n created_time = (\n record[\"created_date\"]\n if \"created_date\" in record\n else record.get(\"created_time\")\n )\n\n updated_time = (\n record[\"updated_date\"]\n if \"updated_date\" in record\n else record.get(\"updated_time\")\n )\n if created_time:\n drs_object[\"created_time\"] = created_time\n if updated_time:\n drs_object[\"updated_time\"] = updated_time\n drs_object[\"size\"] = record[\"size\"]\n drs_object[\"aliases\"] = aliases\n drs_object[\"description\"] = description\n drs_object[\"version\"] = version\n\n return drs_object\n\n\ndef parse_checksums(record, drs_object):\n \"\"\"\n Create valid checksums format from a DB object -\n either a record (\"hashes\") or a bundle (\"checksum\")\n \"\"\"\n ret_checksum = []\n if \"hashes\" in record:\n for k in record[\"hashes\"]:\n ret_checksum.append({\"checksum\": record[\"hashes\"][k], \"type\": k})\n elif \"checksum\" in record:\n try:\n checksums = json.loads(record[\"checksum\"])\n except json.decoder.JSONDecodeError:\n # TODO: Remove the code after fixing the record[\"checksum\"] format\n checksums = [{\"checksum\": record[\"checksum\"], \"type\": \"md5\"}]\n for checksum in checksums:\n ret_checksum.append(\n {\"checksum\": checksum[\"checksum\"], \"type\": checksum[\"type\"]}\n )\n return ret_checksum\n\n\n@blueprint.errorhandler(UserError)\ndef handle_user_error(err):\n ret = {\"msg\": str(err), \"status_code\": 400}\n return flask.jsonify(ret), 400\n\n\n@blueprint.errorhandler(AuthzError)\ndef handle_authz_error(err):\n ret = {\"msg\": str(err), \"status_code\": 401}\n return flask.jsonify(ret), 401\n\n\n@blueprint.errorhandler(AuthError)\ndef handle_requester_auth_error(err):\n ret = {\"msg\": str(err), \"status_code\": 403}\n return flask.jsonify(ret), 403\n\n\n@blueprint.errorhandler(IndexNoRecordFound)\ndef handle_no_index_record_error(err):\n ret = {\"msg\": str(err), \"status_code\": 404}\n return flask.jsonify(ret), 404\n\n\n@blueprint.errorhandler(IndexdUnexpectedError)\ndef handle_unexpected_error(err):\n ret = {\"msg\": err.message, \"status_code\": err.code}\n return flask.jsonify(ret), err.code\n\n\n@blueprint.record\ndef get_config(setup_state):\n index_config = setup_state.app.config[\"INDEX\"]\n blueprint.index_driver = index_config[\"driver\"]\n\n\n@blueprint.record\ndef get_config(setup_state):\n if \"DRS_SERVICE_INFO\" in setup_state.app.config:\n blueprint.service_info = setup_state.app.config[\"DRS_SERVICE_INFO\"]\n","sub_path":"indexd/drs/blueprint.py","file_name":"blueprint.py","file_ext":"py","file_size_in_byte":10751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"204436721","text":"# THIS CODE ISN'T WORKING YET\n\nimport numpy as np\n\n\ndef permutation_matrix_3d (res : int = 25, other_params : int = 0, param_seperated : bool = False):\n cols = 3 + other_params\n # We'll make all other parameters vary together from 0 to 1. This will originate the animation. If other_params = 1, this creates a full view of the universe, if other_params > 1 this will no longer be the case, and will only give a slightly more detailed view of the first 3 params as the other other_params change from 0 to 1 (in unison)\n if other_params > 0:\n rows = res**4\n perm_matrix = np.zeros((res,res,res,res,cols))\n perm_matrix[:,:,:,:,0] = np.linspace(0,1,res)\n perm_matrix[:,:,:,:,1] = np.linspace(np.zeros((res,)),np.ones((res,)),res)\n perm_matrix[:,:,:,:,2] = np.linspace(np.zeros((res,res)),np.ones((res,res)),res)\n perm_matrix[:,:,:,:,3:] = np.linspace(np.zeros((res,res,res,other_params)),np.ones((res,res,res,other_params)),res)\n else:\n rows = res**3\n perm_matrix = np.zeros((res,res,res,3))\n perm_matrix[:,:,:,0] = np.linspace(0,1,res)\n perm_matrix[:,:,:,1] = np.linspace(np.zeros((res,)),np.ones((res,)),res)\n perm_matrix[:,:,:,2] = np.linspace(np.zeros((res,res)),np.ones((res,res)),res)\n #this convoluted shape was only created in order to use numpy's speed, with linspace, we can now use a shape that is actually convenient for us:\n perm_matrix = np.reshape(perm_matrix, (rows, cols))\n return perm_matrix\n\n\ndef add_radius_flag (input : np.ndarray, center : np.ndarray = None):\n \"\"\"\n For each point we want to do:\n (x-x_center)^2 + (y-y_center)^2 + (z-z_center)^2 <= r^2?\n if yes: append 'True' flag\n if no: append 'False' flag\n \"\"\"\n if center is None:\n center = np.array((0.5,0.5,0.5))\n pass\n\n flags = ((input[:,0]-center[0])**2 + (input[:,1]-center[1])**2 + (input[:,2]-center[2])**2) <= input[:,3]\n flags = np.array(flags, dtype=int)\n flags[flags==0] = -1\n flags = flags.reshape((flags.shape[0],1))\n new_arr = np.concatenate((input,flags), axis=1)\n return new_arr\n\n\ndef animate_sphere (res : int = 10, fps:int = 10) -> None:\n to_plot = add_radius_flag(permutation_matrix_3d(res, 1))\n to_plot = np.split(to_plot, res)\n\n import matplotlib.pyplot as plt\n\n fig = plt.figure()\n ax = fig.add_subplot(projection='3d')\n ln, = ax.plot_surface([],[],[],alpha=0.5)\n \n up = np.array(range(res-1))\n down = np.array(range(res))\n down = down[:0:-1]\n frames = np.concatenate((up,down))\n\n frame_text = ax.text(-0.1, -0.1, -0.1, \"\")\n params_text = ax.text(0.2, -0.1, -0.1, \"\")\n\n def init_graph():\n ax.set_xlim3d(0, 1)\n ax.set_ylim3d(0, 1)\n ax.set_zlim3d(0, 1)\n return ln,\n\n def update(frame):\n frame_text.set_text (\"Frame: \" + str((frame+1)%(len(up)+2)) + \"/\" + str(len(up)+1))\n params_text.set_text (\"Param Values: \" + str((frame+1)%(len(up)+2)) + \"/\" + str(len(up)+1))\n this_frame = to_plot[frame]\n params_text.set_text (\"Radius: \" + \"{0:.3f}\".format(this_frame[0,-2]))\n inside_sphere = this_frame[this_frame[:,4] == 1]\n\n xdata = inside_sphere[:,0]\n ydata = inside_sphere[:,1]\n zdata = inside_sphere[:,2]\n ln.set_data_3d(xdata, ydata, zdata)\n return ln,\n\n from matplotlib.animation import FuncAnimation\n anim = FuncAnimation(fig=fig,\n func=update,\n frames=frames, \n init_func=init_graph,\n interval=max(int(1000/fps),1))\n plt.show()\n pass\n\n\nif __name__ == '__main__':\n perm_matrix = animate_sphere(25, fps=10)\n","sub_path":"AnimatedPlots/my_attempt_3d_surface.py","file_name":"my_attempt_3d_surface.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"321564921","text":"from BioLib import *\nimport optparse, os, sys, random\nimport numpy as np\n\ndef parse_options():\n '''\n Parse arguments\n @return options object\n '''\n parser = optparse.OptionParser('analyze_byprotein.py -i PPI_FILE -j JOB_PATH [-v]')\n parser.add_option(\"-i\", dest=\"ppi_file\", action=\"store\", help=\"The ppi file [MANDATORY]\", metavar=\"PPI_FILE\")\n parser.add_option(\"-j\", dest=\"job_path\", action=\"store\", help=\"Job path [MANDATORY]\", metavar=\"JOB_PATH\")\n parser.add_option(\"-v\", dest=\"verbose\", action=\"store_true\", help=\"Verbose\", metavar=\"VERBOSE\")\n\n (options, args) = parser.parse_args()\n if options.ppi_file == None or options.job_path == None:\n parser.error('Missing arguments\\n')\n return options\n\nclass AnalyzePPI(object):\n '''\n Get the scores of each decoy for each protein-protein interaction and analyze the\n diferent locations\n '''\n def __init__(self, ppi_file, job_path, verbose):\n '''\n Contructor\n '''\n self.ppi_file = ppi_file\n self.job_path = job_path\n self.verbose = verbose\n \n def run(self):\n '''\n Runs the computations\n '''\n ppi_fo = open(self.ppi_file, 'r')\n energies_print = []\n for ppi in ppi_fo:\n ppi_type = ppi.strip('\\n').split('\\t')[1]\n if ppi_type[0] != 'E' and ppi_type != 'OX':\n continue\n ppi = ppi.strip('\\n').split('\\t')[0][0:4]\n try:\n ppi_results = self.__on_interaction(ppi)\n energies_print.append(ppi_results)\n if self.verbose:\n sys.stdout.write('[\\033[92mSUCCESS\\033[0m]\\n')\n sys.stdout.flush()\n except RuntimeError as e:\n if self.verbose:\n sys.stdout.write('[\\033[91mFAIL\\033[0m] %s\\n' % str(e))\n sys.stdout.flush()\n ppi_fo.close()\n self.__print(energies_print)\n\n def __on_interaction(self, ppi):\n '''\n Computations for each ppi\n '''\n if self.verbose:\n sys.stdout.write('PPI %s --> ' % ppi)\n sys.stdout.flush()\n # Get the energies by location #\n try:\n location_decoys = self.__get_location_decoys(ppi)\n except RuntimeError as e:\n raise e\n if not location_decoys['N'] or not location_decoys['I'] or not location_decoys['P'] or not location_decoys['E']:\n raise RuntimeError('NO NATIVE, INTERFACE, PARTIAL OR EXTERNAL DECOYS')\n try:\n fiberdock_energies = self.__get_energies(ppi, location_decoys, 'fiberdock')\n sp_energies = self.__get_energies(ppi, location_decoys, 'rmsd_splitpotentials')\n except Exception as e:\n raise e\n # Compute average macrostate energies #\n macrostate_N = np.concatenate((np.mean(fiberdock_energies['N'], axis=0), \n np.mean(sp_energies['N'], axis=0),\n np.std(fiberdock_energies['N'], axis=0),\n np.std(sp_energies['N'], axis=0)))\n macrostate_I = np.concatenate((np.mean(fiberdock_energies['I'], axis=0), \n np.mean(sp_energies['I'], axis=0),\n np.std(fiberdock_energies['I'], axis=0),\n np.std(sp_energies['I'], axis=0)))\n macrostate_P = np.concatenate((np.mean(fiberdock_energies['P'], axis=0), \n np.mean(sp_energies['P'], axis=0),\n np.std(fiberdock_energies['P'], axis=0),\n np.std(sp_energies['P'], axis=0)))\n macrostate_E = np.concatenate((np.mean(fiberdock_energies['E'], axis=0), \n np.mean(sp_energies['E'], axis=0),\n np.std(fiberdock_energies['E'], axis=0),\n np.std(sp_energies['E'], axis=0)))\n return ppi, macrostate_N, macrostate_I, macrostate_P, macrostate_E\n\n def __get_rmsd(self, ppi):\n '''\n Get the RMSD for ach decoy using the sp_iLoops_energies file\n '''\n # Check if needed files exists #\n rmsd_path = os.path.join(self.job_path, ppi, 'rmsd_splitpotentials.txt')\n if not os.path.isfile(rmsd_path):\n raise RuntimeError('NO RMSD FILE FOUND')\n # Get rmsd #\n rmsd_decoys = {}\n rmsd_decoys_fo = open(rmsd_path, 'r')\n for decoy in rmsd_decoys_fo:\n decoy = decoy.strip().split('\\t')\n rmsd_decoys[decoy[0]] = float(decoy[1])\n rmsd_decoys_fo.close()\n return rmsd_decoys\n\n def __get_location_decoys(self, ppi):\n '''\n Get the decoys for each location\n '''\n # Check if needed files exists #\n decoys_location_path = os.path.join(self.job_path, ppi, 'decoys_location.txt')\n if not os.path.isfile(decoys_location_path):\n raise RuntimeError('NO DECOYS LOCATION FILE FOUND')\n # Get rmsds #\n location_decoys = {'N': [],'I': [], 'P': [], 'E': []}\n try:\n rmsd_decoys = self.__get_rmsd(ppi)\n except RuntimeError as e:\n raise e\n # Get location decoys #\n decoys_locations_fo = open(decoys_location_path, 'r')\n for decoy in decoys_locations_fo:\n decoy = decoy.strip('\\n').split('\\t')\n if not decoy[0] in rmsd_decoys:\n continue\n if rmsd_decoys[decoy[0]] < 10:\n location_decoys['N'].append(decoy[0])\n else:\n location_decoys[decoy[1]].append(decoy[0])\n decoys_locations_fo.close()\n return location_decoys\n\n def __get_energies(self, ppi, location_decoys, etype, zscores=False):\n '''\n Gets the energies for each location\n etype: fiberdock, sp or iLoops for choosing the energie type\n '''\n if etype == 'fiberdock':\n separator = '|'\n min_e = 1\n max_e = 11\n energies_path = os.path.join(self.job_path, ppi, '%s_energies.txt' % etype)\n energies_path_ref = os.path.join(self.job_path, ppi, '%s_energies.ref' % etype)\n if os.path.isfile(energies_path_ref):\n energies_path = energies_path_ref\n else:\n separator = '\\t'\n min_e = 2\n max_e = None\n energies_path = os.path.join(self.job_path, ppi, '%s.txt' % etype)\n if not os.path.isfile(energies_path):\n raise RuntimeError('NO %s ENERGIES FILE FOUND' % etype.upper())\n # Get energies #\n energies = {'N': [], 'I': [], 'P': [], 'E': []}\n energies_fo = open(energies_path, 'r')\n for decoy in energies_fo:\n decoy = decoy.strip('\\n').split(separator)\n if decoy[0].strip() in location_decoys['N']:\n energies['N'].append([float(energy.strip()) for energy in decoy[min_e:max_e]])\n if decoy[0].strip() in location_decoys['I']:\n energies['I'].append([float(energy.strip()) for energy in decoy[min_e:max_e]])\n if decoy[0].strip() in location_decoys['P']:\n energies['P'].append([float(energy.strip()) for energy in decoy[min_e:max_e]])\n if decoy[0].strip() in location_decoys['E']:\n energies['E'].append([float(energy.strip()) for energy in decoy[min_e:max_e]])\n energies_fo.close()\n if zscores:\n all_energies = energies['N']+energies['I']+energies['P']+energies['E']\n zenergies = {'N': [], 'I': [], 'P': [], 'E': []}\n zmean = np.nanmean(all_energies, axis=0)\n zstd = np.nanstd(all_energies, axis=0)\n for loc in energies:\n for decoy in energies[loc]:\n zenergies[loc].append((decoy-zmean)/zstd)\n return zenergies\n else:\n return energies\n\n def __print(self, energies):\n '''\n Print the resultant energies\n '''\n ene_fo = open('scores_locations_E+OX_std.txt' , 'w')\n for energie in energies:\n ene_fo.write('%s\\t' % energie[0])\n for x in xrange(len(energie[1])):\n ene_fo.write('%.2f\\t%.2f\\t%.2f\\t%.2f' % (energie[1][x], energie[2][x], energie[3][x], energie[4][x]))\n if x < len(energie[1])-1:\n ene_fo.write('\\t')\n ene_fo.write('\\n')\n ene_fo.close()\n\n#--------------------------#\n# MAIN #\n#--------------------------#\n\nif __name__ == \"__main__\":\n\n options = parse_options()\n\n ppi_file = os.path.abspath(options.ppi_file)\n job_path = os.path.abspath(options.job_path)\n \n analyze_ppi = AnalyzePPI(ppi_file, job_path, options.verbose) \n analyze_ppi.run()\n","sub_path":"src/Binding_Mechanism_Docking/analyze_scores.py","file_name":"analyze_scores.py","file_ext":"py","file_size_in_byte":8910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"319242429","text":"# Created by L.S. Urrea [lurreaferia@uniminuto.edu.co], J. Sanchez-Rojas [jsanchezro8@uniminuto.edu.co], & C.A.Sierra [carlos.andres.sierra.v@gmail.com] on May 2019.\n\n# Collaboration acknowlegments: María Fernanda Chaparro & Fernando Alvarez & Santiago Salazar.\n\n# Copyright (c) 2019 L.S. Urrea, J. Sanchez-Rojas, & C.A.Sierra. Research Group on Athenea. All rights reserved.\n\n#\n\n# This file is part of RaspXbee Project.\n\n#\n\n# RaspXbee Project is free software: you can redistribute it and/or modify it under the terms of the\n\n# GNU General Public License as published by the Free Software Foundation, version 3\n# Generated by Django 2.1.5 on 2019-06-08 22:15\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('appCode', '0005_auto_20190518_1633'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Cauce',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('velocidad', models.DecimalField(decimal_places=6, default=0.0, max_digits=10)),\n ('area', models.DecimalField(decimal_places=6, default=0.0, max_digits=10)),\n ('cauce', models.DecimalField(decimal_places=6, default=0.0, max_digits=10)),\n ('lluvia', models.DecimalField(decimal_places=6, default=0.0, max_digits=10)),\n ('fecha', models.DateField()),\n ('status', models.BooleanField(default='None', max_length=25)),\n ('nodo', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='appCode.Node')),\n ],\n ),\n migrations.AlterField(\n model_name='ethernet',\n name='gateway_fk',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='appCode.Gateway'),\n ),\n migrations.AlterField(\n model_name='node_gateway',\n name='gateway_fk',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='appCode.Gateway'),\n ),\n migrations.AlterField(\n model_name='simcard',\n name='gateway_fk',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='appCode.Gateway'),\n ),\n migrations.AlterField(\n model_name='wifi_gateway',\n name='gateway_fk',\n field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='appCode.Gateway'),\n ),\n ]\n","sub_path":"appCode/migrations/0006_auto_20190608_1715.py","file_name":"0006_auto_20190608_1715.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"15724459","text":"# -*- coding: utf-8 -*-\n# Copyright 2018 Mobicage NV\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# @@license_version:1.3@@\n\nimport datetime\nimport logging\n\nfrom google.appengine.ext import ndb\n\nfrom framework.utils import put_in_chunks, get_epoch_from_datetime\nfrom plugins.trash_calendar.consts import TrashCollector, TrashActivity, \\\n DEFAULT_COUNTRY\nfrom plugins.trash_calendar.models.common import UnconnectedStreet, Collection, Street\nfrom plugins.trash_calendar.utils import read_csv\n\n\ndef import_streets(country, collection_key, postal_code, stream):\n streets = read_csv(stream)\n logging.info(\"import_streets for %s has %s streets\", collection_key, len(streets))\n\n current_streets = {}\n for s in Street.list_by_postal_code(TrashCollector.IVLA, country, postal_code):\n for a in s.aliases:\n current_streets[a] = s.key\n\n to_put = []\n keys = [UnconnectedStreet.create_key(TrashCollector.IVLA, collection_key, s['Straat'])\n for s in streets]\n unconnected_streets = ndb.get_multi(keys)\n for s, us_key, unconnected_street in zip(streets, keys, unconnected_streets):\n if s['Straat'] in current_streets:\n continue\n if not unconnected_street:\n unconnected_street = UnconnectedStreet(key=us_key)\n unconnected_street.manual_conversion = False\n unconnected_street.country_code = DEFAULT_COUNTRY\n unconnected_street.collection_key = collection_key\n unconnected_street.name = s['Straat']\n unconnected_street.postal_code = s['Postcode']\n unconnected_street.city = s['Gemeente']\n to_put.append(unconnected_street)\n\n if to_put:\n logging.info('put %s items', len(to_put))\n put_in_chunks(to_put)\n\n\ndef import_collection_data(country, collection_key, year, stream):\n collections = read_csv(stream)\n logging.info(\"import_collection_data for %s has %s collections\", collection_key, len(collections))\n\n to_put = []\n for c in collections:\n activities = []\n for k, v in c.iteritems():\n if not v:\n continue\n activity = _get_activity_name(k)\n if not activity:\n continue\n activities.append(activity)\n\n if not activities:\n continue\n\n date = datetime.datetime.strptime(c['Datum'], '%b %d')\n epoch = get_epoch_from_datetime(datetime.date(year, date.month, date.day))\n to_put.append(Collection(\n key=Collection.create_key(TrashCollector.IVLA, country, epoch, collection_key),\n activities=activities,\n epoch=epoch,\n year=year,\n month=date.month,\n day=date.day,\n ))\n\n if to_put:\n logging.info('put %s items', len(to_put))\n put_in_chunks(to_put)\n\n\ndef _get_activity_name(name):\n if name in (u'Dag', u'Datum', u'WE - Feestdag',):\n return None\n mapping = {\n 'PMD': TrashActivity.PLASTIC_METAL_CARTONS,\n 'RESTAFVAL': TrashActivity.REST,\n 'P-K': TrashActivity.PAPER_CARDBOARD,\n 'TEXTIEL': TrashActivity.TEXTILE,\n 'SNOEIAFVAL': TrashActivity.PRUNING_WASTE,\n 'SNOEIAFVAL AFROEP': TrashActivity.PRUNING_WASTE_ON_DEMAND,\n 'GROF': TrashActivity.BULKY_WASTE,\n 'GROF AFROEP': TrashActivity.BULKY_WASTE_ON_DEMAND,\n 'KERSTBOOM': TrashActivity.CHRISTMAS_TREE,\n 'GFT': TrashActivity.VEGETABLE_FRUIT_GARDEN_WASTE,\n }\n if name not in mapping:\n raise Exception('Failed to get _get_activity_name for %s' % name)\n return mapping[name]\n","sub_path":"plugins/trash_calendar/bizz/ivla.py","file_name":"ivla.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"644844103","text":"import pandas as pd\nimport psycopg2\nimport os\nfrom ConfigParser import SafeConfigParser\n\n\nclass DBConnection(object):\n \"\"\"\n Opens connection with database based on the development.ini credentials\n \"\"\"\n def _get_db_url(self):\n p = SafeConfigParser()\n p.read(os.path.join(os.getenv(\"HOME\"), \"development.ini\"))\n\n return p.get('Database', 'sqlalchemy.url')\n\n def __enter__(self):\n self.conn = psycopg2.connect(self._get_db_url())\n return self.conn\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.conn.close()\n\n\ndef query_by_chain(chain):\n\n query = \"\"\"select name as gene_name,\n allele as allele,\n sigpend as signal_peptide_end,\n cdna as cdna_seq,\n cds as cds_seq,\n prot as pep_seq\n from binf_germline_seq \n where release_id = '383364251'\n and name like '{}%';\"\"\".format(chain)\n\n return query\n\n\ndef create_fasta_files(chain, query_results, path, is_gapped):\n\n if len(query_results) > 0:\n with open(path + \"/\" + chain + \"_AA_new.fasta\", \"w\") as file_aa:\n with open(path + \"/\" + chain + \"_NT_new.fasta\", \"w\") as file_nt:\n for index in query_results.index:\n result = query_results.iloc[index]\n\n parsed_results = parse_germline_sequences(result[\"gene_name\"],\n result[\"allele\"],\n result[\"cds_seq\"],\n result[\"pep_seq\"],\n result[\"signal_peptide_end\"],\n is_gapped)\n\n file_aa.write(\">\" + str(index) + \"|\" + parsed_results[0] + \"|\" + \" |\" * 13 + \"\\n\" + parsed_results[1] + \"\\n\")\n file_nt.write(\">\" + str(index) + \"|\" + parsed_results[0] + \"|\" + \" |\" * 13 + \"\\n\" + parsed_results[2] + \"\\n\")\n\n file_nt.close()\n file_aa.close()\n\n\ndef parse_germline_sequences(gene_name, allele, nt_seq, aa_seq, sig_pep_end, gapped=False):\n\n # allele_name = get_proper_allele_format(allele)\n full_name = gene_name + \"*\" + allele\n\n if sig_pep_end == -1 or pd.isnull(sig_pep_end):\n sequence_aa = aa_seq\n sequence_nt = nt_seq\n elif sig_pep_end != -1 and not pd.isnull(sig_pep_end):\n sequence_aa = aa_seq[int(sig_pep_end):]\n sequence_nt = nt_seq[int(sig_pep_end)*3:]\n\n if gapped is False:\n sequence_aa = sequence_aa.replace(\".\", \"\")\n sequence_nt = sequence_nt.replace(\".\", \"\")\n\n return (full_name, sequence_aa, sequence_nt)\n\n\ndef get_germline_seqs_from_db(path):\n with DBConnection() as conn:\n query_result = pd.read_sql_query(query_by_chain(\"IGH\"), conn)\n create_fasta_files(\"IGH\", query_result, path, False)\n\n query_result = pd.read_sql_query(query_by_chain(\"IGL\"), conn)\n create_fasta_files(\"IGL\", query_result, path, False)\n\n query_result = pd.read_sql_query(query_by_chain(\"IGK\"), conn)\n create_fasta_files(\"IGK\", query_result, path, False)\n\n\nif __name__ == \"__main__\":\n get_germline_seqs_from_db(\"../data\")\n","sub_path":"src/germline_seq.py","file_name":"germline_seq.py","file_ext":"py","file_size_in_byte":3378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"539513496","text":"import tensorflow as tf\nfrom PIL import Image\nimport numpy as np\nimport cv2\nfrom tensorflow.python.ops import gen_nn_ops\nfrom tensorflow.python.framework import ops\nfrom tensorflow.contrib.graph_editor import subgraph\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.python.util import compat\n\nclass GradCAM:\n def __init__(self, instance, sample_size):\n self.instance = instance\n self.sample_size = sample_size\n self.image_size = (400, 224) # (width, height)\n self.num_classes = 2 # class 개수\n\n def normalize(self, x):\n return tf.div(x, tf.expand_dims(tf.expand_dims(tf.expand_dims(tf.sqrt(\n tf.reduce_mean(tf.square(x), axis=(1, 2, 3))) + tf.constant(1e-5), axis=-1), axis=-1), axis=-1))\n\n def build(self):\n '''\n self.instance.logits: 신경망에서 softmax 거치기 전 layer 출력 변수\n self.instance.prob: softmax 거쳐서 나온 확률 변수\n self.instance.cam_layer: CAM 을 통해 보고자 하는 layer\n self.instance.sess: 해당 신경망 모델에서 사용하는 Session Instance\n '''\n with tf.variable_scope('grad_cam'):\n # cam_layer = self.instance.cam_layer\n # top1 = tf.argmax(tf.reshape(self.instance.prob, [-1]))\n # loss = tf.reduce_sum(tf.multiply(self.instance.prob, tf.one_hot(top1, self.num_classes)), axis=1) # (B, C) -> (B, )\n # grads = tf.gradients(ys=loss, xs=cam_layer)[0] # (B, H, W, C)\n # norm_grads = self.normalize(grads)\n # # norm_grads = tf.div(grads, tf.sqrt(tf.reduce_mean(tf.square(grads))) + 1e-5) # normalize\n #\n # weights = tf.reduce_mean(input_tensor=norm_grads, axis=(1, 2))\n # weights = tf.expand_dims(tf.expand_dims(weights, axis=1), axis=1)\n # height, width = cam_layer.get_shape().as_list()[1: 3]\n # cam = tf.ones(shape=[self.sample_size, height, width], dtype=tf.float32)\n # cam = tf.add(cam, tf.reduce_sum(input_tensor=tf.multiply(weights, cam_layer), axis=-1))\n # self.cam = tf.maximum(cam, 0, name='outputs')\n\n cam_layer = self.instance.cam_layer\n loss = tf.reduce_mean(tf.multiply(self.instance.logits, self.instance.prob), axis=-1)\n grads = tf.gradients(ys=loss, xs=cam_layer)[0] # (B, H, W, C)\n norm_grads = self.normalize(grads)\n\n weights = tf.reduce_mean(input_tensor=norm_grads, axis=(1, 2))\n weights = tf.expand_dims(tf.expand_dims(weights, axis=1), axis=1)\n height, width = cam_layer.get_shape().as_list()[1: 3]\n cam = tf.ones(shape=[self.sample_size, height, width], dtype=tf.float32)\n cam = tf.add(cam, tf.reduce_sum(input_tensor=tf.multiply(weights, cam_layer), axis=-1))\n self.cam = tf.maximum(cam, 0, name='outputs')\n\n def visualize(self, x, file_names):\n cam_output = self.instance.sess.run(self.cam,\n feed_dict={self.instance.x: x})\n cam_list = []\n\n for idx in range(self.sample_size):\n cam_output[idx] = cam_output[idx] / np.max(cam_output[idx])\n cam_list.append(cv2.resize(cam_output[idx], self.image_size))\n\n outputs = []\n\n for idx in range(self.sample_size):\n img = Image.open(file_names[idx], mode='r').convert('RGB')\n img = cv2.resize(np.asarray(img), self.image_size, interpolation=cv2.INTER_NEAREST)\n img = img.astype(float)\n img /= 255.\n\n img_cam = cv2.applyColorMap(np.uint8(255 * cam_list[idx]), cv2.COLORMAP_JET)\n img_cam = cv2.cvtColor(img_cam, cv2.COLOR_BGR2RGB)\n\n '''Grad-CAM 과 원본 이미지 중첩'''\n alpha = 0.0025\n output = img + alpha * img_cam\n output /= output.max()\n outputs.append(output)\n\n return outputs\n\n# def guided_grad(grad):\n# return tf.where(0. < grad, grad, tf.zeros_like(grad))\n#\n# @ops.RegisterGradient(\"GuidedRelu6\")\n# def _guided_grad_relu6(op, grad):\n# return guided_grad(gen_nn_ops._relu6_grad(grad, op.outputs[0]))\n\n\n# @ops.RegisterGradient(\"GuideRelu\")\n# def _GuidedReluGrad(op, grad):\n# return tf.where(0. < grad, gen_nn_ops._relu_grad(grad, op.outputs[0]), tf.zeros_like(grad))\n\nclass GuidedGradCAM:\n def __init__(self, instance, sample_size):\n self.instance = instance\n self.sample_size = sample_size\n self.image_size = (224, 224) # (width, height)\n\n def replace_grad_to_guided_grad(self, g):\n sgv = subgraph.make_view(g)\n with g.gradient_override_map({'Relu6': 'GuideRelu6'}):\n for op in sgv.ops:\n self._replace_grad(g, op)\n\n def _replace_grad(self, g, op):\n # ref: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/framework/ops.py\n # tf.Graph._gradient_override_map\n try:\n op_def = op._op_def\n node_def = op._node_def\n\n if op_def is not None:\n mapped_op_type = g._gradient_override_map[op_def.name]\n node_def.attr[\"_gradient_op_type\"].CopyFrom(\n attr_value_pb2.AttrValue(s=compat.as_bytes(mapped_op_type)))\n except KeyError:\n pass\n\n def normalize(self, x):\n return tf.div(x, tf.expand_dims(tf.expand_dims(tf.expand_dims(tf.sqrt(\n tf.reduce_mean(tf.square(x), axis=(1, 2, 3))) + tf.constant(1e-5), axis=-1), axis=-1), axis=-1))\n\n def build(self):\n '''\n self.instance.y: 신경망에서 사용하는 정답 라벨 변수 (onehot-encoding 으로 변환해야함)\n self.instance.prob: softmax 거쳐서 나온 확률 변수\n '''\n # with tf.get_default_graph().gradient_override_map({'Relu6': 'GuideRelu'}):\n # self.instance.build_graph()\n cam_layer = self.instance.cam_layer\n loss = tf.reduce_mean(tf.multiply(self.instance.logits, self.instance.prob), axis=1)\n grads = tf.gradients(ys=loss, xs=cam_layer)[0] # (B, H, W, C)\n norm_grads = self.normalize(grads)\n\n max_output = tf.reduce_max(cam_layer, axis=2)\n self.saliency_map = tf.gradients(tf.reduce_sum(max_output), self.instance.x)[0]\n\n weights = tf.reduce_mean(input_tensor=norm_grads, axis=(1, 2))\n weights = tf.expand_dims(tf.expand_dims(weights, axis=1), axis=1)\n height, width = cam_layer.get_shape().as_list()[1: 3]\n cam = tf.ones(shape=[self.sample_size, height, width], dtype=tf.float32)\n cam = tf.add(cam, tf.reduce_sum(input_tensor=tf.multiply(weights, cam_layer), axis=-1))\n cam = tf.maximum(cam, 0, name='outputs')\n self.cam = tf.div(cam, tf.reduce_max(cam))\n\n def backpropagation(self, x):\n saliency_val = self.instance.sess.run(self.saliency_map, feed_dict={self.instance.x: x,\n self.instance.is_training: False})\n return saliency_val\n\n def visualize(self, x, file_names):\n '''\n self.instance.logits: 신경망에서 softmax 거치기 전 layer 출력 변수\n self.instance.prob: softmax 거쳐서 나온 확률 변수\n self.instance.cam_layer: CAM 을 통해 보고자 하는 layer\n self.instance.sess: 해당 신경망 모델에서 사용하는 Session Instance\n '''\n cam_output, saliency_val = self.instance.sess.run([self.cam, self.saliency_map],\n feed_dict={self.instance.x: x,\n self.instance.training: False})\n cam = np.maximum(cam_output, 0)\n cam_list = []\n\n for idx in range(self.sample_size):\n cam[idx] = cam[idx] / np.max(cam[idx])\n cam_list.append(cv2.resize(cam[idx], self.image_size))\n\n cam_list = np.asarray(cam_list)[..., None] * saliency_val\n\n for idx in range(self.sample_size):\n cam_list[idx] -= np.mean(cam_list[idx])\n cam_list[idx] /= (np.std(cam_list[idx]) + 1e-5)\n cam_list[idx] *= 0.1\n\n cam_list[idx] += 0.5\n cam_list[idx] = np.clip(cam_list[idx], 0, 1)\n\n cam_list[idx] *= 255\n cam_list[idx] = np.clip(cam_list[idx], 0, 255).astype('uint8')\n cam_list[idx] = cv2.cvtColor(cam_list[idx], cv2.COLOR_BGR2RGB)\n\n return cam_list","sub_path":"Projects/Hongbog/DementiaDiagnosis/mobilenet_v2/native/cam.py","file_name":"cam.py","file_ext":"py","file_size_in_byte":8497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"101140863","text":"\n# coding: utf-8\n\n# Here goes the imports\nimport csv\nimport matplotlib.pyplot as plt\n\n# Let's read the data as a list\nprint(\"Reading the document...\")\nwith open(\"chicago.csv\", \"r\") as file_read:\n data_list = [{k: v for k, v in row.items()}\n for row in csv.DictReader(file_read, skipinitialspace=True)]\nprint(\"Ok!\")\n\n# Let's check how many rows do we have\nprint(\"Number of rows:\")\nprint(len(data_list))\nprint(data_list[0]['Gender'])\n# Printing the first row of data_list to check if it worked.\nprint(\"Row 0: \")\nprint(data_list[0])\n\nprint(\"Row 1: \")\nprint(data_list[1])\n\ninput(\"Press Enter to continue...\")\n# TASK 1\n# Print the first 20 rows using a loop to identify the data.\nprint(\"\\n\\nTASK 1: Printing the first 20 samples\")\nfor i in range(20):\n print(\"Row {} : {}\".format(i+1, data_list[i]))\n\n# We can access the features through name\n# E.g. sample['Gender'] to print gender\n\ninput(\"Press Enter to continue...\")\n# TASK 2\n# Print the `gender` of the first 20 rows\nprint(\"\\nTASK 2: Printing the genders of the first 20 samples\")\nfor i in range(20):\n print(\"Row {} : {}\".format(i+1, data_list[i]['Gender']))\n\n# Cool! We can get the rows(samples) iterating with a for and the columns(features) by name.\n# But it's still hard to get a column in a list. Example: List with all genders\n\ninput(\"Press Enter to continue...\")\n# TASK 3\n# Create a function to add the columns(features) of a list in another list in the same order\ndef column_to_list(data, index):\n \"\"\"\n Creates a list with all values from a collumn\n Args:\n data: The whole csv file with the data.\n index: The collumn index in the csv.\n Returns:\n List of all values in a collumn\n \"\"\"\n key_name = list(data[0].keys())[index]\n column_list = [line[key_name] for line in data]\n # Tip: You can use a for to iterate over the samples, get the feature by index and append into a list\n return column_list\n\n\n# Let's check with the genders if it's working (only the first 20)\nprint(\"\\nTASK 3: Printing the list of genders of the first 20 samples\")\nprint(column_to_list(data_list, -2)[:20])\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(column_to_list(data_list, -2)) is list, \"TASK 3: Wrong type returned. It should return a list.\"\nassert len(column_to_list(data_list, -2)) == 1551505, \"TASK 3: Wrong lenght returned.\"\nassert column_to_list(data_list, -2)[0] == \"\" and column_to_list(data_list, -2)[1] == \"Male\", \"TASK 3: The list doesn't match.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Now we know how to access the features, let's count how many Males and Females the dataset have\n# TASK 4\n# Count each gender. You should not use a function to do that.\ngender_list = column_to_list(data_list, -2)\nmale = sum(1 for gender in gender_list if gender == 'Male')\nfemale = sum(1 for gender in gender_list if gender == 'Female')\n\n\n# Checking the result\nprint(\"\\nTASK 4: Printing how many males and females we found\")\nprint(\"Male: \", male, \"\\nFemale: \", female)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert male == 935854 and female == 298784, \"TASK 4: Count doesn't match.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Why don't we creeate a function to do that?\n# TASK 5\n# Create a function to count the genders. Return a list\n# Should return a list with [count_male, counf_female] (e.g., [10, 15] means 10 Males, 15 Females)\ndef count_gender(data_list):\n \"\"\"\n Counts how many of each gender exists in the csv\n Args:\n data_list: A list with all gender values.\n Returns:\n The count of male and female\n \"\"\"\n male = sum(1 for row in data_list if row['Gender'] == 'Male')\n female = sum(1 for row in data_list if row['Gender'] == 'Female')\n return [male, female]\n\n\nprint(\"\\nTASK 5: Printing result of count_gender\")\nprint(count_gender(data_list))\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(count_gender(data_list)) is list, \"TASK 5: Wrong type returned. It should return a list.\"\nassert len(count_gender(data_list)) == 2, \"TASK 5: Wrong lenght returned.\"\nassert count_gender(data_list)[0] == 935854 and count_gender(data_list)[1] == 298784, \"TASK 5: Returning wrong result!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Now we can count the users, which gender use it the most?\n# TASK 6\n# Create a function to get the most popular gender and print the gender as string.\n# We expect to see \"Male\", \"Female\" or \"Equal\" as answer.\ndef most_popular_gender(data_list):\n \"\"\"\n Retuns which gender is most popular in the data_list\n Args:\n data_list: A list with all gender values.\n Returns:\n A string with the most popular gender(Male or Female); if they are equals returns Equal\n \"\"\"\n male_count, female_count = count_gender(data_list)\n \n if (male_count == female_count):\n return \"Equal\"\n\n return \"Male\" if male_count > female_count else \"Female\"\n\n\nprint(\"\\nTASK 6: Which one is the most popular gender?\")\nprint(\"Most popular gender is: \", most_popular_gender(data_list))\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert type(most_popular_gender(data_list)) is str, \"TASK 6: Wrong type returned. It should return a string.\"\nassert most_popular_gender(data_list) == \"Male\", \"TASK 6: Returning wrong result!\"\n# -----------------------------------------------------\n\n# If it's everything running as expected, check this graph!\ngender_list = column_to_list(data_list, -2)\ntypes = [\"Male\", \"Female\"]\nquantity = count_gender(data_list)\ny_pos = list(range(len(types)))\nplt.bar(y_pos, quantity)\nplt.ylabel('Quantity')\nplt.xlabel('Gender')\nplt.xticks(y_pos, types)\nplt.title('Quantity by Gender')\nplt.show(block=True)\n\ninput(\"Press Enter to continue...\")\n# TASK 7\n# Plot a similar graph for user_types. Make sure the legend is correct.\nprint(\"\\nTASK 7: Check the chart!\")\ndef count_usertype(data_list):\n \"\"\"\n Counts how many of each user type exists in the csv\n Args:\n data_list: A list with all user type values.\n Returns:\n A list with the count of each user type\n \"\"\"\n customer = sum(1 for row in data_list if row['User Type'] == 'Customer')\n subscriber = sum(1 for row in data_list if row['User Type'] == 'Subscriber')\n dependent = sum(1 for row in data_list if row['User Type'] == 'Dependent')\n return [customer, subscriber, dependent]\n\ntypes = [\"Customer\", \"Subscriber\", 'Dependent']\n\nquantity = count_usertype(data_list)\ny_pos = list(range(len(types)))\n\nplt.bar(y_pos, quantity)\nplt.ylabel('Quantity')\nplt.xlabel('User Type')\nplt.xticks(y_pos, types)\nplt.title('Quantity by User Type')\nplt.show(block=True)\n\ninput(\"Press Enter to continue...\")\n# TASK 8\n# Answer the following question\nmale, female = count_gender(data_list)\nprint(\"\\nTASK 8: Why the following condition is False?\")\nprint(\"male + female == len(data_list):\", male + female == len(data_list))\nanswer = \"Some rows do not have information about gender.\"\nprint(\"Answer:\", answer)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert answer != \"Type your answer here.\", \"TASK 8: Write your own answer!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# Let's work with the trip_duration now. We cant get some values from it.\n# TASK 9\n# Find the Minimum, Maximum, Mean and Median trip duration.\n# You should not use ready functions to do that, like max() or min().\ntrip_duration_list = sorted([int(i) for i in column_to_list(data_list, 2)])\ntrip_list_len = len(trip_duration_list)\n\nmin_trip = trip_duration_list[0]\nmax_trip = trip_duration_list[-1]\nmean_trip = sum(trip_duration_list) / trip_list_len\nif trip_list_len % 2 == 0:\n median_trip = sum(trip_duration_list[trip_list_len//2-1:trip_list_len//2+1]) / 2\nelse:\n median_trip = trip_duration_list[trip_list_len//2]\n\n\nprint(\"\\nTASK 9: Printing the min, max, mean and median\")\nprint(\"Min: \", min_trip, \"Max: \", max_trip, \"Mean: \", mean_trip, \"Median: \", median_trip)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert round(min_trip) == 60, \"TASK 9: min_trip with wrong result!\"\nassert round(max_trip) == 86338, \"TASK 9: max_trip with wrong result!\"\nassert round(mean_trip) == 940, \"TASK 9: mean_trip with wrong result!\"\nassert round(median_trip) == 670, \"TASK 9: median_trip with wrong result!\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# TASK 10\n# Gender is easy because usually only have a few options. How about start_stations? How many options does it have?\n# Check types how many start_stations do we have using set()\nuser_types = set(column_to_list(data_list, 3))\n\nprint(\"\\nTASK 10: Printing start stations:\")\nprint(len(user_types))\nprint(user_types)\n\n# ------------ DO NOT CHANGE ANY CODE HERE ------------\nassert len(user_types) == 582, \"TASK 10: Wrong len of start stations.\"\n# -----------------------------------------------------\n\ninput(\"Press Enter to continue...\")\n# TASK 11\n# Go back and make sure you documented your functions. Explain the input, output and what it do. Example:\n# # def new_function(param1: int, param2: str) -> list:\n# \"\"\"\n# Example function with annotations.\n# Args:\n# param1: The first parameter.\n# param2: The second parameter.\n# Returns:\n# List of X values\n\n# \"\"\"\n\ninput(\"Press Enter to continue...\")\n# TASK 12 - Challenge! (Optional)\n# Create a function to count user types without hardcoding the types\n# so we can use this function with a different kind of data.\nprint(\"Will you face it?\")\nanswer = \"yes\"\n\ndef count_items(column_list):\n \"\"\"\n Counts a the unique values from a column and how many itens it have\n Args:\n column_list: A list with all values from a column.\n Returns:\n Returns the unique values from a column and how many itens it have\n \"\"\"\n item_types = set(column_list)\n count_items = list(1 for i in column_list)\n return item_types, count_items\n\n\nif answer == \"yes\":\n # ------------ DO NOT CHANGE ANY CODE HERE ------------\n column_list = column_to_list(data_list, -2)\n types, counts = count_items(column_list)\n print(\"\\nTASK 11: Printing results for count_items()\")\n print(\"Types:\", types, \"Counts:\", counts)\n assert len(types) == 3, \"TASK 11: There are 3 types of gender!\"\n assert sum(counts) == 1551505, \"TASK 11: Returning wrong result!\"\n # -----------------------------------------------------","sub_path":"chicago_bikeshare_en.py","file_name":"chicago_bikeshare_en.py","file_ext":"py","file_size_in_byte":10584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"171276838","text":"import random\n\n# Define a dictionary of possible questions and answers\nquestions = {\n \"What is your computer's operating system?\": [\"Windows\", \"Mac\", \"Linux\"],\n \"What is the error message you are seeing?\": [\"Can't connect to internet\", \"Blue screen of death\", \"Program won't open\"],\n \"Have you tried restarting your computer?\": [\"Yes\", \"No\"]\n}\n\n# Define a function to handle user input and generate a response\ndef chatbot():\n # Ask the user for their name\n name = input(\"Hi! What's your name? \")\n\n # Greet the user\n print(f\"Nice to meet you, {name}! I'm here to help with your IT issue.\")\n\n # Ask questions and get answers from the user\n for question, possible_answers in questions.items():\n answer = input(question + \" \")\n while answer not in possible_answers:\n print(\"Sorry, I didn't understand your answer. Please try again.\")\n answer = input(question + \" \")\n print(\"Great, thanks for letting me know!\")\n\n # Generate a random response to the user's issue\n responses = [\n \"I think I know what's going on. Try restarting your computer and see if that fixes the issue.\",\n \"I'm not sure what the issue is, but I'll create a ticket and have someone from IT contact you soon.\",\n \"I need more information to help you with this issue. Can you provide any more details?\"\n ]\n print(random.choice(responses))\n\n# Call the chatbot function to start the conversation\nchatbot()\n","sub_path":"Chatbot/chatbot2.py","file_name":"chatbot2.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"632002145","text":"# 20-03-02\n# EX 33.6\n\ndef countdown(n):\n def onesec():\n nonlocal n\n n -= 1\n return n + 1\n return onesec\n\nn = int(input())\nc = countdown(n)\nfor i in range(n):\n print(c(), end=' ')\n","sub_path":"dojang/py33_06.py","file_name":"py33_06.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"375185103","text":"''' exercise 16. Write a function filter_long_words() that takes a list of words and an integer n and returns the list of words that are longer than n.\n'''\ndef filter_long_words(input_list, n):\n return_list = []\n for i in input_list:\n if len(i) > n:\n return_list.append(i)\n return return_list\n\n \n","sub_path":"exercise16.py","file_name":"exercise16.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"163351988","text":"import MMIDic\r\nimport MMIRevolver2\r\nimport sys\r\nimport string\r\nimport LPMaker\r\nfrom lpsolve55 import *\r\n\r\n \r\nclass ClusterCandidate:\r\n def __init__(self,cluster,ppiFilter,geneID2IRDic,gtsp,mmiDic):\r\n self.ppiFilter = ppiFilter\r\n self.protein2MotifDic={};\r\n self.mmiDic=mmiDic\r\n self.lpMaker= LPMaker.LPMaker()\r\n self.cluster = cluster\r\n\r\n self.lp=None\r\n self.ppi2mmiDic={}\r\n self.mmi2ppiDic={}\r\n self.variables2ppiOrMmi={}\r\n self.ppiOrMmi2Variables={}\r\n self.ppiVars=set()\r\n self.mmiVars=set()\r\n \r\n self.wholeProteinMotifSet=set()\r\n #print \"ClusterCandidate init id =\",cluster.clusterId\r\n self.makeProtein2MotifDic(cluster,gtsp,geneID2IRDic)\r\n \r\n def makeProtein2MotifDic(self,cluster,gtsp,geneID2IRDic):\r\n for protein in cluster.proteinList:\r\n irList=[]\r\n motifList = gtsp.geneid_to_motif(protein)\r\n if motifList:\r\n self.protein2MotifDic[protein] = motifList\r\n if protein in geneID2IRDic:\r\n irList = geneID2IRDic[protein]\r\n if irList:\r\n for ir in irList:\r\n if protein in self.protein2MotifDic:\r\n self.protein2MotifDic[protein].append(ir)\r\n else:\r\n self.protein2MotifDic[protein]=[ir]\r\n if not irList and not motifList:\r\n wholeMotif= protein+\"Whole\"\r\n self.wholeProteinMotifSet.add(wholeMotif)\r\n\r\n if protein in self.protein2MotifDic:\r\n self.protein2MotifDic[protein].append(wholeMotif)\r\n else:\r\n self.protein2MotifDic[protein]=[wholeMotif]\r\n \"\"\"\r\n if motifList or irList:\r\n sys.stderr.write(\"ClusterCandidate init \"+protein+\":\"+str(len(self.protein2MotifDic[protein]))+\"\\n\")\r\n else:\r\n sys.stderr.write(\"ClusterCandidate init \"+protein+\":\"+\"\\n\")\r\n print\r\n \"\"\" \r\n def getMaxLinks(self):\r\n score = 0\r\n for p1 in self.cluster.proteinList:\r\n for p2 in self.cluster.proteinList:\r\n if p1 !=p2 and self.ppiFilter.isExist(p1,p2):\r\n score +=1\r\n return score/2\r\n def checkMMI(self):\r\n #sys.stderr.write(\"checkMMI\\n\")\r\n keys =self.protein2MotifDic.keys()\r\n length =len(keys)\r\n ppiSet =set()\r\n for i in range(length):\r\n p1 = keys[i]\r\n for j in range(length-(i+1)):\r\n p2 = keys[j+i+1]\r\n if p1 !=p2 and self.ppiFilter.isExist(p1,p2):\r\n selfMotifs = self.protein2MotifDic[p1]\r\n for motif1 in selfMotifs:\r\n otherMotifs = self.protein2MotifDic[p2]\r\n for motif2 in otherMotifs:\r\n if self._isExist(motif1,motif2):\r\n if motif1 in self.mmiDic and motif2 in self.mmiDic:\r\n sourceID =self.mmiDic[motif1][motif2]\r\n else:\r\n sourceID = \"psuedo\"\r\n mmiPair = MMIRevolver2.MMIPair(motif1,motif2,p1,p2,sourceID)\r\n self._putPPI2MMIDic(p1,p2,motif1,motif2,str(mmiPair))\r\n self._putMMI2PPIDic(p1, p2, motif1, motif2,str(mmiPair))\r\n ppiSet.add(p1+p2)\r\n return len(ppiSet)\r\n def getDomainBasedVariables(self):\r\n\r\n for motif in self.mmi2ppiDic:\r\n if len(self.mmi2ppiDic[motif])>1:\r\n for mmiPair in self.mmi2ppiDic[motif]:\r\n self.mmiVars.add(str(mmiPair))\r\n if len(self.mmi2ppiDic[motif])>0:\r\n for mmiPair in self.mmi2ppiDic[motif]:\r\n self.mmiVars.add(str(mmiPair))\r\n def addDomainBasedConstraint(self):\r\n for motif in self.mmi2ppiDic:\r\n if len(self.mmi2ppiDic[motif])>1:\r\n params=self._getMMIParams(self.mmi2ppiDic[motif])\r\n self.lpMaker.addDomainBasedConstraints(self.lp,params)\r\n \r\n def getInteractionBasedVariables(self):\r\n\r\n for p1 in self.ppi2mmiDic:\r\n for p2 in self.ppi2mmiDic[p1]:\r\n ppi=self._getPPI(p1, p2) \r\n mmiList=self.ppi2mmiDic[p1][p2]\r\n self.ppiVars.add(ppi)\r\n\r\n \r\n def addInteractionBasedConstraints(self):\r\n for p1 in self.ppi2mmiDic:\r\n for p2 in self.ppi2mmiDic[p1]:\r\n ppi=self._getPPI(p1, p2) \r\n mmiList=self.ppi2mmiDic[p1][p2] \r\n params = self._getMMIAndPPIParams(ppi,mmiList)\r\n self.lpMaker.addInteractionsBasedConstraints(self.lp,params)\r\n self._getExclusiveParams(mmiList)\r\n params2= self._getExclusiveParams(mmiList)\r\n #self.lpMaker.addSos(self.lp,params2)\r\n def mergeVars(self):\r\n i=0\r\n for ppiVar in self.ppiVars:\r\n #print ppiVar\r\n self.ppiOrMmi2Variables[ppiVar]=i\r\n self.variables2ppiOrMmi[i]=ppiVar\r\n i+=1\r\n for mmiVar in self.mmiVars:\r\n #print mmiVar\r\n self.ppiOrMmi2Variables[mmiVar]=i\r\n self.variables2ppiOrMmi[i]=mmiVar\r\n i+=1\r\n def getProteinSet(self,vars):\r\n ppiNum = len(self.ppiVars)\r\n i=0\r\n proteinSet = set()\r\n \r\n for var in vars:\r\n if var ==1.0 and i=ppiNum:\r\n mmi=self.variables2ppiOrMmi[i]\r\n mmiSet.add(mmi)\r\n i+=1\r\n return mmiSet\r\n \r\n def printMMIs(self):\r\n for p1 in self.ppi2mmiDic:\r\n for p2 in self.ppi2mmiDic[p1]:\r\n mmiList = self.ppi2mmiDic[p1][p2]\r\n print(p1,p2,mmiList)\r\n \r\n def _parsePPI(self,ppi):\r\n return ppi.split(\"_\")\r\n def createLP(self):\r\n self.lp=self.lpMaker.createLP(self.ppiOrMmi2Variables.keys())\r\n self.lpMaker.setVarConstraint(self.lp)\r\n self.lpMaker.setObjectives(len(self.ppiVars),self.ppiOrMmi2Variables.keys(),self.lp)\r\n def _getMMIParams(self,mmiList):\r\n params=[]\r\n \r\n for i in range(len(self.variables2ppiOrMmi.keys())):\r\n \r\n if self.variables2ppiOrMmi[i] in mmiList:\r\n params.append(1)\r\n else:\r\n params.append(0)\r\n return params\r\n def _getMMIAndPPIParams(self,ppi,mmiList):\r\n params=[]\r\n \r\n for i in range(len(self.variables2ppiOrMmi.keys())):\r\n if self.variables2ppiOrMmi[i] == ppi:\r\n params.append(-1)\r\n elif self.variables2ppiOrMmi[i] in mmiList:\r\n params.append(1)\r\n else:\r\n params.append(0)\r\n return params\r\n def _getExclusiveParams(self,mmiList):\r\n params=[]\r\n \r\n for mmi in mmiList:\r\n params.append(self.ppiOrMmi2Variables[mmi]+1)\r\n \r\n return params\r\n \r\n def _putMMI2PPIDic(self,p1,p2,motif1,motif2,mmiPair):\r\n pMotif1=self._getPmotif(p1, motif1)\r\n pMotif2=self._getPmotif(p2, motif2)\r\n\r\n if pMotif1 in self.mmi2ppiDic:\r\n self.mmi2ppiDic[pMotif1].append(mmiPair)\r\n else:\r\n self.mmi2ppiDic[pMotif1]=[mmiPair]\r\n\r\n if pMotif2 in self.mmi2ppiDic:\r\n self.mmi2ppiDic[pMotif2].append(mmiPair)\r\n else:\r\n self.mmi2ppiDic[pMotif2]=[mmiPair]\r\n def _getPmotif(self,p,motif):\r\n return string.join([p,motif], \".\")\r\n def _getPPI(self,p1,p2):\r\n return string.join([p1,p2], \"_\")\r\n \r\n def _putPPI2MMIDic(self,p1,p2,motif1,motif2,mmiPair):\r\n if p1 in self.ppi2mmiDic:\r\n if p2 in self.ppi2mmiDic[p1]:\r\n self.ppi2mmiDic[p1][p2].append(mmiPair) \r\n else:\r\n self.ppi2mmiDic[p1][p2] = [mmiPair] \r\n else:\r\n self.ppi2mmiDic[p1] = {p2:[mmiPair]} \r\n \r\n\r\n def _isExist(self,motif1,motif2):\r\n flag = False\r\n if motif1 in self.mmiDic:\r\n if motif2 in self.mmiDic[motif1]:\r\n flag = True\r\n if motif1 in self.wholeProteinMotifSet or motif2 in self.wholeProteinMotifSet:\r\n flag = True\r\n \r\n return flag\r\n\r\n ","sub_path":"csplugins/trunk/ucsd/rsaito/rs_Progs/rs_Python/rs_Python_Pack/trunk/IVV_Packages/YO_IP/ClusterCandidates2IPFormat4.py","file_name":"ClusterCandidates2IPFormat4.py","file_ext":"py","file_size_in_byte":8850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"445674379","text":"#!/usr/local/bin/python\n\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom serial import Serial, SerialException\nimport math\n\ncxn = Serial('/dev/cu.usbmodem1411', baudrate=9600)\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nver_pos = []\nhor_pos = []\ndist = []\nreadings = []\nrun = 1\n\ndef get_ver_pos(s):\n result = s[0:s.index(',')] \n return int(result)\n\ndef get_hor_pos(s):\n result = s[(s.index(',')+1): (s.rindex(','))]\n return int(result)\n\ndef get_dist(s):\n result = s[(s.rindex(',')+1):]\n return float(result)\n\nwhile(True):\n try:\n cmd_id = int(input(\"Please enter a command ID (1 - start, 2 - do nothing: \"))\n if int(cmd_id) > 2 or int(cmd_id) < 1:\n print(\"Values other than 1 or 2 are ignored.\")\n else:\n cxn.write([int(cmd_id)])\n while cxn.inWaiting() < 1:\n pass\n for i in range(0, 900):\n reading = cxn.readline();\n print(reading)\n readings.append(reading)\n break\n except ValueError:\n print(\"You must enter an integer value between 1 and 2.\")\n\nfor reading in readings:\n reading = reading.decode()\n reading = reading.replace(\"\\r\\n\", \"\")\n ver = get_ver_pos(reading)\n hor = get_hor_pos(reading)\n distance = get_dist(reading)\n ver_pos.append(math.radians(ver))\n hor_pos.append(math.radians(hor))\n dist.append(distance)\nx = []\ny = []\nz = []\nfor i in range(0, len(dist)-1):\n if (dist[i] >= 12 and dist[i] <= 36):\n x.append(dist[i]*math.cos(ver_pos[i])*math.cos(hor_pos[i]))\n y.append(dist[i]*math.cos(ver_pos[i])*math.sin(hor_pos[i]))\n z.append(dist[i]*math.sin(ver_pos[i]))\nprint(x)\n\nplt.scatter(x, y, z)\nax.set_xlabel('X Label')\nax.set_ylabel('Y Label')\nax.set_zlabel('Z Label')\n\nplt.show()\n","sub_path":"SendReceive3d.py","file_name":"SendReceive3d.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"114094408","text":"import pygame\nimport sys\ntry:\n from playsound import playsound\n LOCALaudioAvailable = True\n print(\"Playsound available.\")\nexcept:\n print(\"No Playsound module found!\")\n\ndef main(screen, g, font, pokImg, backImg):\n stage = 0\n if LOCALaudioAvailable == True:\n g.audioAvailable = True\n while stage == 0:\n titleTextImg, rect = font.render(\"ZIRCON\", (44, 93, 255))\n backImg = pygame.transform.scale(backImg, (g.screenWidth, g.screenHeight))\n screen.blit(backImg, (0, 0))\n screen.blit(pokImg, ((g.screenWidth/2)-(pokImg.get_size()[0]/2), (g.screenHeight/2)-(pokImg.get_size()[1]/2)-90))\n screen.blit(titleTextImg, ((g.screenWidth/2)-(titleTextImg.get_size()[0]/2), (g.screenHeight/2)-(titleTextImg.get_size()[1]/2)+90))\n pygame.display.flip()\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.MOUSEBUTTONDOWN:\n g.mouseClickX, g.mouseClickY = event.pos\n playsound(\"assets/audio/select.mp3\")\n stage = 1\n while stage == 1:\n screen.blit(backImg, (50, 50))\n pygame.display.flip()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()","sub_path":"scenes/opening.py","file_name":"opening.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"216818745","text":"import tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport os\n\n#################################################\n## BOUNDING BOX HANDLING\n#################################################\n\ndef getLocations(image_key, config, randomize=True):\n keys = image_key.split(\"/\")\n locations_file = \"{}/locations/{}-{}.csv\".format(\n keys[0], \n keys[1], \n config[\"sampling\"][\"locations_field\"]\n )\n locations_path = os.path.join(config[\"image_set\"][\"path\"], locations_file)\n if os.path.exists(locations_path):\n locations = pd.read_csv(locations_path)\n random_sample = config[\"sampling\"][\"locations\"]\n if randomize and random_sample is not None and random_sample < len(locations):\n return locations.sample(random_sample)\n else:\n return locations\n else:\n y_key = config[\"sampling\"][\"locations_field\"] + \"_Location_Center_Y\"\n x_key = config[\"sampling\"][\"locations_field\"] + \"_Location_Center_X\"\n return pd.DataFrame(columns=[x_key, y_key])\n\n\ndef prepareBoxes(locationsBatch, imageLabels, config):\n all_boxes = []\n all_indices = []\n all_labels = []\n index = 0\n y_key = config[\"sampling\"][\"locations_field\"] + \"_Location_Center_Y\"\n x_key = config[\"sampling\"][\"locations_field\"] + \"_Location_Center_X\"\n for locations in locationsBatch:\n boxes = np.zeros((len(locations), 4), np.float32)\n boxes[:,0] = locations[y_key] - config[\"sampling\"][\"box_size\"]/2\n boxes[:,1] = locations[x_key] - config[\"sampling\"][\"box_size\"]/2\n boxes[:,2] = locations[y_key] + config[\"sampling\"][\"box_size\"]/2\n boxes[:,3] = locations[x_key] + config[\"sampling\"][\"box_size\"]/2\n boxes[:,[0,2]] /= config[\"image_set\"][\"height\"]\n boxes[:,[1,3]] /= config[\"image_set\"][\"width\"]\n box_ind = index * np.ones((len(locations)), np.int32)\n labels = imageLabels[index] * np.ones((len(locations)), np.int32)\n all_boxes.append(boxes)\n all_indices.append(box_ind)\n all_labels.append(labels)\n index += 1\n return np.concatenate(all_boxes), np.concatenate(all_indices), np.concatenate(all_labels)\n\ndef loadBatch(dataset, config):\n batch = dataset.getTrainBatch(config[\"sampling\"][\"images\"])\n batch[\"locations\"] = [ getLocations(x, config) for x in batch[\"keys\"] ]\n return batch\n\n#################################################\n## CROPPING AND TRANSFORMATION OPERATIONS\n#################################################\n\ndef crop(image_ph, boxes_ph, box_ind_ph, box_size):\n with tf.variable_scope(\"cropping\"):\n crop_size_ph = tf.constant([box_size, box_size], name=\"crop_size\")\n crops = tf.image.crop_and_resize(image_ph, boxes_ph, box_ind_ph, crop_size_ph)\n return crops\n\ndef augment(crop):\n with tf.variable_scope(\"augmentation\"):\n augmented = tf.image.random_flip_left_right(crop)\n angle = tf.random_uniform([1], minval=0, maxval=3, dtype=tf.int32)\n augmented = tf.image.rot90(augmented, angle[0])\n return augmented\n\ndef aument_multiple(crops, parallel=10):\n with tf.variable_scope(\"augmentation\"):\n return tf.map_fn(augment, crops, parallel_iterations=parallel)\n","sub_path":"learning/cropping.py","file_name":"cropping.py","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"402893436","text":"'''\nGiven two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.\n'''\nclass Solution:\n def findLength(self, A, B):\n length1 = len(A)\n length2 = len(B)\n temp = [[0] * (length2 + 1) for k in range(length1 + 2)]\n max_num = 0\n for i in range(1, length1 + 1):\n #print(temp[i - 1])\n for j in range(1, length2 + 1):\n if A[i - 1] == B[j - 1]:\n #print(temp[i][j], temp[i - 1][j - 1], i, j)\n temp[i][j] = temp[i - 1][j - 1] + 1\n #print(temp[0])\n #print(temp[1])\n #print(temp[i - 1])\n #print(temp[i])\n #print(temp)\n for m in range(len(temp)):\n max_num = max(max_num, max(temp[m]))\n #print(max_num)\n #(temp)\n return max_num\nnums1 = [1,2,3,2,1]\nnums2 = [3,2,1,4,7]\nfunction = Solution()\nfunction.findLength(nums1, nums2)\n[0, 1, 0, 0, 0, 1]\n[1, 1, 0, 0, 1, 2]\n[0, 1, 2, 3, 1, 2]\n[0, 1, 2, 3, 1, 2]\n[1, 1, 2, 3, 1, 2]\n[1, 1, 2, 3, 4, 5]","sub_path":"Array/problem718/Maximum_Length_of_Repeated_Subarray.py","file_name":"Maximum_Length_of_Repeated_Subarray.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"233226964","text":"# \t7. Given an unsorted integer array A, find the sum of all the elements in A.\r\n\r\n\r\na = [2,9,8,5,6,6]\r\n\r\nsum = 0\r\nfor i in a:\r\n sum = sum + i\r\n\r\nprint(\"Sum of given array is : \",sum)","sub_path":"array7.py","file_name":"array7.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"638755437","text":"from __future__ import absolute_import, unicode_literals\n\nimport logging\n\nfrom django.contrib import messages\nfrom django.shortcuts import get_object_or_404\nfrom django.template import RequestContext\nfrom django.urls import reverse_lazy\nfrom django.utils.translation import ugettext_lazy as _, ungettext\n\nfrom acls.models import AccessControlList\nfrom common.views import (\n MultipleObjectFormActionView, SingleObjectCreateView,\n SingleObjectDeleteView, SingleObjectEditView, SingleObjectListView\n)\nfrom documents.permissions import permission_document_view\nfrom documents.models import Document\nfrom documents.views import DocumentListView\n\nfrom .forms import CabinetListForm\nfrom .icons import icon_cabinet\nfrom .links import (\n link_cabinet_add_document, link_cabinet_child_add, link_cabinet_create\n)\nfrom .models import Cabinet\nfrom .permissions import (\n permission_cabinet_add_document, permission_cabinet_create,\n permission_cabinet_delete, permission_cabinet_edit,\n permission_cabinet_view, permission_cabinet_remove_document\n)\nfrom .widgets import jstree_data\n\nlogger = logging.getLogger(__name__)\n\n\nclass CabinetCreateView(SingleObjectCreateView):\n fields = ('label',)\n model = Cabinet\n post_action_redirect = reverse_lazy('cabinets:cabinet_list')\n view_permission = permission_cabinet_create\n\n def get_extra_context(self):\n return {\n 'title': _('Create cabinet'),\n }\n\n\nclass CabinetChildAddView(SingleObjectCreateView):\n fields = ('label',)\n model = Cabinet\n\n def form_valid(self, form):\n \"\"\"\n If the form is valid, save the associated model.\n \"\"\"\n self.object = form.save(commit=False)\n self.object.parent = self.get_object()\n self.object.save()\n\n return super(CabinetChildAddView, self).form_valid(form)\n\n def get_object(self, *args, **kwargs):\n cabinet = super(CabinetChildAddView, self).get_object(*args, **kwargs)\n\n AccessControlList.objects.check_access(\n permissions=permission_cabinet_edit, user=self.request.user,\n obj=cabinet.get_root()\n )\n\n return cabinet\n\n def get_extra_context(self):\n return {\n 'title': _(\n 'Add new level to: %s'\n ) % self.get_object().get_full_path(),\n }\n\n\nclass CabinetDeleteView(SingleObjectDeleteView):\n model = Cabinet\n object_permission = permission_cabinet_delete\n post_action_redirect = reverse_lazy('cabinets:cabinet_list')\n\n def get_extra_context(self):\n return {\n 'object': self.get_object(),\n 'title': _('Delete the cabinet: %s?') % self.get_object(),\n }\n\n\nclass CabinetDetailView(DocumentListView):\n template_name = 'cabinets/cabinet_details.html'\n\n def get_document_queryset(self):\n queryset = AccessControlList.objects.filter_by_access(\n permission=permission_document_view, user=self.request.user,\n queryset=self.get_object().documents.all()\n )\n\n return queryset\n\n def get_context_data(self, **kwargs):\n context = super(CabinetDetailView, self).get_context_data(**kwargs)\n\n cabinet = self.get_object()\n\n context.update(\n {\n 'column_class': 'col-xs-12 col-sm-6 col-md-4 col-lg-3',\n 'hide_links': True,\n 'jstree_data': '\\n'.join(\n jstree_data(node=cabinet.get_root(), selected_node=cabinet)\n ),\n 'list_as_items': True,\n 'no_results_icon': icon_cabinet,\n 'no_results_main_link': link_cabinet_child_add.resolve(\n context=RequestContext(\n request=self.request, dict_={'object': cabinet}\n )\n ),\n 'no_results_text': _(\n 'Cabinet levels can contain documents or other '\n 'cabinet sub levels. To add documents to a cabinet, '\n 'select the cabinet view of a document view.'\n ),\n 'no_results_title': _('This cabinet level is empty'),\n 'object': cabinet,\n 'title': _('Details of cabinet: %s') % cabinet.get_full_path(),\n }\n )\n\n return context\n\n def get_object(self):\n cabinet = get_object_or_404(Cabinet, pk=self.kwargs['pk'])\n\n if cabinet.is_root_node():\n permission_object = cabinet\n else:\n permission_object = cabinet.get_root()\n\n AccessControlList.objects.check_access(\n permissions=permission_cabinet_view, user=self.request.user,\n obj=permission_object\n )\n\n return cabinet\n\n\nclass CabinetEditView(SingleObjectEditView):\n fields = ('label',)\n model = Cabinet\n object_permission = permission_cabinet_edit\n post_action_redirect = reverse_lazy('cabinets:cabinet_list')\n\n def get_extra_context(self):\n return {\n 'object': self.get_object(),\n 'title': _('Edit cabinet: %s') % self.get_object(),\n }\n\n\nclass CabinetListView(SingleObjectListView):\n object_permission = permission_cabinet_view\n\n def get_extra_context(self):\n return {\n 'hide_link': True,\n 'title': _('Cabinets'),\n 'no_results_icon': icon_cabinet,\n 'no_results_main_link': link_cabinet_create.resolve(\n context=RequestContext(request=self.request)\n ),\n 'no_results_text': _(\n 'Cabinets are a multi-level method to organize '\n 'documents. Each cabinet can contain documents as '\n 'well as other sub level cabinets.'\n ),\n 'no_results_title': _('No cabinets available'),\n }\n\n def get_object_list(self):\n # Add explicit ordering of root nodes since the queryset returned\n # is not affected by the model's order Meta option.\n return Cabinet.objects.root_nodes().order_by('label')\n\n\nclass DocumentCabinetListView(CabinetListView):\n def dispatch(self, request, *args, **kwargs):\n self.document = get_object_or_404(Document, pk=self.kwargs['pk'])\n\n AccessControlList.objects.check_access(\n permissions=permission_document_view, user=request.user,\n obj=self.document\n )\n\n return super(DocumentCabinetListView, self).dispatch(\n request, *args, **kwargs\n )\n\n def get_extra_context(self):\n return {\n 'hide_link': True,\n 'no_results_icon': icon_cabinet,\n 'no_results_main_link': link_cabinet_add_document.resolve(\n context=RequestContext(\n request=self.request, dict_={'object': self.document}\n )\n ),\n 'no_results_text': _(\n 'Documents can be added to many cabinets.'\n ),\n 'no_results_title': _(\n 'This document is not in any cabinet'\n ),\n 'object': self.document,\n 'title': _('Cabinets containing document: %s') % self.document,\n }\n\n def get_object_list(self):\n return self.document.document_cabinets().all()\n\n\nclass DocumentAddToCabinetView(MultipleObjectFormActionView):\n form_class = CabinetListForm\n model = Document\n object_permission = permission_cabinet_add_document\n success_message = _(\n 'Add to cabinet request performed on %(count)d document'\n )\n success_message_plural = _(\n 'Add to cabinet request performed on %(count)d documents'\n )\n\n def get_extra_context(self):\n queryset = self.get_queryset()\n\n result = {\n 'submit_label': _('Add'),\n 'title': ungettext(\n singular='Add %(count)d document to cabinets',\n plural='Add %(count)d documents to cabinets',\n number=queryset.count()\n ) % {\n 'count': queryset.count(),\n }\n }\n\n if queryset.count() == 1:\n result.update(\n {\n 'object': queryset.first(),\n 'title': _(\n 'Add document \"%s\" to cabinets'\n ) % queryset.first()\n }\n )\n\n return result\n\n def get_form_extra_kwargs(self):\n queryset = self.get_queryset()\n result = {\n 'help_text': _(\n 'Cabinets to which the selected documents will be added.'\n ),\n 'permission': permission_cabinet_add_document,\n 'user': self.request.user\n }\n\n if queryset.count() == 1:\n result.update(\n {\n 'queryset': Cabinet.objects.exclude(\n pk__in=queryset.first().cabinets.all()\n )\n }\n )\n\n return result\n\n def object_action(self, form, instance):\n cabinet_membership = instance.cabinets.all()\n\n for cabinet in form.cleaned_data['cabinets']:\n AccessControlList.objects.check_access(\n obj=cabinet, permissions=permission_cabinet_add_document,\n user=self.request.user\n )\n if cabinet in cabinet_membership:\n messages.warning(\n self.request, _(\n 'Document: %(document)s is already in '\n 'cabinet: %(cabinet)s.'\n ) % {\n 'document': instance, 'cabinet': cabinet\n }\n )\n else:\n cabinet.add_document(\n document=instance, user=self.request.user\n )\n messages.success(\n self.request, _(\n 'Document: %(document)s added to cabinet: '\n '%(cabinet)s successfully.'\n ) % {\n 'document': instance, 'cabinet': cabinet\n }\n )\n\n\nclass DocumentRemoveFromCabinetView(MultipleObjectFormActionView):\n form_class = CabinetListForm\n model = Document\n object_permission = permission_cabinet_remove_document\n success_message = _(\n 'Remove from cabinet request performed on %(count)d document'\n )\n success_message_plural = _(\n 'Remove from cabinet request performed on %(count)d documents'\n )\n\n def get_extra_context(self):\n queryset = self.get_queryset()\n\n result = {\n 'submit_label': _('Remove'),\n 'title': ungettext(\n singular='Remove %(count)d document from cabinets',\n plural='Remove %(count)d documents from cabinets',\n number=queryset.count()\n ) % {\n 'count': queryset.count(),\n }\n }\n\n if queryset.count() == 1:\n result.update(\n {\n 'object': queryset.first(),\n 'title': _(\n 'Remove document \"%s\" from cabinets'\n ) % queryset.first()\n }\n )\n\n return result\n\n def get_form_extra_kwargs(self):\n queryset = self.get_queryset()\n result = {\n 'help_text': _(\n 'Cabinets from which the selected documents will be removed.'\n ),\n 'permission': permission_cabinet_remove_document,\n 'user': self.request.user\n }\n\n if queryset.count() == 1:\n result.update(\n {\n 'queryset': queryset.first().cabinets.all()\n }\n )\n\n return result\n\n def object_action(self, form, instance):\n cabinet_membership = instance.cabinets.all()\n\n for cabinet in form.cleaned_data['cabinets']:\n AccessControlList.objects.check_access(\n obj=cabinet, permissions=permission_cabinet_remove_document,\n user=self.request.user\n )\n\n if cabinet not in cabinet_membership:\n messages.warning(\n self.request, _(\n 'Document: %(document)s is not in cabinet: '\n '%(cabinet)s.'\n ) % {\n 'document': instance, 'cabinet': cabinet\n }\n )\n else:\n cabinet.remove_document(\n document=instance, user=self.request.user\n )\n messages.success(\n self.request, _(\n 'Document: %(document)s removed from cabinet: '\n '%(cabinet)s.'\n ) % {\n 'document': instance, 'cabinet': cabinet\n }\n )\n","sub_path":"mayan/apps/cabinets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"20321291","text":"import pandas as pd\nimport os\nimport numpy as np\n\n\nyears_f = ['2014', '2015', '2016', '2017', '2018', '2019']\npath_f = '/mnt/pgth04b/DATABASES_CRIS/embeddings_saliency/finalistas'\n\nyears_nf = ['2017', '2018', '2019']\npath_nf = '/mnt/pgth04b/DATABASES_CRIS/embeddings1024/no_finalistas'\n\ndef find_max(years, path):\n maxh = 0\n maxw = 0\n notempty = 0\n for y in years:\n path_to_saliency = os.path.join(path, y)\n saliency_in_year = os.listdir(path_to_saliency)\n for s in saliency_in_year:\n if s[-3:] != 'npy':\n path_df = os.path.join(path_to_saliency, s)\n saliency = pd.read_csv(path_df, index_col=0, thousands=',')\n if not saliency.empty:\n notempty += 1\n print(str(notempty))\n saliency = saliency.drop(['0', '1'], axis=1)\n salarr = saliency.to_numpy()\n sh = salarr.shape[0]\n sw = salarr.shape[1]\n if sh > maxh:\n maxh = salarr.shape[0]\n if sw > maxw:\n maxw = salarr.shape[1]\n\n size = [maxh, maxw]\n return size\n\nmax_f = find_max(years_f, path_f)\nmax_nf = find_max(years_nf, path_nf)\n\nif max_f[0] > max_nf[0]:\n print('Max h size is ' + str(max_f[0]))\nelse:\n print('Max h size is ' + str(max_nf[0]))\n\nif max_f[1] > max_nf[1]:\n print('Max w size is ' + str(max_f[1]))\nelse:\n print('Max w size is ' + str(max_nf[1]))\n","sub_path":"scripts/get_max_hw_saliency.py","file_name":"get_max_hw_saliency.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"543455916","text":"\"\"\"--------------------------------------------------------------------------------------------------------------------------------------\nMODULE\n LoanRepaymentNoticeXMLGenerator\n\nDESCRIPTION\n This module contains classes used to generate the XML that will\n be fed into the XML template through the XML hooks called. This specifically uses a constructor\n that is fed into the xml generator that returns an acmtemplate to make up the body of the xml.\n\n This is called in the XML hooks module for repayment notices called LoanRepaymentNoticeXMLHooks\n\n-----------------------------------------------------------------------------------------------------------------------------------------\nHISTORY\n=========================================================================================================================================\nDate Change no Developer Requester Description\n-----------------------------------------------------------------------------------------------------------------------------------------\n2018-11-20 Stuart Wilson Loan Ops XML generator for repayment notices\n-----------------------------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nfrom datetime import date as datef\nfrom datetime import datetime\n\nimport acm\n\nfrom DocumentXMLGenerator import GenerateDocumentXMLRequest, DocumentXMLGenerator\nimport LoanNoticeGeneral\nimport LoanRepaymentNoticeScript\n\ncalculation_space = acm.Calculations().CreateStandardCalculationsSpaceCollection()\n\n\nclass GenerateRepaymentNoticeXMLRequest(GenerateDocumentXMLRequest):\n\n def __init__(self, from_party, from_party_contact, to_party, to_party_contact, confirmation):\n \"\"\"\n Constructor class for rate notice xml generator\n \"\"\"\n super(GenerateRepaymentNoticeXMLRequest, self).__init__(from_party, from_party_contact, to_party, to_party_contact)\n self.trade = confirmation.Trade()\n self.confirmation = confirmation\n self.date = str(datef.fromtimestamp(confirmation.CreateTime()))\n self.paydate = acm.Time().DateAddDelta(self.date, 0, 0, 7)\n self.valid_trades_list = LoanRepaymentNoticeScript.get_valid_trades_per_party_acquirer_pair((to_party, from_party), self.paydate)\n self.currencies = LoanRepaymentNoticeScript.get_currencies_from_trades(self.valid_trades_list)\n\nclass RepaymentNoticeXMLGenerator(DocumentXMLGenerator):\n\n def add_redemption_to_fixed_amount(self, trade, cashflow_fixed_and_redemption):\n fixed_amount = 0\n redemption_amount = 0\n if cashflow_fixed_and_redemption[0]:\n fixed_amount = cashflow_fixed_and_redemption[0].Calculation().Projected(calculation_space, trade).Number()\n\n if cashflow_fixed_and_redemption[1]:\n redemption_amount = cashflow_fixed_and_redemption[1].Calculation().Projected(calculation_space, trade).Number()\n\n return fixed_amount + redemption_amount\n\n def get_trade_pm_facility_id(self, trade, trade_currency):\n \"\"\"\n Function to get trade additional info PM_Facility_ID and splits the value(e.g\n CORPL|AUG16|TL|A = AUG16|TL|A)\n \"\"\"\n trade_facility_id = trade.AdditionalInfo().PM_FacilityID()\n facility_id = trade_facility_id[trade_facility_id.index('|') + 1:].replace('|', ' ').replace(trade_currency, '')\n\n return facility_id\n\n def rate_notice_facility_agreement(self, confirmation):\n \"\"\"\n This Function returns the Facility agreement between counterparty and acquirer\n \"\"\"\n if confirmation.Acquirer().Name() == 'IMPUMELELO SERIES 1 ACQUIRER':\n fac_agreement = (\n \"Facility Agreement/s entered into between {0} (administered by Absa \"\n \"through its Corporate and Investment Banking division) and {1}\").format(\n confirmation.AcquirerContactRef().Fullname2(),\n confirmation.Counterparty().Fullname())\n\n else:\n fac_agreement = (\n \"Facility Agreement/s entered into between {0} (acting through \"\n \"its Corporate and Investment \"\n \"Banking division) and {1}\").format(confirmation.AcquirerContactRef().Fullname2(),\n confirmation.Counterparty().Fullname())\n return fac_agreement\n\n def get_facility_instrument_cashflow(self, trade, date):\n \"\"\"\n This function returns the trade facility cashflow details\n \"\"\"\n cashflow_fixed_and_redemption = LoanRepaymentNoticeScript.seven_days_before_pay_day_fixed_cashflow(trade, date)\n cashflow = LoanRepaymentNoticeScript.seven_days_before_pay_day_cashflow(trade, date)\n\n if cashflow_fixed_and_redemption[0] is None and cashflow_fixed_and_redemption[1] is None:\n capital_due = 0\n else:\n capital_due = self.add_redemption_to_fixed_amount(trade, cashflow_fixed_and_redemption)\n \n if cashflow is None:\n interest_due = 0\n forward_rate = 0\n\n if cashflow_fixed_and_redemption[0] is not None:\n cashflow_for_dates = cashflow_fixed_and_redemption[0]\n\n elif cashflow_fixed_and_redemption[0] is None and cashflow_fixed_and_redemption[1] is not None:\n cashflow_for_dates = cashflow_fixed_and_redemption[1]\n\n previous_cashflow = LoanNoticeGeneral.get_previous_cashflow(cashflow_for_dates)\n commencement_date = datetime.strptime(previous_cashflow.StartDate(), '%Y-%m-%d').strftime('%d/%m/%Y')\n end_date = datetime.strptime(previous_cashflow.EndDate(), '%Y-%m-%d').strftime('%d/%m/%Y')\n\n else:\n commencement_date = datetime.strptime(cashflow.StartDate(), '%Y-%m-%d').strftime('%d/%m/%Y')\n end_date = datetime.strptime(cashflow.EndDate(), '%Y-%m-%d').strftime('%d/%m/%Y')\n interest_due = cashflow.Calculation().Projected(calculation_space, trade).Number()\n forward_rate = (cashflow.Calculation().ForwardRate(calculation_space) * 100)\n for reset in cashflow.Resets():\n if reset.Day() == date:\n if LoanNoticeGeneral.match_primelinked_trades(trade):\n rate = reset.FixingValue()\n forward_rate = rate + cashflow.Spread()\n \n\n trade_currency = trade.Currency().Name()\n facility_dict = dict()\n\n facility_dict['FACILITY_ID'] = self.get_trade_pm_facility_id(trade, trade_currency)\n facility_dict['APPLICABLERATE'] = \"{:0.9g}\".format(float(forward_rate))\n facility_dict['COMMENCEMENTDATE'] = commencement_date\n facility_dict['MATURITYDATE'] = end_date\n facility_dict['NOMINAL_AMOUNT'] = LoanNoticeGeneral.sum_nominal_before_payday(trade, date)\n facility_dict['CURRENCY'] = trade_currency\n facility_dict['INTEREST_DUE'] = \"{:0.2f}\".format(float(interest_due))\n facility_dict['CAPITAL_DUE'] = \"{:0.2f}\".format(float(capital_due))\n facility_dict['RUNNING_TOTAL'] = \"{:0.2f}\".format(float(capital_due)+float(interest_due))\n return facility_dict\n\n def get_facility_cashflow_element(self, trade, date):\n \"\"\"\n Function to create facility cashflow xml child element 'FACILITY'\n \"\"\"\n facility_dict = self.get_facility_instrument_cashflow(trade, date)\n element = self._generate_element('FACILITY')\n for tag_name, value in list(facility_dict.items()):\n element.append(self._generate_element(tag_name, str(value)))\n return element\n\n def get_totals_in_facilities(self, element):\n capital_due = 0\n interest_due = 0\n for tag in element:\n for subtag in tag:\n if subtag.tag == 'CAPITAL_DUE':\n capital_due += float(subtag.text)\n elif subtag.tag == 'INTEREST_DUE':\n interest_due += float(subtag.text)\n\n return capital_due, interest_due\n\n def get_facilities_xml_element(self, xml_request, currency):\n element = self._generate_element('FACILITIES')\n date = xml_request.date\n\n if xml_request.valid_trades_list:\n\n for trade in xml_request.valid_trades_list:\n if trade.Currency() == currency:\n if abs(LoanNoticeGeneral.sum_nominal_before_payday(trade, date)) > 0.00:\n element.append(self.get_facility_cashflow_element(trade, date))\n totals = self.get_totals_in_facilities(element)\n element.append(self._generate_element('CAPITAL_DUE_TOTAL', \"{:0.2f}\".format(totals[0])))\n element.append(self._generate_element('INTEREST_DUE_TOTAL', \"{:0.2f}\".format(totals[1])))\n element.append(self._generate_element('GRAND_TOTAL', \"{:0.2f}\".format(totals[0] + totals[1])))\n\n return element\n\n def get_legalnotice_loan(self, xml_request):\n normal_disclaimer = LoanNoticeGeneral.loan_notice_get_documentation_parameter('normal_disclaimer')\n prime_disclaimer = LoanNoticeGeneral.loan_notice_get_documentation_parameter('prime_disclaimer')\n for trade in xml_request.valid_trades_list:\n if LoanNoticeGeneral.match_primelinked_trades(trade):\n disclaimer1 = '{prime}\\n\\n{normal}'.format(prime=prime_disclaimer,\n normal=normal_disclaimer)\n return self._generate_element('REPAYMENT_NOTICE_DISClAIMER', disclaimer1)\n disclaimer2 = normal_disclaimer\n return self._generate_element('REPAYMENT_NOTICE_DISClAIMER', disclaimer2)\n\n def get_account_details(self, xml_request, currency):\n date = xml_request.paydate\n element = self._generate_element('ACCOUNT')\n for trade in xml_request.valid_trades_list:\n if trade.Currency().Name() == currency:\n accounts = trade.GenerateSettlements(date, date)\n break\n\n if accounts:\n account = accounts[0].AcquirerAccountRef()\n if currency == 'ZAR':\n\n element.append(self._generate_element('NAME', xml_request.confirmation.AcquirerContactRef().Fullname2()))\n element.append(self._generate_element('NUMBER', account.Account()[7:18]))\n element.append(self._generate_element('BANK', account.CorrespondentBank().Name()))\n element.append(self._generate_element('BRANCH', account.Account()[:6]))\n element.append(self._generate_element('REFERENCE', str(xml_request.trade.Counterparty().Fullname())))\n element.append(self._generate_element('CURRENCY', str(currency)))\n else:\n element.append(self._generate_element('NAME', xml_request.confirmation.AcquirerContactRef().Fullname2()))\n element.append(self._generate_element('NUMBER', account.Account()))\n element.append(self._generate_element('BANK', account.CorrespondentBank().Name()))\n element.append(self._generate_element('BRANCH', account.Bic().Name()))\n element.append(self._generate_element('REFERENCE', str(xml_request.trade.Counterparty().Fullname())))\n element.append(self._generate_element('CURRENCY', str(currency)))\n return element\n\n def get_date_payable(self, xml_request):\n\n date = datetime.strptime(acm.Time().DateAddDelta(xml_request.date, 0, 0, 7), '%Y-%m-%d').strftime('%d %B %Y')\n\n return self._generate_element('PAY_DATE', date)\n\n def _generate_subject_element(self, xml_request):\n \"\"\"\n Generate the document SUBJECT XML element and sub-\n elements.\n \"\"\"\n return self._generate_element('SUBJECT', 'Repayment Notice')\n\n def is_last_element_curr_loop(self, currency, xml_request):\n\n return self._generate_element('LAST_ELEMENT', str(currency == xml_request.currencies[-1]))\n\n def _generate_document_specific_element(self, xml_request):\n \"\"\"\n Generate the document RATENOTICE XML element and sub-\n elements.\n \"\"\"\n main_element = self._generate_element('REPAYMENTNOTICE')\n facility_agreement = xml_request.confirmation\n facility_aggr = self.rate_notice_facility_agreement(facility_agreement)\n\n for currency in xml_request.currencies:\n element = self._generate_element('MAIN_CURRENCY')\n element.append(self._generate_element('FACIL_AGREE', facility_aggr))\n element.append(self.get_facilities_xml_element(xml_request, currency))\n element.append(self.get_legalnotice_loan(xml_request))\n element.append(self.get_account_details(xml_request, currency.Name()))\n element.append(self.get_date_payable(xml_request))\n element.append(self.is_last_element_curr_loop(currency, xml_request))\n main_element.append(element)\n\n return main_element\n\n\n\n","sub_path":"Extensions/ABSA Documentation/FPythonCode/LoanRepaymentNoticeXMLGenerator.py","file_name":"LoanRepaymentNoticeXMLGenerator.py","file_ext":"py","file_size_in_byte":13120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"349500791","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom ddpg import parse_args\nfrom cl_main import cl_run\nfrom cl_learning import Helper\nargs = parse_args()\n\nargs['rb_min_size'] = 1000\nargs['reach_return'] = 526.0\nargs['default_damage'] = 4132.00\nargs['perf_td_error'] = True\nargs['perf_l2_reg'] = True\nargs['steps'] = 300000\nargs[\"rb_max_size\"] = args['steps']\n#args[\"cl_batch_norm\"] = True\n#args['cl_structure'] = 'ffcritic:fc_relu_4;fc_relu_3;fc_relu_3'\nargs[\"cl_batch_norm\"] = False\nargs['cl_structure'] = 'rnnc:gru_tanh_6_dropout;fc_linear_3'\nargs[\"cl_stages\"] = \"balancing_tf;balancing;walking:monotonic\"\nargs['cl_depth'] = 2\nargs['cl_pt_shape'] = (args['cl_depth'],3)\nargs['test_interval'] = 30\n\n\n#args[\"cl_target\"] = True\nexport_names = \"eq_curriculum_network_depth_\" + str(args['cl_depth'])\nnn_params = (export_names, \"{}_stat.pkl\".format(export_names))\nargs[\"cl_pt_load\"] = nn_params[1]\n\n\n# Parameters\ntasks = {\n 'balancing_tf': 'cfg/leo_balancing_tf.yaml',\n 'balancing': 'cfg/leo_balancing.yaml',\n 'walking': 'cfg/leo_walking.yaml'\n }\nstarting_task = 'balancing_tf'\nhp = Helper(args, 'cl', 'ddpg', tasks, starting_task, 1, use_mp=False)\n\n# Run actual script.\nconfig, tasks, starting_task = hp.gen_cfg([None], 1)[0]\nconfig[\"cl_load\"] = nn_params[0]\ncl_run(tasks, starting_task, **config)\n","sub_path":"grl_learn_using_cl.py","file_name":"grl_learn_using_cl.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"501659566","text":"# -*- coding: utf-8 -*-\n#################################################################################\n# Author : Acespritech Solutions Pvt. Ltd. ()\n# Copyright(c): 2012-Present Acespritech Solutions Pvt. Ltd.\n# All Rights Reserved.\n#\n# This program is copyright property of the author mentioned above.\n# You can`t redistribute it and/or modify it.\n#\n#################################################################################\n\nfrom odoo import models, fields, api,_\n\n\nclass hr_employee(models.Model):\n _inherit = \"hr.employee\"\n\n weekday_ot_rate = fields.Float(string=\"Weekday OT Rate\")\n weekend_ot_rate = fields.Float(string=\"Weekend OT Rate\")\n overtime_count = fields.Integer(stirng=\"Overtime Count\", compute='get_overtime_count')\n\n @api.multi\n def get_overtime_count(self):\n for each in self:\n each.overtime_count = self.env['hr.employee.overtime'].search_count([('employee_id', '=', each.id)])\n\n @api.multi\n def related_overtime_view(self):\n return {\n 'type': 'ir.actions.act_window',\n 'name': _('Employee Overtime'),\n 'res_model': 'hr.employee.overtime',\n 'view_type': 'form',\n 'view_mode': 'tree',\n 'target': 'current',\n 'domain': [('employee_id', '=', self.id)]\n }\n\n\nclass hr_attendance(models.Model):\n _inherit = \"hr.attendance\"\n\n employee_ot_id = fields.Many2one('hr.employee.overtime', string=\"Related Overtime\", readonly=True)\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","sub_path":"quality_control_team/flexi_hr_ee/hr_overtime/models/hr_employee 2.py","file_name":"hr_employee 2.py","file_ext":"py","file_size_in_byte":1614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"261673941","text":"import tkinter as tk\nfrom tkinter import ttk\n\n\nclass UserForm(tk.Frame):\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # Declaring Variables.\n self.user_name = tk.StringVar()\n self.greetings = tk.StringVar()\n\n label_user_name = ttk.Label(self, text=\"Enter your name:\")\n text_user_name = ttk.Entry(self, textvariable=self.user_name)\n\n button_update_message = ttk.Button(self, text=\"Update\", command=self.on_name_change)\n\n label_greetings = ttk.Label(self, textvariable=self.greetings)\n\n # Form Layout\n label_user_name.grid(row=0, column=0, sticky=tk.W)\n text_user_name.grid(row=0, column=1, sticky=(tk.W + tk.E))\n button_update_message.grid(row=0, column=2, sticky=tk.E)\n\n label_greetings.grid(row=1, column=0, columnspan=3)\n\n\n def on_name_change(self):\n if self.user_name.get().strip():\n self.greetings.set(f'Hello {self.user_name.get()}')\n else:\n self.greetings.set(f'Hello No Name')\n\n\nclass UserInformationApplication(tk.Tk):\n\n def __init__(self, screenName=None, baseName=None, className=\"User Information\", useTk=1, sync=0, use=None):\n super().__init__(screenName=screenName, baseName=baseName,\n className=className, useTk=useTk, sync=sync, use=use)\n\n # Windows Properties\n self.title(\"User Information\")\n self.geometry(\"400x150\")\n\n # Creating the Form\n UserForm(self).grid(sticky=(tk.E + tk.W + tk.N + tk.S))\n\n\ndef main():\n window = UserInformationApplication()\n window.mainloop()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Intermediate/Day9/5guiinputdemo.py","file_name":"5guiinputdemo.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"30405437","text":"#!/usr/bin/env python\r\n# -- coding: utf-8 --\r\nimport sys\r\nimport json\r\nimport operator\r\nimport jieba\r\nimport os\r\n\r\njieba.load_userdict('../raw_datas/jieba_dict_lower.txt')\r\n\r\nreload(sys)\r\nsys.setdefaultencoding(\"utf-8\")\r\n\r\nclass Titleclassify():\r\n def __init__(self,title_dict_path,classify_dict_path,vocab_target_path,data_to_classify_path):\r\n self.title_dict_path=title_dict_path\r\n self.classify_dict_path=classify_dict_path\r\n self.vocab_target_path=vocab_target_path\r\n self.title_dict=self.load_title_dict()\r\n self.classify_dict = self.load_classify_dict()\r\n self.vocab_target_dict = self.load_vocab_target()\r\n self.data_to_classify_path = data_to_classify_path\r\n\r\n def load_title_dict(self):\r\n title_dict = json.load(open(self.title_dict_path, 'r'))\r\n return title_dict\r\n\r\n def load_classify_dict(self):\r\n classify_dict = json.load(open(self.classify_dict_path, 'r'))\r\n return classify_dict\r\n\r\n def load_vocab_target(self):\r\n vocab_target_dict = {line.strip().split('\\x01')[0].decode('utf-8'): line.strip().split('\\x01')[1] for line in\r\n open(self.vocab_target_path, 'r').readlines()}\r\n return vocab_target_dict\r\n\r\n def title_classify(self,line):\r\n classify_result={}\r\n title=line.strip().split('\\x01')[0].decode('utf-8')\r\n for k,v in self.title_dict.items():\r\n for t,rank in v.items():\r\n if t in title:\r\n classify_result[k]=rank\r\n break\r\n print(classify_result)\r\n sort_dict=sorted(classify_result.iteritems(),key=operator.itemgetter(1),reverse=False)\r\n subtype_num=0\r\n res={}\r\n for k, v in sort_dict:\r\n subtype_num += 1\r\n if subtype_num < 6:\r\n res[k] = v\r\n return res\r\n\r\n\r\n\r\n def content_classify(self,line,class_dict):\r\n kw_freq_dict = {}\r\n line_dict = {}\r\n job_desc = line.strip().split('\\x01')[0] + ' ' + line.strip().split('\\x01')[1]\r\n cut_list = list(jieba.cut(job_desc, cut_all=False))\r\n for kw in cut_list:\r\n line_dict.setdefault(kw, 0)\r\n line_dict[kw] += 1\r\n for kw in line_dict:\r\n if kw in self.vocab_target_dict:\r\n kw_freq_dict[kw] = line_dict[kw]\r\n classify_result_prob_dict = {}\r\n for subtype in class_dict:\r\n condition_prob = 0.0\r\n for k in kw_freq_dict:\r\n if k in class_dict[subtype][\"exist_kw_conprob\"]:\r\n condition_prob += class_dict[subtype][\"exist_kw_conprob\"][k] * kw_freq_dict[k]\r\n else:\r\n condition_prob += class_dict[subtype][\"nexist_kw_conprob\"] * kw_freq_dict[k]\r\n classify_result_prob_dict[subtype] = class_dict[subtype][\"prob_log\"] + condition_prob\r\n sort_dict = sorted(classify_result_prob_dict.iteritems(), key=operator.itemgetter(1), reverse=True)\r\n subtype_num = 0\r\n result = {}\r\n for k, v in sort_dict:\r\n subtype_num += 1\r\n if subtype_num < 6:\r\n result[k] = v\r\n return result\r\n\r\n\r\n\r\n def combine_classify(self):\r\n class_dict = self.classify_dict\r\n with open('combine_0.6_1.0_result', 'a') as fw:\r\n line_counter = 0\r\n correct_counter = 0\r\n classify_type_num = 0\r\n for filename in os.listdir(self.data_to_classify_path):\r\n print(filename)\r\n input = open(self.data_to_classify_path + filename)\r\n line = str(input.readline())\r\n line_counter_1 = 0\r\n correct_counter_1 = 0\r\n while line != None and len(line) > 1:\r\n line_counter+=1\r\n line_counter_1+=1\r\n print(line_counter_1)\r\n position_title=line.strip().split('\\x01')[0].decode('utf-8')\r\n if len(position_title) > 8:\r\n # print(position_title)\r\n result=self.content_classify(line,class_dict=class_dict)\r\n else:\r\n result=self.title_classify(line)\r\n if result=={}:\r\n result = self.content_classify(line, class_dict=class_dict)\r\n if filename.split('_')[1] in result:\r\n correct_counter_1 += 1\r\n correct_counter+=1\r\n line = str(input.readline())\r\n print(filename.split('_')[1])\r\n acc_rate_1 = float(correct_counter_1) / float(line_counter_1)\r\n classify_type_num += 1\r\n print('classified_type_num:', str(classify_type_num))\r\n with open('combine_test_result', 'a') as fw1:\r\n fw1.write(\r\n filename + '\\x01' + str(line_counter_1) + '\\x01' + str(correct_counter_1) + '\\x01' + format(\r\n acc_rate_1, '.5f') + '\\n')\r\n acc_rate = float(correct_counter) / float(line_counter)\r\n print(format(acc_rate, '.5f'))\r\n fw.write(str(len(self.vocab_target_dict)) + '\\x01' + str(line_counter) + '\\x01' + str(\r\n correct_counter) + '\\x01' + format(acc_rate, '.5f') + '\\n')\r\n\r\n\r\nif __name__ == '__main__':\r\n # title_dict_path='D:/wrokmy/position_rec/target_datas/title_dict'\r\n # data_to_classify_path='D:/wrokmy/position_rec/target_datas/'\r\n # classify_dict_path='D:/wrokmy\\position_rec/target_datas/1_plus_remove_0.6_1.0/classify_dict'\r\n # vocab_target_path='D:/wrokmy\\position_rec/target_datas/1_plus_remove_0.6_1.0/all_type_vocab_dict_target'\r\n\r\n title_dict_path='filter_title_dict'\r\n data_to_classify_path='../process_datas/test_data_files_1per/'\r\n classify_dict_path='classify_dict'\r\n vocab_target_path='all_type_vocab_dict_target'\r\n\r\n model=Titleclassify(title_dict_path=title_dict_path,data_to_classify_path=data_to_classify_path,\r\n classify_dict_path=classify_dict_path,vocab_target_path=vocab_target_path)\r\n model.combine_classify()","sub_path":"position_rec/data_position_title/filter_title_classify.py","file_name":"filter_title_classify.py","file_ext":"py","file_size_in_byte":6183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"631771175","text":"import os\nimport sys\nfrom pathlib import Path\nfrom typing import Type\n\nimport numpy as np\nfrom qtpy.QtCore import QByteArray, QEvent, Qt\nfrom qtpy.QtGui import QIcon, QKeyEvent, QKeySequence, QResizeEvent\nfrom qtpy.QtWidgets import (\n QCheckBox,\n QComboBox,\n QGridLayout,\n QHBoxLayout,\n QInputDialog,\n QLabel,\n QMessageBox,\n QPushButton,\n QVBoxLayout,\n QWidget,\n)\n\nimport PartSegData\nfrom PartSeg.common_gui.custom_load_dialog import CustomLoadDialog\nfrom PartSeg.common_gui.main_window import BaseMainMenu, BaseMainWindow\nfrom PartSeg.common_gui.stacked_widget_with_selector import StackedWidgetWithSelector\nfrom PartSeg.segmentation_analysis.measurement_widget import MeasurementWidget\nfrom PartSegCore import state_store\nfrom PartSegCore.algorithm_describe_base import SegmentationProfile\nfrom PartSegCore.analysis import ProjectTuple, algorithm_description, load_functions\nfrom PartSegCore.analysis.analysis_utils import SegmentationPipeline, SegmentationPipelineElement\nfrom PartSegCore.analysis.io_utils import create_history_element_from_project\nfrom PartSegCore.analysis.save_functions import save_dict\nfrom PartSegCore.io_utils import HistoryElement, WrongFileTypeException\nfrom PartSegCore.mask_create import calculate_mask_from_project\nfrom PartSegCore.segmentation.algorithm_base import SegmentationResult\nfrom PartSegCore.segmentation_info import SegmentationInfo\nfrom PartSegImage import TiffImageReader\n\nfrom ..common_gui.algorithms_description import AlgorithmChoose, InteractiveAlgorithmSettingsWidget\nfrom ..common_gui.channel_control import ChannelProperty\nfrom ..common_gui.custom_save_dialog import SaveDialog\nfrom ..common_gui.equal_column_layout import EqualColumnLayout\nfrom ..common_gui.mask_widget import MaskDialogBase\nfrom ..common_gui.multiple_file_widget import MultipleFileWidget\nfrom ..common_gui.stack_image_view import ColorBar\nfrom ..common_gui.universal_gui_part import TextShow\nfrom ..common_gui.waiting_dialog import ExecuteFunctionDialog, WaitingDialog\nfrom .advanced_window import SegAdvancedWindow\nfrom .batch_window import BatchWindow\nfrom .calculation_pipeline_thread import CalculatePipelineThread\nfrom .image_view import CompareImageView, ResultImageView, SynchronizeView\nfrom .partseg_settings import PartSettings\n\nCONFIG_FOLDER = os.path.join(state_store.save_folder, \"analysis\")\n\n\nclass Options(QWidget):\n def __init__(\n self,\n settings: PartSettings,\n channel_control2: ChannelProperty,\n left_image: ResultImageView,\n main_image: ResultImageView,\n synchronize: SynchronizeView,\n ):\n super().__init__()\n self._settings = settings\n self.left_panel = left_image\n self._ch_control2 = channel_control2\n self.synchronize_val = False\n self.hide_left_panel_chk = QCheckBox(\"Hide left panel\")\n self.hide_left_panel_chk.stateChanged.connect(self.hide_left_panel)\n self.synchronize_checkbox = QCheckBox(\"Synchronize view\")\n self.synchronize_checkbox.stateChanged.connect(synchronize.set_synchronize)\n self.interactive_use = QCheckBox(\"Interactive use\")\n self.execute_btn = QPushButton(\"Execute\")\n self.execute_btn.clicked.connect(self.execute_algorithm)\n self.execute_btn.setStyleSheet(\"QPushButton{font-weight: bold;}\")\n self.save_pipe_btn = QPushButton(\"Save pipeline\")\n self.save_pipe_btn.clicked.connect(self.save_pipeline)\n self.save_pipe_btn.setToolTip(\"Save current pipeline. Last element is last executed algorithm\")\n self.choose_pipe = QComboBox()\n self.choose_pipe.addItem(\"\")\n self.choose_pipe.addItems(list(self._settings.segmentation_pipelines.keys()))\n self.choose_pipe.currentTextChanged.connect(self.choose_pipeline)\n self.choose_pipe.setToolTip(\"Execute chosen pipeline\")\n self.save_profile_btn = QPushButton(\"Save profile\")\n self.save_profile_btn.setToolTip(\"Save values from current view\")\n self.save_profile_btn.clicked.connect(self.save_profile)\n self.choose_profile = QComboBox()\n self.choose_profile.addItem(\"\")\n self.choose_profile.addItems(list(self._settings.segmentation_profiles.keys()))\n self.choose_profile.setToolTip(\"Select profile to restore its settings. Execute if interactive is checked\")\n # image state\n self.compare_btn = QPushButton(\"Compare\")\n self.compare_btn.setDisabled(True)\n self.compare_btn.clicked.connect(self.compare_action)\n left_image.hide_signal.connect(self.compare_btn.setHidden)\n\n self.update_tooltips()\n self.choose_profile.currentTextChanged.connect(self.change_profile)\n self.interactive_use.stateChanged.connect(self.execute_btn.setDisabled)\n self.interactive_use.stateChanged.connect(self.interactive_change)\n self.algorithm_choose_widget = AlgorithmChoose(settings, algorithm_description.analysis_algorithm_dict)\n self.algorithm_choose_widget.result.connect(self.execution_done)\n self.algorithm_choose_widget.finished.connect(self.calculation_finished)\n self.algorithm_choose_widget.value_changed.connect(self.interactive_algorithm_execute)\n self.algorithm_choose_widget.algorithm_changed.connect(self.interactive_algorithm_execute)\n\n self.label = TextShow()\n\n # self.label.setWordWrap(True)\n # self.label.setTextInteractionFlags(Qt.TextSelectableByMouse)\n layout = QVBoxLayout()\n layout2 = QHBoxLayout()\n layout2.setSpacing(1)\n layout2.setContentsMargins(0, 0, 0, 0)\n layout3 = QHBoxLayout()\n layout3.setContentsMargins(0, 0, 0, 0)\n layout.setContentsMargins(0, 0, 0, 0)\n layout5 = QHBoxLayout()\n layout5.setContentsMargins(0, 0, 0, 0)\n layout5.addWidget(self.save_pipe_btn)\n layout5.addWidget(self.choose_pipe)\n layout4 = QHBoxLayout()\n layout4.setContentsMargins(0, 0, 0, 0)\n layout4.addWidget(self.save_profile_btn)\n layout4.addWidget(self.choose_profile)\n layout3.addWidget(self.interactive_use)\n layout3.addWidget(self.execute_btn)\n layout.addLayout(layout5)\n layout.addLayout(layout4)\n layout.addLayout(layout3)\n layout.addWidget(self.algorithm_choose_widget, 1)\n # layout.addLayout(self.stack_layout)\n layout.addWidget(self.label)\n # layout.addStretch(1)\n layout2.addWidget(self.hide_left_panel_chk)\n layout2.addWidget(self.synchronize_checkbox)\n layout.addLayout(layout2)\n layout.addWidget(self._ch_control2)\n # layout.setSpacing(0)\n self.setLayout(layout)\n\n def compare_action(self):\n if self.compare_btn.text() == \"Compare\":\n self._settings.set_segmentation_to_compare(self._settings.segmentation_info)\n self.compare_btn.setText(\"Remove\")\n else:\n self._settings.set_segmentation_to_compare(SegmentationInfo(None))\n self.compare_btn.setText(\"Compare\")\n\n def calculation_finished(self):\n self.execute_btn.setDisabled(self.interactive_use.isChecked())\n self.interactive_use.setEnabled(True)\n\n def save_pipeline(self):\n history = self._settings.get_history()\n if not history:\n QMessageBox.information(self, \"No mask created\", \"There is no new mask created\", QMessageBox.Ok)\n return\n mask_history = []\n for el in history:\n mask = el.mask_property\n segmentation = SegmentationProfile(\n name=\"Unknown\",\n algorithm=el.segmentation_parameters[\"algorithm_name\"],\n values=el.segmentation_parameters[\"values\"],\n )\n new_el = SegmentationPipelineElement(mask_property=mask, segmentation=segmentation)\n mask_history.append(new_el)\n name = self._settings.last_executed_algorithm\n if not name:\n QMessageBox.information(self, \"No segmentation\", \"No segmentation executed\", QMessageBox.Ok)\n return\n values = self._settings.get(f\"algorithms.{name}\", {})\n if len(values) == 0:\n QMessageBox.information(self, \"Some problem\", \"Pleas run execution again\", QMessageBox.Ok)\n return\n current_segmentation = SegmentationProfile(name=\"Unknown\", algorithm=name, values=values)\n\n while True:\n text, ok = QInputDialog.getText(self, \"Pipeline name\", \"Input pipeline name here\")\n if not ok:\n return\n if text in self._settings.segmentation_pipelines:\n if QMessageBox.No == QMessageBox.warning(\n self,\n \"Already exists\",\n \"Profile with this name already exist. Overwrite?\",\n QMessageBox.Yes | QMessageBox.No,\n QMessageBox.No,\n ):\n continue\n profile = SegmentationPipeline(name=text, segmentation=current_segmentation, mask_history=mask_history)\n self._settings.segmentation_pipelines[text] = profile\n self._settings.dump()\n self.choose_pipe.addItem(text)\n break\n\n def choose_pipeline(self, text):\n if text == \"\":\n return\n pipeline = self._settings.segmentation_pipelines[text]\n process_thread = CalculatePipelineThread(self._settings.image, self._settings.mask, pipeline)\n dial = WaitingDialog(process_thread)\n\n if dial.exec() and process_thread.result:\n pipeline_result = process_thread.result\n self._settings.mask = pipeline_result.mask\n self._settings.segmentation = pipeline_result.segmentation\n self._settings.full_segmentation = pipeline_result.full_segmentation\n self._settings.set_history(pipeline_result.history)\n self.label.setText(pipeline_result.description)\n self.algorithm_choose_widget.change_algorithm(pipeline.segmentation.algorithm, pipeline.segmentation.values)\n self.choose_pipe.setCurrentIndex(0)\n\n def update_tooltips(self):\n for i in range(1, self.choose_profile.count()):\n if self.choose_profile.itemData(i, Qt.ToolTipRole) is not None:\n continue\n text = self.choose_profile.itemText(i)\n profile: SegmentationProfile = self._settings.segmentation_profiles[text]\n tool_tip_text = str(profile)\n self.choose_profile.setItemData(i, tool_tip_text, Qt.ToolTipRole)\n for i in range(1, self.choose_pipe.count()):\n if self.choose_pipe.itemData(i, Qt.ToolTipRole) is not None:\n continue\n text = self.choose_pipe.itemText(i)\n profile: SegmentationPipeline = self._settings.segmentation_pipelines[text]\n tool_tip_text = str(profile)\n self.choose_pipe.setItemData(i, tool_tip_text, Qt.ToolTipRole)\n\n @staticmethod\n def update_combo_box(combo_box: QComboBox, dkt: dict):\n current_names = set(dkt.keys())\n prev_names = {combo_box.itemText(i) for i in range(1, combo_box.count())}\n new_names = current_names - prev_names\n delete_names = prev_names - current_names\n if len(delete_names) > 0:\n i = 1\n while i < combo_box.count():\n if combo_box.itemText(i) in delete_names:\n combo_box.removeItem(i)\n else:\n i += 1\n if len(new_names) > 0:\n combo_box.addItems(list(sorted(new_names)))\n\n def event(self, event: QEvent):\n if event.type() == QEvent.WindowActivate:\n # update combobox for segmentation\n self.update_combo_box(self.choose_profile, self._settings.segmentation_profiles)\n # update combobox for pipeline\n self.update_combo_box(self.choose_pipe, self._settings.segmentation_pipelines)\n self.update_tooltips()\n return super().event(event)\n\n def keyPressEvent(self, event: QKeyEvent):\n if (event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return) and (event.modifiers() == Qt.ControlModifier):\n self.execute_btn.click()\n\n def save_profile(self):\n widget: InteractiveAlgorithmSettingsWidget = self.algorithm_choose_widget.current_widget()\n while True:\n text, ok = QInputDialog.getText(self, \"Profile Name\", \"Input profile name here\")\n if not ok:\n return\n if text in self._settings.segmentation_profiles:\n if QMessageBox.No == QMessageBox.warning(\n self,\n \"Already exists\",\n \"Profile with this name already exist. Overwrite?\",\n QMessageBox.Yes | QMessageBox.No,\n QMessageBox.No,\n ):\n continue\n resp = SegmentationProfile(text, widget.name, widget.get_values())\n self._settings.segmentation_profiles[text] = resp\n self._settings.dump()\n self.choose_profile.addItem(text)\n self.update_tooltips()\n break\n\n def change_profile(self, val):\n self.choose_profile.setToolTip(\"\")\n if val == \"\":\n return\n interactive = self.interactive_use.isChecked()\n self.interactive_use.setChecked(False)\n profile = self._settings.segmentation_profiles[val]\n self.algorithm_choose_widget.change_algorithm(profile.algorithm, profile.values)\n self.choose_profile.blockSignals(True)\n self.choose_profile.setCurrentIndex(0)\n self.choose_profile.blockSignals(False)\n self.interactive_use.setChecked(interactive)\n\n @property\n def segmentation(self):\n return self._settings.segmentation\n\n @property\n def interactive(self):\n return self.interactive_use.isChecked()\n\n def hide_left_panel(self, val):\n self._settings.set_in_profile(\"hide_left_panel\", val)\n if val:\n self.synchronize_val = self.synchronize_checkbox.isChecked()\n self.synchronize_checkbox.setChecked(False)\n else:\n self.synchronize_checkbox.setChecked(self.synchronize_val)\n self.synchronize_checkbox.setDisabled(val)\n self.left_panel.parent().setHidden(val)\n\n def interactive_change(self, val):\n if val:\n self.execute_algorithm()\n\n def algorithm_change(self, val):\n self._settings.set(\"current_algorithm\", val)\n if self.interactive:\n self.execute_algorithm()\n\n def interactive_algorithm_execute(self):\n if self.interactive:\n self.execute_algorithm()\n\n def execute_algorithm(self):\n widget: InteractiveAlgorithmSettingsWidget = self.algorithm_choose_widget.current_widget()\n if self._settings.image.is_time and not widget.algorithm.support_time():\n QMessageBox.information(\n self, \"Not supported\", \"This algorithm do not support time data. \" \"You can convert it in image adjust\"\n )\n return\n if self._settings.image.is_stack and not widget.algorithm.support_z():\n QMessageBox.information(\n self, \"Not supported\", \"This algorithm do not support stack data. \" \"You can convert it in image adjust\"\n )\n return\n self._settings.last_executed_algorithm = widget.name\n self.execute_btn.setDisabled(True)\n self.interactive_use.setDisabled(True)\n widget.execute()\n\n def execution_done(self, segmentation: SegmentationResult):\n if segmentation.info_text != \"\":\n QMessageBox.information(self, \"Algorithm info\", segmentation.info_text)\n self._settings.segmentation = segmentation.segmentation\n self.compare_btn.setEnabled(\n isinstance(segmentation.segmentation, np.ndarray) and np.any(segmentation.segmentation)\n )\n self._settings.additional_layers = segmentation.additional_layers\n self.label.setText(self.sender().get_info_text())\n\n def showEvent(self, _event):\n self.hide_left_panel_chk.setChecked(self._settings.get_from_profile(\"hide_left_panel\", False))\n\n\nclass MainMenu(BaseMainMenu):\n def __init__(self, settings: PartSettings, main_window):\n super().__init__(settings, main_window)\n self.settings = settings\n self.open_btn = QPushButton(\"Open\")\n self.save_btn = QPushButton(\"Save\")\n self.advanced_btn = QPushButton(\"Settings and Measurement\")\n self.mask_manager_btn = QPushButton(\"Mask manager\")\n self.batch_processing_btn = QPushButton(\"Batch Processing\")\n\n layout = QHBoxLayout()\n # layout.setSpacing(0)\n layout.setContentsMargins(0, 0, 4, 4)\n layout.addWidget(self.open_btn)\n layout.addWidget(self.save_btn)\n layout.addWidget(self.advanced_btn)\n layout.addWidget(self.mask_manager_btn)\n layout.addWidget(self.batch_processing_btn)\n self.setLayout(layout)\n\n self.open_btn.clicked.connect(self.load_data)\n self.save_btn.clicked.connect(self.save_file)\n self.advanced_btn.clicked.connect(self.advanced_window_show)\n self.mask_manager_btn.clicked.connect(self.mask_manager)\n self.batch_processing_btn.clicked.connect(self.batch_window)\n self.setFocusPolicy(Qt.StrongFocus)\n # self.test_btn.clicked.connect(self.test_fun)\n\n def resizeEvent(self, event: QResizeEvent):\n if event.size().width() < 800:\n self.batch_processing_btn.hide()\n else:\n self.batch_processing_btn.show()\n\n def keyPressEvent(self, event: QKeyEvent):\n if event.matches(QKeySequence.Save):\n self.save_file()\n elif event.matches(QKeySequence.Open):\n self.load_data()\n super().keyPressEvent(event)\n\n def save_file(self):\n base_values = self.settings.get(\"save_parameters\", dict())\n dial = SaveDialog(\n save_dict, system_widget=False, base_values=base_values, history=self.settings.get_path_history()\n )\n dial.selectFile(os.path.splitext(os.path.basename(self.settings.image_path))[0])\n dial.setDirectory(\n self.settings.get(\"io.save_directory\", self.settings.get(\"io.open_directory\", str(Path.home())))\n )\n dial.selectNameFilter(self.settings.get(\"io.save_filter\", \"\"))\n if dial.exec():\n save_location, selected_filter, save_class, values = dial.get_result()\n project_info = self.settings.get_project_info()\n self.settings.set(\"io.save_filter\", selected_filter)\n save_dir = os.path.dirname(save_location)\n self.settings.set(\"io.save_directory\", save_dir)\n self.settings.add_path_history(save_dir)\n base_values[selected_filter] = values\n\n def exception_hook(exception):\n from qtpy.QtCore import QMetaObject\n from qtpy.QtWidgets import QApplication\n\n instance = QApplication.instance()\n if isinstance(exception, ValueError):\n instance.warning = \"Save error\", f\"Error during saving\\n{exception}\"\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n else:\n raise exception\n\n dial2 = ExecuteFunctionDialog(\n save_class.save, [save_location, project_info, values], exception_hook=exception_hook\n )\n dial2.exec()\n\n def mask_manager(self):\n if self.settings.segmentation is None:\n QMessageBox.information(self, \"No segmentation\", \"Cannot create mask without segmentation\")\n return\n dial = MaskDialog(self.settings)\n dial.exec_()\n\n def load_data(self):\n def exception_hook(exception):\n from qtpy.QtCore import QMetaObject\n from qtpy.QtWidgets import QApplication\n\n instance = QApplication.instance()\n if isinstance(exception, ValueError) and exception.args[0] == \"Incompatible shape of mask and image\":\n instance.warning = (\n \"Open error\",\n \"Most probably you try to load mask from other image. \" \"Check selected files\",\n )\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n elif isinstance(exception, MemoryError):\n instance.warning = \"Open error\", f\"Not enough memory to read this image: {exception}\"\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n elif isinstance(exception, IOError):\n instance.warning = \"Open error\", f\"Some problem with reading from disc: {exception}\"\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n elif isinstance(exception, KeyError):\n instance.warning = \"Open error\", f\"Some problem project file: {exception}\"\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n print(exception, file=sys.stderr)\n elif isinstance(exception, WrongFileTypeException):\n instance.warning = (\n \"Open error\",\n \"No needed files inside archive. Most probably you choose file from segmentation mask\",\n )\n QMetaObject.invokeMethod(instance, \"show_warning\", Qt.QueuedConnection)\n else:\n raise exception\n\n try:\n dial = CustomLoadDialog(load_functions.load_dict, history=self.settings.get_path_history())\n dial.setDirectory(self.settings.get(\"io.open_directory\", str(Path.home())))\n dial.selectNameFilter(self.settings.get(\"io.open_filter\", next(iter(load_functions.load_dict.keys()))))\n if dial.exec_():\n result = dial.get_result()\n self.settings.set(\"io.open_filter\", result.selected_filter)\n load_dir = os.path.dirname(result.load_location[0])\n self.settings.set(\"io.open_directory\", load_dir)\n self.settings.add_path_history(load_dir)\n dial2 = ExecuteFunctionDialog(\n result.load_class.load,\n [result.load_location],\n {\"metadata\": {\"default_spacing\": self.settings.image_spacing}},\n exception_hook=exception_hook,\n )\n if dial2.exec():\n result = dial2.get_result()\n self.set_data(result)\n\n except ValueError as e:\n QMessageBox.warning(self, \"Open error\", \"{}\".format(e))\n\n def batch_window(self):\n if self.main_window.batch_window is not None:\n if self.main_window.batch_window.isVisible():\n self.main_window.batch_window.activateWindow()\n else:\n self.main_window.batch_window.show()\n else:\n self.main_window.batch_window = BatchWindow(self.settings)\n self.main_window.batch_window.show()\n\n def advanced_window_show(self):\n if self.main_window.advanced_window.isVisible():\n self.main_window.advanced_window.activateWindow()\n else:\n self.main_window.advanced_window.show()\n\n\nclass MaskDialog(MaskDialogBase):\n def next_mask(self):\n project_info: ProjectTuple = self.settings.get_project_info()\n mask_property = self.mask_widget.get_mask_property()\n self.settings.set(\"mask_manager.mask_property\", mask_property)\n mask = calculate_mask_from_project(mask_description=mask_property, project=project_info)\n self.settings.add_history_element(create_history_element_from_project(project_info, mask_property,))\n if self.settings.history_redo_size():\n history: HistoryElement = self.settings.history_next_element()\n self.settings.set(\"current_algorithm\", history.segmentation_parameters[\"algorithm_name\"])\n self.settings.set(\n f\"algorithm.{history.segmentation_parameters['algorithm_name']}\",\n history.segmentation_parameters[\"values\"],\n )\n self.settings.mask = mask\n self.close()\n\n def prev_mask(self):\n history: HistoryElement = self.settings.history_pop()\n algorithm_name = self.settings.last_executed_algorithm\n algorithm_values = self.settings.get(f\"algorithms.{algorithm_name}\")\n self.settings.fix_history(algorithm_name=algorithm_name, algorithm_values=algorithm_values)\n self.settings.set(\"current_algorithm\", history.segmentation_parameters[\"algorithm_name\"])\n self.settings.set(\n f\"algorithm.{history.segmentation_parameters['algorithm_name']}\", history.segmentation_parameters[\"values\"]\n )\n history.arrays.seek(0)\n seg = np.load(history.arrays)\n history.arrays.seek(0)\n self.settings.segmentation = seg[\"segmentation\"]\n self.settings.full_segmentation = seg[\"full_segmentation\"]\n if \"mask\" in seg:\n self.settings.mask = seg[\"mask\"]\n else:\n self.settings.mask = None\n self.close()\n\n\nclass MainWindow(BaseMainWindow):\n @classmethod\n def get_setting_class(cls) -> Type[PartSettings]:\n return PartSettings\n\n initial_image_path = PartSegData.segmentation_analysis_default_image\n\n def __init__(\n self, config_folder=CONFIG_FOLDER, title=\"PartSeg\", settings=None, signal_fun=None, initial_image=None\n ):\n super().__init__(config_folder, title, settings, signal_fun)\n self.channel_info = \"result_image\"\n self.files_num = 2\n self.setMinimumWidth(600)\n # thi isinstance is only for hinting in IDE\n assert isinstance(self.settings, PartSettings) # nosec\n self.main_menu = MainMenu(self.settings, self)\n # self.channel_control1 = ChannelControl(self.settings, name=\"raw_control\", text=\"Left panel:\")\n self.channel_control2 = ChannelProperty(self.settings, start_name=\"result_control\")\n self.raw_image = CompareImageView(self.settings, self.channel_control2, \"raw_image\")\n self.measurements = MeasurementWidget(self.settings)\n self.left_stack = StackedWidgetWithSelector()\n self.left_stack.addWidget(self.raw_image, \"Image\")\n self.left_stack.addWidget(self.measurements, \"Measurements\")\n self.result_image = ResultImageView(self.settings, self.channel_control2, \"result_image\")\n self.color_bar = ColorBar(self.settings, [self.raw_image, self.result_image])\n self.info_text = QLabel()\n self.info_text.setMinimumHeight(25)\n self.raw_image.text_info_change.connect(self.info_text.setText)\n self.result_image.text_info_change.connect(self.info_text.setText)\n self.synchronize_tool = SynchronizeView(self.raw_image, self.result_image, self)\n # image_view_control = self.image_view.get_control_view()\n self.options_panel = Options(\n self.settings, self.channel_control2, self.raw_image, self.result_image, self.synchronize_tool\n )\n # self.main_menu.image_loaded.connect(self.image_read)\n self.settings.image_changed.connect(self.image_read)\n self.advanced_window = SegAdvancedWindow(self.settings, reload_list=[self.reload])\n self.batch_window = None # BatchWindow(self.settings)\n\n self.multiple_files = MultipleFileWidget(self.settings, load_functions.load_dict, True)\n\n if initial_image is None:\n reader = TiffImageReader()\n im = reader.read(self.initial_image_path)\n im.file_path = \"\"\n self.settings.image = im\n elif initial_image is False:\n # FIXME This is for test opening\n pass\n else:\n self.settings.image = initial_image\n\n icon = QIcon(os.path.join(PartSegData.icons_dir, \"icon.png\"))\n self.setWindowIcon(icon)\n\n menu_bar = self.menuBar()\n file_menu = menu_bar.addMenu(\"File\")\n file_menu.addAction(\"&Open\").triggered.connect(self.main_menu.load_data)\n file_menu.addAction(\"&Save\").triggered.connect(self.main_menu.save_file)\n file_menu.addAction(\"Batch processing\").triggered.connect(self.main_menu.batch_window)\n view_menu = menu_bar.addMenu(\"View\")\n view_menu.addAction(\"Settings and Measurement\").triggered.connect(self.main_menu.advanced_window_show)\n view_menu.addAction(\"Additional output\").triggered.connect(self.additional_layers_show)\n view_menu.addAction(\"Additional output with data\").triggered.connect(lambda: self.additional_layers_show(True))\n view_menu.addAction(\"Napari viewer\").triggered.connect(self.napari_viewer_show)\n action = view_menu.addAction(\"Screenshot right panel\")\n action.triggered.connect(self.screenshot(self.result_image))\n action.setShortcut(QKeySequence.Print)\n view_menu.addAction(\"Screenshot left panel\").triggered.connect(self.screenshot(self.raw_image))\n image_menu = menu_bar.addMenu(\"Image operations\")\n image_menu.addAction(\"Image adjustment\").triggered.connect(self.image_adjust_exec)\n image_menu.addAction(\"Mask manager\").triggered.connect(self.main_menu.mask_manager)\n help_menu = menu_bar.addMenu(\"Help\")\n help_menu.addAction(\"State directory\").triggered.connect(self.show_settings_directory)\n help_menu.addAction(\"About\").triggered.connect(self.show_about_dialog)\n\n layout = QGridLayout()\n # layout.setContentsMargins(0, 0, 0, 0)\n layout.setSpacing(0)\n info_layout = QHBoxLayout()\n info_layout.addWidget(self.left_stack.selector)\n info_layout.addWidget(self.options_panel.compare_btn)\n info_layout.addWidget(self.info_text, 1, Qt.AlignHCenter)\n\n image_layout = EqualColumnLayout()\n image_layout.addWidget(self.left_stack)\n image_layout.addWidget(self.result_image)\n\n layout.setSpacing(0)\n layout.addWidget(self.main_menu, 0, 0, 1, 3)\n layout.addLayout(info_layout, 1, 1, 1, 2)\n layout.addWidget(self.multiple_files, 2, 0)\n layout.addWidget(self.color_bar, 2, 1)\n # layout.addWidget(self.left_stack, 2, 2)\n # layout.addWidget(self.result_image, 2, 3)\n layout.addLayout(image_layout, 2, 2, 1, 1)\n layout.addWidget(self.options_panel, 0, 3, 3, 1)\n layout.setColumnStretch(2, 1)\n widget = QWidget()\n widget.setLayout(layout)\n # self.multiple_files.setHidden(True)\n self.setCentralWidget(widget)\n try:\n geometry = self.settings.get_from_profile(\"main_window_geometry\")\n self.restoreGeometry(QByteArray.fromHex(bytes(geometry, \"ascii\")))\n except KeyError:\n pass\n\n def image_read(self):\n # self.raw_image.set_image()\n # self.raw_image.reset_image_size()\n # self.result_image.set_image()\n # self.result_image.reset_image_size()\n self.options_panel.interactive_algorithm_execute()\n self.setWindowTitle(f\"{self.title_base}: {os.path.basename(self.settings.image_path)}\")\n\n def read_drop(self, paths):\n self._read_drop(paths, load_functions)\n\n def reload(self):\n self.options_panel.algorithm_choose_widget.reload(algorithm_description.analysis_algorithm_dict)\n\n def event(self, event: QEvent):\n if event.type() == QEvent.WindowActivate:\n self.multiple_files.setVisible(self.settings.get(\"multiple_files\", False))\n return super().event(event)\n\n def closeEvent(self, event):\n # print(self.settings.dump_view_profiles())\n # print(self.settings.segmentation_dict[\"default\"].my_dict)\n self.settings.set_in_profile(\"main_window_geometry\", self.saveGeometry().toHex().data().decode(\"ascii\"))\n self.options_panel.algorithm_choose_widget.recursive_get_values()\n if self.batch_window is not None:\n if self.batch_window.is_working():\n ret = QMessageBox.warning(\n self,\n \"Batch work\",\n \"Batch work is not finished. \" \"Would you like to terminate it?\",\n QMessageBox.No | QMessageBox.Yes,\n )\n if ret == QMessageBox.Yes:\n self.batch_window.terminate()\n else:\n event.ignore()\n return\n self.batch_window.close()\n self.advanced_window.close()\n self.settings.dump()\n del self.batch_window\n del self.advanced_window\n super().closeEvent(event)\n\n @staticmethod\n def get_project_info(file_path, image):\n return ProjectTuple(file_path=file_path, image=image)\n\n def set_data(self, data):\n self.main_menu.set_data(data)\n","sub_path":"package/PartSeg/segmentation_analysis/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":32938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"18248301","text":"import tensorflow as tf\n\nEPSILON = 0.00001\n\ndef conv_wrapper(x, shape, strides, padding):\n weights = tf.get_variable(\"weights\",\n shape,\n initializer = tf.contrib.layers.xavier_initializer_conv2d())\n biases = tf.get_variable(\"biases\",\n [shape[3]],\n initializer = tf.constant_initializer(0.1))\n\n #tf.histogram_summary(\"weights_summary\", weights)\n\n conv = tf.nn.conv2d(x,\n weights,\n strides = strides,\n padding = padding)\n return conv + biases\n\ndef bn_wrapper(x, is_training):\n gamma = tf.get_variable(\"gamma\",\n [x.get_shape()[-1]],\n initializer = tf.constant_initializer(1.0))\n beta = tf.get_variable(\"beta\",\n [x.get_shape()[-1]],\n initializer = tf.constant_initializer(1.0))\n moving_mean = tf.get_variable(\"moving_mean\",\n [x.get_shape()[-1]],\n initializer = tf.constant_initializer(0.0),\n trainable = False)\n moving_variance = tf.get_variable(\"moving_variance\",\n [x.get_shape()[-1]],\n initializer = tf.constant_initializer(1.0),\n trainable = False)\n return tf.cond(is_training,\n lambda: bn_train_time(x, beta, gamma, moving_mean, moving_variance),\n lambda: bn_test_time(x, beta, gamma, moving_mean, moving_variance))\n\ndef bn_train_time(x, beta, gamma, moving_mean, moving_variance):\n mean, variance = tf.nn.moments(x, axes = [0,1,2])\n ALPHA = 0.90\n op_moving_mean = tf.assign(moving_mean,\n moving_mean * ALPHA + mean * (1-ALPHA))\n op_moving_variance = tf.assign(moving_variance,\n moving_variance * ALPHA + variance * (1-ALPHA))\n with tf.control_dependencies([op_moving_mean, op_moving_variance]):\n return tf.nn.batch_normalization(x,\n mean,\n variance,\n offset = beta,\n scale = gamma,\n variance_epsilon = EPSILON)\n\ndef bn_test_time(x, beta, gamma, moving_mean, moving_variance):\n return tf.nn.batch_normalization(x,\n moving_mean,\n moving_variance,\n offset = beta,\n scale = gamma,\n variance_epsilon = EPSILON)\n\ndef residual_block(x, C, is_training):\n with tf.variable_scope(\"h1_conv_bn\"):\n conv1 = conv_wrapper(x, shape = [3,3,C,C], strides = [1, 1, 1, 1], padding = \"SAME\")\n bn1 = bn_wrapper(conv1, is_training)\n relu1 = tf.nn.relu(bn1)\n with tf.variable_scope(\"h2_conv_bn\"):\n conv2 = conv_wrapper(relu1, shape = [3,3,C,C], strides = [1, 1, 1, 1], padding = \"SAME\")\n bn2 = bn_wrapper(conv2, is_training)\n\n res = x + bn2\n return tf.nn.relu(res)\n\ndef residual_block_reduce_size(x, C, is_training):\n last_C = x.get_shape().as_list()[-1]\n with tf.variable_scope(\"h1_conv_bn\"):\n conv1 = conv_wrapper(x, shape = [3,3,last_C,C], strides = [1, 2, 2, 1], padding = \"VALID\")\n bn1 = bn_wrapper(conv1, is_training)\n relu1 = tf.nn.relu(bn1)\n with tf.variable_scope(\"h2_conv_bn\"):\n conv2 = conv_wrapper(relu1, shape = [3,3,C,C], strides = [1, 1, 1, 1], padding = \"SAME\")\n bn2 = bn_wrapper(conv2, is_training)\n\n return tf.nn.relu(bn2)\n","sub_path":"resnet.py","file_name":"resnet.py","file_ext":"py","file_size_in_byte":3840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"35730699","text":"from rest_framework import viewsets\nfrom .models import ListModel\nfrom . import serializers\nfrom utils.page import MyPageNumberPagination\nfrom rest_framework.filters import OrderingFilter\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework.response import Response\nfrom .filter import Filter\nfrom rest_framework.exceptions import APIException\n\nclass APIViewSet(viewsets.ModelViewSet):\n \"\"\"\n retrieve:\n Response a data list(get)\n\n list:\n Response a data list(all)\n\n create:\n Create a data line(post)\n\n delete:\n Delete a data line(delete)\n\n partial_update:\n Partial_update a data(patch:partial_update)\n\n update:\n Update a data(put:update)\n \"\"\"\n pagination_class = MyPageNumberPagination\n filter_backends = [DjangoFilterBackend, OrderingFilter, ]\n ordering_fields = ['id', \"create_time\", \"update_time\", ]\n filter_class = Filter\n\n def get_project(self):\n try:\n id = self.kwargs.get('pk')\n return id\n except:\n return None\n\n def get_queryset(self):\n id = self.get_project()\n if self.request.user:\n if id is None:\n return ListModel.objects.filter(openid=self.request.auth.openid, is_delete=False)\n else:\n return ListModel.objects.filter(openid=self.request.auth.openid, id=id, is_delete=False)\n else:\n return ListModel.objects.none()\n\n def get_serializer_class(self):\n if self.action in ['list', 'retrieve', 'destroy']:\n return serializers.GoodscolorGetSerializer\n elif self.action in ['create']:\n return serializers.GoodscolorPostSerializer\n elif self.action in ['update']:\n return serializers.GoodscolorUpdateSerializer\n elif self.action in ['partial_update']:\n return serializers.GoodscolorPartialUpdateSerializer\n else:\n return self.http_method_not_allowed(request=self.request)\n\n def create(self, request, *args, **kwargs):\n data = self.request.data\n data['openid'] = self.request.auth.openid\n if ListModel.objects.filter(openid=data['openid'], goods_color=data['goods_color'], is_delete=False).exists():\n raise APIException({\"detail\": \"Data exists\"})\n else:\n serializer = self.get_serializer(data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=200, headers=headers)\n\n def update(self, request, pk):\n qs = self.get_object()\n if qs.openid != self.request.auth.openid:\n raise APIException({\"detail\": \"Cannot update data which not yours\"})\n else:\n data = self.request.data\n serializer = self.get_serializer(qs, data=data)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=200, headers=headers)\n\n def partial_update(self, request, pk):\n qs = self.get_object()\n if qs.openid != self.request.auth.openid:\n raise APIException({\"detail\": \"Cannot partial_update data which not yours\"})\n else:\n data = self.request.data\n serializer = self.get_serializer(qs, data=data, partial=True)\n serializer.is_valid(raise_exception=True)\n serializer.save()\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=200, headers=headers)\n\n def destroy(self, request, pk):\n qs = self.get_object()\n if qs.openid != self.request.auth.openid:\n raise APIException({\"detail\": \"Cannot delete data which not yours\"})\n else:\n qs.is_delete = True\n qs.save()\n serializer = self.get_serializer(qs, many=False)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=200, headers=headers)\n","sub_path":"goodscolor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"263254108","text":"def solution(n, words):\n answer = [0, 0]\n\n turn = 1\n mem, prev = [words[0]], words[0]\n for idx, word in enumerate(words[1:]):\n if prev[-1] == word[0] and mem.count(word) == 0:\n prev = word\n mem.append(word)\n else:\n p_idx = n if (idx + 2) % n == 0 else (idx + 2) % n\n answer = [p_idx, turn]\n break\n if (idx + 2) % n == 0:\n turn += 1\n\n for turn in range(1, len(words)):\n if words[turn - 1][-1] != words[turn][0] or\\\n words[turn] in words[:turn]:\n return [(turn % n) + 1, (turn // n) + 1]\n\n # for p in range(1, len(words)):\n # if words[p][0] != words[p - 1][-1] or words[p] in words[:p]: return [(p % n) + 1, (p // n) + 1]\n # else:\n # return [0, 0]\n\n return answer\n\n\nprint(solution(3, [\"tank\", \"kick\", \"know\", \"wheel\", \"land\", \"dream\", \"mother\", \"robot\", \"tank\"]))\nprint(solution(5,\t[\"hello\", \"observe\", \"effect\", \"take\", \"either\", \"recognize\", \"encourage\", \"ensure\", \"establish\", \"hang\", \"gather\", \"refer\", \"reference\", \"estimate\", \"executive\"]))\nprint(solution(2,\t[\"hello\", \"one\", \"even\", \"never\", \"now\", \"world\", \"draw\"]))","sub_path":"prev/programmers/level2/영어_끝말잇기.py","file_name":"영어_끝말잇기.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"615601010","text":"# ----------------------------------------\n# LSM with BCM for MNIST test\n# add neurons to readout layer for multi-classification(one-versus-the-rest)\n# using softmax(logistic regression)\n# input layer is changed to 781*1 with encoding method\n# change the LSM structure according to Maass paper\n# new calculate flow as Maass_ST\n# simplify the coding method with only extend the rank\n# ----------------------------------------\n\nfrom brian2 import *\nfrom brian2tools import *\nimport scipy as sp\nimport struct\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import accuracy_score\nimport pickle\nfrom bqplot import *\nimport ipywidgets as widgets\nimport warnings\nimport os\n\n\nwarnings.filterwarnings(\"ignore\")\nprefs.codegen.target = \"numpy\"\nstart_scope()\nnp.random.seed(100)\ndata_path = '../../../Data/MNIST_data/'\n\n\n#-------define brian2 function------------\n@check_units(spike_window=1,result=1)\ndef get_rate(spike_window):\n return np.sum(spike_window, axis = 1)/spike_window.shape[1]\n\n@check_units(spike_window=1, spike = 1, result=1)\ndef get_spike_window(spike_window, spike):\n new_window = np.zeros(spike_window.shape)\n new_window[:,:-1] = spike_window[:,1:]\n new_window[:,-1] = spike\n return new_window\n\n\n#-------define general function------------\nclass Function():\n def __init__(self):\n pass\n\n def logistic(self, f):\n return 1 / (1 + np.exp(-f))\n\n def softmax(self, z):\n return np.array([(np.exp(i) / np.sum(np.exp(i))) for i in z])\n\n def gamma(self, a, size):\n return sp.stats.gamma.rvs(a, size=size)\n\n\nclass Base():\n def __init__(self, duration, dt):\n self.duration = duration\n self.dt = dt\n self.interval = duration * dt\n\n def get_states(self, input, running_time, sample, normalize=False):\n n = int(running_time / self.interval)\n step = int(self.interval / sample / defaultclock.dt)\n interval_ = int(self.interval / defaultclock.dt)\n temp = []\n for i in range(n):\n sum = np.sum(input[:, i * interval_: (i + 1) * interval_][:, ::-step], axis=1)\n temp.append(sum)\n if normalize:\n return MinMaxScaler().fit_transform(np.asarray(temp)).T\n else:\n return np.asarray(temp).T\n\n def update_states(self, type='pandas', *args, **kwargs):\n for seq, state in enumerate(kwargs):\n if type == 'pandas':\n kwargs[state] = kwargs[state].append(pd.DataFrame(args[seq]))\n elif type == 'numpy':\n kwargs[state] = self.np_extend(kwargs[state], args[seq], 1)\n return kwargs\n\n def normalization_min_max(self, arr):\n arr_n = arr\n for i in range(arr.size):\n x = float(arr[i] - np.min(arr)) / (np.max(arr) - np.min(arr))\n arr_n[i] = x\n return arr_n\n\n def mse(self, y_test, y):\n return sp.sqrt(sp.mean((y_test - y) ** 2))\n\n def classification(self, thea, data):\n data_n = self.normalization_min_max(data)\n data_class = []\n for a in data_n:\n if a >= thea:\n b = 1\n else:\n b = 0\n data_class.append(b)\n return np.asarray(data_class), data_n\n\n def allocate(self, G, X, Y, Z):\n V = np.zeros((X, Y, Z), [('x', float), ('y', float), ('z', float)])\n V['x'], V['y'], V['z'] = np.meshgrid(np.linspace(0, Y - 1, Y), np.linspace(0, X - 1, X),\n np.linspace(0, Z - 1, Z))\n V = V.reshape(X * Y * Z)\n np.random.shuffle(V)\n n = 0\n for g in G:\n for i in range(g.N):\n g.x[i], g.y[i], g.z[i] = V[n][0], V[n][1], V[n][2]\n n += 1\n return G\n\n def w_norm2(self, n_post, Synapsis):\n for i in range(n_post):\n a = Synapsis.w[np.where(Synapsis._synaptic_post == i)[0]]\n Synapsis.w[np.where(Synapsis._synaptic_post == i)[0]] = a / np.linalg.norm(a)\n\n def np_extend(self, a, b, axis=0):\n if a is None:\n shape = list(b.shape)\n shape[axis] = 0\n a = np.array([]).reshape(tuple(shape))\n return np.append(a, b, axis)\n\n def np_append(self, a, b):\n shape = list(b.shape)\n shape.insert(0, -1)\n if a is None:\n a = np.array([]).reshape(tuple(shape))\n return np.append(a, b.reshape(tuple(shape)), axis=0)\n\n def connection_matrix(self, n_pre, n_post, sources, targets, values):\n full_matrix = np.zeros((n_pre, n_post))\n full_matrix[targets, sources] = values\n return full_matrix\n\n def spectral_radius(self, S, is_norm = False):\n if isinstance(S, Synapses):\n n_pre = S.N_pre\n n_post = S.N_post\n sources = S.i[:]\n targets = S.j[:]\n values = S.w[:] - np.mean(S.variables['w'].get_value())\n if n_pre== n_post:\n ma = self.connection_matrix(n_pre, n_post, sources, targets, values)\n if is_norm :\n ma = ma /np.sqrt(np.var(ma))/np.sqrt(n_post)\n else:\n ma = ma /np.sqrt(n_post)\n else:\n return np.array(-1)\n a, b = np.linalg.eig(ma)\n return np.max(np.abs(a))\n else:\n raise ('The input need to be a object of Synapses')\n\n\nclass Readout():\n def __init__(self, function):\n self.function = function\n\n def data_init(self, M_train, M_test, label_train, label_test, rate, theta):\n self.rate = rate\n self.theta = theta\n self.iter = 0\n self.X_train = self.add_bis(M_train)\n self.X_test = self.add_bis(M_test)\n self.Y_train = self.prepare_Y(label_train)\n self.Y_test = self.prepare_Y(label_test)\n self.P = np.random.rand(self.X_train.shape[1], self.Y_train.shape[1])\n self.cost_train = 1e+100\n self.cost_test = 1e+100\n\n def predict_logistic(self, results):\n labels = (results > 0.5).astype(int).T\n return labels\n\n def calculate_score(self, label, label_predict):\n return [accuracy_score(i, j) for i, j in zip(label, label_predict)]\n\n def add_bis(self, data):\n one = np.ones((data.shape[1], 1)) # bis\n X = np.hstack((data.T, one))\n return X\n\n def prepare_Y(self, label):\n if np.asarray(label).ndim == 1:\n return np.asarray([label]).T\n else:\n return np.asarray(label).T\n\n def cost(self, X, Y, P):\n left = np.multiply(Y, np.log(self.function(X.dot(P))))\n right = np.multiply((1 - Y), np.log(1 - self.function(X.dot(P))))\n return -np.sum(np.nan_to_num(left + right), axis=0) / (len(Y))\n\n def train(self, X, Y, P):\n P_ = P + X.T.dot(Y - self.function(X.dot(P))) * self.rate\n return P_\n\n def test(self, X, p):\n return self.function(X.dot(p))\n\n def stop_condition(self):\n return ((self.cost_train - self.cost(self.X_train, self.Y_train, self.P)) > self.theta).any() and \\\n ((self.cost_test - self.cost(self.X_test, self.Y_test, self.P)) > self.theta).any() or self.iter < 100\n\n def readout(self):\n self.iter = 0\n while self.stop_condition():\n self.iter += 1\n self.cost_train = self.cost(self.X_train, self.Y_train, self.P)\n self.cost_test = self.cost(self.X_test, self.Y_test, self.P)\n self.P = self.train(self.X_train, self.Y_train, self.P)\n if self.iter % 10000 == 0:\n print(self.iter, self.cost_train, self.cost_test)\n print(self.iter, self.cost_train, self.cost_test)\n return self.test(self.X_train, self.P), self.test(self.X_test, self.P)\n\n def readout_sk(self, X_train, X_test, y_train, y_test, **kwargs):\n from sklearn.linear_model import LogisticRegression\n lr = LogisticRegression(**kwargs)\n lr.fit(X_train.T, y_train.T)\n y_train_predictions = lr.predict(X_train.T)\n y_test_predictions = lr.predict(X_test.T)\n return accuracy_score(y_train_predictions, y_train.T), accuracy_score(y_test_predictions, y_test.T)\n\n\nclass Result():\n def __init__(self):\n pass\n\n def result_save(self, path, *arg, **kwarg):\n if os.path.exists(path):\n os.remove(path)\n fw = open(path, 'wb')\n pickle.dump(kwarg, fw)\n fw.close()\n\n def result_pick(self, path):\n fr = open(path, 'rb')\n data = pickle.load(fr)\n fr.close()\n return data\n\n def animation(self, t, v, interval, duration, a_step=10, a_interval=100, a_duration=10):\n xs = LinearScale()\n ys = LinearScale()\n line = Lines(x=t[:interval], y=v[:, :interval], scales={'x': xs, 'y': ys})\n xax = Axis(scale=xs, label='x', grid_lines='solid')\n yax = Axis(scale=ys, orientation='vertical', tick_format='0.2f', label='y', grid_lines='solid')\n fig = Figure(marks=[line], axes=[xax, yax], animation_duration=a_duration)\n\n def on_value_change(change):\n line.x = t[change['new']:interval + change['new']]\n line.y = v[:, change['new']:interval + change['new']]\n\n play = widgets.Play(\n interval=a_interval,\n value=0,\n min=0,\n max=duration,\n step=a_step,\n description=\"Press play\",\n disabled=False\n )\n slider = widgets.IntSlider(min=0, max=duration)\n widgets.jslink((play, 'value'), (slider, 'value'))\n slider.observe(on_value_change, names='value')\n return play, slider, fig\n\n\nclass MNIST_classification(Base):\n def __init__(self, shape, duration, dt):\n super().__init__(duration, dt)\n self.shape = shape\n\n def load_Data_MNIST(self, n, path_value, path_label, is_norm=True):\n with open(path_value, 'rb') as f1:\n buf1 = f1.read()\n with open(path_label, 'rb') as f2:\n buf2 = f2.read()\n\n image_index = 0\n image_index += struct.calcsize('>IIII')\n im = []\n for i in range(n):\n temp = struct.unpack_from('>784B', buf1, image_index)\n im.append(np.reshape(temp, self.shape))\n image_index += struct.calcsize('>784B')\n\n label_index = 0\n label_index += struct.calcsize('>II')\n label = np.asarray(struct.unpack_from('>' + str(n) + 'B', buf2, label_index))\n if is_norm:\n f = lambda x: (x - np.min(x)) / (np.max(x) - np.min(x))\n df = pd.DataFrame({'value': pd.Series(im).apply(f), 'label': pd.Series(label)})\n else:\n df = pd.DataFrame({'value': pd.Series(im), 'label': pd.Series(label)})\n return df\n\n def load_Data_MNIST_all(self, path, is_norm=True):\n self.train = self.load_Data_MNIST(60000, path + 'train-images.idx3-ubyte',\n path + 'train-labels.idx1-ubyte', is_norm)\n self.test = self.load_Data_MNIST(10000, path + 't10k-images.idx3-ubyte',\n path + 't10k-labels.idx1-ubyte', is_norm)\n\n def select_data(self, fraction, data_frame, is_order=True, **kwargs):\n try:\n selected = kwargs['selected']\n except KeyError:\n selected = np.arange(10)\n if is_order:\n data_frame_selected = data_frame[data_frame['label'].isin(selected)].sample(\n frac=fraction).sort_index().reset_index(drop=True)\n else:\n data_frame_selected = data_frame[data_frame['label'].isin(selected)].sample(frac=fraction).reset_index(\n drop=True)\n return data_frame_selected\n\n def _encoding_cos_rank(self, x, n, A):\n encoding = np.zeros((x.shape[0] * A, n * x.shape[1]), dtype=' 0 and priority < 100\n assert assoc in (ASSOC_NONE, ASSOC_LEFT, ASSOC_RIGHT)\n self.type = type\n self.symbol = symbol\n self.priority = priority\n self.function = function\n self.assoc = assoc\n def is_left_assoc(self):\n return self.assoc == ASSOC_LEFT\n\nclass OperatorGroup:\n lengths = []\n by_symbol = {}\n def __init__(self, operators):\n self.by_symbol = { op.symbol: op for op in operators }\n length_set = set([ len(op.symbol) for op in operators ])\n self.lengths = sorted(length_set, reverse=True)\n def parse(self, s):\n for length in self.lengths:\n saved_pos = s.tell()\n op = self.by_symbol.get(s.read(length))\n if op:\n return op\n s.seek(saved_pos)\n return None\n\n# priority booster allows to raise a priority of an infix operator\n# based on types and/or values of LHS and RHS operands\nclass InfixPriorityBooster:\n # is_applicable is a function of three arguments:\n # LHS value, RHS value and an operator (the instance of Operator).\n def __init__(self, is_applicable, boost_value):\n self.is_applicable = is_applicable\n self.boost_value = boost_value\n\nclass ExpressionTraits:\n def __init__(self,\\\n operators,\n infix_boosters=[],\n parse_elementary_factor=parse_number,\n fcall=lambda name, args: 0,\n on_missing_right_paren = lambda lparen_pos: None):\n self.unary_prefix_ops = OperatorGroup(\n [ op for op in operators if op.type == UNARY_PREFIX ])\n self.binary_infix_ops = OperatorGroup(\n [ op for op in operators if op.type == BINARY_INFIX ])\n self.infix_boosters = sorted(\n infix_boosters,\n key=lambda b: b.value,\n reverse=True)\n # add the default boost with zero boost\n default_infix_booster = InfixPriorityBooster(\n lambda lhs, rhs, op: True,\n 0)\n self.infix_boosters.append(default_infix_booster)\n #\n self.parse_elementary_factor = parse_elementary_factor\n self.fcall = fcall\n self.on_missing_right_paren = on_missing_right_paren\n\nnumerical_expression_traits = ExpressionTraits(\n [\n Operator(BINARY_INFIX, '+', 10, operator.add, ASSOC_LEFT),\n Operator(BINARY_INFIX, '-', 10, operator.sub, ASSOC_LEFT),\n Operator(BINARY_INFIX, '*', 20, operator.mul, ASSOC_LEFT),\n Operator(BINARY_INFIX, '·', 20, operator.mul, ASSOC_LEFT),\n Operator(BINARY_INFIX, '/', 20, operator.truediv, ASSOC_LEFT),\n Operator(UNARY_PREFIX, '-', 30, operator.neg, ASSOC_NONE),\n Operator(UNARY_PREFIX, '+', 30, operator.pos, ASSOC_NONE),\n Operator(BINARY_INFIX, '^', 40, operator.pow, ASSOC_RIGHT),\n Operator(BINARY_INFIX, '**', 40, operator.pow, ASSOC_RIGHT)\n ])\n\n# the expression parser is based on \"precedence climbing\" algorithm\n# http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm\n#\n# min_priority is a minimum allowed priority of an operator to be parsed\n# (thus we can set a barrier)\ndef parse_expression(s, traits=numerical_expression_traits, min_priority=0):\n saved_pos = s.tell()\n lhs = parse_term(s, traits)\n if not lhs:\n s.seek(saved_pos)\n return None\n while 1:\n saved_pos = s.tell()\n\n op = parse_binary_infix_op(s, traits)\n if not op:\n # no more infix operators. the result is in lhs\n break\n # allow whitespace after an infix operator\n parse_whitespace(s)\n\n # boosters are sorted in descending order;\n # the default booster (zero boost for any LHS and RHS)\n # added to the end of the sorted list\n rhs = None\n for booster in traits.infix_boosters:\n boosted_priority = op.priority + booster.boost_value\n if boosted_priority >= min_priority:\n barrier = boosted_priority + 1 if op.is_left_assoc() else boosted_priority\n pos_before_expr = s.tell()\n rhs = parse_expression(s, traits, min_priority=barrier)\n if rhs and booster.is_applicable(lhs, rhs, op):\n lhs = op.function(lhs, rhs)\n break\n else:\n s.seek(pos_before_expr)\n rhs = None\n if not rhs:\n break\n s.seek(saved_pos)\n return lhs\n\ndef parse_binary_infix_op(s, traits):\n saved_pos = s.tell()\n ws = parse_whitespace(s)\n op = traits.binary_infix_ops.parse(s)\n if op or not ws:\n return op\n # allow whitespace to be an a binary infix op\n s.seek(saved_pos)\n return traits.binary_infix_ops.parse(s)\n\ndef parse_term(s, traits):\n saved_pos = s.tell()\n op = traits.unary_prefix_ops.parse(s)\n if op:\n expr = parse_expression(s, traits, min_priority=op.priority)\n if expr:\n return op.function(expr)\n else:\n return parse_factor(s, traits)\n s.seek(saved_pos)\n return None\n\ndef parse_factor(s, traits):\n saved_pos = s.tell()\n lparen_pos = s.tell()\n if s.read(1) == '(':\n parse_whitespace(s)\n factor = parse_expression(s, traits)\n parse_whitespace(s)\n if s.read(1) == ')':\n return factor\n else:\n traits.on_missing_right_paren(lparen_pos)\n else:\n s.seek(saved_pos)\n res = parse_function(s, traits)\n if res is None:\n res = traits.parse_elementary_factor(s)\n if res is not None:\n return res\n s.seek(saved_pos)\n return None\n\n#\n# function call\n#\n\ndef parse_function(s, traits):\n saved_pos = s.tell()\n name = parse_function_name(s)\n parse_whitespace(s)\n lparen_pos = s.tell()\n if s.read(1) == '(':\n parse_whitespace(s)\n args = parse_comma_separated_list(s, traits)\n parse_whitespace(s)\n if s.read(1) == ')':\n return traits.fcall(name, args)\n else:\n traits.on_missing_right_paren(lparen_pos)\n s.seek(saved_pos)\n return None\n\ndef parse_function_name(s):\n saved_pos = s.tell()\n h = s.read(1)\n if h.isalpha() or h == '_':\n return h + (parse_while(s, lambda c: c.isalnum() or c == '_') or '')\n s.seek(saved_pos)\n return None\n\ndef parse_comma_separated_list(s, traits):\n items = []\n while 1:\n saved_pos = s.tell()\n item = None\n if items:\n parse_whitespace(s)\n item = parse_comma_separated_item(s, traits)\n else:\n item = parse_expression(s, traits)\n if not item:\n s.seek(saved_pos)\n return items\n items.append(item)\n\ndef parse_comma_separated_item(s, traits):\n saved_pos = s.tell()\n if s.read(1) == ',':\n parse_whitespace(s)\n expr = parse_expression(s, traits)\n if expr:\n return expr\n s.seek(saved_pos)\n return None\n","sub_path":"pydimensions/parser/expression.py","file_name":"expression.py","file_ext":"py","file_size_in_byte":7547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"272036381","text":"import bisect\nimport collections\n\n\nclass Solution:\n def sumOfFlooredPairs_slow(self, nums) -> int:\n mod = 10 ** 9 + 7\n d = collections.Counter(nums)\n a = sorted(d.keys())\n n = len(a)\n count = [0]\n for i in range(n):\n count.append(count[-1] + d[a[i]])\n res = 0\n\n for i in range(n - 1, -1, -1):\n x = a[i]\n up = i + 1\n s = 0\n while up > 0:\n multi = x // a[up - 1]\n j = bisect.bisect_right(a, x // (multi + 1))\n s += (count[up] - count[j]) * multi * d[x]\n up = j\n res = (res + s) % mod\n return res\n\n def sumOfFlooredPairs(self, nums) -> int:\n mod = 10 ** 9 + 7\n d = collections.Counter(nums)\n a = sorted(d.keys())\n n = len(a)\n count = [0]\n for i in range(n):\n count.append(count[-1] + d[a[i]])\n res = 0\n\n for i in range(n):\n x = a[i]\n j = i\n s = 0\n while j < n:\n multi = a[j] // x\n k = bisect.bisect_left(a, x * (multi + 1))\n s += (count[k] - count[j]) * multi * d[x]\n j = k\n res = (res + s) % mod\n return res\n\n\ns = Solution()\nprint(s.sumOfFlooredPairs([2, 5, 9]))\nprint(s.sumOfFlooredPairs([7, 7, 7, 7, 7, 7, 7]))\n","sub_path":"leetcode/2021/bicontest/bcontest-052/bContest4.py","file_name":"bContest4.py","file_ext":"py","file_size_in_byte":1395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"441881085","text":"# '''\n# Please read the license file.\n# LabMate.AI was designed to help identifying optimized conditions for chemical reactions.\n# You will need the Python libraries below (NumPy, Pandas and Scikit-learn) and 10 random reactions to run LabMate.AI.\n# '''\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import KFold\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.externals.joblib import dump\nimport random\nimport time\n# pwd\nprint('Welcome! Let me work out what is the best experiment for you to run...')\n# print(\"Time: %s\", time.time())\nprint(time.strftime(\"%Y/%m/%d %H:%M:%S\"))## 带日期的12小时格式\n#\n# '''\n# The training data should be a tab separated file named 'train_data.txt'. The first column of the file is the reaction identifier and the last column is the objective variable (target). The columns in between correspond to descriptors. Otherwise please change accordingly.\n# See example files\n# '''\n# pwd\n# cd ActiveLearning-master/\nfilename = 'train_data716.txt'\ntrain = pd.read_csv(filename, sep= '\\\\t', engine='python')\nprint(train.head())#.head查看头5行\n# type(train)\n\narray = train.values\n# array\nX = array[:,:-1] #从第1列到倒数第二列,注意up to but not including\n# X\nY = array[:,-1]\n# Y #Y是最后一列数据\n\n\n\n\n\n'''\nGeneral settings below. These do not need to be changed.\nThe seed value is what makes the whole process deterministic. You may choose to change this number. #种子数很重要,决定性的\nThe possible number of estimators, max_features and max_depth is a good compromise, but may need to be adapted, if the number of features (columns) is very different.\n'''\n\nseed = 1 #随机数种子=1\nkfold = KFold(n_splits = 10, shuffle=True, random_state = seed) #10折,数据重新洗牌,随机数种子1\nscoring = 'neg_mean_absolute_error' #评分:neg_mean_absolute_error'\nmodel = RandomForestRegressor(random_state=seed) #建模,随机数种子1\nestimators = np.arange(100, 1050, 50) #估计器数量,100到1050,取50个数\n# estimators\nestimators_int = np.ndarray.tolist(estimators) #把array 变成list\n# estimators_int\nparam_grid = {'n_estimators':estimators_int, 'max_features':('auto', 'sqrt'), 'max_depth':[None, 2, 4]}\n\n\nprint('All good till now. I am figuring out the best method to analyze your data. Bear with me...')\n\n\n'''\nThis section makes LabMate.AI search for the best hyperparameters autonomously.\nIt will also save a file with the best score and store the ideal hyperparameters for future use.\n'''\n\ngrid = GridSearchCV(estimator=model, param_grid=param_grid, scoring=scoring, cv=kfold, n_jobs=6) #n_jobs要变成4核试试才行,先6核不要怕\ngrid_result = grid.fit(X, Y)\nnp.savetxt('best_score.txt', [\"best_score: %s\" % grid.best_score_], fmt ='%s')\nbest_params = pd.DataFrame([grid.best_params_], columns=grid.best_params_.keys())\n\n\nprint('... done! It is going to be lightspeed from here on out! :)')\n\n\n'''\nThis section loads all possible reactions (search space) and deletes all previously executed reactions from that file.\nThe file has the same format as the training data, but no \"Target\" column. Please check example file.\n'''\n\nfilename2 = 'all_combos.txt'\ndf_all_combos = pd.read_csv(filename2, sep= '\\\\t', engine='python')\ndf_train_corrected = train.iloc[:,:-1] #测试样本数据\nunseen = pd.concat([df_all_combos, df_train_corrected], sort = True).drop_duplicates(keep=False) #把all和train合并,去重\narray2 = unseen.values #去重后的数据传入array2\nX2 = array2[:,:] #X2的数据为: 合并后的数据,从第二列到最后一列,都是已知参数\n# X2.shape\ndf_all_combos2 = df_all_combos.iloc[:,:] #不要第一列pyridine 不知道为什么???\n\n\n\n\n\n'''\nLabMate.AI predicts the future in this section. It builds the model using the best hyperparameter set and predicts the reaction yield (numeric value) for each instance.\nFor your reference, the method creates a file with the feature importances\n'''\n\nmodel2 = RandomForestRegressor(n_estimators = grid.best_params_['n_estimators'], max_features = grid.best_params_['max_features'], max_depth = grid.best_params_['max_depth'], random_state = seed)\n#model2使用之前网格搜索得到的最优参数\nRF_fit = model2.fit(X, Y) #用X Y拟合model2\npredictions = model2.predict(X2) #预测 X2值\n# np.isnan(X2)\npredictions_df = pd.DataFrame(data=predictions, columns=['Prediction'])\nfeat_imp = pd.DataFrame(data=model2.feature_importances_, index=list(df_all_combos2.columns.values), columns=['Feature_importances'])\n#得到model2的特征重要性,构建一个dataframe\nfeat_imp = feat_imp.sort_values(by=['Feature_importances'], ascending = False)\n#排序\n\n\n\n\n\n'''\nLabMate.AI calculates variances for the predictions, which allows prioritizing the next best experiment, and creates a table with all the generated information.\n'''\n\nall_predictions = []\nfor e in model2.estimators_:\n all_predictions += [e.predict(X2)]\n #随机森林里产生了很多的estimators 用所有的估计器去预测X2的数据,返回预测值,构建一个包含所有预测值的list\n# all_predictions\nvariance = np.var(all_predictions, axis=0) #计算偏差,以横轴??\nvariance_df = pd.DataFrame(data=variance, columns=['Variance'])\n\nassert len(variance) == len(predictions) # control line\ninitial_data = pd.DataFrame(data=array2, columns = list(unseen.columns.values))\ndf = pd.concat([initial_data, predictions_df, variance_df], axis=1) #得到新的表格,包含原始值,预测值,偏差\n\n\n\n\n\n'''\nLabMate.AI now selects the next reaction to be performed.\n'''\n#看它用什么选\nfeat_imp_T = feat_imp.transpose() # creates a table with a single row stating the importance (0-1 scale) of each variable\nkeys1 = list(feat_imp_T.keys()) # collects the names of the features\nkeys2 = list(feat_imp_T.keys()) # same as above\nkeys1.insert(7,'Prediction') # Inserts \"Prediction\" in position 7 of the previously generated list\nkeys2.insert(7, 'Variance') # Inserts \"Variance\" in position 7 of the previously generated list\n\ndf_sorted = df.sort_values(by=[keys1[-1], keys1[0]], ascending=[False, False]) # Fetches the table with the predictions and variance and sorts: 1) high prediction first; 2) most important feature second (descending order) for overlapping predictions\npreliminary = df_sorted.iloc[0:5] # Collects the first five columns 最优数据\ndf_sorted2 = preliminary.sort_values(by=[keys2[-1], keys2[0]], ascending=[True, False]) # Sorts the top five rows by: 1) Low variance first; 2) most important feature second (descending order) for overlapping predictions\ntoPerform = df_sorted2.iloc[0] # First row is the selected reaction\n\n\n\n\n\n\n\n'''\nSave files\n'''\n\nfeat_imp.to_csv('feature_importances.txt', sep= '\\t')\nbest_params.to_csv('best_parameters.txt', sep= '\\t')\ntoPerform.to_csv('selected_reaction.txt', sep = '\\t', header=False)\ndf_sorted.to_csv('predictions.txt', sep = '\\t')\nfilename3 = 'random_forest_model_grid.sav'\ndump(grid, filename3)\n\nprint('You are all set! Have a good one, mate!')\n\n\n\n\n'''\nAfter performing the reaction simply edit the train_data.txt file with the reaction conditions used and target value, before running the script again. Enjoy and happy chemistry :)\n'''\nprint(time.strftime(\"%Y/%m/%d %H:%M:%S\"))## 带日期的12小时格式\n","sub_path":"continuous-variables/literature-code-in-python/LabMate-AI-changed.py","file_name":"LabMate-AI-changed.py","file_ext":"py","file_size_in_byte":7337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"449030271","text":"from flask import Flask, render_template, redirect\nfrom flask_pymongo import PyMongo\nimport scrape_mars\n\napp = Flask(__name__)\n\n\n# Use PyMongo to establish Mongo connection\nmongo = PyMongo(app, uri=\"mongodb://localhost:27017/mars_app\")\n\n\n# Set route\n@app.route(\"/\")\ndef index():\n mars_info = mongo.db.mars_info.find_one()\n \n return render_template(\"index.html\", mars_info=mars_info)\n\n@app.route(\"/scrape\")\ndef scraper():\n mars_info_collection = mongo.db.mars_info\n\n results_dict = scrape_mars.scrape()\n\n mars_info_collection.update({}, results_dict, upsert=True)\n \n return redirect(\"/\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"290282378","text":"import sys\nsys.stdin = open('input.txt','r')\ndef bfs(n,si,sj):\n cnt = 0\n di = [1,0,-1,0]\n dj = [0,1,0,-1]\n q = [0]*n*n*2\n\n front = -1\n rear = -1\n\n rear += 1\n q[rear] = si\n rear += 1\n q[rear] = sj\n arr[si][sj] = 0\n while(front!=rear):\n\n front += 1\n i = q[front]\n front += 1\n j = q[front]\n\n\n cnt+=1\n for k in range(4):\n ni = i + di[k]\n nj = j + dj[k]\n if(ni>=0 and ni=0 and njx:\n# a[t],a[i]=a[i],a[t]\n# t-=1\n# i-=1 #remain in the same i in this case\n# i+=1\n# return j\n# =============================================================================\ndef partition3(a,l,r):\n pivot_value=a[l]\n p_l=i=l\n p_r=r\n \n while i<=p_r:\n if a[i]= r:\n return\n k = random.randint(l, r)\n a[l], a[k] = a[k], a[l]\n #use partition3\n m = partition3(a, l, r)\n randomized_quick_sort(a, l, m[0] - 1);\n randomized_quick_sort(a, m[1] + 1, r);\n\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n n, *a = list(map(int, input.split()))\n randomized_quick_sort(a, 0, n - 1)\n for x in a:\n print(x, end=' ')\n","sub_path":"week4_divide_and_conquer/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"371310183","text":"# Name: Bunmi Oluwatudimu\r\n# Date: March 6th, 2020\r\n\r\n# The LinkedList class: a collection of nodes (Node: data and a link to the next node)\r\nfrom node import Node\r\n\r\nclass LinkedList():\r\n def __init__(self):\r\n self.__head = None\r\n\r\n def isEmpty(self):\r\n return self.__head == None\r\n\r\n # add a node at the end of the linked list\r\n def append(self, data):\r\n newNode = Node(data)\r\n\r\n if self.isEmpty(): # if list is empty, head will point to newNode\r\n self.__head = newNode\r\n\r\n else: # list is not empty, go to end of list and add newNode there\r\n current = self.__head\r\n while current.getNext() != None:\r\n current = current.getNext()\r\n current.setNext(newNode)\r\n\r\n # remove a node from the linked list\r\n def remove(self, item):\r\n current = self.__head\r\n previous = None\r\n found = False\r\n\r\n # first find item in the list\r\n while not found:\r\n if current.getData() == item:\r\n found = True\r\n else:\r\n previous = current\r\n current = current.getNext()\r\n\r\n if previous == None: # item was in the fist node\r\n self.__head = current.getNext()\r\n else: # item was somewhere after the first node\r\n previous.setNext(current.getNext())\r\n\r\n # search for item in linked list\r\n def search(self, item):\r\n current = self.__head\r\n found = False\r\n while current != None and not found:\r\n if current.getData() == item:\r\n found = True\r\n else:\r\n current = current.getNext()\r\n\r\n return found\r\n\r\n # overloaded operators\r\n def __getitem__(self, index): # used to suppport []\r\n current = self.__head\r\n\r\n for i in range(index):\r\n current = current.getNext()\r\n\r\n return current.getData()\r\n\r\n def __str__(self): # used to support print(myLinkedList)\r\n mystr = ''\r\n current = self.__head\r\n\r\n while current != None:\r\n mystr += str(current.getData())\r\n current = current.getNext()\r\n return mystr\r\n\r\n def __len__(self): # used to support len(myLinkedList)\r\n if self.__head == None: # if list is empty return 0\r\n return 0\r\n\r\n current = self.__head # list is not empty and has at least 1 Node\r\n counter = 1\r\n\r\n while current.getNext() != None:\r\n counter += 1\r\n current = current.getNext()\r\n return counter\r\n","sub_path":"linkedList.py","file_name":"linkedList.py","file_ext":"py","file_size_in_byte":2578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"359649435","text":"# -*- coding: UTF-8 -*-\n\n\"\"\"\nThis file is part of Pondus, a personal weight manager.\nCopyright (C) 2008-10 Eike Nicklas \n\nThis program is free software licensed under the MIT license. For details\nsee LICENSE or http://www.opensource.org/licenses/mit-license.php\n\"\"\"\n\nimport os\nimport sys\n\nimport pygtk\npygtk.require('2.0')\nimport gtk\n\nfrom pondus.core import parameters\nfrom pondus.gui.dialog_message import MessageDialog\n\n\nclass FileLock(object):\n \"\"\"Implements a very simple file locking mechanism to prevent two\n instances of editing the same file.\"\"\"\n\n def __init__(self):\n \"\"\"Gets data neccessary to lock the datafile, asks for confirmation\n if the file is already locked and performs the lock if wanted.\"\"\"\n self.lockfilename = parameters.userdatafile + '.lck'\n self.pid = str(os.getpid())\n self.first_lock()\n\n def first_lock(self):\n \"\"\"Locks the datafile, asks for confirmation if the file is already\n locked and performs the lock if wanted.\"\"\"\n if not self.is_locked():\n self.lock()\n return\n elif not self.own_lock():\n title = _('Datafile locked, continue?')\n message = _('Another instance of pondus seems to be editing \\\nthe same datafile. Do you really want to continue and loose all the changes \\\nfrom the other instance?')\n response = MessageDialog('question', title, message).run()\n if response == gtk.RESPONSE_YES:\n self.take_over_lock()\n return\n elif response == gtk.RESPONSE_NO:\n sys.exit(1)\n\n def lock(self):\n \"\"\"Locks the datafile to prevent editing with a second instance.\"\"\"\n lockfile = open(self.lockfilename, 'w')\n lockfile.write(self.pid)\n lockfile.close()\n\n def unlock(self):\n \"\"\"Unlocks the datafile if the instance owns the lock.\"\"\"\n if self.own_lock():\n os.remove(self.lockfilename)\n\n def is_locked(self):\n \"\"\"Checks, whether the datafile is locked.\"\"\"\n return os.path.exists(self.lockfilename)\n\n def own_lock(self):\n \"\"\"Checks, whether the current instance owns the lock.\"\"\"\n if self.is_locked():\n lockfile = open(self.lockfilename, 'r')\n lockpid = lockfile.read()\n lockfile.close()\n return self.pid == lockpid\n\n def take_over_lock(self):\n \"\"\"Deletes the current lockfile and creates a new one.\"\"\"\n os.remove(self.lockfilename)\n self.lock()\n","sub_path":"pondus/core/filelock.py","file_name":"filelock.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"548001035","text":"# Copyright © Garima Kapila\n\nfrom scipy.optimize import curve_fit\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nfrom DataCollector.DataParser import *\nfrom Visualizer import *\n\n\n\n# keep/delete certain columns\ndef filter_cols(features_file, include=[], exclude=[]):\n\tfeatures = pd.read_csv(features_file)\n\tcols = [\n\t\tcol for col in features.columns if\n\t\t\t(any(keyword in col for keyword in include) and\n\t\t\t all(keyword not in col for keyword in exclude))\n\t]\n\tresults = features[cols]\n\tresults_file = features_file.replace('Features', 'Reduced')\n\tresults.to_csv(results_file, index = False)\n\treturn results_file\n\n# standardize data then PCA\ndef dimensionality_reduction(file_name, scree_file_name='', graph=False):\n\tdata, labels = columns_from_data(file_name)\n\tstd_data = standardize_data(data)\n\tn_cols = len(data.columns)\n\tn, scree, log_scree = get_n_components(std_data, n_cols)\n\tscree_plots_name = file_name.replace('Features', 'Scree_Plots')\n\twrite_images_to_ppt([scree, log_scree], scree_plots_name, scree_file_name)\n\tpca = PCA(n_components = n).fit(std_data)\n\treduced = pca.transform(std_data)\n\tif graph:\n\t\tscatter_plots(file_name, reduced)\n\treduced_file = 'Reduced_' + file_name\n\tnp.savetxt(reduced_file, reduced, delimiter = ',')\n\treturn n, reduced_file, scree_file_name\n\n# scatter points using PCA and TSNE\ndef scatter_plots(data, labels):\n\tscatter_graph(data, labels)\n\n# scale features by standardization\ndef standardize_data(data):\n\tscaler = preprocessing.StandardScaler()\n\tstd_scale = scaler.fit(data)\n\tstd_data = std_scale.transform(data)\n\treturn std_data\n\n# get top principal components (# at kink in scree plot)\ndef get_n_components(data, n_cols):\n\tpca = PCA(n_components = n_cols).fit(data)\n\tdata = pca.transform(data)\n\tvariance = pca.explained_variance_\n\tlog_variance = np.log(variance)\n\tscree, log_scree = scree_plot(variance, log_variance)\n\tn = int((np.abs(log_variance)).argmin() * 1.5)\n\treturn n, scree, log_scree\n\n# visualize kink of explained variance plot\ndef scree_plot(variance, log_variance):\n\ttitle = 'Scree Plot'\n\tx_axis = 'Principal Component #'\n\ty_axis = 'Explained Variance'\n\tscree = line_graph(variance, title, x_axis, y_axis)\n\ttitle = 'Log Scree Plot'\n\ty_axis = 'Log Explained Variance'\n\tlog_scree = line_graph(log_variance, title, x_axis, y_axis)\n\treturn scree, log_scree\n\n# get number columns and labels\ndef columns_from_data(file_name):\n\tdata = pd.read_csv(file_name, sep = ',')\n\tdata = data.select_dtypes(['number'])\n\tlabels = data['Label']\n\tdata = data.drop(['Label'], axis = 1)\n\treturn data, labels\n\n# For scatter plots\n\ndef pca_2D(reduced_pca_data):\n\treturn reduced_pca_data[:, 0], reduced_pca_data[:, 1]\n\ndef tsne_2D(reduced_data):\n\treturn TSNE(n_components = 2).fit_transform(reduced_data)\n\t\n\ndef combine_features(file_path):\n\tfeatures = pd.read_csv(file_path, sep=',')\n\tfeatures = add_blosum_positives(features)\n\tfeatures = add_score_averages(features)\n\tfeatures = join_pair_columns(features)\n\tfeatures = move_col_to_end(features, 'Database')\n\tfeatures = move_col_to_end(features, 'Label')\n\tfile_name = file_path.split('/')[-1]\n\tfile_name_prefix = file_name.split('_')[0]\n\tfile_name = file_name.replace(file_name_prefix, 'Features')\n\tfeatures.fillna(value = 0)\n\tfeatures.to_csv(file_name, sep = ',', index = False)\n\treturn file_name\n\n\n# input pandas dataframe, dataframe split by labels\ndef split_by_label(dataframe, labels_col, labels=[0, 1]):\n\tlabel_name = labels_col.name\n\tdataframe[label_name] = labels_col\n\tsplits = [dataframe[dataframe[label_name] == label] for label in labels]\n\treturn [split.drop(columns=[label_name]) for split in splits]\n\n\n### Helper methods for add_features_to_interologs ###\n\n# Add blosum match + similar (non-match) to get positives column\ndef add_blosum_positives(features):\n\tfor col in features.columns.values:\n\t\tif '_Match' in col and '_Blosum' in col:\n\t\t\tcol_type = column_type(col)\n\t\t\tpr_type = pair_type(col)\n\t\t\tfor col2 in features.columns.values:\n\t\t\t\tif '_Similar' in col2 and pr_type == pair_type(col2) and \\\n\t\t\t\t\tcol_type == column_type(col2):\n\t\t\t\t\tfeatures[col_type + '_Sum_Blosum_Positive_Scores_Pair_' \\\n\t\t\t\t\t+ pr_type] = features[col] + features[col2]\n\treturn features\n\n# average # or score divided by length\ndef add_score_averages(features):\n\t\n\t# Put column names that have 'length' in a dictionary along with pair type\n\tlengths_dict = {}\n\tfor col in features.columns.values:\n\t\tif 'Length' in col:\n\t\t\tcol_type = column_type(col)\n\t\t\tpr_type = pair_type(col)\n\t\t\tlengths_dict[col_type + pr_type] = col\n\t\t\t# avoid infinite values\n\t\t\tfeatures[col] = features[col].replace(0, 1)\n\n\t# Get averages/percents using lengths\n\tfor col in features.columns.values:\n\t\tif 'Sum' in col or 'Count' in col or 'Difference' in col:\n\t\t\tlength_col = column_type(col) + pair_type(col)\n\t\t\tif length_col in lengths_dict.keys():\n\t\t\t\tlengths = features[lengths_dict[length_col]]\n\t\t\t\tfactor = 1\n\t\t\t\tif 'Count' in col:\n\t\t\t\t\tfactor = 100\n\t\t\t\tnew_col = col.replace('Sum', 'Average_Sum')\n\t\t\t\tnew_col = new_col.replace('Count', 'Percent')\n\t\t\t\tnew_col = new_col.replace('Difference', 'Average_Difference')\n\t\t\t\tfeatures[new_col] = features[col] * factor / lengths\n\t\t\t\tfeatures[new_col] = features[new_col].round(3)\n\t\n\t# Add % interface residues\n\tfor col in features.columns.values:\n\t\tif 'Interface_' in col and 'Length' in col:\n\t\t\tpr_type = pair_type(col)\n\t\t\tfasta_length = lengths_dict['Fasta' + pr_type]\n\t\t\tnew_col = col.replace('Length', 'Percent')\n\t\t\tfeatures[new_col] = 100 * features[col] / features[fasta_length]\n\t\t\tfeatures[new_col].round(3)\n\t\n\treturn features\n\n# Get joint columns for pair 1, pair 2 across features\ndef join_pair_columns(features):\n\tfor col1 in features.columns:\n\t\tif 'Pair_1' in col1:\n\t\t\tcolumn_name = col1.replace('Pair_1', 'Joint')\n\t\t\tdata1 = features[col1]\n\t\t\tcol2 = col1[:-1] + '2'\n\t\t\tdata2 = features[col2]\n\t\t\tjoint = data1 * data2\n\t\t\tfeatures[column_name] = joint\n\treturn features\n\n# first part of name is column type, types: Blast, Global, Interface, etc\ndef column_type(column):\n\treturn column.split('_')[0]\n\n# last part of name is pair type, ex. Pair_1 = 1\ndef pair_type(column):\n\treturn column.split('_')[-1]\n\ndef filter_interologs(features_file):\n\tdata = pd.read_csv(features_file)\n\tdata0 = data[data['Label'] == 0]\n\tdata1 = data[data['Label'] == 1]\n\tq0_0, q0_1, q1_0, q1_1 = 0, 0, 0, 0\n\tfor x in range(0, 10):\n\t\tx /= float(100)\n\t\tpercent_m1, percent_m2 = [\n\t\t\t'Interface_Matching_Percent_Pair_1',\n\t\t\t'Interface_Matching_Percent_Pair_2',\n\t\t]\n\t\tx0_0 = data0[percent_m1].quantile(x)\n\t\tx0_1 = data0[percent_m2].quantile(x)\n\t\tif x0_0 == 0 and x0_1 == 0:\n\t\t\tq0_0 = x0_0\n\t\t\tq0_1 = x0_1\n\t\t\tq1_0 = data1[percent_m1].quantile(x)\n\t\t\tq1_1 = data1[percent_m2].quantile(x)\n\t\telse:\n\t\t\tbreak\n","sub_path":"ML/DataParser.py","file_name":"DataParser.py","file_ext":"py","file_size_in_byte":6772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"188607069","text":"\"\"\"\n Message_parsers file contains all classes to parse a SDMX-ML Message\n\"\"\"\n\nfrom sdmxthon.model.definitions import DataStructureDefinition, \\\n DataFlowDefinition, ContentConstraint\nfrom sdmxthon.model.header import Header\nfrom sdmxthon.model.itemScheme import Codelist, AgencyScheme, ConceptScheme\nfrom sdmxthon.parsers.data_generic import DataSetType as GenericDataSet\nfrom sdmxthon.parsers.data_parser import DataParser\nfrom sdmxthon.parsers.data_structure import DataSetType as StructureDataSet\nfrom sdmxthon.parsers.footer_parser import FooterType\nfrom sdmxthon.parsers.gdscollector import GdsCollector\nfrom sdmxthon.utils.handlers import add_indent\nfrom sdmxthon.utils.mappings import messageAbbr, structureAbbr\n\n\nclass MessageType(DataParser):\n \"\"\"MessageType is an abstract dim_type which is used by all of the\n messages, to allow inheritance of common features. Every message\n consists of a mandatory header, followed by optional payload (which may\n occur multiple times), and finally an optional footer section for\n conveying error, warning, and informational messages. \"\"\"\n\n def __init__(self, header=None, Footer=None, gds_collector_=None,\n **kwargs_):\n super(MessageType, self).__init__(gds_collector_, **kwargs_)\n self._gds_collector_ = gds_collector_\n self._header = header\n self._footer = Footer\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of MessageType\"\"\"\n return MessageType(**kwargs_)\n\n @property\n def header(self):\n \"\"\"Header of the Message\"\"\"\n return self._header\n\n @header.setter\n def header(self, value):\n self._header = value\n\n @property\n def footer(self):\n \"\"\"Footer of the Message\"\"\"\n return self._footer\n\n @footer.setter\n def footer(self, value):\n self._footer = value\n\n\n# end class MessageType\n\nclass GenericDataType(MessageType):\n \"\"\"GenericDataType defines the contents of a generic data message.\"\"\"\n __hash__ = DataParser.__hash__\n subclass = None\n superclass = MessageType\n\n def __init__(self, header=None, Footer=None, DataSet=None,\n gds_collector_=None, **kwargs_):\n super(GenericDataType, self).__init__(header, Footer, gds_collector_,\n **kwargs_)\n\n if DataSet is None:\n self._dataSet = []\n else:\n self._dataSet = DataSet\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of GenericDataType\"\"\"\n return GenericDataType(*args_, **kwargs_)\n\n @property\n def dataset(self):\n \"\"\"List of Datasets in a Generic Message\"\"\"\n return self._dataSet\n\n @dataset.setter\n def dataset(self, value):\n if value is None:\n self._dataSet = []\n elif isinstance(value, list):\n self._dataSet = value\n else:\n raise TypeError('Dataset must be a list')\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Header':\n obj_ = Header._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._header = obj_\n obj_.original_tagname_ = 'Header'\n elif nodeName_ == 'DataSet':\n obj_ = GenericDataSet._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._dataSet.append(obj_)\n obj_.original_tag_name_ = 'DataSet'\n elif nodeName_ == 'Footer':\n obj_ = FooterType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._footer = obj_\n obj_.original_tag_name_ = 'Footer'\n\n\n# end class GenericDataType\n\nclass CodelistsType(DataParser):\n \"\"\"CodelistsType is the parser for the Codelists XML element\"\"\"\n\n def __init__(self, codelist=None, gds_collector_=None, **kwargs_):\n super(CodelistsType, self).__init__(gds_collector_, **kwargs_)\n\n if codelist is None:\n self._codelists = {}\n else:\n self._codelists = codelist\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of CodelistsType\"\"\"\n return CodelistsType(*args_, **kwargs_)\n\n @property\n def codelists(self):\n \"\"\"Dict of Codelists\"\"\"\n return self._codelists\n\n @codelists.setter\n def codelists(self, value):\n self._codelists = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Codelist':\n obj_ = Codelist._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._codelists[obj_.unique_id] = obj_\n\n\nclass ConceptsType(DataParser):\n \"\"\"ConceptsType is the parser for the Concepts XML element\"\"\"\n\n def __init__(self, concepts=None, gds_collector_=None, **kwargs_):\n super(ConceptsType, self).__init__(gds_collector_, **kwargs_)\n\n self._cl_references = []\n if concepts is None:\n self._concepts = {}\n else:\n self._concepts = concepts\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of ConceptsType\"\"\"\n return ConceptsType(*args_, **kwargs_)\n\n @property\n def concepts(self):\n \"\"\"Dict of Concepts\"\"\"\n return self._concepts\n\n @concepts.setter\n def concepts(self, value):\n self._concepts = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'ConceptScheme':\n obj_ = ConceptScheme._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self.concepts[obj_.unique_id] = obj_\n\n\nclass DataStructuresType(DataParser):\n \"\"\"DataStructuresType is the parser for the DataStructures XML element\"\"\"\n\n def __init__(self, dsds=None, gds_collector_=None, **kwargs_):\n super(DataStructuresType, self).__init__(gds_collector_, **kwargs_)\n\n self._cl_references = []\n self._dsds = dsds\n\n self._non_unique = None\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of DataStructuresType\"\"\"\n return DataStructuresType(*args_, **kwargs_)\n\n @property\n def dsds(self):\n \"\"\"Dict of DSDs\"\"\"\n return self._dsds\n\n @dsds.setter\n def dsds(self, value):\n self._dsds = value\n\n @property\n def non_unique(self):\n \"\"\"Dict of non-unique dsds\"\"\"\n return self._non_unique\n\n def add_non_unique(self, id_):\n \"\"\"Method to add a non-unique DSD to generate the error\"\"\"\n if self._non_unique is None:\n self._non_unique = []\n self._non_unique.append(id_)\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'DataStructure':\n obj_ = DataStructureDefinition._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n\n if self._dsds is None:\n self._dsds = {}\n\n if obj_.unique_id in self.dsds:\n self.add_non_unique(obj_.unique_id)\n else:\n self.dsds[obj_.unique_id] = obj_\n\n\nclass OrganisationSchemesType(DataParser):\n \"\"\"OrganisationSchemesType is the parser for the OrganisationScheme XML\n element \"\"\"\n\n def __init__(self, agency_scheme=None, gds_collector_=None, **kwargs_):\n super(OrganisationSchemesType, self).__init__(gds_collector_,\n **kwargs_)\n\n if agency_scheme is None:\n self._agency_schemes = []\n else:\n self._agency_schemes = agency_scheme\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of OrganisationSchemesType\"\"\"\n return OrganisationSchemesType(*args_, **kwargs_)\n\n @property\n def agencySchemes(self):\n \"\"\"Getter of the AgencyScheme\"\"\"\n return self._agency_schemes\n\n @agencySchemes.setter\n def agencySchemes(self, value):\n self._agency_schemes = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'AgencyScheme':\n obj_ = AgencyScheme._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._agency_schemes = obj_\n\n\nclass DataflowsType(DataParser):\n \"\"\"DataflowsType is the parser for the DataFlowDefinition XML element\"\"\"\n\n def __init__(self, dataflows=None, gds_collector_=None, **kwargs_):\n super(DataflowsType, self).__init__(gds_collector_, **kwargs_)\n\n if dataflows is None:\n self._dataflows = {}\n else:\n self._dataflows = dataflows\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of DataflowsType\"\"\"\n return DataflowsType(*args_, **kwargs_)\n\n @property\n def dataflows(self):\n \"\"\"Dict of Dataflows\"\"\"\n return self._dataflows\n\n @dataflows.setter\n def dataflows(self, value):\n self._dataflows = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Dataflow':\n obj_ = DataFlowDefinition._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self.dataflows[obj_.unique_id] = obj_\n\n\nclass ConstraintsType(DataParser):\n \"\"\"ConstraintsType is the parser for the Constraint XML element\"\"\"\n\n def __init__(self, constraints=None, gds_collector_=None):\n super(ConstraintsType, self).__init__(gds_collector_)\n\n if constraints is None:\n self._constraints = {}\n else:\n self._constraints = constraints\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of ConstraintsType\"\"\"\n return ConstraintsType(*args_, **kwargs_)\n\n @property\n def constraints(self):\n \"\"\"Dict of Dataflows\"\"\"\n return self._constraints\n\n @constraints.setter\n def constraints(self, value):\n self._constraints = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'ContentConstraint':\n obj_ = ContentConstraint._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self.constraints[obj_.unique_id] = obj_\n\n\nclass Structures(DataParser):\n \"\"\"Structures class is the Metadata holder to access all elements in a\n Structures SDMX_ML file \"\"\"\n __hash__ = DataParser.__hash__\n\n def __init__(self, codelists=None, concepts=None, dsds=None,\n organisations=None, dataflows=None, constraints=None,\n gds_collector_=None):\n super(Structures, self).__init__(gds_collector_)\n\n self._dataflows = dataflows\n\n self._dsds = dsds\n\n self._codelists = codelists\n\n self._organisations = organisations\n\n self._concepts = concepts\n\n self._constraints = constraints\n\n self._errors = None\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n def __eq__(self, other):\n if isinstance(other, Structures):\n if self.codelists is not None:\n for e in self.codelists.values():\n e._checked = False\n\n if self.concepts is not None:\n for e in self.concepts.values():\n e._checked = False\n\n return (self._dataflows == other._dataflows and\n self._dsds == other._dsds and\n self._codelists == other._codelists and\n self._organisations == other._organisations and\n self._concepts == other._concepts and\n self._errors == other._errors)\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of Structures\"\"\"\n return Structures(*args_, **kwargs_)\n\n @property\n def dataflows(self):\n \"\"\"Dict of dataflows\"\"\"\n return self._dataflows\n\n @dataflows.setter\n def dataflows(self, value):\n self._dataflows = value\n\n @property\n def organisations(self):\n \"\"\"Dict of OrganisationScheme\"\"\"\n return self._organisations\n\n @organisations.setter\n def organisations(self, value):\n self._organisations = value\n\n @property\n def dsds(self):\n \"\"\"Dict of DataStructureDefinition\"\"\"\n return self._dsds\n\n @dsds.setter\n def dsds(self, value):\n self._dsds = value\n\n @property\n def codelists(self):\n \"\"\"Dict of Codelists\"\"\"\n return self._codelists\n\n @codelists.setter\n def codelists(self, value):\n self._codelists = value\n\n @property\n def concepts(self):\n \"\"\"Dict of Concepts\"\"\"\n return self._concepts\n\n @concepts.setter\n def concepts(self, value):\n self._concepts = value\n\n @property\n def constraints(self):\n return self._constraints\n\n @constraints.setter\n def constraints(self, value):\n self._constraints = value\n\n @property\n def errors(self):\n \"\"\"List of Errors\"\"\"\n return self._errors\n\n def add_error(self, error):\n \"\"\"Method to add an error in the Structures\"\"\"\n if self._errors is None:\n self._errors = []\n self._errors.append(error)\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'OrganisationSchemes':\n obj_ = OrganisationSchemesType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._organisations = obj_.agencySchemes\n elif nodeName_ == 'Codelists':\n obj_ = CodelistsType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._codelists = obj_.codelists\n elif nodeName_ == 'Concepts':\n obj_ = ConceptsType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._concepts = obj_.concepts\n elif nodeName_ == 'DataStructures':\n obj_ = DataStructuresType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n if obj_.non_unique is not None:\n for e in obj_.non_unique:\n self.add_error({'Code': 'MS06', 'ErrorLevel': 'CRITICAL',\n 'ObjectID': f'{e}', 'ObjectType': 'DSD',\n 'Message': f'DSD {e} is not unique'})\n self._dsds = obj_.dsds\n\n elif nodeName_ == 'Dataflows':\n obj_ = DataflowsType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._dataflows = obj_.dataflows\n\n elif nodeName_ == 'Constraints':\n obj_ = ConstraintsType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._constraints = obj_.constraints\n\n def to_XML(self, prettyprint=True):\n\n if prettyprint:\n indent = '\\t'\n newline = '\\n'\n else:\n indent = newline = ''\n\n outfile = f'{indent}<{messageAbbr}:Structures>'\n if self.organisations is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:OrganisationSchemes>'\n outfile += self.organisations. \\\n _parse_XML(indent_child, f'{structureAbbr}:AgencyScheme')\n outfile += f'{indent_child}{structureAbbr}:OrganisationSchemes>'\n\n if self.dataflows is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:Dataflows>'\n for e in self.dataflows.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:Dataflow')\n outfile += f'{indent_child}{structureAbbr}:Dataflows>'\n\n if self.codelists is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:Codelists>'\n for e in self.codelists.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:Codelist')\n outfile += f'{indent_child}{structureAbbr}:Codelists>'\n\n if self.concepts is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:Concepts>'\n for e in self.concepts.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:ConceptScheme')\n outfile += f'{indent_child}{structureAbbr}:Concepts>'\n\n if self.dsds is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:DataStructures>'\n for e in self.dsds.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:DataStructure')\n outfile += f'{indent_child}{structureAbbr}:DataStructures>'\n\n if self.constraints is not None:\n indent_child = newline + add_indent(indent)\n outfile += f'{indent_child}<{structureAbbr}:Constraints>'\n for e in self.constraints.values():\n outfile += e._parse_XML(indent_child,\n f'{structureAbbr}:ContentConstraint')\n outfile += f'{indent_child}{structureAbbr}:Constraints>'\n\n outfile += f'{newline}{indent}{messageAbbr}:Structures>{newline}'\n\n return outfile\n\n\nclass MetadataType(MessageType):\n \"\"\"MetadataType is a type of Message that starts with the tag Structure\n and contains the Metadata information \"\"\"\n __hash__ = DataParser.__hash__\n superclass = MessageType\n\n def __init__(self, header=None, footer=None, structures=None,\n gds_collector_=None, **kwargs_):\n super(MetadataType, self).__init__(header, footer, gds_collector_,\n **kwargs_)\n\n self._structures = structures\n\n if gds_collector_ is not None:\n self._gds_collector = gds_collector_\n else:\n self._gds_collector = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of MetadataType\"\"\"\n return MetadataType(*args_, **kwargs_)\n\n @property\n def structures(self):\n \"\"\"Reference to the Structure in the Message\"\"\"\n return self._structures\n\n @structures.setter\n def structures(self, value):\n self._structures = value\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Header':\n obj_ = Header._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._header = obj_\n elif nodeName_ == 'Structures':\n obj_ = Structures._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._structures = obj_\n elif nodeName_ == 'Footer':\n obj_ = FooterType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._footer = obj_\n\n\nclass StructureSpecificDataType(MessageType):\n \"\"\"StructureSpecificDataType defines the structure of the structure\n specific data message. Note that the data set payload dim_type is\n abstract, and therefore it will have to be assigned a dim_type in an\n instance. This dim_type must be derived from the base dim_type\n referenced. This base dim_type defines a general structure which can be\n followed to allow for generic processing of the data even if the exact\n details of the data structure specific format are not known. \"\"\"\n __hash__ = MessageType.__hash__\n subclass = None\n superclass = MessageType\n\n def __init__(self, header=None, Footer=None, DataSet=None,\n gds_collector_=None, **kwargs_):\n super(StructureSpecificDataType, self).__init__(header, Footer,\n gds_collector_,\n **kwargs_)\n\n if DataSet is None:\n self._dataSet = []\n else:\n self._dataSet = DataSet\n self._name = 'StructureSpecificDataType'\n\n if gds_collector_ is not None:\n self.gds_collector_ = gds_collector_\n else:\n self.gds_collector_ = GdsCollector()\n\n @staticmethod\n def _factory(*args_, **kwargs_):\n \"\"\"Factory Method of StructureSpecificDataType\"\"\"\n return StructureSpecificDataType(*args_, **kwargs_)\n\n @property\n def dataset(self):\n \"\"\"List of Datasets in a Structure Specific Message\"\"\"\n return self._dataSet\n\n @dataset.setter\n def dataset(self, value):\n if value is None:\n self._dataSet = []\n elif isinstance(value, list):\n self._dataSet = value\n else:\n raise TypeError('Dataset must be a list')\n\n def _build_children(self, child_, node, nodeName_, fromsubclass_=False,\n gds_collector_=None):\n \"\"\"Builds the childs of the XML element\"\"\"\n if nodeName_ == 'Header':\n obj_ = Header._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._header = obj_\n obj_.original_tagname_ = 'Header'\n elif nodeName_ == 'DataSet':\n obj_ = StructureDataSet._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._dataSet.append(obj_)\n obj_.original_tag_name_ = 'DataSet'\n elif nodeName_ == 'Footer':\n obj_ = FooterType._factory()\n obj_._build(child_, gds_collector_=gds_collector_)\n self._footer = obj_\n obj_.original_tag_name_ = 'Footer'\n\n\n# end class StructureSpecificDataType\n","sub_path":"sdmxthon/parsers/message_parsers.py","file_name":"message_parsers.py","file_ext":"py","file_size_in_byte":23911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"18174995","text":"import FWCore.ParameterSet.Config as cms\n\nfrom FWCore.ParameterSet.VarParsing import VarParsing\n\n###############################\n####### Parameters ############\n###############################\n\noptions = VarParsing ('python')\n\noptions.register('reportEvery', 10,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.int,\n \"Report every N events (default is N=10)\"\n)\noptions.register('wantSummary', False,\n VarParsing.multiplicity.singleton,\n VarParsing.varType.bool,\n \"Print out trigger and timing summary\"\n)\n\n## 'maxEvents' is already registered by the Framework, changing default value\noptions.setDefault('maxEvents', 100)\n\noptions.parseArguments()\n\nprocess = cms.Process(\"USER\")\n\nprocess.load(\"Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff\")\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc')\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = options.reportEvery\n\n## Events to process\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents) )\n\n## Input files\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n # /TTJets_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/RunIISpring15DR74-Asympt25ns_MCRUN2_74_V9-v2/MINIAODSIM\n '/store/mc/RunIISpring15DR74/TTJets_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/Asympt25ns_MCRUN2_74_V9-v2/00000/06B5178E-F008-E511-A2CF-00261894390B.root'\n )\n)\n\n## Options and Output Report\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(options.wantSummary),\n allowUnscheduled = cms.untracked.bool(True)\n)\n\n#################################################\n## Make jets\n#################################################\n\n## Filter out neutrinos from packed GenParticles\nprocess.packedGenParticlesForJetsNoNu = cms.EDFilter(\"CandPtrSelector\", src = cms.InputTag(\"packedGenParticles\"), cut = cms.string(\"abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16\"))\n## Fat GenJets\nfrom RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets\nprocess.ak8GenJetsNoNu = ak4GenJets.clone(\n rParam = cms.double(0.8),\n src = cms.InputTag(\"packedGenParticlesForJetsNoNu\")\n)\n## Pruned fat GenJets (two jet collections are produced, fat jets and subjets)\nfrom RecoJets.JetProducers.SubJetParameters_cfi import SubJetParameters\nfrom RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets\nprocess.ak8GenJetsNoNuPruned = ak4GenJets.clone(\n SubJetParameters,\n rParam = cms.double(0.8),\n src = cms.InputTag(\"packedGenParticlesForJetsNoNu\"),\n usePruning = cms.bool(True),\n writeCompound = cms.bool(True),\n jetCollInstanceName=cms.string(\"SubJets\")\n)\n\n## Select charged hadron subtracted packed PF candidates\nprocess.pfCHS = cms.EDFilter(\"CandPtrSelector\", src = cms.InputTag(\"packedPFCandidates\"), cut = cms.string(\"fromPV\"))\nfrom RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets\n## Fat PFJets\nfrom RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets\nprocess.ak8PFJetsCHS = ak4PFJets.clone(\n rParam = cms.double(0.8),\n src = cms.InputTag(\"pfCHS\"),\n doAreaFastjet = cms.bool(True),\n jetPtMin = cms.double(50.)\n)\n## Pruned fat PFJets (two jet collections are produced, fat jets and subjets)\nfrom RecoJets.JetProducers.ak5PFJetsPruned_cfi import ak5PFJetsPruned\nprocess.ak8PFJetsCHSPruned = ak5PFJetsPruned.clone(\n rParam = cms.double(0.8),\n src = cms.InputTag(\"pfCHS\"),\n doAreaFastjet = cms.bool(True),\n writeCompound = cms.bool(True),\n jetCollInstanceName=cms.string(\"SubJets\"),\n jetPtMin = cms.double(50.)\n)\n\n#################################################\n## Make PAT jets\n#################################################\n\n## b-tag discriminators\nbTagDiscriminators = [\n 'pfTrackCountingHighEffBJetTags',\n 'pfTrackCountingHighPurBJetTags',\n 'pfJetProbabilityBJetTags',\n 'pfJetBProbabilityBJetTags',\n 'pfSimpleSecondaryVertexHighEffBJetTags',\n 'pfSimpleSecondaryVertexHighPurBJetTags',\n 'pfCombinedSecondaryVertexV2BJetTags',\n 'pfCombinedInclusiveSecondaryVertexV2BJetTags',\n 'pfCombinedMVABJetTags',\n 'pfDeepCSVJetTags:probb',\n 'pfDeepCSVJetTags:probbb'\n]\n\nfrom PhysicsTools.PatAlgos.tools.jetTools import *\n## PATify fat jets\naddJetCollection(\n process,\n labelName = 'AK8PFCHS',\n jetSource = cms.InputTag('ak8PFJetsCHS'),\n algo = 'ak', # needed for jet flavor clustering\n rParam = 0.8, # needed for jet flavor clustering\n pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),\n pfCandidates = cms.InputTag('packedPFCandidates'),\n svSource = cms.InputTag('slimmedSecondaryVertices'),\n muSource = cms.InputTag('slimmedMuons'),\n elSource = cms.InputTag('slimmedElectrons'),\n btagDiscriminators = bTagDiscriminators,\n jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),\n genJetCollection = cms.InputTag('ak8GenJetsNoNu'),\n genParticles = cms.InputTag('prunedGenParticles')\n)\n## PATify pruned fat jets\naddJetCollection(\n process,\n labelName = 'AK8PFCHSPruned',\n jetSource = cms.InputTag('ak8PFJetsCHSPruned'),\n btagDiscriminators = ['None'],\n jetCorrections = ('AK8PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),\n genJetCollection = cms.InputTag('ak8GenJetsNoNu'),\n genParticles = cms.InputTag('prunedGenParticles'),\n getJetMCFlavour = False # jet flavor disabled\n)\n## PATify pruned subjets\naddJetCollection(\n process,\n labelName = 'AK8PFCHSPrunedSubjets',\n jetSource = cms.InputTag('ak8PFJetsCHSPruned','SubJets'),\n algo = 'ak', # needed for subjet flavor clustering\n rParam = 0.8, # needed for subjet flavor clustering\n pvSource = cms.InputTag('offlineSlimmedPrimaryVertices'),\n pfCandidates = cms.InputTag('packedPFCandidates'),\n svSource = cms.InputTag('slimmedSecondaryVertices'),\n muSource = cms.InputTag('slimmedMuons'),\n elSource = cms.InputTag('slimmedElectrons'),\n btagDiscriminators = bTagDiscriminators,\n jetCorrections = ('AK4PFchs', ['L1FastJet', 'L2Relative', 'L3Absolute'], 'None'),\n genJetCollection = cms.InputTag('ak8GenJetsNoNuPruned','SubJets'),\n genParticles = cms.InputTag('prunedGenParticles'),\n explicitJTA = True, # needed for subjet b tagging\n svClustering = True, # needed for subjet b tagging\n fatJets=cms.InputTag('ak8PFJetsCHS'), # needed for subjet flavor clustering\n groomedFatJets=cms.InputTag('ak8PFJetsCHSPruned') # needed for subjet flavor clustering\n)\n\n## Establish references between PATified fat jets and subjets using the BoostedJetMerger\nprocess.selectedPatJetsAK8PFCHSPrunedPacked = cms.EDProducer(\"BoostedJetMerger\",\n jetSrc=cms.InputTag(\"selectedPatJetsAK8PFCHSPruned\"),\n subjetSrc=cms.InputTag(\"selectedPatJetsAK8PFCHSPrunedSubjets\")\n)\n\n## Pack fat jets with subjets\nprocess.packedPatJetsAK8PFCHS = cms.EDProducer(\"JetSubstructurePacker\",\n jetSrc = cms.InputTag('selectedPatJetsAK8PFCHS'),\n distMax = cms.double(0.8),\n algoTags = cms.VInputTag( cms.InputTag('selectedPatJetsAK8PFCHSPrunedPacked') ),\n algoLabels = cms.vstring( 'Pruned' ),\n fixDaughters = cms.bool(False)\n)\n\nfrom PhysicsTools.PatAlgos.tools.pfTools import *\n## Adapt primary vertex collection\nadaptPVs(process, pvCollection=cms.InputTag('offlineSlimmedPrimaryVertices'))\n\n#################################################\n\n## Let it run\nprocess.p = cms.Path(process.selectedPatJetsAK8PFCHS + process.selectedPatJetsAK8PFCHSPrunedPacked)\n","sub_path":"test/BTagSubJet_cfg.py","file_name":"BTagSubJet_cfg.py","file_ext":"py","file_size_in_byte":7685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"600894225","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport os\nimport re\n\npipelinename = \"pipeline\"\npipelineurl = \"pipelineurl\"\n\nresults = {}\nversion_files = [x for x in os.listdir('.') if x.endswith('.version.txt')]\nfor version_file in version_files:\n\n software = version_file.replace('.version.txt','')\n\n with open(version_file) as fin:\n version = fin.read().strip()\n \n if software == 'pipelinename':\n pipelinename = version\n elif software == 'pipelineurl':\n pipelineurl = version\n else:\n results[software] = version\n\nresults[pipelinename] = results.pop(\"pipeline\")\n\n# Dump to YAML\nprint ('''\nid: 'software_versions'\nsection_name: '%s Software Versions'\nsection_href: '%s'\nplot_type: 'html'\ndescription: 'are collected at run time from the software output.'\ndata: |\n \n''' % (pipelinename, pipelineurl))\nfor k,v in sorted(results.items()):\n print(\" {} {} \".format(k,v))\nprint (\" \")\n\n# Write out regexes as csv file:\nwith open('software_versions.csv', 'w') as f:\n for k,v in sorted(results.items()):\n f.write(\"{}\\t{}\\n\".format(k,v))\n","sub_path":"bin/scrape_software_versions.py","file_name":"scrape_software_versions.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"380480147","text":"from django.db import models\nfrom django.conf import settings\nfrom accounts.models import CustomUser\n# Create your models here.\n\n# jenis surat: keterangan kuliah, cuti kuliah\nJENIS_SURAT_CHOISES = (\n ('KK', 'Keterangan Kuliah'),\n ('CK', 'Cuti Kuliah')\n)\n\n\nclass Agenda(models.Model):\n no_surat = models.AutoField(primary_key=True, )\n tgl_surat = models.DateField(auto_now=True)\n jenis_surat = models.CharField(choices=JENIS_SURAT_CHOISES, max_length=2)\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n to_field='nim',\n related_name='surats',\n on_delete=models.CASCADE\n )\n","sub_path":"cuti/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"375748171","text":"# Copyright 2015 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 time\n\nfrom proboscis import test\nfrom proboscis.asserts import assert_equal\n\nfrom fuelweb_test import settings\nfrom fuelweb_test.helpers.decorators import log_snapshot_after_test\nfrom fuelweb_test.tests.base_test_case import TestBasic\n\n\n@test(groups=['failover_group_mongo'])\nclass FailoverGroupMongo(TestBasic):\n \"\"\" FailoverGroupMongo \"\"\" # TODO documentation\n\n @test(depends_on_groups=[\"prepare_slaves_9\"],\n groups=['deploy_mongo_cluster'])\n @log_snapshot_after_test\n def deploy_mongo_cluster(self):\n \"\"\"Deploy cluster with MongoDB nodes\n\n Scenario:\n 1. Create environment with enabled Ceilometer and Neutron VLAN\n 2. Add 3 controller, 3 mongodb, 1 compute and 1 cinder nodes\n 3. Verify networks\n 4. Deploy environment\n 5. Verify networks\n 6. Run OSTF tests\n\n Duration 200m\n Snapshot deploy_mongo_cluster\n \"\"\"\n\n self.env.revert_snapshot('ready_with_9_slaves')\n\n self.show_step(1, initialize=True)\n data = {\n 'ceilometer': True,\n 'tenant': 'mongo',\n 'user': 'mongo',\n 'password': 'mongo',\n \"net_provider\": 'neutron',\n \"net_segment_type\": settings.NEUTRON_SEGMENT['vlan'],\n }\n cluster_id = self.fuel_web.create_cluster(\n name=self.__class__.__name__,\n settings=data\n )\n\n self.show_step(2)\n self.fuel_web.update_nodes(\n cluster_id,\n {\n 'slave-01': ['controller'],\n 'slave-02': ['controller'],\n 'slave-03': ['controller'],\n 'slave-04': ['mongo'],\n 'slave-05': ['mongo'],\n 'slave-06': ['mongo'],\n 'slave-07': ['compute'],\n 'slave-08': ['cinder'],\n }\n )\n\n self.show_step(3)\n self.fuel_web.verify_network(cluster_id)\n\n self.show_step(4)\n self.fuel_web.deploy_cluster_wait(cluster_id)\n\n self.show_step(5)\n self.fuel_web.verify_network(cluster_id)\n\n self.show_step(6)\n self.fuel_web.run_ostf(cluster_id,\n test_sets=['smoke', 'sanity',\n 'ha', 'tests_platform'],\n timeout=50 * 60)\n self.env.make_snapshot('deploy_mongo_cluster', is_make=True)\n\n @test(depends_on_groups=[\"deploy_mongo_cluster\"],\n groups=['kill_mongo_processes'])\n @log_snapshot_after_test\n def kill_mongo_processes(self):\n \"\"\"Kill mongo processes\n\n Scenario:\n 1. Pre-condition - do steps from 'deploy_mongo_cluster' test\n 2. Kill mongo processes on 1st node\n 3. Wait 1 minute\n 4. Check new mongo processes exist on 1st node\n 5. Kill mongo processes on 2nd node\n 6. Wait 1 minute\n 7. Check new mongo processes exist on 2nd node\n 8. Kill mongo processes on 3rd node\n 9. Wait 1 minute\n 10. Check new mongo processes exist on 3rd node\n 11. Run OSTF tests\n\n Duration 60m\n Snapshot kill_mongo_processes\n \"\"\"\n\n self.show_step(1, initialize=True)\n self.env.revert_snapshot('deploy_mongo_cluster')\n\n cluster_id = self.fuel_web.get_last_created_cluster()\n mongodb = self.fuel_web.get_nailgun_cluster_nodes_by_roles(cluster_id,\n ['mongo'])\n assert_equal(len(mongodb), 3,\n \"Environment doesn't have 3 MongoDB nodes, \"\n \"found {} nodes!\".format(len(mongodb)))\n step = 2\n for node in mongodb:\n old_pids = self.ssh_manager.execute(\n ip=node['ip'], cmd='pgrep -f mongo')['stdout']\n self.show_step(step)\n self.ssh_manager.execute_on_remote(\n ip=node['ip'], cmd='pkill -9 -f mongo')\n\n self.show_step(step + 1)\n time.sleep(60)\n\n self.show_step(step + 2)\n new_pids = self.ssh_manager.execute(\n ip=node['ip'], cmd='pgrep -f mongo')['stdout']\n bad_pids = set(old_pids) & set(new_pids)\n assert_equal(len(bad_pids), 0,\n 'MongoDB processes with PIDs {} '\n 'were not killed!'.format(bad_pids))\n step += 3\n\n self.show_step(11)\n self.fuel_web.run_ostf(cluster_id,\n test_sets=['smoke', 'sanity',\n 'ha', 'tests_platform'],\n timeout=50 * 60)\n\n self.env.make_snapshot('kill_mongo_processes')\n\n @test(depends_on_groups=['deploy_mongo_cluster'],\n groups=['close_connections_for_mongo'])\n @log_snapshot_after_test\n def close_connections_for_mongo(self):\n \"\"\"Close connection for Mongo node\n\n Scenario:\n 1. Pre-condition - do steps from 'deploy_mongo_cluster' test\n 2. Close management network for 1 Mongo node\n 3. Run OSTF tests\n\n Duration 60m\n Snapshot close_connections_for_mongo\n \"\"\"\n\n self.show_step(1, initialize=True)\n self.env.revert_snapshot('deploy_mongo_cluster')\n\n cluster_id = self.fuel_web.get_last_created_cluster()\n mongodb = self.fuel_web.get_nailgun_cluster_nodes_by_roles(cluster_id,\n ['mongo'])\n assert_equal(len(mongodb), 3,\n \"Environment doesn't have 3 MongoDB nodes, \"\n \"found {} nodes!\".format(len(mongodb)))\n\n self.show_step(2)\n self.ssh_manager.execute_on_remote(\n ip=mongodb[0]['ip'],\n cmd='iptables -I INPUT -i br-mgmt -j DROP && '\n 'iptables -I OUTPUT -o br-mgmt -j DROP')\n\n self.show_step(3)\n self.fuel_web.run_ostf(cluster_id,\n test_sets=['smoke', 'sanity',\n 'ha', 'tests_platform'],\n timeout=50 * 60)\n\n self.env.make_snapshot('close_connections_for_mongo')\n\n @test(depends_on_groups=['deploy_mongo_cluster'],\n groups=['shut_down_mongo_node'])\n @log_snapshot_after_test\n def shut_down_mongo_node(self):\n \"\"\"Shut down Mongo node for Neutron\n\n Scenario:\n 1. Pre-condition - do steps from 'deploy_mongo_cluster' test\n 2. Shut down 1 Mongo node\n 3. Verify networks\n 4. Run OSTF tests\n 5. Turn on Mongo node\n 6. Verify networks\n 7. Run OSTF tests\n\n Duration: 60 min\n Snapshot: shut_down_mongo_node\n \"\"\"\n\n self.show_step(1, initialize=True)\n self.env.revert_snapshot('deploy_mongo_cluster')\n cluster_id = self.fuel_web.get_last_created_cluster()\n mongodb = self.fuel_web.get_nailgun_cluster_nodes_by_roles(cluster_id,\n ['mongo'])\n assert_equal(len(mongodb), 3,\n \"Environment doesn't have 3 MongoDB nodes, \"\n \"found {} nodes!\".format(len(mongodb)))\n\n target_node = self.fuel_web.get_devops_node_by_nailgun_node(mongodb[0])\n\n self.show_step(2)\n self.fuel_web.warm_shutdown_nodes([target_node])\n\n self.show_step(3)\n self.fuel_web.verify_network(cluster_id)\n\n self.show_step(4)\n self.fuel_web.run_ostf(cluster_id=cluster_id, should_fail=1)\n\n self.show_step(5)\n self.fuel_web.warm_start_nodes([target_node])\n\n self.show_step(6)\n self.fuel_web.verify_network(cluster_id)\n\n self.show_step(7)\n self.fuel_web.run_ostf(cluster_id,\n should_fail=1,\n test_sets=['smoke', 'sanity',\n 'ha', 'tests_platform'],\n timeout=50 * 60)\n\n self.env.make_snapshot('shut_down_mongo_node')\n","sub_path":"fuelweb_test/tests/tests_strength/test_failover_mongo.py","file_name":"test_failover_mongo.py","file_ext":"py","file_size_in_byte":8770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"651261967","text":"# -*- coding: utf-8 -\r\nfrom aceproxy import Playlist, Channel\r\nimport requests, json\r\nimport logging, re\r\n\r\nreplacements = [ (u'\\s+Резерв\\s+\\d+',u'') ]\r\n\r\nclass TorrentTelikPlaylist(Playlist):\r\n def load(self):\r\n self.logger = logging.getLogger('torrent-telik')\r\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1' }\r\n data = requests.get( 'http://torrent-telik.com/channels/torrent-tv.json', headers=headers ).json()\r\n self.clear()\r\n for ch in data['channels']:\r\n for rep in replacements:\r\n ch['name'] = re.sub( rep[0], rep[1], ch['name'], re.U+re.I )\r\n\r\n channel = Channel( \r\n id = self.uuid( ch['name'].encode('utf-8') ),\r\n name = ch['name'], \r\n url = ch['url'].replace(\"acestream://\",\"\"),\r\n tags = [ch['cat'].lower()],\r\n hd = ' HD' in ch['name'],\r\n logo = None\r\n )\r\n self.add(channel)\r\n self.logger.info('Loaded %d channels', len(self.items) )\r\n pass\r\n","sub_path":"playlists/torrenttelik.py","file_name":"torrenttelik.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"51702326","text":"from __future__ import division\nimport os\nimport io\nimport sys\nimport datetime\nimport numpy as np\nimport numpy.random as nr\nimport tensorflow as tf\n\nsentiment = dict()\nsentiment[\"postive\"] = np.array([1, 0]) # Is mispelled in the data file.\nsentiment[\"negative\"] = np.array([0, 1])\n\ndef read_word_vectors(filename):\n if os.path.isfile(filename):\n word_to_index = dict()\n index_to_word = list()\n word_vectors = list()\n counter = 0\n with open(filename,'r') as infile:\n for line in infile:\n parts = [x.strip() for x in line.split(\",\", 1)]\n word_to_index[parts[0]] = counter\n index_to_word.append(parts[0])\n word_vectors.append(np.genfromtxt(io.StringIO(unicode(parts[1], \"utf-8\")), delimiter=\",\"))\n counter += 1\n return word_to_index, index_to_word, word_vectors\n else:\n raise Exception(\"Word vector file does not exist\")\n\ndef read_data(filename):\n if os.path.isfile(filename):\n labels = []\n data = []\n maxsenlen = 0\n minsenlen = sys.maxsize\n with open(filename, 'r') as infile:\n for line in infile:\n parts = [x.strip() for x in line.split(\",\", 1)]\n labels.append(sentiment[parts[0]])\n data.append(parts[1])\n maxsenlen = np.max([maxsenlen, len(parts[1].split())])\n minsenlen = np.min([minsenlen, len(parts[1].split())])\n return data, labels, maxsenlen, minsenlen\n else:\n pass\n\ndef get_sentence_in_word_indices(sentence, word_to_index, max_sentence_length = 100):\n sentence_in_word_indices = np.zeros(max_sentence_length, dtype=np.int32)\n words_in_sentence = sentence.split()\n for i, word in enumerate(words_in_sentence):\n # Left pad with zero vectors\n sentence_in_word_indices[i + (max_sentence_length - len(words_in_sentence))] = word_to_index[word]\n return sentence_in_word_indices\n\ndef main(wordvecfile = \"sentiment-data/word-vectors-refine.txt\",\n trainfile = \"sentiment-data/train.csv\",\n testfile = \"sentiment-data/test.csv\"):\n word_to_index, index_to_word, word_vectors = read_word_vectors(wordvecfile)\n word_vectors = np.array(word_vectors, dtype=np.float32)\n \n train_data, train_labels, maxsenlen, minsenlen = read_data(trainfile)\n train_labels = np.array(train_labels)\n no_train_sentences = len(train_data)\n train_data_ints = np.zeros((no_train_sentences, maxsenlen), dtype=np.int32)\n print(\"Maximum sentence length in training data: \", maxsenlen)\n print(\"Minimum sentence length in training data: \", minsenlen)\n print(\"Total no. of sentences in training data : \", no_train_sentences)\n\n # convert each sentence into integer sequence\n for i, sentence in enumerate(train_data):\n train_data_ints[i, :] = get_sentence_in_word_indices(train_data[i], word_to_index, maxsenlen)\n \n test_data, test_labels, maxsenlen_test, minsenlen_test = read_data(testfile)\n test_labels = np.array(test_labels)\n no_test_sentences = len(test_data)\n test_data_ints = np.zeros((no_test_sentences, maxsenlen), dtype=np.int32)\n\n assert(maxsenlen_test <= maxsenlen)\n\n print(\"Maximum sentence length in testing data: \", maxsenlen_test)\n print(\"Minimum sentence length in testing data: \", minsenlen_test)\n print(\"Total no. of sentences in testing data : \", no_test_sentences)\n \n # convert each test sentence into integer sequence\n for i, sentence in enumerate(test_data):\n test_data_ints[i, :] = get_sentence_in_word_indices(test_data[i], word_to_index, maxsenlen)\n \n # RNN Parameters\n batch_size = 100\n n_tr_batches = np.int(np.ceil(no_train_sentences/batch_size))\n\n # Split the training data into different batches\n train_data_indices = np.arange(no_train_sentences)\n nr.shuffle(train_data_indices)\n train_data_indices = np.array_split(train_data_indices, n_tr_batches)\n batched_train_data = [train_data_ints[indices] for indices in train_data_indices]\n batched_train_labels = [train_labels[indices] for indices in train_data_indices] \n \n n_lstm_cell = 64\n n_classes = 2\n maxiter = 10\n wordvecdim = 50\n\n # reset the default graph\n tf.reset_default_graph()\n\n # Create placeholder for labels\n t_labels = tf.placeholder(tf.float32, [None, n_classes]) # labels\n t_data = tf.placeholder(tf.int32, [None, maxsenlen]) # training or test data\n\n \n # Create variables to hold the 3D tensor data of examples, words in sentences, word vectors\n indata = tf.nn.embedding_lookup(word_vectors, t_data)\n \n # Setup LSTM\n lstm_cell = tf.nn.rnn_cell.LSTMCell(n_lstm_cell)\n outputs, state = tf.nn.dynamic_rnn(lstm_cell, indata, dtype=tf.float32)\n\n # weights for last softmax\n W = tf.Variable(tf.random_uniform([n_lstm_cell, n_classes]))\n b = tf.Variable(tf.constant(0.1, shape=[n_classes]))\n\n H = tf.transpose(outputs, [1, 0, 2])\n h_final = tf.gather(H, int(H.get_shape()[0]) - 1)\n prediction = tf.matmul(h_final, W) + b\n\n correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(t_labels,1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=t_labels))\n optimizer = tf.train.AdamOptimizer().minimize(loss)\n\n sess = tf.Session()\n saver = tf.train.Saver()\n\n sess.run(tf.global_variables_initializer())\n\n for epoch in xrange(maxiter):\n for i in xrange(n_tr_batches):\n sess.run(optimizer, {t_data: batched_train_data[i],\n t_labels: batched_train_labels[i]})\n \n if ((epoch + 1) % 2 == 0):\n save_path = saver.save(sess, \"models/pretrained_lstm.ckpt\", global_step=epoch)\n print(\"Saved checkpoint to %s\" % save_path)\n \n print(\"Accuracy: \", sess.run(accuracy, feed_dict={t_data: test_data_ints,\n t_labels: test_labels}))\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"homework2/homework2qrnn_lstm.py","file_name":"homework2qrnn_lstm.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"637959671","text":"import numpy as np \n\ndef to_homogeneous(A):\n \"\"\" \n converts (Nxd) matrix to homogeneous coordinates \n \"\"\"\n N, d = A.shape\n out = np.ones(shape=(N,d+1))\n out[:,:-1] = A \n\n return out\n\n\ndef quat_rot(q):\n \"\"\" \n rotation matrix in terms of quaternions \n \"\"\"\n [q0, q1, q2, q3] = q.tolist()\n\n R = np.zeros(shape=(3,3))\n\n R[0][0] = q0**2 + q1**2 - q2**2 - q3**2\n R[0][1] = 2*(q1*q2 - q0*q3)\n R[0][2] = 2*(q1*q3 + q0*q2)\n\n R[1][0] = 2*(q1*q2 + q0*q3)\n R[1][1] = q0**2 + q2**2 - q1**2 - q3**2\n R[1][2] = 2*(q2*q3 - q0*q1)\n\n R[2][0] = 2*(q1*q3 - q0*q2)\n R[2][1] = 2*(q2*q3 + q0*q1)\n R[2][2] = q0**2 + q3**2 - q1**2 - q2**2\n\n return R\n\n\ndef quat_to_euler(q):\n \"\"\" \n transform quaternion to euler angles, based on wikipedia formuas\n \"\"\"\n [q0, q1, q2, q3] = q.tolist()\n\n phi = np.arctan2(\n (2*(q0*q1+q2*q3)),\n (1 - 2*(q1**2 + q2**2))\n )\n\n theta = np.arcsin(\n 2*(q0*q2 + q3*q1)\n )\n\n psi = np.arctan2(\n (2*(q0*q3 + q1*q2)),\n (1 - 2*(q2**2 + q3**2))\n )\n\n return np.array([phi, theta, psi])\n\n\ndef affine(A, angles, translation, inverse=False):\n \"\"\" \n affine transform\n phi, theta, psi = euler angles\n x, y, z = translations\n assumes A is in homogeneous coordinates\n \"\"\"\n phi = angles[0]\n theta = angles[1]\n psi = angles[2]\n\n x = translation[0]\n y = translation[1]\n z = translation[2]\n\n N = A.shape[0]\n out = np.zeros(shape=(N,3))\n\n R = np.array([\n [np.cos(theta) * np.cos(psi), \n np.cos(theta) * np.sin(psi), \n -np.sin(theta), \n x],\n \n [np.sin(phi) * np.sin(theta) * np.cos(psi) - np.cos(phi) * np.sin(psi), \n np.sin(phi) * np.sin(theta) * np.sin(psi) + np.cos(phi) * np.cos(psi), \n np.sin(phi) * np.cos(theta), \n y],\n\n [np.cos(phi) * np.sin(theta) * np.cos(psi) + np.sin(phi) * np.sin(psi), \n np.cos(phi) * np.sin(theta) * np.sin(psi) - np.sin(phi) * np.cos(psi), \n np.cos(phi) * np.cos(theta), \n z] ])\n\n # for inverse affine transform\n R_T = np.zeros(shape=(3,4))\n R_T[:,:3] = np.linalg.inv(R[:,:3])\n R_T[0][3] = x\n R_T[1][3] = y\n R_T[2][3] = z\n\n if inverse:\n out = np.dot(R_T, A.T)\n return out.T, R_T\n else:\n out = np.dot(R, A.T)\n return out.T, R\n\n return\n\n\ndef cube_points(N, add_noise=False):\n \"\"\" make a numpy cube array, assumes N divisible by 12 \"\"\"\n Y = np.zeros(shape=(N,3))\n seg = np.linspace(0,1,N/12)\n Y[:int(N/12),0] = seg\n Y[int(N/12):2*int(N/12),1] = seg\n Y[2*int(N/12):3*int(N/12),2] = seg\n\n Y[3*int(N/12):4*int(N/12),0] = seg\n Y[3*int(N/12):4*int(N/12),1] = 1\n\n Y[4*int(N/12):5*int(N/12),0] = seg\n Y[4*int(N/12):5*int(N/12),2] = 1\n\n Y[5*int(N/12):6*int(N/12),1] = seg\n Y[5*int(N/12):6*int(N/12),2] = 1\n\n Y[6*int(N/12):7*int(N/12),2] = seg\n Y[6*int(N/12):7*int(N/12),1] = 1\n\n Y[7*int(N/12):8*int(N/12),1] = seg\n Y[7*int(N/12):8*int(N/12),0] = 1\n\n Y[8*int(N/12):9*int(N/12),2] = seg\n Y[8*int(N/12):9*int(N/12),0] = 1\n\n Y[9*int(N/12):10*int(N/12),0] = seg\n Y[9*int(N/12):10*int(N/12),1] = 1\n Y[9*int(N/12):10*int(N/12),2] = 1\n\n Y[10*int(N/12):11*int(N/12),1] = seg\n Y[10*int(N/12):11*int(N/12),0] = 1\n Y[10*int(N/12):11*int(N/12),2] = 1\n\n Y[11*int(N/12):12*int(N/12),2] = seg\n Y[11*int(N/12):12*int(N/12),0] = 1\n Y[11*int(N/12):12*int(N/12),1] = 1\n\n if add_noise:\n noise = np.random.randn(N, 3) / 100\n Y += noise\n\n return Y\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ros_node/src/icp_node/nodes/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"192840573","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nFile initial creation on Sun Nov 18 2018\n\n@author: Kenneth E. Carlton\n\nThis program compares two BOMs: one originating from SolidWorks (SW) and the\nother from SyteLine (SL). The structure of the BOMs (headings, structure,\netc.) are very unique to my company. Therefore this program, unaltered, will\nfail to function at another company.\n\nRun this program from the command line like this: python bomcheck.py '*'\n\nWithout any arguments help info is shown: python bomcheck.py\n\nRun from a python console terminal like this: bomcheck('*')\n\nTo see how to create an EXE file from this program, see the file named\nhowtocompile.md.\n\"\"\"\n\n__version__ = '1.8.1'\n__author__ = 'Kenneth E. Carlton'\n\nimport glob, argparse, sys, warnings\nimport pandas as pd\nimport os.path\nimport os\nimport tempfile\nimport re\nfrom datetime import datetime\nimport fnmatch\nimport ast\nwarnings.filterwarnings('ignore') # the program has its own error checking.\npd.set_option('display.max_rows', 150)\npd.set_option('display.max_columns', 10)\npd.set_option('display.max_colwidth', 100)\npd.set_option('display.width', 200)\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"\"))\n\n\ndef get_version():\n return __version__\n\n\ndef getcfg():\n ''' Return the value of \"cfg\". cfg shows configuration\n variables and values thereof that are applied to\n bomcheck when it is run. For example, the variable \n \"accuracy\" is the no. of decimal places that length\n values are rounded to. (See the function \"setcfg\")\n \n Returns\n =======\n \n out: dictionary\n \n Examples\n ========\n \n getcfg()\n '''\n return cfg\n\n\ndef setcfg(**kwargs):\n ''' Set configuration variables that effect how bomcheck\n operates. For example, set the unit of measure that\n length values are calculated to. Run the function \n getcfg() to see the names of variables that can be set. \n Open the file bc_config.py to see an explanation of the\n variables. \n \n The object type that a variable holds (list, string, \n etc.) should be like that seen via the getcfg()\n function, else bomcheck could crash (correcting is just\n a matter rerunning setcfg with the correct values). \n \n Values can be set to something more permanent by \n altering the file bc_config.py.\n \n Examples\n ========\n \n setcfg(drop=[\"3*-025\", \"3*-008\"], accuracy=4) \n '''\n global cfg\n if not kwargs:\n print(\"You did not set any configuration values. Do so like this:\")\n print(\"setcfg(drop=['3886-*'], from_um='IN', to_um='FT')\")\n print(\"Do help(setcfg) for more info\")\n else:\n cfg.update(kwargs)\n\n \ndef set_globals():\n ''' Create a global variables including the primary one named cfg.\n cfg is a dictionary containing settings used by this program.\n\n set_globals() is ran when bomcheck first starts up.\n\n set_globals() tries to derive settings from the file named bc_bomcheck.py\n if it can be located and if values have been established there.\n Otherwise set_globals() creates its on settings for cfg.\n\n (see the function named create_bc_config to find where the file bc_check.py\n is located on you disk drive.)\n '''\n global cfg, printStrs, excelTitle\n\n cfg = {}\n printStrs = []\n excelTitle = []\n\n try:\n import bc_config\n except ModuleNotFoundError:\n def bc_config(): # do this so that doing \"dir(bc_config)\" just below doesn't fail\n pass\n\n cfg = {}\n def insert_into_cfg(var, default):\n ''' Function to insert key/value pairs into the dictionary named cfg.\n Use values set in the file named bc_config.py when available.'''\n global cfg\n cfg[var] = bc_config.__dict__[var] if (var in dir(bc_config)) else default\n\n # default settings for bomcheck. See bc_config.py are explanations about variables.\n list1 = [('accuracy', 2), ('ignore', ['3086-*']),\n ('drop', ['3*-025']), ('exceptions', []),\n ('from_um', 'IN'), ('to_um', 'FT'),\n ('toL_um', 'GAL'), ('toA_um', 'SQF')]\n # Give to bomcheck names of columns that it can expect to see in BOMs. If\n # one of the names, except length names, in each group shown in brackets\n # below is not found, then bomcheck will fail.\n list2 = [('part_num', [\"PARTNUMBER\", \"PART NUMBER\", \"Part Number\", \"Item\", \"Material\"]),\n ('qty', [\"QTY\", \"QTY.\", \"Qty\", \"Quantity\", \"Qty Per\"]),\n ('descrip', [\"DESCRIPTION\", \"Material Description\", \"Description\"]),\n ('um_sl', [\"UM\", \"U/M\"]), # not required in a SW BOM\n ('level_sl', [\"Level\"]), # not required in a SW BOM\n ('itm_sw', [\"ITEM NO.\"]), # not required in a SL BOM\n ('length_sw', [\"LENGTH\", \"Length\", \"L\", \"SIZE\", \"AMT\", \"AMOUNT\", \"MEAS\"])] # not required in a SL or SW BOM\n\n # The function \"insert_into_cfg\" is called upon below. It will fill the\n # dictionary named cfg with values from the bc_config.py file, that is if\n # the values can be found there, otherwise the \"default\" values shown in\n # the two lists above will be used.\n for k, v in list1:\n insert_into_cfg(k, v)\n cfg['accuracy'] = int(cfg['accuracy']) # make sure is an int and not a float\n for k, v in list2:\n insert_into_cfg(k, v)\n\n\ndef getresults(i=1):\n ''' If i = 0, return a dataframe containing SW's BOMs for which no matching\n SL BOMs were found. If i = 1, return a dataframe containing compared\n SW/SL BOMs. If i = 2, return a tuple of two items:\n (getresults(0), getresults(1))'''\n r = []\n r.append(None) if not results[0] else r.append(results[0][0][1])\n r.append(None) if not results[1] else r.append(results[1][0][1])\n if i == 0 or i == 1:\n return r[i]\n elif i == 2:\n return getresults(0), getresults(1)\n else:\n print('i = 0, 1, or 2 only')\n return None\n\n\ndef main():\n '''This fuction allows this bomcheck.py program to be run from the command\n line. It is started automatically (via the \"if __name__=='__main__'\"\n command at the bottom of this file) when bomecheck.py is run.\n\n calls: bomcheck\n\n Examples\n ========\n\n $ python bomcheck.py \"078551*\"\n\n $ python bomcheck.py \"C:/pathtomyfile/6890-*\"\n\n $ python bomcheck.py \"*\"\n\n $ python bomcheck.py --help\n\n '''\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n description='Program compares SolidWorks BOMs to SyteLine BOMs. ' +\n 'Output is sent to a Microsoft Excel spreadsheet.')\n parser.add_argument('filename', help='Name of file containing a BOM. Name ' +\n 'must end with _sw.xlsx, _sl.xlsx. _sw.csv, or ' +\n '_sl.csv. Enclose filename in quotes! An asterisk, *, ' +\n 'caputures multiple files. Examples: \"6890-*\", \"*\". ' +\n 'Or if filename is instead a directory, all _sw and _sl files ' +\n 'in that directory and subdirectories thereof will be ' +\n 'gathered. BOMs gathered from _sl files without ' +\n 'corresponding SolidWorks BOMs found are ignored.')\n parser.add_argument('-a', '--accuracy', help='Decimal place accuracy applied ' +\n 'to lengths in a SolidWorks BOM', default=cfg['accuracy'],\n metavar='value')\n parser.add_argument('-c', '--sheets', action='store_true', default=False,\n help='Break up results across multiple sheets in the ' +\n 'Excel file that is output.') \n parser.add_argument('-d', '--drop_bool', action='store_true', default=False,\n help='Ignore 3*-025 pns, i.e. do not use in the bom check')\n parser.add_argument('-f', '--followlinks', action='store_false', default=False,\n help='Follow symbolic links when searching for files to process. ' +\n \" (MS Windows doesn't honor this option.)\")\n parser.add_argument('--from_um', default=cfg['from_um'], help='The unit of measure ' +\n 'to apply to lengths in a SolidWorks BOM unless otherwise ' +\n 'specified', metavar='value')\n parser.add_argument('--to_um', default=cfg['to_um'], help='The unit of measure ' +\n 'to convert SolidWorks lengths to', metavar='value')\n parser.add_argument('-p', '--pause', help='Pause the program just before the program ' +\n 'the program would normally close after completing its work.',\n default=False, action='store_true')\n parser.add_argument('-v', '--version', action='version', version=__version__,\n help=\"Show program's version number and exit\")\n parser.add_argument('-x', '--excel', help='Create Excel file showing check results.',\n default=False, action='store_true')\n\n if len(sys.argv)==1:\n parser.print_help(sys.stderr)\n sys.exit(1)\n args = parser.parse_args()\n\n bomcheck(args.filename, vars(args))\n\n\ndef bomcheck(fn, dic={}, **kwargs):\n '''\n This is the primary function of the bomcheck program\n and acts as a hub for other functions within the \n bomcheck module.\n\n This function will handle single and multilevel BOMs \n that are derived from SW and/or SL. For multilevel \n BOMs, subassemblies will automatically be extracted \n from the top level BOM.\n\n Any BOMs from SW files found for which no matching SL \n file is found will be converted into a SyteLine like\n BOM format. If a SL BOM is present for which no \n corresponding SW BOM is found, the SW file is ignored;\n that is, no output is shown for this SW file.\n \n See the function setcfg for controlling other\n variables in bomcheck. Do: help(setcfg)\n\n This fuction calls these functions: \n gatherBOMs_from_fnames, collect_checked_boms, \n concat_boms, export2excel, get_fnames\n\n Parmeters\n =========\n\n fn: string or list\n * Files constaining BOMs from SolidWorks and/or \n SyteLine. Files from Solidworks must end with \n _sw.xlsx or _sw.csv. Files from SyteLine must\n end with _sl.xlsx or _sl.csv.\n * An asterisk, *, matches any characters. E.g. \n 6890-083544-* will match 6890-083544-1_sw.xlsx, \n 6890-083544-2_sw.xlsx, etc. \n * fn can be a directory name, in which case\n files in that directory, and subdirectories\n thereof, will be analized.\n * If a list is given, then it is a list of \n filenames and/or directories.\n * PNs shown in filenames must correspond, e.g. \n 099238_sw.xlsx and 099238_sl.xlsx. Exception: \n BOM from SyteLine is a multilevel BOM.\n\n dic: dictionary\n default: {} (i.e. an empty dictionary). This \n variable is only used if the function \"main\" is\n used to run the bomcheck program... that is, the\n bomcheck program was inititiated from the command\n line. If so, keys named \"drop\", \"sheets\", \n \"from_um\", and \"to_um\" and corresponding values \n thereof will have been put into dic.\n\n kwargs: dictionary\n Unlike dic, no values in kwargs are derived from the \n \"main\" function; i.e. bomcheck was not run from the\n command line. I.e., was from from Jupyter Notebook. \n The dictionary key/value items that this function\n looks for are:\n\n c: bool\n Break up results across multiple sheets within\n the Excel bomcheck.xlsx file. Default: False\n\n d: bool\n If True, employ the list named drop which will\n have been created by the function named \n \"set_globals\". (E.g. ignore pt. nos. from a \n SW BOM like 3*-025) Default: False\n \n f: bool\n If True, follow symbolic links when searching \n for files to process. Default: False\n \n l: bool\n Export a list of errors, if any, that occured \n during the bomcheck. Default: False\n \n m: int\n Max no. of rows to display when results are \n output. (This does not effect results that are\n exported an Excel file.) Default: None (That \n is, all rows are output. Nothing is truncated.)\n\n u: str\n Username. This will be fed to the export2exel \n function so that a username will be placed\n into the footer of the bomcheck.xlsx file. \n Default: 'unknown'\n\n x: bool\n Export results to an Excel file named \n bomcheck.xlsx. (If bomcheckgui is used, name \n can be changed.) Default: False\n\n Returns\n =======\n\n out: list|tuple\n\n If argument l is set to True:\n return a list of strings. Each string describes \n an error that occurred during the bomcheck. If\n no errors occurred, return [], i.e. an empty \n string. (bomcheckgui automatically sets \n l = True).\n Else:\n Return a tuple of two items that contains \n bomcheck results. Each of the two items of the \n tuple is a Pandas dataframe object.\n * The first dataframe shows SolidWorks BOMs for\n which no SyteLine BOMs were found to compare\n them to. \n * The second dataframe is SW to SL BOM \n comparisons.\n\n Examples\n ========\n\n >>> # files names starting with 6890\n >>> bomcheck(\"folder1/6890*\", d=True, u=\"John Doe\") \n\n >>> # all files in 'folder1' and in subfolders thereof\n >>> bomcheck(\"folder1\")\n\n >>> # all files, one level deep\n >>> bomcheck(\"folder1/*\") \n\n >>> bomcheck([\"folder1/*\", \"folder2/*\"], d=True)\n\n '''\n global printStrs, cfg, results\n printStrs = []\n results = [None, None]\n # Set settings depending on 1. if input was derived from running this\n # program from the command line (i.e. values from dic), 2. if from\n # excecuting the bomcheck() function within a python console or called by\n # some other python function (i.e. from kwargs), or 3. if the settings were\n # imported from bc_config.py. Many default values (e.g. cfg['from_um'])\n # were initially establisd by the set_globals() function.\n cfg['from_um'] = (dic.get('from_um') if dic.get('from_um')\n else kwargs.get('from_um', cfg['from_um']))\n cfg['to_um'] = (dic.get('to_um') if dic.get('to_um')\n else kwargs.get('to_um', cfg['to_um']))\n cfg['accuracy'] = (dic.get('accuracy') if dic.get('accuracy')\n else kwargs.get('a', cfg['accuracy']))\n cfg['drop_bool'] = (dic.get('drop_bool') if dic.get('drop_bool')\n else kwargs.get('d', False))\n c = (dic.get('sheets') if dic.get('sheets') else kwargs.get('c', False))\n u = kwargs.get('u', 'unknown')\n x = kwargs.get('x', False)\n f = kwargs.get('f', False)\n l = kwargs.get('l', False)\n m = kwargs.get('m', None)\n p = dic.get('pause', False)\n x = dic.get('excel', x)\n\n # If dbdic is in kwargs, it comes from bomcheckgui.\n # Variables thereof take precedence.\n if 'dbdic' in kwargs:\n dbdic = kwargs['dbdic']\n udrop = dbdic.get('udrop', '')\n uexceptions = dbdic.get('uexceptions', '')\n udrop = udrop.replace(',', ' ')\n uexceptions = uexceptions.replace(',', ' ')\n if udrop:\n cfg['drop'] = udrop.split()\n if uexceptions:\n cfg['exceptions'] = uexceptions.split()\n cfg['file2save2'] = dbdic.get('file2save2', 'bomcheck')\n cfg['overwrite'] = dbdic.get('overwrite', False)\n cfg['accuracy'] = dbdic.get('accuracy', 2)\n cfg['from_um'] = dbdic.get('from_um', 'in')\n cfg['to_um'] = dbdic.get('to_um', 'FT')\n u = dbdic.get('author', 'unknown')\n else:\n cfg['file2save2'] = 'bomcheck'\n cfg['overwrite'] = False\n\n if isinstance(fn, str) and fn.startswith('[') and fn.endswith(']'):\n # fn = eval(fn) # change a string to a list\n fn = ast.literal_eval(fn) # change a string to a list\n elif isinstance(fn, str):\n fn = [fn]\n \n pd.set_option('display.max_rows', m)\n\n fn = get_fnames(fn, followlinks=f) # get filenames with any extension.\n\n dirname, swfiles, slfiles = gatherBOMs_from_fnames(fn)\n\n # lone_sw is a dic; Keys are assy nos; Values are DataFrame objects (SW\n # BOMs only). merged_sw2sl is a dic; Keys are assys nos; Values are\n # Dataframe objects (merged SW and SL BOMs).\n lone_sw, merged_sw2sl = collect_checked_boms(swfiles, slfiles)\n\n title_dfsw = [] # Create a list of tuples: [(title, swbom)... ]\n for k, v in lone_sw.items(): # where \"title\" is is the title of the BOM,\n title_dfsw.append((k, v)) # usually the part no. of the BOM.\n\n title_dfmerged = [] # Create a list of tuples: [(title, mergedbom)... ]\n for k, v in merged_sw2sl.items():\n title_dfmerged.append((k, v))\n\n if title_dfsw:\n printStr = '\\nNo matching SyteLine BOMs found for these SolidWorks files:\\n'\n printStr += '\\n'.join(list(map(lambda x: ' ' + x[0], title_dfsw))) + '\\n'\n printStrs.append(printStr)\n print(printStr)\n\n if c == False: # concat_boms is a bomcheck function\n title_dfsw, title_dfmerged = concat_boms(title_dfsw, title_dfmerged)\n results = title_dfsw, title_dfmerged\n\n if x:\n try:\n if title_dfsw or title_dfmerged:\n export2excel(dirname, cfg['file2save2'], title_dfsw + title_dfmerged, u)\n else:\n printStr = ('\\nNotice 203\\n\\n' +\n 'No SolidWorks files found to process. (Lone SyteLine\\n' +\n 'BOMs will be ignored.) Make sure file names end with\\n' +\n '_sw.xlsx, _sw.csv, _sl.xlsx, or _sl.csv.\\n')\n printStrs.append(printStr)\n print(printStr)\n except PermissionError:\n printStr = ('\\nError 202:\\n\\nFailed to write to bomcheck.xlsx\\n'\n 'Cause unknown')\n printStrs.append(printStr)\n print(printStr)\n\n if p == True:\n input(\"Press enter to exit\")\n\n if title_dfsw or title_dfmerged:\n print('calculation done')\n else:\n print('program produced no results')\n\n if l:\n return printStrs\n else:\n return getresults(2)\n\n\ndef get_fnames(fn, followlinks=False):\n ''' Interpret fn to get a list of filenames based on fn's value.\n\n Parameters\n ----------\n fn: str or list\n fn is a filename or a list of filenames. A filename can also be a\n directory name. Example 1, strings: \"C:/myfile_.xlsx\", \"C:/dirname\",\n or \"['filename1', 'filename2', 'dirname1' ...]\". Example 2, list:\n [\"filename1\", \"filename2\", \"dirname1\", \"dirname2\"]. When a a directory\n name is given, filenames are gathered from that directory and from\n subdirectories thereof.\n followlinks: Boolean, optional\n If True, follow symbolic links. If a link is to a direcory, then\n filenames are gathered from that directory and from subdirectories\n thereof. The default is False.\n\n Returns\n -------\n _fn: list\n A list of filenames, e.g. [\"filename1\", \"filename2\", ...]. Each value\n in the list is a string. Each string is the name of a file. The\n filename can be a pathname, e.g. \"C:/dir1/dir2/filename\". The\n filenames can have any type of extension.\n '''\n if isinstance(fn, str) and fn.startswith('[') and fn.endswith(']'):\n #fn = eval(fn) # if fn a string like \"['fname1', 'fname2', ...]\", convert to a list\n fn = ast.literal_eval(fn) # if fn a string like \"['fname1', 'fname2', ...]\", convert to a list\n elif isinstance(fn, str):\n fn = [fn] # fn a string like \"fname1\", convert to a list like [fname1]\n\n _fn1 = []\n for f in fn:\n _fn1 += glob.glob(f)\n\n _fn2 = [] # temporary holder\n for f in _fn1:\n if followlinks==True and os.path.islink(f) and os.path.exists(f):\n _fn2 += get_fnames(os.readlink(f))\n elif os.path.isdir(f): # if a dir, gather all filenames in dirs and subdirs thereof\n for root, dirs, files in os.walk(f, followlinks=followlinks):\n for filename in files:\n _fn2.append(os.path.join(root, filename))\n else:\n _fn2.append(f)\n\n return _fn2\n\n\ndef make_csv_file_stable(filename):\n ''' Except for any commas in a parts DESCRIPTION, replace all commas\n in a csv file with a $ character. Commas will sometimes exist in a\n DESCRIPTION field, e.g, \"TANK, 60GAL\". But commas are intended to be field\n delimeters; commas in a DESCRIPTION field are not. Excess commas in\n a line from a csv file will cause a program crash. Remedy: change those\n commas meant to be delimiters to a dollor sign character, $.\n\n Parmeters\n =========\n\n filename: string\n Name of SolidWorks csv file to process.\n\n Returns\n =======\n\n out: list\n A list of all the lines (rows) in filename is returned. Commas in each\n line are changed to dollar signs except for any commas in the\n DESCRIPTION field.\n '''\n with open(filename, encoding=\"ISO-8859-1\") as f:\n data1 = f.readlines()\n # n1 = number of commas in 2nd line of filename (i.e. where column header\n # names located). This is the no. of commas that should be in each row.\n n1 = data1[1].count(',')\n n2 = data1[1].upper().find('DESCRIPTION') # locaton of the word DESCRIPTION within the row.\n n3 = data1[1][:n2].count(',') # number of commas before the word DESCRIPTION\n data2 = list(map(lambda x: x.replace(',', '$') , data1)) # replace ALL commas with $\n data = []\n for row in data2:\n n4 = row.count('$')\n if n4 != n1:\n # n5 = location of 1st ; character within the DESCRIPTION field\n # that should be a , character\n n5 = row.replace('$', '?', n3).find('$')\n # replace those ; chars that should be , chars in the DESCRIPTION field:\n data.append(row[:n5] + row[n5:].replace('$', ',', (n4-n1))) # n4-n1: no. commas needed\n else:\n data.append(row)\n return data\n\n\ndef common_data(list1, list2):\n ''' function to determine if two lists have at least one common element'''\n result = False\n for x in list1:\n for y in list2:\n if x == y:\n result = True\n return result\n\n\ndef gatherBOMs_from_fnames(filename):\n ''' Gather all SolidWorks and SyteLine BOMs derived from \"filename\".\n \"filename\" can be a string containing wildcards, e.g. 6890-085555-*, which\n allows the capture of multiple files; or \"filename\" can be a list of such\n strings. These files (BOMs) will be converted to Pandas DataFrame objects.\n\n Only files prefixed with _sw.xlsx, _sw.csv, _sl.xlsx, or _sl.csv will be\n chosen; others are discarded. These files will then be converted into two\n python dictionaries. One dictionary will contain SolidWorks BOMs only, and\n the other will contain only SyteLine BOMs.\n\n If a filename has a BOM containing a multiple level BOM, then the\n subassembly BOMs will be extracted from that BOM and be added to the\n dictionaries.\n\n calls: make_csv_file_stable, deconstructMultilevelBOM, test_for_missing_columns\n\n Parmeters\n =========\n\n filename: list\n List of filenames to be analyzed.\n\n Returns\n =======\n\n out: tuple\n The output tuple contains three items. The first is the directory\n corresponding to the first file in the filename list. If this\n directory is an empty string, then it refers to the current working\n directory. The remainder of the tuple items are two python\n dictionaries. The first dictionary contains SolidWorks BOMs, and the\n second contains SyteLine BOMs. The keys for these two dictionaries\n are part nos. of assemblies derived from the filenames (e.g. 085952\n from 085953_sw.xlsx), or derived from subassembly part numbers of a\n file containing multilevel BOM.\n '''\n dirname = '.' # to this will assign the name of 1st directory a _sw is found in\n global printStrs\n def fixcolnames(df):\n '''rid any column names of '\\n' char if exists'''\n colnames = []\n for colname in df.columns:\n colnames.append(str(colname).replace('\\n', ''))\n return colnames\n swfilesdic = {}\n slfilesdic = {}\n for f in filename: # from filename extract all _sw & _sl files and put into swfilesdic & slfilesdic\n i = f.rfind('_')\n if f[i:i+4].lower() == '_sw.' or f[i:i+4].lower() == '_sl.':\n dname, fname = os.path.split(f)\n k = fname.rfind('_')\n fntrunc = fname[:k] # Name of the sw file, excluding path, and excluding _sw.xlsx\n if f[i:i+4].lower() == '_sw.' and '~' not in fname: # Ignore names like ~$085637_sw.xlsx\n swfilesdic.update({fntrunc: f})\n if dirname == '.':\n dirname = os.path.dirname(os.path.abspath(f)) # use 1st dir where a _sw file is found to put bomcheck.xlsx\n elif f[i:i+4].lower() == '_sl.' and '~' not in fname:\n slfilesdic.update({fntrunc: f})\n swdfsdic = {} # for collecting SW BOMs to a dic\n for k, v in swfilesdic.items():\n try:\n _, file_extension = os.path.splitext(v)\n if file_extension.lower() == '.csv' or file_extension.lower() == '.txt':\n data = make_csv_file_stable(v)\n temp = tempfile.TemporaryFile(mode='w+t')\n for d in data:\n temp.write(d)\n temp.seek(0)\n df = pd.read_csv(temp, na_values=[' '], skiprows=1, sep='$',\n encoding='iso8859_1', engine='python',\n dtype = dict.fromkeys(cfg['itm_sw'], 'str'))\n df.columns = fixcolnames(df)\n if test_for_missing_columns('sw', df, '', printerror=False):\n df = pd.read_csv(temp, na_values=[' '], sep='$',\n encoding='iso8859_1', engine='python',\n dtype = dict.fromkeys(cfg['itm_sw'], 'str'))\n df.columns = fixcolnames(df)\n temp.close()\n elif file_extension.lower() == '.xlsx' or file_extension.lower() == '.xls':\n df = pd.read_excel(v, na_values=[' '], skiprows=1)\n df.columns = fixcolnames(df)\n if test_for_missing_columns('sw', df, '', printerror=False):\n df = pd.read_excel(v, na_values=[' '])\n df.columns = fixcolnames(df)\n\n if not test_for_missing_columns('sw', df, k):\n swdfsdic.update(deconstructMultilevelBOM(df, 'sw', k))\n except:\n printStr = '\\nError processing file: ' + v + '\\nIt has been excluded from the BOM check.\\n'\n printStrs.append(printStr)\n print(printStr)\n sldfsdic = {} # for collecting SL BOMs to a dic\n for k, v in slfilesdic.items():\n try:\n _, file_extension = os.path.splitext(v)\n if file_extension.lower() == '.csv' or file_extension.lower() == '.txt':\n try:\n df = pd.read_csv(v, na_values=[' '], engine='python',\n #skiprows=cfg['skiprows_sl'],\n encoding='utf-16', sep='\\t')\n except UnicodeError:\n printStr = (\"\\nError 204.\\n\\n.\"\n \"Probable cause: This program expects Unicode text encoding from\\n\"\n \"a csv file. The file \" + v + \" does not have this. The\\n\"\n \"correct way to achieve a functional csv file is:\\n\\n\"\n ' From Excel, save the file as type “Unicode Text (*.txt)”, and then\\n'\n ' change the file extension from txt to csv.\\n\\n'\n \"On the other hand, easiest solution: use an Excel file instead.\\n\")\n printStrs.append(printStr)\n print(printStr)\n sys.exit(1)\n elif file_extension.lower() == '.xlsx' or file_extension.lower == '.xls':\n df = pd.read_excel(v, na_values=[' ']) #, skiprows=cfg['skiprows_sl'])\n\n if (not (test_for_missing_columns('sl', df, k)) and\n common_data(cfg['level_sl'], df.columns)):\n sldfsdic.update(deconstructMultilevelBOM(df, 'sl', 'TOPLEVEL'))\n elif not test_for_missing_columns('sl', df, k):\n sldfsdic.update(deconstructMultilevelBOM(df, 'sl', k))\n\n except:\n printStr = ('\\nError 201.\\n\\n' + ' processing file: ' + v +\n '\\nIt has been excluded from the BOM check.\\n')\n printStrs.append(printStr)\n print(printStr)\n try:\n df = pd.read_clipboard(engine='python', na_values=[' '])\n if not test_for_missing_columns('sl', df, 'BOMfromClipboard', printerror=False):\n sldfsdic.update(deconstructMultilevelBOM(df, 'sl', 'TOPLEVEL'))\n except:\n pass\n if os.path.islink(dirname):\n dirname = os.readlink(dirname)\n return dirname, swdfsdic, sldfsdic\n\n\ndef test_for_missing_columns(bomtype, df, pn, printerror=True):\n ''' SolidWorks and SyteLine BOMs require certain essential columns to be\n present. This function looks at those BOMs that are within df to see if\n any required columns are missing. If found, print to screen.\n\n calls: test_alternative_column_names\n\n Parameters\n ==========\n\n bomtype: string\n \"sw\" or \"sl\"\n\n df: Pandas DataFRame\n A SW or SL BOM\n\n pn: string\n Part number of the BOM\n\n Returns\n =======\n\n out: bool\n True if BOM afoul. Otherwise False.\n '''\n global printStrs\n if bomtype == 'sw':\n required_columns = [cfg['qty'], cfg['descrip'],\n cfg['part_num'], cfg['itm_sw']]\n else: # 'for sl bom'\n required_columns = [cfg['qty'], cfg['descrip'],\n cfg['part_num'], cfg['um_sl']]\n\n missing = []\n for r in required_columns:\n if isinstance(r, str) and r not in df.columns:\n missing.append(r)\n elif isinstance(r, list) and test_alternative_column_names(r, df.columns):\n missing.append(' or '.join(test_alternative_column_names(r, df.columns)))\n if missing and bomtype=='sw' and printerror:\n printStr = ('\\nEssential BOM columns missing. SolidWorks requires a BOM header\\n' +\n 'to be in place. This BOM will not be processed:\\n\\n' +\n ' missing: ' + ' ,'.join(missing) + '\\n' +\n ' missing in: ' + pn + '\\n')\n printStrs.append(printStr)\n print(printStr)\n return True\n elif missing and printerror:\n printStr = ('\\nEssential BOM columns missing. This BOM will not be processed:\\n' +\n ' missing: ' + ' ,'.join(missing) + '\\n\\n' +\n ' missing in: ' + pn + '\\n')\n printStrs.append(printStr)\n print(printStr)\n return True\n elif missing:\n return True\n else:\n return False\n\n\ndef test_alternative_column_names(tpl, lst):\n ''' tpl contains alternative names for a required column in a bom. If\n none of the names in tpl match a name in lst, return tpl so that the\n user can be notified that one of those alternative names should have been\n present. On the other hand, if a match was found, return None.\n\n Parameters\n ==========\n tpl: tuple or list\n Each item of tpl is a string. Each item is an alternative column name,\n e.g. (\"Qty\", \"Quantity\")\n\n lst: list\n A list of the required columns that a bom must have in order for a bom\n check to be correctly completed.\n\n Returns\n =======\n out: tpl|None\n If no match found, return the same tuple, tpl, that was an input\n parameter. Else return None\n '''\n flag = True\n for t in tpl:\n if t in lst:\n flag = False # A required column name was found in the tuple, so good to proceed with bom check\n if flag:\n return tpl # one of the tuple items is a required column. Report that one or the other is missing\n\n\ndef col_name(df, col):\n '''\n Parameters\n ----------\n df: Pandas DataFrame\n\n col: list\n List of column names that will be compared to the list of column\n names from df (i.e. from df.columns)\n\n Returns\n -------\n out: string\n Name of column that is common to both df.columns and col\n '''\n try:\n df_cols_as_set = set(list(df.columns))\n intersect = df_cols_as_set.intersection(col)\n return list(intersect)[0]\n except IndexError:\n return \"\"\n\n\ndef deconstructMultilevelBOM(df, source, top='TOPLEVEL'):\n ''' If the BOM is a multilevel BOM, pull out the BOMs thereof; that is,\n pull out the main assembly and the subassemblies thereof. These\n assys/subassys are placed in a python dictionary and returned. If df is\n a single level BOM, a dictionary with one item is returned.\n\n For this function to pull out subassembly BOMs from a SyteLine BOM, the\n column named Level must exist in the SyteLine BOM. It contains integers\n indicating the level of a subassemby within the BOM; e.g. 1, 2, 3, 2, 3,\n 3, 3, 4, 4, 2. Only multilevel SyteLine BOMs contain this column.\n On the other hand for this function to pull out subassemblies from a\n SolidWorks BOM, the column ITEM NO. (see set_globals() for other optional\n names) must exist and contain values that indicate which values are\n subassemblies; e.g, with item numbers like \"1, 2, 2.1, 2.2, 3, 4, etc.,\n items 2.1 and 2.2 are members of the item number 2 subassembly.\n\n Parmeters\n =========\n\n df: Pandas DataFrame\n The DataFrame is that of a SolidWorks or SyteLine BOM.\n\n source: string\n Choices for source are \"sw\" or \"sl\". That is, is the BOM being\n deconstructed from SolidWorks or SyteLine.\n\n top: string\n Top level part number. This number is automatically generated by the\n bomcheck program in two ways: 1. If df originated from a SolidWorks\n BOM or from a single level SyteLine BOM, then “top” is derived from\n the filename; e.g. 091828 from the filename 091828_sw.xlsx. 2. If df\n originated from a multilevel BOM, then it has a column named “Level”\n (i.e. the level of subassemblies and parts within subassemblies\n relative to the main, top, assembly part number). In this case the\n part number associated with level \"0\" is assigned to \"top\".\n\n Returns\n =======\n\n out: python dictionary\n The dictionary has the form {assypn1: BOM1, assypn2: BOM2, ...},\n where assypn1, assypn2, etc. are string objects and are the part\n numbers for BOMs; and BOM1, BOM2, etc. are pandas DataFrame objects\n that pertain to those part numbers.\n '''\n __lvl = col_name(df, cfg['level_sl'])\n __itm = col_name(df, cfg['itm_sw'])\n __pn = col_name(df, cfg['part_num']) # get the column name for pns\n\n p = None\n df[__pn] = df[__pn].astype('str').str.strip() # make sure pt nos. are \"clean\"\n df[__pn].replace('', 'no pn from BOM!', inplace=True)\n\n # https://stackoverflow.com/questions/2974022/is-it-possible-to-assign-the-same-value-to-multiple-keys-in-a-dict-object-at-onc\n values = dict.fromkeys((cfg['qty'] + cfg['length_sw']), 0)\n values.update(dict.fromkeys(cfg['descrip'], 'no descrip from BOM!'))\n values.update(dict.fromkeys(cfg['part_num'], 'no pn from BOM!'))\n df.fillna(value=values, inplace=True)\n\n # Generate a column named __Level which contains integers based based upon\n # the level of a part within within an assembly or within subassembly of\n # an assembly. 0 is the top level assembly, 1 is a part or subassembly one\n # level deep, and 2, 3, etc. are levels within subassemblies.\n if source=='sw' and __itm and __itm in df.columns:\n __itm = df[__itm].astype('str')\n __itm = __itm.str.replace('.0', '') # stop something like 5.0 from slipping through\n df['__Level'] = __itm.str.count('\\.') # level is the number of periods (.) in the string\n elif source=='sl' and __lvl and __lvl in df.columns:\n df['__Level'] = df[__lvl]\n else:\n df['__Level'] = 0\n\n # Take the the column named \"__Level\" and create a new column: \"Level_pn\".\n # Instead of the level at which a part exists within an assembly, like\n # \"__Level\" which contains integers like [0, 1, 2, 2, 1], \"Level_pn\" contains\n # the parent part no. of the part at a particular level, e.g.\n # ['TOPLEVEL', '068278', '2648-0300-001', '2648-0300-001', '068278']\n lvl = 0\n level_pn = [] # storage of pns of parent assy/subassy of the part at rows 0, 1, 2, 3, ...\n assys = [] # storage of all assys/subassys found (stand alone parts ignored)\n for item, row in df.iterrows():\n if row['__Level'] == 0:\n poplist = []\n level_pn.append(top)\n if top != \"TOPLEVEL\":\n assys.append(top)\n elif 'Description' in df.columns and lvl == 0:\n excelTitle.append((row[__pn], row['Description'])) # info for a global variable\n elif row['__Level'] > lvl:\n if p in assys:\n poplist.append('repeat')\n else:\n assys.append(p)\n poplist.append(p)\n level_pn.append(poplist[-1])\n elif row['__Level'] == lvl:\n level_pn.append(poplist[-1])\n elif row['__Level'] < lvl:\n i = row['__Level'] - lvl # how much to pop. i is a negative number.\n poplist = poplist[:i] # remove, i.e. pop, i items from end of list\n level_pn.append(poplist[-1])\n p = row[__pn]\n lvl = row['__Level']\n df['Level_pn'] = level_pn\n # collect all assys/subassys within df and return a dictionary. keys\n # of the dictionary are pt. numbers of assys/subassys.\n dic_assys = {}\n for k in assys:\n dic_assys[k.upper()] = df[df['Level_pn'] == k]\n return dic_assys\n\n\ndef is_in(find, series, xcept):\n '''Argument \"find\" is a list of strings that are glob expressions. The\n Pandas Series \"series\" will be evaluated to see if any members of find\n exists as substrings within each member of series. Glob expressions are\n strings like '3086-*-025' or *2020*. '3086-*-025' for example will match\n '3086-0050-025' and '3086-0215-025'.\n\n The output of the is_in function is a Pandas Series. Each member of the\n Series is True or False depending on whether a substring has been found\n or not.\n\n xcept is a list of exceptions to those in the find list. For example, if\n '3086-*-025' is in the find list and '3086-3*-025' is in the xcept list,\n then series members like '3086-0515-025' or '3086-0560-025' will return\n a True, and '3086-3050-025' or '3086-3060-025' will return a False.\n\n For reference, glob expressions are explained at:\n https://en.wikipedia.org/wiki/Glob_(programming)\n\n Parmeters\n =========\n\n find: string or list of strings\n Items to search for\n\n series: Pandas Series\n Series to search\n\n xcept: string or list of strings\n Exceptions to items to search for\n\n Returns\n =======\n\n out: Pandas Series, dtype: bool\n Each item is True or False depending on whether a match was found or not\n '''\n if not isinstance(find, list):\n find = [find]\n if not isinstance(xcept, list) and xcept:\n xcept = [xcept]\n elif isinstance(xcept, list):\n pass\n else:\n xcept = []\n series = series.astype(str).str.strip() # ensure that all elements are strings & strip whitespace from ends\n find2 = []\n for f in find:\n find2.append('^' + fnmatch.translate(str(f)) + '$') # reinterpret user input with a regex expression\n xcept2 = []\n for x in xcept: # exceptions is also a global variable\n xcept2.append('^' + fnmatch.translate(str(x)) + '$')\n if find2 and xcept2:\n filtr = (series.str.contains('|'.join(find2)) & ~series.str.contains('|'.join(xcept2)))\n elif find2:\n filtr = series.str.contains('|'.join(find2))\n else:\n filtr = pd.Series([False]*series.size)\n return filtr\n\n\ndef convert_sw_bom_to_sl_format(df):\n '''Take a SolidWorks BOM and restructure it to be like that of a SyteLine\n BOM. That is, the following is done:\n\n - For parts with a length provided, the length is converted from from_um to\n to_um (see the function main for a definition of these variables).\n Typically the unit of measure in a SolidWorks BOM is inches, and in\n SyteLine, feet.\n - If the part is a pipe or beam and it is listed multiple times in the BOM,\n the BOM is updated so that only one listing is shown and the lengths\n of the removed listings are added to the remaining listing.\n - Similar to above, parts such as pipe nipples will show up more that\n once on a BOM. Remove the excess listings and add the quantities of\n the removed listings to the remaining listing.\n - If global variable cfg['drop'] is set to True, off the shelf parts, which\n are usually pipe fittings, are removed from the SolidWorks BOM. (As a\n general rule, off-the-shelf parts are not shown on SyteLine BOMs.) The\n list that governs this rule is in a file named drop.py. Other part nos.\n may be added to this list as required. (see the function set_globals\n for more information)\n - Column titles are changed to match those of SyteLine and thus will allow\n merging to a SyteLine BOM.\n\n calls: create_um_factors\n\n Parmeters\n =========\n\n df: Pandas DataFrame\n SolidWorks DataFrame object to process.\n\n Returns\n =======\n\n out: pandas DataFrame\n A SolidWorks BOM with a structure like that of SyteLine.\n\n \\u2009\n '''\n\n values = dict.fromkeys(cfg['part_num'], 'Item')\n values.update(dict.fromkeys(cfg['length_sw'], 'LENGTH'))\n values.update(dict.fromkeys(cfg['descrip'], 'Description'))\n values.update(dict.fromkeys(cfg['qty'], 'Q'))\n df.rename(columns=values, inplace=True)\n\n if 'LENGTH' in df.columns: # convert lengths to other unit of measure, i.e. to_um\n ser = df['LENGTH']\n value = ser.replace('[^\\d.]', '', regex=True).apply(str).str.strip('.').astype(float) # \"3.5MM\" -> 3.5\n from_um = ser.apply(str).replace('[\\d.]', '', regex=True) # e.g. \"3.5MM\" -> \"mm\"\n from_um.replace('', cfg['from_um'].lower(), inplace=True) # e.g. \"\" -> \"ft\"\n from_um = from_um.str.strip().str.lower() # e.g. \"SQI\\n\" -> \"sqi\"\n to_um = from_um.apply(lambda x: cfg['toL_um'].lower() if x.lower() in liquidUMs else\n (cfg['toA_um'].lower() if x.lower() in areaUMs else cfg['to_um'].lower()))\n ignore_filter = ~is_in(cfg['ignore'], df['Item'], [])\n df['U'] = to_um.str.upper().mask(value <= 0.0001, 'EA').mask(~ignore_filter, 'EA')\n factors = (from_um.map(factorpool) * 1/to_um.map(factorpool)).fillna(-1)\n q = df['Q'].replace('[^\\d]', '', regex=True).apply(str).str.strip('.') # strip away any text\n q = q.replace('', '0').astype(float) # if any empty strings, set to '0'\n value2 = value * q * factors * ignore_filter\n df['Q'] = q*(value2<.0001) + value2 # move lengths to the Qty column\n else:\n df['U'] = 'EA' # if no length colunm exists then set all units of measure to EA\n\n df = df.reindex(['Op', 'WC','Item', 'Q', 'Description', 'U'], axis=1) # rename and/or remove columns\n dd = {'Q': 'sum', 'Description': 'first', 'U': 'first'} # funtions to apply to next line\n df = df.groupby('Item', as_index=False).aggregate(dd).reindex(columns=df.columns)\n\n if cfg['drop_bool']==True:\n filtr3 = is_in(cfg['drop'], df['Item'], cfg['exceptions'])\n df.drop(df[filtr3].index, inplace=True)\n\n df['WC'] = 'PICK' # WC is a standard column shown in a SL BOM.\n df['Op'] = 10 # Op is a standard column shown in a SL BOM, usually set to 10\n df.set_index('Op', inplace=True)\n\n return df\n\n\ndef compare_a_sw_bom_to_a_sl_bom(dfsw, dfsl):\n '''This function takes in one SW BOM and one SL BOM and then merges them.\n This merged BOM shows the BOM check allowing differences between the\n SW and SL BOMs to be easily seen.\n\n A set of columns in the output are labeled i, q, d, and u. Xs at a row in\n any of these columns indicate something didn't match up between the SW\n and SL BOMs. An X in the i column means the SW and SL Items (i.e. pns)\n don't match. q means quantity, d means description, u means unit of\n measure.\n\n Parmeters\n =========\n\n dfsw: Pandas DataFrame\n A DataFrame of a SolidWorks BOM\n\n dfsl: Pandas DataFrame\n A DataFrame of a SyteLine BOM\n\n Returns\n =======\n\n df_merged: Pandas DataFrame\n df_merged is a DataFrame that shows a side-by-side comparison of a\n SolidWorks BOM to a SyteLine BOM.\n\n \\u2009\n '''\n global printStrs\n if not str(type(dfsw))[-11:-2] == 'DataFrame':\n printStr = '\\nProgram halted. A fault with SolidWorks DataFrame occurred.\\n'\n printStrs.append(printStr)\n print(printStr)\n sys.exit()\n\n # A BOM can be derived from different locations within SL. From one location\n # the `Item` is the part number. From another `Material` is the part number.\n # When `Material` is the part number, a useless 'Item' column is also present.\n # It causes the bomcheck program confusion and the program crashes. Thus a fix:\n if 'Item' in dfsl.columns and 'Material' in dfsl.columns:\n dfsl.drop(['Item'], axis=1, inplace=True) # the \"drop\" here is not that in the cfg dictionary\n if 'Description' in dfsl.columns and 'Material Description' in dfsl.columns:\n dfsl.drop(['Description'], axis=1, inplace=True)\n\n values = dict.fromkeys(cfg['part_num'], 'Item')\n values.update(dict.fromkeys(cfg['um_sl'], 'U'))\n values.update(dict.fromkeys(cfg['descrip'], 'Description'))\n values.update(dict.fromkeys(cfg['qty'], 'Q'))\n values.update({'Obsolete Date': 'Obsolete'})\n dfsl.rename(columns=values, inplace=True)\n\n if 'Obsolete' in dfsl.columns: # Don't use any obsolete pns (even though shown in the SL BOM)\n filtr4 = dfsl['Obsolete'].notnull()\n dfsl.drop(dfsl[filtr4].index, inplace=True) # https://stackoverflow.com/questions/13851535/how-to-delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression\n\n # When pns are input into SyteLine, all the characters of pns should\n # be upper case. But on occasion people have mistakently used lower case.\n # Correct this and report what pns have been in error.\n x = dfsl['Item'].copy()\n dfsl['Item'] = dfsl['Item'].str.upper() # make characters upper case\n x_bool = x != dfsl['Item']\n x_lst = [i for i in list(x*x_bool) if i]\n if x_lst:\n printStr = (\"\\nLower case part nos. in SyteLine's BOM have been converted \" +\n \"to upper case for \\nthis BOM check:\\n\")\n printStrs.append(printStr)\n print(printStr)\n for y in x_lst:\n printStr = ' ' + y + ' changed to ' + y.upper() + '\\n'\n printStrs.append(printStr)\n print(printStr)\n\n dfmerged = pd.merge(dfsw, dfsl, on='Item', how='outer', suffixes=('_sw', '_sl') ,indicator=True)\n dfmerged.Q_sw.fillna(0, inplace=True)\n dfmerged.U_sl.fillna('', inplace=True)\n\n ###########################################################################\n # If U/M in SW isn't the same as that in SL, adjust SW's length values #\n # so that lengths are per SL's U/M. Then replace the U/M in the column #\n # named U_sw with the updated U/M that matches that in SL. #\n from_um = dfmerged.U_sw.str.lower().fillna('') #\n to_um = dfmerged.U_sl.str.lower().fillna('') #\n factors = (from_um.map(factorpool) * 1/to_um.map(factorpool)).fillna(1) #\n dfmerged.Q_sw = dfmerged.Q_sw * factors #\n dfmerged.Q_sw = round(dfmerged.Q_sw, cfg['accuracy']) #\n func = lambda x1, x2: x1 if (x1 and x2) else x2 #\n dfmerged.U_sw = to_um.combine(from_um, func, fill_value='').str.upper() #\n ###########################################################################\n\n dfmerged.sort_values(by=['Item'], inplace=True)\n filtrI = dfmerged['_merge'].str.contains('both') # this filter determines if pn in both SW and SL\n maxdiff = .51 / (10**cfg['accuracy'])\n filtrQ = abs(dfmerged['Q_sw'] - dfmerged['Q_sl']) < maxdiff # If diff in qty greater than this value, show X\n filtrM = dfmerged['Description_sw'].str.split() == dfmerged['Description_sl'].str.split()\n filtrU = dfmerged['U_sw'].astype('str').str.upper().str.strip() == dfmerged['U_sl'].astype('str').str.upper().str.strip()\n chkmark = '-'\n err = 'X'\n\n dfmerged['i'] = filtrI.apply(lambda x: chkmark if x else err) # X = Item not in SW or SL\n dfmerged['q'] = filtrQ.apply(lambda x: chkmark if x else err) # X = Qty differs btwn SW and SL\n dfmerged['d'] = filtrM.apply(lambda x: chkmark if x else err) # X = Mtl differs btwn SW & SL\n dfmerged['u'] = filtrU.apply(lambda x: chkmark if x else err) # X = U differs btwn SW & SL\n dfmerged['i'] = ~dfmerged['Item'].duplicated(keep=False) * dfmerged['i'] # duplicate in SL? i-> blank\n dfmerged['q'] = ~dfmerged['Item'].duplicated(keep=False) * dfmerged['q'] # duplicate in SL? q-> blank\n dfmerged['d'] = ~dfmerged['Item'].duplicated(keep=False) * dfmerged['d'] # duplicate in SL? d-> blank\n dfmerged['u'] = ~dfmerged['Item'].duplicated(keep=False) * dfmerged['u'] # duplicate in SL? u-> blank\n\n dfmerged = dfmerged[['Item', 'i', 'q', 'd', 'u', 'Q_sw', 'Q_sl',\n 'Description_sw', 'Description_sl', 'U_sw', 'U_sl']]\n dfmerged.fillna('', inplace=True)\n dfmerged.set_index('Item', inplace=True)\n dfmerged.Q_sw.replace(0, '', inplace=True)\n\n return dfmerged\n\n\ndef collect_checked_boms(swdic, sldic):\n ''' Match SolidWorks assembly nos. to those from SyteLine and then merge\n their BOMs to create a BOM check. For any SolidWorks BOMs for which no\n SyteLine BOM was found, put those in a separate dictionary for output.\n\n calls: convert_sw_bom_to_sl_format, compare_a_sw_bom_to_a_sl_bom\n\n Parameters\n ==========\n\n swdic: dictionary\n Dictinary of SolidWorks BOMs. Dictionary keys are strings and they\n are of assembly part numbers. Dictionary values are pandas DataFrame\n objects which are BOMs for those assembly pns.\n\n sldic: dictionary\n Dictinary of SyteLine BOMs. Dictionary keys are strings and they\n are of assembly part numbers. Dictionary values are pandas DataFrame\n objects which are BOMs for those assembly pns.\n\n Returns\n =======\n\n out: tuple\n The output tuple contains two values: 1. Dictionary containing\n SolidWorks BOMs for which no matching SyteLine BOM was found. The\n BOMs have been converted to a SyteLine like format. Keys of the\n dictionary are assembly part numbers. 2. Dictionary of merged\n SolidWorks and SyteLine BOMs, thus creating a BOM check. Keys for the\n dictionary are assembly part numbers.\n '''\n lone_sw_dic = {} # sw boms with no matching sl bom found\n combined_dic = {} # sl bom found for given sw bom. Then merged\n for key, dfsw in swdic.items():\n if key in sldic:\n combined_dic[key] = compare_a_sw_bom_to_a_sl_bom(\n convert_sw_bom_to_sl_format(dfsw), sldic[key])\n else:\n df = convert_sw_bom_to_sl_format(dfsw)\n df['Q'] = round(df['Q'], cfg['accuracy'])\n #lone_sw_dic[key + '_sw'] = df\n lone_sw_dic[key] = df\n return lone_sw_dic, combined_dic\n\n\ndef concat_boms(title_dfsw, title_dfmerged):\n ''' Concatenate all the SW BOMs into one long list (if there are any SW\n BOMs without a matching SL BOM being found), and concatenate all the\n merged SW/SL BOMs into another long list.\n\n Each BOM, before concatenation, will get a new column added: assy. Values\n for assy will all be the same for a given BOM: the pn (a string) of the BOM.\n BOMs are then concatenated. Finally Pandas set_index function will applied\n to the assy column resulting in the ouput being categorized by the assy pn.\n\n\n Parameters\n ==========\n\n title_dfsw: list\n A list of tuples, each tuple has two items: a string and a DataFrame.\n The string is the assy pn for the DataFrame. The DataFrame is that\n derived from a SW BOM.\n\n title_dfmerged: list\n A list of tuples, each tuple has two items: a string and a DataFrame.\n The string is the assy pn for the DataFrame. The DataFrame is that\n derived from a merged SW/SL BOM.\n\n Returns\n =======\n\n out: tuple\n The output is a tuple comprised of two items. Each item is a list.\n Each list contains one item: a tuple. The structure has the form:\n\n ``out = ([(\"SW BOMS\", DataFrame1)], [(\"BOM Check\", DataFrame2)])``\n\n Where...\n \"SW BOMS\" is the title. (when c=True in the bomcheck function, the\n title will be an assembly part no.).\n DataFrame1 = SW BOMs that have been concatenated together.\n\n \"BOM Check\" is another title.\n DataFrame2 = Merged SW/SL BOMs that have been concatenated together.\n '''\n dfswDFrames = []\n dfmergedDFrames = []\n swresults = []\n mrgresults = []\n for t in title_dfsw:\n t[1]['assy'] = t[0]\n dfswDFrames.append(t[1])\n for t in title_dfmerged:\n t[1]['assy'] = t[0]\n dfmergedDFrames.append(t[1])\n if dfswDFrames:\n dfswCCat = pd.concat(dfswDFrames).reset_index()\n swresults.append(('SW BOMs', dfswCCat.set_index(['assy', 'Op']).sort_index(axis=0)))\n if dfmergedDFrames:\n dfmergedCCat = pd.concat(dfmergedDFrames).reset_index()\n mrgresults.append(('BOM Check', dfmergedCCat.set_index(['assy', 'Item']).sort_index(axis=0)))\n return swresults, mrgresults\n\n\ndef export2excel(dirname, filename, results2export, uname):\n '''Export to an Excel file the results of all the BOM checks.\n\n calls: len2, autosize_excel_columns, autosize_excel_column_df, definefn...\n (these functions are defined internally within the export2exel function)\n\n Parmeters\n =========\n\n dirname: string\n The directory to which the Excel file that this function generates\n will be sent.\n\n filename: string\n The name of the Excel file.\n\n results2export: list\n List of tuples. The number of tuples in the list varies according to\n the number of BOMs analyzed, and if bomcheck's c (sheets) option was\n invoked or not. Each tuple has two items. The first item of a tuple\n is a string and is the name to be assigned to the tab of the Excel\n worksheet. It is typically an assembly part number. The second item\n is a BOM (a DataFrame object). The list of tuples consists of:\n\n *1* SolidWorks BOMs that have been converted to SyteLine format. SW\n BOMs will only occur if no corresponding SL BOM was found.\n\n *2* Merged SW/SL BOMs.\n\n That is, if c=1, the form will be:\n\n - [('2730-2019-544_sw', df1), ('080955', df2),\n ('6890-080955-1', df3), ('0300-2019-533', df4), ...]\n\n and if c=0, the form will be:\n\n - [('SW BOMs', dfForSWboms), ('BOM Check', dfForMergedBoms)]\n\n\n uname : string\n Username to attach to the footer of the Excel file.\n\n Returns\n =======\n\n out: None\n An Excel file will result named bomcheck.xlsx.\n\n \\u2009\n '''\n global printStrs\n\n def len2(s):\n ''' Extract from within a string either a decimal number truncated to two\n decimal places, or an int value; then return the length of that substring.\n Why used? Q_sw, Q_sl, Q, converted to string, are on ocasion something\n like 3.1799999999999997. This leads to wrong length calc using len.'''\n match = re.search(r\"\\d*\\.\\d\\d|\\d+\", s)\n if match:\n return len(match.group())\n else:\n return 0\n\n def autosize_excel_columns(worksheet, df):\n ''' Adjust column width of an Excel worksheet (ref.: https://stackoverflow.com/questions/\n 17326973/is-there-a-way-to-auto-adjust-excel-column-widths-with-pandas-excelwriter)'''\n autosize_excel_columns_df(worksheet, df.index.to_frame())\n autosize_excel_columns_df(worksheet, df, offset=df.index.nlevels)\n\n def autosize_excel_columns_df(worksheet, df, offset=0):\n for idx, col in enumerate(df):\n x = 1 # add a little extra width to the Excel column\n if df.columns[idx] in ['i', 'q', 'd', 'u']:\n x = 0\n series = df[col]\n if df.columns[idx][0] == 'Q':\n max_len = max((\n series.astype(str).map(len2).max(),\n len(str(series.name))\n )) + x\n else:\n max_len = max((\n series.astype(str).map(len).max(),\n len(str(series.name))\n )) + x\n worksheet.set_column(idx+offset, idx+offset, max_len)\n\n def definefn(dirname, filename, i=0):\n ''' If bomcheck.xlsx slready exists, return bomcheck(1).xlsx. If that\n exists, return bomcheck(2).xlsx... and so forth.'''\n global printStrs\n d, f = os.path.split(filename)\n f, e = os.path.splitext(f)\n if d:\n dirname = d # if user specified a directory, use it instead\n if e and not e.lower()=='.xlsx':\n printStr = '\\n(Output filename extension needs to be .xlsx' + '\\nProgram aborted.\\n'\n printStrs.append(printStr)\n print(printStr)\n sys.exit(0)\n else:\n e = '.xlsx'\n if i == 0:\n fn = os.path.join(dirname, f+e)\n else:\n fn = os.path.join(dirname, f+ '(' + str(i) + ')'+e)\n if os.path.exists(fn):\n return definefn(dirname, filename, i+1)\n else:\n return fn\n\n ok2go = True\n if cfg['overwrite']:\n fn = os.path.join(dirname, filename + '.xlsx')\n if os.path.exists(fn):\n try:\n os.remove(fn)\n except Exception as e:\n printStr = ('\\nOverwrite of output file failed.' +\n '\\nPossibly the current file is open in Excel.' +\n '\\n' + str(e) + '\\n')\n printStrs.append(printStr)\n ok2go = False\n else:\n fn = definefn(dirname, filename)\n\n if uname != 'unknown':\n username = uname\n elif os.getenv('USERNAME'):\n username = os.getenv('USERNAME') # Works only on MS Windows\n else:\n username = 'unknown'\n\n localtime_now = datetime.now()\n time = localtime_now.strftime(\"%m-%d-%Y %I:%M %p\")\n\n comment1 = 'This workbook created ' + time + ' by ' + username + '. '\n comment2 = 'The drop list was NOT employed for this BOM check. '\n bomfooter = '&LCreated ' + time + ' by ' + username + '&CPage &P of &N'\n if cfg['drop_bool']:\n comment2 = ('The drop list was employed for this BOM check: '\n + 'drop = ' + str(cfg['drop']) + ', exceptions = ' + str(cfg['exceptions']))\n bomfooter = bomfooter + '&Rdrop: yes'\n\n if excelTitle and len(excelTitle) == 1:\n bomheader = '&C&A: ' + excelTitle[0][0] + ', ' + excelTitle[0][1]\n else:\n bomheader = '&C&A'\n\n\n if ok2go:\n try:\n with pd.ExcelWriter(fn) as writer:\n for r in results2export:\n sheetname = r[0]\n df = r[1]\n if not df.empty: #TODO: some test code\n df.to_excel(writer, sheet_name=sheetname)\n try:\n worksheet = writer.sheets[sheetname] # pull worksheet object\n autosize_excel_columns(worksheet, df) #<<<\n worksheet.set_header(bomheader) #<<< see: https://xlsxwriter.readthedocs.io/page_setup.html\n worksheet.set_footer(bomfooter) #<<<\n worksheet.set_landscape() #<<<\n worksheet.fit_to_pages(1, 0) #<<<\n worksheet.hide_gridlines(2) #<<<\n worksheet.write_comment('A1', comment1 + comment2, {'x_scale': 3}) #<<<\n except Exception as e:\n msg = (str(e) + '. (Minor error caused by Colab. Can be ignored.)')\n #print(msg)\n try:\n workbook = writer.book\n workbook.set_properties({'title': 'BOM Check', 'author': username, #<<<\n 'subject': 'Compares a SolidWorks BOM to a SyteLine BOM',\n 'company': 'Dekker Vacuum Technologies, Inc.',\n 'comments': comment1 + comment2})\n except Exception as e:\n msg = (str(e) + '. (Minor error caused by Colab. Can be ignored.)')\n #print(msg)\n writer.save()\n printStr = \"\\nCreated file: \" + fn + '\\n'\n printStrs.append(printStr)\n print(printStr)\n\n if sys.platform[:3] == 'win': # Open bomcheck.xlsx in Excel when on Windows platform\n try:\n os.startfile(os.path.abspath(fn))\n except:\n printStr = '\\nAttempt to open bomcheck.xlsx in Excel failed.\\n'\n printStrs.append(printStr)\n print(printStr)\n except Exception as e:\n printStr = ('\\nOverwrite of output file failed.' +\n '\\nPossibly the current file is open in Excel.' +\n '\\n' + str(e) + '\\n')\n printStrs.append(printStr)\n\n\n# before program begins, create global variables\nset_globals()\n\n# An example of how the factorpool is used: to convert 29mm to inch:\n# 1/(25.4*12) = 0.00328 (inches to feet)\n# 1/12 = .08333, (foot to inches)\n# Then: 29 * factorpool['mm'] / factorpool['in'] = 0.00328 / .08333 = 1.141\n# Only lower case keys are acceptable. No digits allowed in keys (like \"2\" in \"ft2\")\nfactorpool = {'in':1/12, '\"':1/12, 'inch':1/12, chr(8221):1/12,\n 'ft':1.0, \"'\":1.0, 'feet':1.0, 'foot':1.0, chr(8217):1.0,\n 'yrd':3.0, 'yd':3.0, 'yard':3.0,\n 'mm': 1/(25.4*12), 'millimeter':1/(25.4*12),\n 'cm':10/(25.4*12), 'centimeter':10/(25.4*12),\n 'm':1000/(25.4*12), 'meter':1000/(25.4*12), 'mtr':1000/(25.4*12),\n 'sqin':1/144, 'sqi':1/144,\n 'sqft':1, 'sqf':1, 'sqyd':3, 'sqy':3,\n 'sqmm':1/92903.04, 'sqcm':1/929.0304, 'sqm':1/(.09290304),\n 'pint':1/8, 'pt':1/8, 'qt':1/4, 'quart':1/4,\n 'gal':1.0, 'g':1.0, 'gallon':1.0,\n 'ltr':0.2641720524, 'liter':0.2641720524, 'l':0.2641720524}\nareaUMs = set(['sqi', 'sqin','sqf', 'sqft', 'sqyd', 'sqy', 'sqmm', 'sqcm', 'sqm'])\nliquidUMs = set(['pint', 'pt', 'quart', 'qt', 'gallon', 'g', 'gal' 'ltr', 'liter', 'l'])\n\n\nif __name__=='__main__':\n main() # comment out this line for testing -.- . -.-.\n #bomcheck('*') # use for testing\n\n\n\n","sub_path":"bomcheck.py","file_name":"bomcheck.py","file_ext":"py","file_size_in_byte":64884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"155483801","text":"\"\"\"\r\nClass for the Proof of Retrievability according to Shacham and Waters. The variables are\r\nnamed according to the paper.\r\n\"Compact Proofs of Retrievability\"\r\nJ. Cryptology, 26(3):442–83, Jul. 2013.\r\nhttp://cseweb.ucsd.edu/~hovav/papers/sw13.html\r\n\r\nAll the numbers are currently numbers. When stuff in this class\r\nbecomes a bottleneck, a starting point could be to convert all those\r\nnumbers to bytes.\r\n\"\"\"\r\n\r\nfrom koppercoin.crypto.AbstractProofOfRetrievability import AbstractProofOfRetrievability\r\nfrom pypbc import *\r\nfrom Crypto.Random import random as srandom\r\nfrom Crypto.PublicKey import DSA\r\nimport hashlib\r\nimport os\r\nimport random\r\n\r\n\r\ndef hash(message):\r\n \"\"\"computes a hash\"\"\"\r\n return hashlib.sha512(message).digest()\r\n\r\n\r\ndef str_to_bytes(string):\r\n \"\"\"Takes a string and returns a byte-representation\"\"\"\r\n return str.encode(string)\r\n\r\n\r\ndef int_to_bytes(n):\r\n \"\"\"Takes an integer and returns a byte-representation\"\"\"\r\n return n.to_bytes((n.bit_length() + 7) // 8, 'little') or b'\\0'\r\n # http://stackoverflow.com/questions/846038/convert-a-python-int-into-a-big-endian-string-of-bytes\r\n\r\n\r\ndef bytes_to_int(byte):\r\n \"\"\"Takes some Bytes and returns an Integer.\"\"\"\r\n return int.from_bytes(byte, 'little')\r\n\r\n\r\n# The SW-scheme needs a signing algorithm. We will pick DSA for\r\n# this. Since PyCrypto exposes too much stuff, we have implemented a\r\n# wrapper class\r\nclass SignatureScheme:\r\n def keygen(self):\r\n \"\"\"Key generation. Returns a (public, private)-keypair\"\"\"\r\n key = DSA.generate(1024)\r\n return (key.publickey(), key)\r\n\r\n def sign(self, privkey, message):\r\n \"\"\"Signs a message\"\"\"\r\n h = hash(message)\r\n k = srandom.StrongRandom().randint(1, privkey.q-1)\r\n return privkey.sign(h, k)\r\n\r\n def verify(self, pubkey, message, signature):\r\n \"\"\"Verifies a signature\r\n\r\n >>> SigScheme=SignatureScheme()\r\n >>> (pub, priv) = SigScheme.keygen()\r\n >>> message = str.encode(\"abcdef\")\r\n >>> sig = SigScheme.sign(priv, message)\r\n >>> SigScheme.verify(pub, message, sig)\r\n True\r\n \"\"\"\r\n h = hash(message)\r\n return pubkey.verify(h, signature)\r\n\r\n\r\nclass SWProofOfRetrievability(AbstractProofOfRetrievability):\r\n _s = 2\r\n # In the Shacham-Waters scheme the file is split into blocks. Each\r\n # block is s sectors long. Each sector is in Z/pZ.\r\n # The storage overhead of the encoded file is 1+1/s times the filesize\r\n _sectorsize_prime = 730750818665451621361119245571504901405976559617\r\n # _sectorsize_prime is the prime number p\r\n _sectorsize = 20\r\n # since splitting the file in parts of exactly p involves division\r\n # with remainder of big numbers, which is too slow (yes, I had it\r\n # implemented) we split the file in parts of multiple bytes.\r\n # How many bytes should we take? The biggest amount of bytes where the\r\n # numbers which can be represented are smaller than _sectorsize_prime\r\n # this number is _sectorsize\r\n _stored_params = \"\"\"type a\r\n q 8780710799663312522437781984754049815806883199414208211028653399266475630880222957078625179422662221423155858769582317459277713367317481324925129998224791\r\n h 12016012264891146079388821366740534204802954401251311822919615131047207289359704531102844802183906537786776\r\n r 730750818665451621361119245571504901405976559617\r\n exp2 159\r\n exp1 107\r\n sign1 1\r\n sign0 1\r\n \"\"\"\r\n _params = Parameters(param_string=_stored_params)\r\n _pairing = Pairing(_params)\r\n # these parameters are from test_bls from pypbc\r\n\r\n @staticmethod\r\n def keygen():\r\n \"\"\"returns a (public, private)-keypair\r\n\r\n >>> (publick, secretk) = SWProofOfRetrievability.keygen()\r\n \"\"\"\r\n sigscheme = SignatureScheme()\r\n (spk, ssk) = sigscheme.keygen()\r\n # signing public key, signing secret key\r\n alpha = Element.random(SWProofOfRetrievability._pairing, Zr)\r\n sk = (alpha, ssk)\r\n # secret key\r\n generator_G2 = Element.random(SWProofOfRetrievability._pairing, G2)\r\n v = generator_G2**alpha\r\n pk = (generator_G2, v, spk)\r\n return (pk, sk)\r\n\r\n @staticmethod\r\n def _split_data(data):\r\n \"\"\"splits the data in blocks and sectors. The result looks\r\n like this: [[1,..],[2,..],..]. We also apply a padding.\"\"\"\r\n # split the file in sectors\r\n sectorsize = SWProofOfRetrievability._sectorsize\r\n sectors = []\r\n # Each sector consists of sectorsize bytes\r\n for pointerpos in range(0, len(data), sectorsize):\r\n mi = data[pointerpos: pointerpos + sectorsize]\r\n sectors.append(mi)\r\n # Each block has s sectors\r\n s = SWProofOfRetrievability._s\r\n mij = []\r\n for j in range(0, len(sectors), s):\r\n mi = sectors[j: j+s]\r\n mij.append(mi)\r\n # if the last block does not have s elements, then include as\r\n # many ones as needed. Note that one is the multiplicative\r\n # neutral in Z/pZ\r\n # In fact it is not a padding, in the sense that it can be\r\n # inverted. We just fill up the blocks in a well-defined way.\r\n while len(mij[-1]) != SWProofOfRetrievability._s:\r\n mij[-1] = mij[-1] + [int_to_bytes(1)]\r\n return mij\r\n\r\n @staticmethod\r\n def encode(privatekey, publickey, data):\r\n \"\"\"encodes the data into chunks and generates the\r\n authenticators and the filehandle.\r\n\r\n >>> message = \"abcdefghijklmnopqrstuvwxyz\"*5\r\n >>> data = bytes(message, 'utf-8')\r\n >>> (pk, sk) = SWProofOfRetrievability.keygen()\r\n >>> (mij, authenticators, filehandle) = SWProofOfRetrievability.encode(sk, pk, data)\r\n >>> SWProofOfRetrievability.encode(sk, pk, data) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS\r\n ([[b'abcdefghijklmnopqrst', b'uvwxyzabcdefghijklmn'],\r\n [b'opqrstuvwxyzabcdefgh', b'ijklmnopqrstuvwxyzab'],\r\n [b'cdefghijklmnopqrstuv', b'wxyzabcdefghijklmnop'],\r\n [b'qrstuvwxyz', b'...']],\r\n [[..., ...],\r\n [..., ...],\r\n [..., ...],\r\n [..., ...]],\r\n [[b..., 4,\r\n [[..., ...],\r\n [..., ...]]],\r\n (..., ...)])\r\n \"\"\"\r\n # split the file\r\n mij = SWProofOfRetrievability._split_data(data)\r\n # generate the filehandle\r\n s = SWProofOfRetrievability._s\r\n u = [Element.random(SWProofOfRetrievability._pairing, G1) for i in range(0, s)]\r\n # Filename chosen at random from some sufficiently large domain, compare with paper\r\n filename = os.urandom(32)\r\n t0 = [filename] + [len(mij)] + [u]\r\n (alpha, ssk) = privatekey\r\n sigscheme = SignatureScheme()\r\n t = [t0] + [sigscheme.sign(ssk, str.encode(str(t0)))]\r\n filehandle = t\r\n # filehandle t = [ [filename, #blocks, u1, ..., us], sig]\r\n # generate one authenticator per block\r\n authenticators = []\r\n for i in range(len(mij)):\r\n # compute H(filename|i) * prod_j u_j^mij\r\n prod = Element.one(SWProofOfRetrievability._pairing, G1)\r\n for j in range(s):\r\n prod *= u[j] ** bytes_to_int(mij[i][j])\r\n hashval = Element.from_hash(SWProofOfRetrievability._pairing, G1, hash(filename+str_to_bytes(str(i))))\r\n authenticators.append((hashval * prod) ** alpha)\r\n return (mij, authenticators, filehandle)\r\n\r\n @staticmethod\r\n def genChallenge(nonce):\r\n \"\"\"Generates a challenge.\r\n In the Shacham-Waters scheme one needs to know the filelength\r\n for creating challenges. We are using a nonce and will derive\r\n the set Q={(i,v_i)} from the nonce in the function\r\n _expandChallenge.\"\"\"\r\n return nonce\r\n\r\n @staticmethod\r\n def _expandChallenge(nonce, num_of_blocks):\r\n \"\"\"takes a nonce and generates a challenge Q={(i,v_i)}\r\n according to the SW-paper. See also the documentation for\r\n genChallenge.\"\"\"\r\n random.seed(nonce)\r\n # if this is not generated deterministically we have a huge\r\n # problem\r\n indices = random.sample(range(num_of_blocks), num_of_blocks//2)\r\n indices.sort()\r\n # coefficients are chosen mod p\r\n p = SWProofOfRetrievability._sectorsize_prime\r\n coefficients = [random.randint(1, p-1) for i in indices]\r\n challenge = list(zip(indices, coefficients))\r\n return challenge\r\n\r\n @staticmethod\r\n def genproof(publickey, data, authenticators, challenge, filehandle):\r\n \"\"\"generates a proof of retrievability.\r\n\r\n >>> message = \"abcdefghijklmnopqrstuvwxyz\"*100\r\n >>> data = bytes(message, 'utf-8')\r\n >>> (pk, sk) = SWProofOfRetrievability.keygen()\r\n >>> (mij, authenticators, filehandle) = SWProofOfRetrievability.encode(sk, pk, data)\r\n >>> challenge = os.urandom(32)\r\n >>> (sigma, mu) = SWProofOfRetrievability.genproof(pk, data, authenticators, challenge, filehandle)\r\n \"\"\"\r\n # split the file\r\n mij = SWProofOfRetrievability._split_data(data)\r\n # recover all values\r\n (generator, v, spk) = publickey\r\n [t0, sig] = filehandle\r\n [filename, len_mij, u] = t0\r\n if len(mij) != len_mij:\r\n raise InvalidInputError(\"Stated number of blocks does not match real number of blocks\")\r\n sigscheme = SignatureScheme()\r\n if not sigscheme.verify(spk, str.encode(str(t0)), sig):\r\n raise InvalidInputError(\"Signature contained in filehandle does not verify\")\r\n # generate the challenge set\r\n Q_chal = SWProofOfRetrievability._expandChallenge(challenge, len_mij)\r\n # compute sigma, the aggregated authenticators\r\n sigma = Element.one(SWProofOfRetrievability._pairing, G1)\r\n for (index, coeff) in Q_chal:\r\n sigma *= authenticators[index]**coeff\r\n # compute mu, the list of the aggregated blocks\r\n mu = []\r\n p = SWProofOfRetrievability._sectorsize_prime\r\n for j in range(SWProofOfRetrievability._s):\r\n mu_j = 0\r\n for (index, coeff) in Q_chal:\r\n mu_j = (mu_j + coeff * bytes_to_int(mij[index][j])) % p\r\n mu.append(mu_j)\r\n return (sigma, mu)\r\n\r\n @staticmethod\r\n def verify(proof, publickey, challenge, filehandle):\r\n \"\"\"verifies a proof of retrievability.\r\n\r\n >>> message = \"abcdefghijklmnopqrstuvwxyz\"*100\r\n >>> data = bytes(message, 'utf-8')\r\n >>> (pk, sk) = SWProofOfRetrievability.keygen()\r\n >>> (mij, authenticators, filehandle) = SWProofOfRetrievability.encode(sk, pk, data)\r\n >>> challenge = os.urandom(32)\r\n >>> proof = SWProofOfRetrievability.genproof(pk, data, authenticators, challenge, filehandle)\r\n >>> SWProofOfRetrievability.verify(proof, pk, challenge, filehandle)\r\n True\r\n \"\"\"\r\n # parse all the data\r\n (generator, v, spk) = publickey\r\n [t0, sig] = filehandle\r\n [filename, len_mij, u] = t0\r\n (sigma, mu) = proof\r\n Q_chal = SWProofOfRetrievability._expandChallenge(challenge, len_mij)\r\n sigscheme = SignatureScheme()\r\n # check if signature in filehandle is correct\r\n if not sigscheme.verify(spk, str.encode(str(t0)), sig):\r\n return False\r\n # for verification we need to check if RHS = LHS\r\n # compute LHS = e[ H(filename|i)^coeff * prod_j u_j^muj , v ]\r\n # prodhash = H(filename|i)^coeff\r\n # produ = prod_j u_j^muj\r\n prodhash = Element.one(SWProofOfRetrievability._pairing, G1)\r\n for (i, coeff) in Q_chal:\r\n hashval = Element.from_hash(SWProofOfRetrievability._pairing, G1, hash(filename+str_to_bytes(str(i))))\r\n prodhash *= hashval ** coeff\r\n produ = Element.one(SWProofOfRetrievability._pairing, G1)\r\n for j in range(SWProofOfRetrievability._s):\r\n produ *= u[j] ** mu[j]\r\n pairing = SWProofOfRetrievability._pairing\r\n LHS = pairing.apply(prodhash*produ, v)\r\n # RHS = e(sigma, generator)\r\n RHS = pairing.apply(sigma, generator)\r\n if RHS == LHS:\r\n return True\r\n return False\r\n\r\n\r\nclass InvalidInputError(Exception):\r\n pass\r\n","sub_path":"koppercoin/crypto/SWProofOfRetrievability.py","file_name":"SWProofOfRetrievability.py","file_ext":"py","file_size_in_byte":12308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"327712421","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 26 18:32:28 2018\n\n@author: Figo\n\"\"\"\n\nimport string\nimport numpy as np\n\nsamples = ['The cat sat on the mat.', 'The dog ate my homework.']\ncharacters = string.printable\n# 将可打印字符进行编号\ntoken_index = dict(zip(characters, range(1, len(characters) + 1)))\n\n# 分词只考虑前 50 个字符\nmax_length = 50\nresults = np.zeros((len(samples), max_length, max(token_index.values()) + 1))\nfor i, sample in enumerate(samples):\n for j, character in enumerate(sample[:max_length]):\n index = token_index.get(character)\n results[i, j, index] = 1.","sub_path":"deep_learning_code/deep_learning_2018/6-2Character_level_one-hot_encoding.py","file_name":"6-2Character_level_one-hot_encoding.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"221406649","text":"\"\"\"empty message\n\nRevision ID: df1692a0837\nRevises: 4164f6638019\nCreate Date: 2018-01-31 01:05:16.206689\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'df1692a0837'\ndown_revision = '4164f6638019'\n\nfrom alembic import op\nimport sqlalchemy as sa\nimport geoalchemy2\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('project', sa.Column('completion', sa.SmallInteger(), nullable=False))\n op.add_column('property', sa.Column('completion', sa.SmallInteger(), nullable=False))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('property', 'completion')\n op.drop_column('project', 'completion')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/df1692a0837_.py","file_name":"df1692a0837_.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"217745836","text":"import json\nimport requests\nimport random\nimport string\nfrom faker import Faker\nfrom json.decoder import JSONDecodeError\nfrom user import User\n\nGET_POSTS_URL = \"http://api:8000/posts\"\n\nclass Bot:\n def __init__(self, config):\n self.__dict__.update(config)\n self.faker = Faker()\n self.old_users = get_users()\n self.new_users = []\n\n\n def write_users(self):\n with open(\"users.json\", \"w\") as file:\n new_users = [user.to_dict() for user in self.new_users]\n old_users = [user.to_dict() for user in self.old_users]\n json.dump(old_users + new_users, file, indent=4)\n\n def generate_user(self):\n rand_chars = get_random_string(3, only_lowercase=True)\n name = self.faker.name()\n email = name.replace(\" \", \"\").lower() + rand_chars + \"@mail.com\"\n password = get_random_string(12)\n return User({\"username\": name, \"email\": email, \"password\": password})\n\n def generate_post(self):\n title = self.faker.sentence()\n content = self.faker.paragraph(random.randint(5, 15))\n return {\"title\": title, \"content\": content}\n\n def _signup_users(self):\n print(\"Sign up users({}): \".format(self.number_of_users), end=\"\")\n for _ in range(self.number_of_users):\n user = self.generate_user()\n result = user.signup()\n if result:\n self.new_users.append(user)\n print(\"+\", end=\"\")\n else:\n print(\"\\nUnable to signup user {}.\".format(user.username), end=\"\")\n print()\n\n def _delete_new_users(self):\n for _ in range(len(self.new_users)):\n user = self.new_users.pop()\n user.delete(silent=False)\n\n def _create_posts(self):\n print(\"Creating posts for every new user: \", end=\"\")\n for user in self.new_users:\n number_of_posts = random.randint(1, self.max_posts_per_user)\n for _ in range(number_of_posts):\n post = self.generate_post()\n result = user.create_post(post)\n if result:\n print(\"+\", end=\"\")\n print()\n\n def get_all_posts(self):\n resp = requests.get(GET_POSTS_URL)\n return resp.json()[\"posts\"] if resp.status_code == 200 else []\n\n def _like_posts(self):\n posts = self.get_all_posts()\n if not posts:\n print(\"No post comes for likes\")\n return False\n print(\"Like posts for every new user: \", end=\"\")\n for user in self.new_users:\n for _ in range(random.randint(1, self.max_likes_per_user)):\n post = random.choice(posts)\n result = user.like_post(post)\n if result:\n print(\"+\", end=\"\")\n print()\n\n\n def create_activity(self):\n self._signup_users()\n self._create_posts()\n self._like_posts()\n\n resp = input(\"Should I delete created users from the service? (y/n):\")\n if resp in [\"Y\", \"y\", \"yes\", \"yes\"]:\n self._delete_new_users()\n else:\n self.write_users()\n\n\ndef get_users():\n with open(\"users.json\", \"r\") as file:\n try:\n users = json.load(file)\n except JSONDecodeError:\n return []\n return [User(user) for user in users]\n\n\ndef get_random_string(length, only_lowercase=False):\n letters = string.ascii_lowercase if only_lowercase else string.ascii_letters\n return \"\".join(random.choice(letters + string.digits) for _ in range(length))\n\n\ndef read_config(path):\n with open(path, \"r\") as file:\n return json.load(file)\n\nif __name__ == \"__main__\":\n config = read_config(\"config.json\")\n bot = Bot(config)\n bot.create_activity()\n","sub_path":"bot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":3744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"642684451","text":"import lxml\r\nimport requests\r\nimport time\r\nimport sys\r\nimport progress_bar as PB\r\nimport json\r\n\r\nYOUTUBE_IN_LINK = 'https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=100&order=relevance&pageToken={pageToken}&videoId={videoId}&key={key}'\r\nYOUTUBE_LINK = 'https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&maxResults=100&order=relevance&videoId={videoId}&key={key}'\r\nkey = '' #Change to your Google API\r\n\r\ndef commentExtract(videoId, count = -1,leastlikes=300):\r\n\tprint (\"\\nComments downloading\")\r\n\t#Close the HTTP connection and increase the number of reconnections\r\n\r\n\r\n\r\n\tpage_info = requests.get(YOUTUBE_LINK.format(videoId = videoId, key = key))\r\n\twhile page_info.status_code != 200:\r\n\t\tif page_info.status_code != 429:\r\n\t\t\tprint (\"Comments disabled\")\r\n\t\t\tsys.exit()\r\n\r\n\t\ttime.sleep(20)\r\n\t\tpage_info = requests.get(YOUTUBE_LINK.format(videoId = videoId, key = key))\r\n\r\n\tpage_info = page_info.json()\r\n\t#test\r\n\t# print(page_info)\r\n\r\n\tcomments = []\r\n\tlikes=[]\r\n\tco = 0\r\n\tfor i in range(len(page_info['items'])):\r\n\t\t#The comments above like Leastlike are reserved, which can be changed as needed\r\n\t\tif page_info['items'][i]['snippet']['topLevelComment']['snippet']['likeCount']>=leastlikes:\r\n\t\t\tcomments.append(page_info['items'][i]['snippet']['topLevelComment']['snippet']['textOriginal'])\r\n\t\t\tlikes.append(page_info['items'][i]['snippet']['topLevelComment']['snippet']['likeCount'])\r\n\t\t\tco += 1\r\n\t\tif co == count:\r\n\t\t\tPB.progress(co, count, cond = True)\r\n\t\t\treturn comments,likes\r\n\r\n\tPB.progress(co, count)\r\n\t# INFINTE SCROLLING\r\n\twhile 'nextPageToken' in page_info:\r\n\t\ttemp = page_info\r\n\t\tpage_info = requests.get(YOUTUBE_IN_LINK.format(videoId = videoId, key = key, pageToken = page_info['nextPageToken']))\r\n\r\n\t\twhile page_info.status_code != 200:\r\n\t\t\ttime.sleep(20)\r\n\t\t\tpage_info = requests.get(YOUTUBE_IN_LINK.format(videoId = videoId, key = key, pageToken = temp['nextPageToken']))\r\n\t\tpage_info = page_info.json()\r\n\r\n\t\tfor i in range(len(page_info['items'])):\r\n\t\t\tif page_info['items'][i]['snippet']['topLevelComment']['snippet']['likeCount']>=leastlikes:\r\n\t\t\t\tcomments.append(page_info['items'][i]['snippet']['topLevelComment']['snippet']['textOriginal'])\r\n\t\t\t\tlikes.append(page_info['items'][i]['snippet']['topLevelComment']['snippet']['likeCount'])\r\n\t\t\t\tco += 1\r\n\t\t\tif co == count:\r\n\t\t\t\tPB.progress(co, count, cond = True)\r\n\t\t\t\treturn comments,likes\r\n\t\tPB.progress(co, count)\r\n\tPB.progress(count, count, cond = True)\r\n\tprint ()\r\n\r\n\treturn comments,likes\r\n\r\n","sub_path":"comment_downloader.py","file_name":"comment_downloader.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"246747419","text":"def dep():\n \"\"\"dep.csv와 member.csv를 조인하여 depmember.csv를 만든다. dep-result.csv 참고\"\"\"\n fdep = open(\"dep.csv\")\n fmember = open(\"member.csv\")\n\n # dep dictionary\n header_dep = fdep.readline().strip().split(\",\")\n list_dep = []\n for row in fdep:\n data = row.strip().split(\",\")\n zipped = zip(header_dep, data)\n list_dep.append(dict(zipped))\n\n # member dictionary\n header_member = fmember.readline().strip().split(\",\")\n list_member = []\n for row in fmember:\n data = row.strip().split(\",\")\n zipped = zip(header_member, data)\n list_member.append(dict(zipped))\n\n # result list\n result = []\n result.append([\"DEPNO\", \"DEPNM\", \"EMPNO\", \"EMPNAME\"]) # insert header\n for dep in list_dep:\n depno = dep[\"DEPNO\"]\n depnm = dep[\"DEPNM\"]\n for member in list_member:\n if member[\"DEPNO\"] == depno:\n row = [depno, depnm, member[\"EMPNO\"], member[\"EMPNAME\"]]\n result.append(row)\n\n # write csv file\n fw = open(\"dep-result.csv\", \"w\")\n for line in result:\n fw.write(\",\".join(line)+\"\\n\")\n\n # close file handler\n fdep.close()\n fmember.close()\n fw.close()\n\n\nif __name__ == \"__main__\":\n dep()\n","sub_path":"src/dep.py","file_name":"dep.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"635701606","text":"# coding = utf-8\r\nimport os\r\nimport cv2\r\nimport time\r\nimport pandas as pd\r\n\r\nif __name__ == '__main__':\r\n data_dir = \"data\"\r\n save_path_name = \"image_classification.csv\"\r\n out_dir = \"out\"\r\n if not os.path.exists(out_dir):\r\n os.makedirs(out_dir)\r\n width = 256\r\n height = 256\r\n path_list = []\r\n label_index_list = []\r\n label_name_list = []\r\n time1 = time.time()\r\n file_lists = os.listdir(data_dir)\r\n print(\"file_lists\",file_lists)\r\n for filename in file_lists:\r\n img_dir = data_dir + '/' + filename\r\n img_lists = os.listdir(img_dir)\r\n img_lists = [i for i in img_lists\r\n if (i.startswith(\"Meter\")) and (i.endswith(\".jpg\"))]\r\n print(\"img_lists\", img_lists)\r\n for imgname in img_lists:\r\n if filename == \"Meter1\" :\r\n label_index = 1\r\n label_name = \"meter1\"\r\n elif filename == \"Meter2\" :\r\n label_index = 2\r\n label_name = \"meter2\"\r\n elif filename == \"Meter3\" :\r\n label_index = 3\r\n label_name = \"meter3\"\r\n elif filename == \"Meter4\" :\r\n label_index = 4\r\n label_name = \"meter4\"\r\n path_list.append(\"./\" + str(label_index) + \"/\" + imgname)\r\n label_name_list.append(label_name)\r\n label_index_list.append(label_index)\r\n\r\n ####################读入图像###############################\r\n img_path = img_dir + '/' + imgname\r\n image = cv2.imread(img_path, cv2.IMREAD_COLOR)\r\n res = cv2.resize(image, (width, height), interpolation=cv2.INTER_LINEAR)\r\n ####################写入图像########################\r\n save_img_dir = out_dir + '/' + str(label_index)\r\n if not os.path.exists(save_img_dir):\r\n os.makedirs(save_img_dir)\r\n cv2.imwrite(save_img_dir + '/' + imgname, res)\r\n print(\"%s has been resized!\" % imgname)\r\n\r\n df_dict = {\r\n \"path\": path_list,\r\n \"label_name\": label_name_list,\r\n \"label_index\": label_index_list\r\n }\r\n df = pd.DataFrame(data=df_dict)\r\n df.to_csv(save_path_name, header=False, index=False)\r\n time2=time.time()\r\n print (u'总共耗时:' + str(time2 - time1) + 's')\r\n","sub_path":"0203_图像分类分拣1预处理python/resize_save_path_csv.py","file_name":"resize_save_path_csv.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"141340880","text":"import urllib3, re\nimport pandas as pd\nimport numpy as np\n\n#setting up urllib\nhttp = urllib3.PoolManager()\n\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\ndef gender(name):\n\n #get data from gender prediction API\n genderAPI = \"https://api.bundle.io/v1/nametogender?name=\"+name+\"&api_key=KgXjmD0kETqhUmZJv4zMb1ORs\"\n\n response = http.request('GET', genderAPI)\n\n #get gender field\n array = re.split(':|,|\\n',response.data.decode('utf-8'))\n\n #printing gender\n return array[3].replace(\"\\\"\", '')\n\ndef getListOfNames(df):\n full_names = df['Student name'].tolist()\n\n first_names = {}\n for full_name in full_names:\n if (len(full_name.split(\", \")) > 1):\n first_names[full_name.split(\", \")[1].split()[0]] = 1\n else:\n first_names[full_name] = 1\n return list(first_names)\n\n\n# Loads our stored dictionary with associated genders for names in our dataset.\n# Sometimes this function may crash, this is usually caused by either an Unexpected\n# special character in the name we're passing that doesn't fit in unicode8 OR\n# the API messed up in some way.\n# Just restart and resume from where i left off. Alter the listOfName entries left to process.\ndef load_genders(year):\n\n df = pd.read_csv(year+\".csv\")\n listOfNames = getListOfNames(df)\n print(len(listOfNames))\n\n i = 0\n for name in listOfNames:\n print(str(i)+'\\t'+name)\n genders = np.load('all_genders.npy').item()\n if name not in genders:\n genders[name] = gender(name)\n np.save('all_genders.npy', genders)\n\n i += 1\n\n print(genders)\n","sub_path":"data/gender.py","file_name":"gender.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"373012327","text":"#\n# Config Handler Class\n#\nimport json\nfrom src.ConfigSettings import ConfigSettings\n\n\nclass ConfigHandler:\n \"\"\" Class to handle config files \"\"\"\n\n def __init__(self):\n \"\"\" class constructor \"\"\"\n self.config_contents = {}\n\n def read_config(self, file_path):\n \"\"\" parses config file in json format\"\"\"\n\n config_file = open(file_path)\n self.config_contents = json.load(config_file)\n config_file.close()\n\n return self.config_contents\n\n def create_config_settings(self, file_path):\n \"\"\" returns a ConfigSettings object constructed from config_contents\"\"\"\n self.config_contents = self.read_config(file_path)\n # create empty config file object\n cs = ConfigSettings()\n\n # populate logfile related config settings\n logfile_config = self.config_contents.get('logfile')\n cs.logfile_file_name = logfile_config.get('file_name')\n cs.logfile_date_stamp_file_name = logfile_config.get('date_stamp_file_name')\n cs.logfile_time_stamp_file_name = logfile_config.get('time_stamp_file_name')\n cs.logfile_save_location = logfile_config.get('save_location')\n\n # populate sccs related config settings\n sccs_config = self.config_contents.get('sccs')\n cs.sccs_check_in_message = sccs_config.get('check_in_message')\n\n # populate version history related config settings\n version_config = self.config_contents.get('version_history')\n cs.version_history_clear_history = version_config.get('clear_message')\n cs.version_history_message = version_config.get('clear_history')\n\n # return populated Config Settings file.\n return cs\n","sub_path":"v2_0_0_alpha/src/ConfigHandler.py","file_name":"ConfigHandler.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"450596384","text":"import pandas as pd\nimport numpy as np\n\n\ndef reduce_memory(df):\n \"\"\" iterate through all the columns of a dataframe and modify the data type\n to reduce memory usage.\n \"\"\"\n start_mem = df.memory_usage().sum() / 1024 ** 2\n print('Memory usage of dataframe was {:.2f} MB'.format(start_mem))\n\n for col in df.columns:\n col_type = df[col].dtype\n\n if col_type != object:\n c_min = df[col].min()\n c_max = df[col].max()\n if str(col_type)[:3] == 'int':\n if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n df[col] = df[col].astype(np.int8)\n elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n df[col] = df[col].astype(np.int16)\n elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n df[col] = df[col].astype(np.int32)\n elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n df[col] = df[col].astype(np.int64)\n else:\n if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n df[col] = df[col].astype(np.float16)\n elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n df[col] = df[col].astype(np.float32)\n else:\n df[col] = df[col].astype(np.float64)\n else:\n df[col] = df[col].astype('category')\n\n end_mem = df.memory_usage().sum() / 1024 ** 2\n print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n\n return df\n\n\ndef df_basic_info(df):\n print(\"Basic summary : \\n\")\n print(\"Features : \",df.shape[1])\n print(\"\\nPCA Features :\", len(df.columns[1:29]),\"--\", df.iloc[:,1:29].dtypes[0])\n print(\"Other Features : Time --\",df.Time.dtype,\"Amount --\",df.Amount.dtype)\n print(\"Labels :\",df.columns[-1], df.Class.unique(),\"--\", df.Class.dtype)\n print(\"\\nRows : \",df.shape[0])\n print(\"\\nClass normal : \", len(df[df.Class == 0]))\n print(\"Fraud : \",len(df[df.Class == 1]))\n print(\"Fraud cases percentage : \",round(len(df[df.Class == 1])/len(df[df.Class == 0])*100,4),\"%\")\n print(\"\\nMissing values : \",df.isnull().sum().sum())\n\n\ndef print_best_corelations(df):\n df_corr = df.corr().unstack().sort_values().drop_duplicates()\n print(\"Top five positive corelation : \\n\")\n print(df_corr.tail().sort_values(ascending=False))\n\n print(\"\\nTop five negative corelation : \\n\")\n print(df_corr.head())\n\n\ndef ecdf(data):\n \"\"\"Compute ECDF for a one-dimensional array of measurements.\"\"\"\n # Number of data points: n\n n = len(data)\n\n # x-data for the ECDF: x\n x = np.sort(data)\n\n # y-data for the ECDF: y\n y = np.arange(1, n+1) / n\n\n return x, y","sub_path":"src/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"195811596","text":"from __future__ import unicode_literals\r\nfrom __future__ import print_function\r\nfrom __future__ import unicode_literals\r\n\r\nimport telnetlib\r\nimport textwrap, re, io, paramiko,hashlib,copy,threading, socket,getopt,os, sys, time\r\nfrom os import path\r\nfrom collections import deque\r\nfrom paramiko.pkey import PKey\r\nfrom paramiko import file\r\n\r\nfrom paramiko.ssh_exception import (\r\n SSHException,\r\n PasswordRequiredException,\r\n BadAuthenticationType,\r\n ChannelException,\r\n BadHostKeyException,\r\n AuthenticationException,\r\n )\r\nfrom paramiko.client import (\r\n SSHClient,\r\n MissingHostKeyPolicy,\r\n AutoAddPolicy,\r\n RejectPolicy,\r\n WarningPolicy,\r\n)\r\n\r\nimport logging\r\n\r\nunicode = str\r\n\r\n# Log\r\nlog = logging.getLogger(__name__) # noqa\r\nlog.addHandler(logging.NullHandler()) # noqa\r\n\r\n# Variables\r\n\r\nSGR = {\r\n 'reset': 0,\r\n 'bold': 1,\r\n 'underline': 4,\r\n 'blink': 5,\r\n 'negative': 7,\r\n 'underline_off': 24,\r\n 'blink_off': 25,\r\n 'positive': 27,\r\n 'black': 30,\r\n 'red': 31,\r\n 'green': 32,\r\n 'yellow': 33,\r\n 'blue': 34,\r\n 'magenta': 35,\r\n 'cyan': 36,\r\n 'white': 37,\r\n 'fg_reset': 39,\r\n 'bg_black': 40,\r\n 'bg_red': 41,\r\n 'bg_green': 42,\r\n 'bg_yellow': 43,\r\n 'bg_blue': 44,\r\n 'bg_magenta': 45,\r\n 'bg_cyan': 46,\r\n 'bg_white': 47,\r\n 'bg_reset': 49,\r\n }\r\n\r\n# Provide a familar descriptive word for some ansi sequences.\r\nFG_COLOR_WORDS = {'black': ['black'],\r\n 'dark_gray': ['bold', 'black'],\r\n 'blue': ['blue'],\r\n 'light_blue': ['bold', 'blue'],\r\n 'green': ['green'],\r\n 'light_green': ['bold', 'green'],\r\n 'cyan': ['cyan'],\r\n 'light_cyan': ['bold', 'cyan'],\r\n 'red': ['red'],\r\n 'light_red': ['bold', 'red'],\r\n 'purple': ['magenta'],\r\n 'light_purple': ['bold', 'magenta'],\r\n 'brown': ['yellow'],\r\n 'yellow': ['bold', 'yellow'],\r\n 'light_gray': ['white'],\r\n 'white': ['bold', 'white']}\r\n\r\nBG_COLOR_WORDS = {'black': ['bg_black'],\r\n 'red': ['bg_red'],\r\n 'green': ['bg_green'],\r\n 'yellow': ['bg_yellow'],\r\n 'dark_blue': ['bg_blue'],\r\n 'purple': ['bg_magenta'],\r\n 'light_blue': ['bg_cyan'],\r\n 'grey': ['bg_white']}\r\n\r\nANSI_START = '\\001'\r\nANSI_END = '\\002'\r\n\r\n\r\nsgr_re = re.compile(r'(%s?\\033\\[\\d+(?:;\\d+)*m%s?)' % (\r\n ANSI_START, ANSI_END))\r\n\r\n\r\nunicode = str\r\nPY2 = sys.version_info.major == 2\r\nPY3 = sys.version_info.major == 3\r\nif PY3:\r\n string_types = (str,)\r\n text_type = str\r\n bufferedio_types = io.BufferedIOBase\r\nelse:\r\n string_types = (str,) # noqa\r\n text_type = unicode # noqa\r\n bufferedio_types = (io.BufferedIOBase, file) # noqa # paramiko\r\n\r\nMAX_BUFFER = 65535\r\nBACKSPACE_CHAR = \"\\x08\"\r\n\r\nLINUX_PROMPT_PRI = os.getenv(\"Net_Connect_LINUX_PROMPT_PRI\", \"$\")\r\nLINUX_PROMPT_ALT = os.getenv(\"Net_Connect_LINUX_PROMPT_ALT\", \"#\")\r\nLINUX_PROMPT_ROOT = os.getenv(\"Net_Connect_LINUX_PROMPT_ROOT\", \"#\")\r\n\r\n\r\n# Network Base Connection\r\nclass BaseConnection(object):\r\n \"\"\"\r\n Defines vendor independent methods.\r\n\r\n Otherwise method left as a stub method.\r\n \"\"\"\r\n def __init__(\r\n self,\r\n ip=\"\",\r\n host=\"\",\r\n username=\"\",\r\n password=None,\r\n secret=\"\",\r\n port=None,\r\n device_type=\"\",\r\n verbose=False,\r\n global_delay_factor=5,\r\n use_keys=False,\r\n key_file=None,\r\n pkey=None,\r\n passphrase=None,\r\n allow_agent=False,\r\n ssh_strict=False,\r\n system_host_keys=False,\r\n alt_host_keys=False,\r\n alt_key_file=\"\",\r\n ssh_config_file=None,\r\n timeout=100,\r\n session_timeout=60,\r\n auth_timeout=None,\r\n blocking_timeout=8,\r\n banner_timeout=5,\r\n keepalive=0,\r\n default_enter=None,\r\n response_return=None,\r\n serial_settings=None,\r\n fast_cli=False,\r\n session_log=None,\r\n session_log_record_writes=False,\r\n session_log_file_mode=\"write\",\r\n allow_auto_change=False,\r\n encoding=\"ascii\",\r\n ):\r\n\r\n self.remote_conn = None\r\n\r\n self.TELNET_RETURN = \"\\r\\n\"\r\n if default_enter is None:\r\n if \"telnet\" not in device_type:\r\n self.RETURN = \"\\n\"\r\n else:\r\n self.RETURN = self.TELNET_RETURN\r\n else:\r\n self.RETURN = default_enter\r\n\r\n # Line Separator in response lines\r\n self.RESPONSE_RETURN = \"\\n\" if response_return is None else response_return\r\n if ip:\r\n self.host = ip.strip()\r\n elif host:\r\n self.host = host.strip()\r\n if port is None:\r\n if \"telnet\" in device_type:\r\n port = 23\r\n else:\r\n port = 22\r\n self.port = int(port)\r\n\r\n self.username = username\r\n self.password = password\r\n self.secret = secret\r\n self.device_type = device_type\r\n self.ansi_escape_codes = False\r\n self.verbose = verbose\r\n self.timeout = timeout\r\n self.auth_timeout = auth_timeout\r\n self.banner_timeout = banner_timeout\r\n self.session_timeout = session_timeout\r\n self.blocking_timeout = blocking_timeout\r\n self.keepalive = keepalive\r\n self.allow_auto_change = allow_auto_change\r\n self.encoding = encoding\r\n\r\n # Net_Connect will close the session_log if we open the file\r\n self.session_log = None\r\n self.session_log_record_writes = session_log_record_writes\r\n self._session_log_close = False\r\n # Ensures last write operations prior to disconnect are recorded.\r\n self._session_log_fin = False\r\n if session_log is not None:\r\n if isinstance(session_log, string_types):\r\n # If session_log is a string, open a file corresponding to string name.\r\n self.open_session_log(filename=session_log, mode=session_log_file_mode)\r\n elif isinstance(session_log, bufferedio_types):\r\n # In-memory buffer or an already open file handle\r\n self.session_log = session_log\r\n else:\r\n raise ValueError(\r\n \"session_log must be a path to a file, a file handle, \"\r\n \"or a BufferedIOBase subclass.\"\r\n )\r\n\r\n self.fast_cli = fast_cli\r\n self.global_delay_factor = global_delay_factor\r\n if self.fast_cli and self.global_delay_factor == 5:\r\n self.global_delay_factor = 0.1\r\n\r\n # set in set_base_prompt method\r\n self.base_prompt = \"\"\r\n self._session_locker = threading.Lock()\r\n\r\n # determine if telnet or SSH\r\n if \"_telnet\" in device_type:\r\n self.protocol = \"telnet\"\r\n self.password = password or \"\"\r\n else:\r\n self.protocol = \"ssh\"\r\n\r\n if not ssh_strict:\r\n self.key_policy = AutoAddPolicy()\r\n else:\r\n self.key_policy = paramiko.RejectPolicy()\r\n\r\n # Options for SSH host_keys\r\n self.use_keys = use_keys\r\n self.key_file = key_file\r\n self.pkey = pkey\r\n self.passphrase = passphrase\r\n self.allow_agent = allow_agent\r\n self.system_host_keys = system_host_keys\r\n self.alt_host_keys = alt_host_keys\r\n self.alt_key_file = alt_key_file\r\n\r\n # For SSH proxy support\r\n self.ssh_config_file = ssh_config_file\r\n\r\n # Establish the remote connection\r\n self._open()\r\n\r\n def _open(self):\r\n \"\"\"Decouple connection creation from __init__ for mocking.\"\"\"\r\n self._modify_connection_params()\r\n self.establish_connection()\r\n self._try_session_preparation()\r\n\r\n def __enter__(self):\r\n \"\"\"Establish a session using a Context Manager.\"\"\"\r\n return self\r\n\r\n def __exit__(self, exc_type, exc_value, traceback):\r\n \"\"\"Gracefully close connection on Context Manager exit.\"\"\"\r\n self.disconnect()\r\n\r\n def _modify_connection_params(self):\r\n \"\"\"Modify connection parameters prior to SSH connection.\"\"\"\r\n pass\r\n\r\n def _timeout_exceeded(self, start, msg=\"Timeout exceeded!\"):\r\n \"\"\"Raise Net_ConnectTimeoutException if waiting too much in the serving queue.\r\n\r\n :param start: Initial start time to see if session lock timeout has been exceeded\r\n :type start: float (from time.time() call i.e. epoch time)\r\n\r\n :param msg: Exception message if timeout was exceeded\r\n :type msg: str\r\n \"\"\"\r\n if not start:\r\n # Must provide a comparison time\r\n return False\r\n if time.time() - start > self.session_timeout:\r\n # session_timeout exceeded\r\n raise Net_ConnectTimeoutException(msg)\r\n return False\r\n\r\n def _lock_Net_Connect_session(self, start=None):\r\n \"\"\"Try to acquire the Net_Connect session lock. If not available, wait in the queue until\r\n the channel is available again.\r\n\r\n :param start: Initial start time to measure the session timeout\r\n :type start: float (from time.time() call i.e. epoch time)\r\n \"\"\"\r\n if not start:\r\n start = time.time()\r\n # Wait here until the SSH channel lock is acquired or until session_timeout exceeded\r\n while not self._session_locker.acquire(False) and not self._timeout_exceeded(\r\n start, \"The Net_Connect channel is not available!\"\r\n ):\r\n time.sleep(0.1)\r\n return True\r\n\r\n def _unlock_Net_Connect_session(self):\r\n \"\"\"\r\n Release the channel at the end of the task.\r\n \"\"\"\r\n if self._session_locker.locked():\r\n self._session_locker.release()\r\n\r\n def _write_channel(self, out_data):\r\n \"\"\"Generic handler that will write to both SSH and telnet channel.\r\n\r\n :param out_data: data to be written to the channel\r\n :type out_data: str (can be either unicode/byte string)\r\n \"\"\"\r\n if self.protocol == \"ssh\":\r\n self.remote_conn.sendall(write_bytes(out_data, encoding=self.encoding))\r\n elif self.protocol == \"telnet\":\r\n self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))\r\n else:\r\n raise ValueError(\"Invalid protocol specified\")\r\n try:\r\n log.debug(\r\n \"write_channel: {}\".format(\r\n write_bytes(out_data, encoding=self.encoding)\r\n )\r\n )\r\n if self._session_log_fin or self.session_log_record_writes:\r\n self._write_session_log(out_data)\r\n except UnicodeDecodeError:\r\n # Don't log non-ASCII characters; this is null characters and telnet IAC (PY2)\r\n pass\r\n\r\n def _write_session_log(self, data):\r\n if self.session_log is not None and len(data) > 0:\r\n # Hide the password and secret in the session_log\r\n if self.password:\r\n data = data.replace(self.password, \"********\")\r\n if self.secret:\r\n data = data.replace(self.secret, \"********\")\r\n self.session_log.write(write_bytes(data, encoding=self.encoding))\r\n self.session_log.flush()\r\n\r\n def write_channel(self, out_data):\r\n \"\"\"Generic handler that will write to both SSH and telnet channel.\r\n\r\n :param out_data: data to be written to the channel\r\n :type out_data: str (can be either unicode/byte string)\r\n \"\"\"\r\n self._lock_Net_Connect_session()\r\n try:\r\n self._write_channel(out_data)\r\n finally:\r\n # Always unlock the SSH channel, even on exception.\r\n self._unlock_Net_Connect_session()\r\n\r\n def is_alive(self):\r\n \"\"\"Returns a boolean flag with the state of the connection.\"\"\"\r\n null = chr(0)\r\n if self.remote_conn is None:\r\n log.error(\"Connection is not initialised, is_alive returns False\")\r\n return False\r\n if self.protocol == \"telnet\":\r\n try:\r\n # Try sending IAC + NOP (IAC is telnet way of sending command)\r\n # IAC = Interpret as Command; it comes before the NOP.\r\n log.debug(\"Sending IAC + NOP\")\r\n # Need to send multiple times to test connection\r\n self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)\r\n self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)\r\n self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)\r\n return True\r\n except AttributeError:\r\n return False\r\n else:\r\n # SSH\r\n try:\r\n # Try sending ASCII null byte to maintain the connection alive\r\n log.debug(\"Sending the NULL byte\")\r\n self.write_channel(null)\r\n return self.remote_conn.transport.is_active()\r\n except (socket.error, EOFError):\r\n log.error(\"Unable to send\", exc_info=True)\r\n # If unable to send, we can tell for sure that the connection is unusable\r\n return False\r\n return False\r\n\r\n def _read_channel(self):\r\n \"\"\"Generic handler that will read all the data from an SSH or telnet channel.\"\"\"\r\n if self.protocol == \"ssh\":\r\n output = \"\"\r\n while True:\r\n if self.remote_conn.recv_ready():\r\n outbuf = self.remote_conn.recv(MAX_BUFFER)\r\n if len(outbuf) == 0:\r\n raise EOFError(\"Channel stream closed by remote device.\")\r\n output += outbuf.decode(\"utf-8\", \"ignore\")\r\n else:\r\n break\r\n elif self.protocol == \"telnet\":\r\n output = self.remote_conn.read_very_eager().decode(\"utf-8\", \"ignore\")\r\n log.debug(\"read_channel: {}\".format(output))\r\n self._write_session_log(output)\r\n return output\r\n\r\n def read_channel(self):\r\n \"\"\"Generic handler that will read all the data from an SSH or telnet channel.\"\"\"\r\n output = \"\"\r\n self._lock_Net_Connect_session()\r\n try:\r\n output = self._read_channel()\r\n finally:\r\n # Always unlock the SSH channel, even on exception.\r\n self._unlock_Net_Connect_session()\r\n return output\r\n\r\n def _read_channel_expect(self, pattern=\"\", re_flags=0, max_loops=500):\r\n output = \"\"\r\n if not pattern:\r\n pattern = re.escape(self.base_prompt)\r\n log.debug(\"Pattern is: {}\".format(pattern))\r\n\r\n i = 1\r\n loop_delay = 0.1\r\n # Default to making loop time be roughly equivalent to self.timeout (support old max_loops\r\n # argument for backwards compatibility).\r\n if max_loops == 500:\r\n max_loops = int(self.timeout / loop_delay)\r\n while i < max_loops:\r\n if self.protocol == \"ssh\":\r\n try:\r\n # If no data available will wait timeout seconds trying to read\r\n self._lock_Net_Connect_session()\r\n new_data = self.remote_conn.recv(MAX_BUFFER)\r\n if len(new_data) == 0:\r\n raise EOFError(\"Channel stream closed by remote device.\")\r\n new_data = new_data.decode(\"utf-8\", \"ignore\")\r\n log.debug(\"_read_channel_expect read_data: {}\".format(new_data))\r\n output += new_data\r\n self._write_session_log(new_data)\r\n except socket.timeout:\r\n raise Net_ConnectTimeoutException(\r\n \"Timed-out reading channel, data not available.\"\r\n )\r\n finally:\r\n self._unlock_Net_Connect_session()\r\n if re.search(pattern, output, flags=re_flags):\r\n log.debug(\"Pattern found: {} {}\".format(pattern, output))\r\n return output\r\n time.sleep(loop_delay * self.global_delay_factor)\r\n i += 1\r\n raise Net_ConnectTimeoutException(\r\n \"Timed-out reading channel, pattern not found in output: {}\".format(pattern)\r\n )\r\n\r\n def _read_channel_timing(self, delay_factor=1, max_loops=500):\r\n # Time to delay in each read loop\r\n loop_delay = 0.1\r\n final_delay = 2\r\n\r\n # Default to making loop time be roughly equivalent to self.timeout (support old max_loops\r\n # and delay_factor arguments for backwards compatibility).\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n if delay_factor == 1 and max_loops == 150:\r\n max_loops = int(self.timeout / loop_delay)\r\n\r\n channel_data = \"\"\r\n i = 0\r\n while i <= max_loops:\r\n time.sleep(loop_delay * delay_factor)\r\n new_data = self.read_channel()\r\n if new_data:\r\n channel_data += new_data\r\n else:\r\n # Safeguard to make sure really done\r\n time.sleep(final_delay * delay_factor)\r\n new_data = self.read_channel()\r\n if not new_data:\r\n break\r\n else:\r\n channel_data += new_data\r\n i += 1\r\n return channel_data\r\n\r\n def read_until_prompt(self, *args, **kwargs):\r\n \"\"\"Read channel until self.base_prompt detected. Return ALL data available.\"\"\"\r\n return self._read_channel_expect(*args, **kwargs)\r\n\r\n def read_until_pattern(self, *args, **kwargs):\r\n \"\"\"Read channel until pattern detected. Return ALL data available.\"\"\"\r\n return self._read_channel_expect(*args, **kwargs)\r\n\r\n def read_until_prompt_or_pattern(self, pattern=\"\", re_flags=0):\r\n combined_pattern = re.escape(self.base_prompt)\r\n if pattern:\r\n combined_pattern = r\"({}|{})\".format(combined_pattern, pattern)\r\n return self._read_channel_expect(combined_pattern, re_flags=re_flags)\r\n\r\n\r\n def telnet_login(\r\n self,\r\n pri_prompt_terminator=r\"#\\s*$\",\r\n alt_prompt_terminator=r\">\\s*$\",\r\n username_pattern=r\"(?:user:|username|login|user name)\",\r\n pwd_pattern=r\"assword\",\r\n delay_factor=1,\r\n max_loops=20,\r\n ):\r\n\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n time.sleep(1 * delay_factor)\r\n\r\n output = \"\"\r\n return_msg = \"\"\r\n i = 1\r\n while i <= max_loops:\r\n try:\r\n output = self.read_channel()\r\n return_msg += output\r\n\r\n # Search for username pattern / send username\r\n if re.search(username_pattern, output, flags=re.I):\r\n self.write_channel(self.username + self.TELNET_RETURN)\r\n time.sleep(1 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n\r\n # Search for password pattern / send password\r\n if re.search(pwd_pattern, output, flags=re.I):\r\n self.write_channel(self.password + self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(\r\n pri_prompt_terminator, output, flags=re.M\r\n ) or re.search(alt_prompt_terminator, output, flags=re.M):\r\n return return_msg\r\n\r\n # Check if proper data received\r\n if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(\r\n alt_prompt_terminator, output, flags=re.M\r\n ):\r\n return return_msg\r\n\r\n self.write_channel(self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n i += 1\r\n except EOFError:\r\n self.remote_conn.close()\r\n msg = \"Login failed: {}\".format(self.host)\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n # Last try to see if we already logged in\r\n self.write_channel(self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(\r\n alt_prompt_terminator, output, flags=re.M\r\n ):\r\n return return_msg\r\n\r\n msg = \"Login failed: {}\".format(self.host)\r\n self.remote_conn.close()\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n def _try_session_preparation(self):\r\n try:\r\n self.session_preparation()\r\n except Exception:\r\n self.disconnect()\r\n raise\r\n\r\n def session_preparation(self):\r\n self._test_channel_read()\r\n self.set_base_prompt()\r\n self.disable_paging()\r\n self.set_terminal_width()\r\n\r\n # Clear the read buffer\r\n time.sleep(0.3 * self.global_delay_factor)\r\n self.clear_buffer()\r\n\r\n def _use_ssh_config(self, dict_arg):\r\n connect_dict = dict_arg.copy()\r\n\r\n # Use SSHConfig to generate source content.\r\n full_path = path.abspath(path.expanduser(self.ssh_config_file))\r\n if path.exists(full_path):\r\n ssh_config_instance = paramiko.SSHConfig()\r\n with io.open(full_path, \"rt\", encoding=\"utf-8\") as f:\r\n ssh_config_instance.parse(f)\r\n source = ssh_config_instance.lookup(self.host)\r\n else:\r\n source = {}\r\n\r\n # Keys get normalized to lower-case\r\n if \"proxycommand\" in source:\r\n proxy = paramiko.ProxyCommand(source[\"proxycommand\"])\r\n elif \"proxyjump\" in source:\r\n hops = list(reversed(source[\"proxyjump\"].split(\",\")))\r\n if len(hops) > 1:\r\n raise ValueError(\r\n \"ProxyJump with more than one proxy server is not supported.\"\r\n )\r\n port = source.get(\"port\", self.port)\r\n host = source.get(\"hostname\", self.host)\r\n # -F {full_path} forces the continued use of the same SSH config file\r\n cmd = \"ssh -F {} -W {}:{} {}\".format(full_path, host, port, hops[0])\r\n proxy = paramiko.ProxyCommand(cmd)\r\n else:\r\n proxy = None\r\n\r\n # Only update 'hostname', 'sock', 'port', and 'username'\r\n # For 'port' and 'username' only update if using object defaults\r\n if connect_dict[\"port\"] == 22:\r\n connect_dict[\"port\"] = int(source.get(\"port\", self.port))\r\n if connect_dict[\"username\"] == \"\":\r\n connect_dict[\"username\"] = source.get(\"user\", self.username)\r\n if proxy:\r\n connect_dict[\"sock\"] = proxy\r\n connect_dict[\"hostname\"] = source.get(\"hostname\", self.host)\r\n\r\n return connect_dict\r\n\r\n def _connect_params_dict(self):\r\n \"\"\"Generate dictionary of Paramiko connection parameters.\"\"\"\r\n conn_dict = {\r\n \"hostname\": self.host,\r\n \"port\": self.port,\r\n \"username\": self.username,\r\n \"password\": self.password,\r\n \"look_for_keys\": self.use_keys,\r\n \"allow_agent\": self.allow_agent,\r\n \"key_filename\": self.key_file,\r\n \"pkey\": self.pkey,\r\n \"passphrase\": self.passphrase,\r\n \"timeout\": self.timeout,\r\n \"auth_timeout\": self.auth_timeout,\r\n \"banner_timeout\": self.banner_timeout,\r\n }\r\n\r\n # Check if using SSH 'config' file mainly for SSH proxy support\r\n if self.ssh_config_file:\r\n conn_dict = self._use_ssh_config(conn_dict)\r\n return conn_dict\r\n\r\n def _sanitize_output(\r\n self, output, strip_command=False, command_string=None, strip_prompt=False\r\n ):\r\n\r\n if self.ansi_escape_codes:\r\n output = self.strip_ansi_escape_codes(output)\r\n output = self.normalize_linefeeds(output)\r\n if strip_command and command_string:\r\n command_string = self.normalize_linefeeds(command_string)\r\n output = self.strip_command(command_string, output)\r\n if strip_prompt:\r\n output = self.strip_prompt(output)\r\n return output\r\n\r\n def establish_connection(self, width=None, height=None):\r\n\r\n if self.protocol == \"telnet\":\r\n self.remote_conn = telnetlib.Telnet(\r\n self.host, port=self.port, timeout=self.timeout\r\n )\r\n self.telnet_login()\r\n elif self.protocol == \"ssh\":\r\n ssh_connect_params = self._connect_params_dict()\r\n self.remote_conn_pre = self._build_ssh_client()\r\n\r\n # initiate SSH connection\r\n try:\r\n self.remote_conn_pre.connect(**ssh_connect_params)\r\n except socket.error:\r\n self.paramiko_cleanup()\r\n msg = \"Connection to device timed-out: {device_type} {ip}:{port}\".format(\r\n device_type=self.device_type, ip=self.host, port=self.port\r\n )\r\n raise Net_ConnectTimeoutException(msg)\r\n except paramiko.ssh_exception.AuthenticationException as auth_err:\r\n self.paramiko_cleanup()\r\n msg = \"Authentication failure: unable to connect {device_type} {ip}:{port}\".format(\r\n device_type=self.device_type, ip=self.host, port=self.port\r\n )\r\n msg += self.RETURN + text_type(auth_err)\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n if self.verbose:\r\n print(\r\n \"SSH connection established to {}:{}\".format(self.host, self.port)\r\n )\r\n\r\n # Use invoke_shell to establish an 'interactive session'\r\n if width and height:\r\n self.remote_conn = self.remote_conn_pre.invoke_shell(\r\n term=\"vt100\", width=width, height=height\r\n )\r\n else:\r\n self.remote_conn = self.remote_conn_pre.invoke_shell()\r\n\r\n self.remote_conn.settimeout(self.blocking_timeout)\r\n if self.keepalive:\r\n self.remote_conn.transport.set_keepalive(self.keepalive)\r\n self.special_login_handler()\r\n if self.verbose:\r\n print(\"Interactive SSH session established\")\r\n return \"\"\r\n\r\n def _test_channel_read(self, count=40, pattern=\"\"):\r\n\r\n def _increment_delay(main_delay, increment=1.1, maximum=8):\r\n \"\"\"Increment sleep time to a maximum value.\"\"\"\r\n main_delay = main_delay * increment\r\n if main_delay >= maximum:\r\n main_delay = maximum\r\n return main_delay\r\n\r\n i = 0\r\n delay_factor = self.select_delay_factor(delay_factor=0)\r\n main_delay = delay_factor * 0.1\r\n time.sleep(main_delay * 10)\r\n new_data = \"\"\r\n while i <= count:\r\n new_data += self._read_channel_timing()\r\n if new_data and pattern:\r\n if re.search(pattern, new_data):\r\n break\r\n elif new_data:\r\n break\r\n else:\r\n self.write_channel(self.RETURN)\r\n main_delay = _increment_delay(main_delay)\r\n time.sleep(main_delay)\r\n i += 1\r\n\r\n # check if data was ever present\r\n if new_data:\r\n return new_data\r\n else:\r\n raise Net_ConnectTimeoutException(\"Timed out waiting for data\")\r\n\r\n def _build_ssh_client(self):\r\n \"\"\"Prepare for Paramiko SSH connection.\"\"\"\r\n # Create instance of SSHClient object\r\n remote_conn_pre = paramiko.SSHClient()\r\n\r\n # Load host_keys for better SSH security\r\n if self.system_host_keys:\r\n remote_conn_pre.load_system_host_keys()\r\n if self.alt_host_keys and path.isfile(self.alt_key_file):\r\n remote_conn_pre.load_host_keys(self.alt_key_file)\r\n\r\n # Default is to automatically add untrusted hosts (make sure appropriate for your env)\r\n remote_conn_pre.set_missing_host_key_policy(self.key_policy)\r\n return remote_conn_pre\r\n\r\n def select_delay_factor(self, delay_factor):\r\n if self.fast_cli:\r\n if delay_factor <= self.global_delay_factor:\r\n return delay_factor\r\n else:\r\n return self.global_delay_factor\r\n else:\r\n if delay_factor >= self.global_delay_factor:\r\n return delay_factor\r\n else:\r\n return self.global_delay_factor\r\n\r\n def special_login_handler(self, delay_factor=5):\r\n \"\"\"Handler for devices like WLC, Extreme ERS that throw up characters prior to login.\"\"\"\r\n pass\r\n\r\n def disable_paging(self, command=\"terminal length 0\", delay_factor=5):\r\n\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n time.sleep(delay_factor * 0.1)\r\n self.clear_buffer()\r\n command = self.normalize_cmd(command)\r\n log.debug(\"In disable_paging\")\r\n log.debug(\"Command: {0}\".format(command))\r\n self.write_channel(command)\r\n output = self.read_until_prompt()\r\n if self.ansi_escape_codes:\r\n output = self.strip_ansi_escape_codes(output)\r\n log.debug(\"{0}\".format(output))\r\n log.debug(\"Exiting disable_paging\")\r\n return output\r\n\r\n def set_terminal_width(self, command=\"\", delay_factor=5):\r\n if not command:\r\n return \"\"\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n command = self.normalize_cmd(command)\r\n self.write_channel(command)\r\n output = self.read_until_prompt()\r\n if self.ansi_escape_codes:\r\n output = self.strip_ansi_escape_codes(output)\r\n return output\r\n\r\n def set_base_prompt(\r\n self, pri_prompt_terminator=\"#\", alt_prompt_terminator=\">\", delay_factor=5\r\n ):\r\n\r\n prompt = self.find_prompt(delay_factor=delay_factor)\r\n if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):\r\n raise ValueError(\"Router prompt not found: {0}\".format(repr(prompt)))\r\n # Strip off trailing terminator\r\n self.base_prompt = prompt[:-1]\r\n return self.base_prompt\r\n\r\n def find_prompt(self, delay_factor=5):\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n self.clear_buffer()\r\n self.write_channel(self.RETURN)\r\n time.sleep(delay_factor * 0.1)\r\n\r\n # Initial attempt to get prompt\r\n prompt = self.read_channel()\r\n if self.ansi_escape_codes:\r\n prompt = self.strip_ansi_escape_codes(prompt)\r\n\r\n # Check if the only thing you received was a newline\r\n count = 0\r\n prompt = prompt.strip()\r\n while count <= 10 and not prompt:\r\n prompt = self.read_channel().strip()\r\n if prompt:\r\n if self.ansi_escape_codes:\r\n prompt = self.strip_ansi_escape_codes(prompt).strip()\r\n else:\r\n self.write_channel(self.RETURN)\r\n time.sleep(delay_factor * 0.1)\r\n count += 1\r\n\r\n # If multiple lines in the output take the last line\r\n prompt = self.normalize_linefeeds(prompt)\r\n prompt = prompt.split(self.RESPONSE_RETURN)[-1]\r\n prompt = prompt.strip()\r\n if not prompt:\r\n raise ValueError(\"Unable to find prompt: {}\".format(prompt))\r\n time.sleep(delay_factor * 0.1)\r\n self.clear_buffer()\r\n return prompt\r\n\r\n def clear_buffer(self):\r\n \"\"\"Read any data available in the channel.\"\"\"\r\n self.read_channel()\r\n\r\n def send_command_timing(\r\n self,\r\n command_string,\r\n delay_factor=5,\r\n max_loops=150,\r\n strip_prompt=True,\r\n strip_command=True,\r\n normalize=True,\r\n use_textfsm=False,\r\n use_genie=False,\r\n ):\r\n\r\n output = \"\"\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n self.clear_buffer()\r\n if normalize:\r\n command_string = self.normalize_cmd(command_string)\r\n\r\n self.write_channel(command_string)\r\n output = self._read_channel_timing(\r\n delay_factor=delay_factor, max_loops=max_loops\r\n )\r\n output = self._sanitize_output(\r\n output,\r\n strip_command=strip_command,\r\n command_string=command_string,\r\n strip_prompt=strip_prompt,\r\n )\r\n # If both TextFSM and Genie are set, try TextFSM then Genie\r\n for parser_flag, parser_func in (\r\n (use_textfsm, get_structured_data),\r\n (use_genie, get_structured_data_genie),\r\n ):\r\n if parser_flag:\r\n structured_output = parser_func(\r\n output, platform=self.device_type, command=command_string.strip()\r\n )\r\n # If we have structured data; return it.\r\n if not isinstance(structured_output, string_types):\r\n return structured_output\r\n return output\r\n\r\n def strip_prompt(self, a_string):\r\n\r\n response_list = a_string.split(self.RESPONSE_RETURN)\r\n last_line = response_list[-1]\r\n if self.base_prompt in last_line:\r\n return self.RESPONSE_RETURN.join(response_list[:-1])\r\n else:\r\n return a_string\r\n\r\n def _first_line_handler(self, data, search_pattern):\r\n\r\n try:\r\n # First line is the echo line containing the command. In certain situations\r\n # it gets repainted and needs filtered\r\n lines = data.split(self.RETURN)\r\n first_line = lines[0]\r\n if BACKSPACE_CHAR in first_line:\r\n pattern = search_pattern + r\".*$\"\r\n first_line = re.sub(pattern, repl=\"\", string=first_line)\r\n lines[0] = first_line\r\n data = self.RETURN.join(lines)\r\n return (data, True)\r\n except IndexError:\r\n return (data, False)\r\n\r\n def send_command(\r\n self,\r\n command_string,\r\n expect_string=None,\r\n delay_factor=5,\r\n max_loops=500,\r\n auto_find_prompt=True,\r\n strip_prompt=True,\r\n strip_command=True,\r\n normalize=True,\r\n use_textfsm=False,\r\n use_genie=False,\r\n ):\r\n\r\n # Time to delay in each read loop\r\n loop_delay = 0.2\r\n\r\n # Default to making loop time be roughly equivalent to self.timeout (support old max_loops\r\n # and delay_factor arguments for backwards compatibility).\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n if delay_factor == 1 and max_loops == 500:\r\n # Default arguments are being used; use self.timeout instead\r\n max_loops = int(self.timeout / loop_delay)\r\n\r\n # Find the current router prompt\r\n if expect_string is None:\r\n if auto_find_prompt:\r\n try:\r\n prompt = self.find_prompt(delay_factor=delay_factor)\r\n except ValueError:\r\n prompt = self.base_prompt\r\n else:\r\n prompt = self.base_prompt\r\n search_pattern = re.escape(prompt.strip())\r\n else:\r\n search_pattern = expect_string\r\n\r\n if normalize:\r\n command_string = self.normalize_cmd(command_string)\r\n\r\n time.sleep(delay_factor * loop_delay)\r\n self.clear_buffer()\r\n self.write_channel(command_string)\r\n\r\n i = 1\r\n output = \"\"\r\n past_three_reads = deque(maxlen=3)\r\n first_line_processed = False\r\n\r\n # Keep reading data until search_pattern is found or until max_loops is reached.\r\n while i <= max_loops:\r\n new_data = self.read_channel()\r\n if new_data:\r\n if self.ansi_escape_codes:\r\n new_data = self.strip_ansi_escape_codes(new_data)\r\n\r\n output += new_data\r\n past_three_reads.append(new_data)\r\n\r\n # Case where we haven't processed the first_line yet (there is a potential issue\r\n # in the first line (in cases where the line is repainted).\r\n if not first_line_processed:\r\n output, first_line_processed = self._first_line_handler(\r\n output, search_pattern\r\n )\r\n # Check if we have already found our pattern\r\n if re.search(search_pattern, output):\r\n break\r\n\r\n else:\r\n # Check if pattern is in the past three reads\r\n if re.search(search_pattern, \"\".join(past_three_reads)):\r\n break\r\n\r\n time.sleep(delay_factor * loop_delay)\r\n i += 1\r\n else: # nobreak\r\n raise IOError(\r\n \"Search pattern never detected in send_command_expect: {}\".format(\r\n search_pattern\r\n )\r\n )\r\n\r\n output = self._sanitize_output(\r\n output,\r\n strip_command=strip_command,\r\n command_string=command_string,\r\n strip_prompt=strip_prompt,\r\n )\r\n\r\n # If both TextFSM and Genie are set, try TextFSM then Genie\r\n for parser_flag, parser_func in (\r\n (use_textfsm, get_structured_data),\r\n (use_genie, get_structured_data_genie),\r\n ):\r\n if parser_flag:\r\n structured_output = parser_func(\r\n output, platform=self.device_type, command=command_string.strip()\r\n )\r\n # If we have structured data; return it.\r\n if not isinstance(structured_output, string_types):\r\n return structured_output\r\n return output\r\n\r\n def send_command_expect(self, *args, **kwargs):\r\n\r\n return self.send_command(*args, **kwargs)\r\n\r\n @staticmethod\r\n def strip_backspaces(output):\r\n backspace_char = \"\\x08\"\r\n return output.replace(backspace_char, \"\")\r\n\r\n def strip_command(self, command_string, output):\r\n backspace_char = \"\\x08\"\r\n\r\n # Check for line wrap (remove backspaces)\r\n if backspace_char in output:\r\n output = output.replace(backspace_char, \"\")\r\n output_lines = output.split(self.RESPONSE_RETURN)\r\n new_output = output_lines[1:]\r\n return self.RESPONSE_RETURN.join(new_output)\r\n else:\r\n command_length = len(command_string)\r\n return output[command_length:]\r\n\r\n def normalize_linefeeds(self, a_string):\r\n newline = re.compile(\"(\\r\\r\\r\\n|\\r\\r\\n|\\r\\n|\\n\\r)\")\r\n a_string = newline.sub(self.RESPONSE_RETURN, a_string)\r\n if self.RESPONSE_RETURN == \"\\n\":\r\n # Convert any remaining \\r to \\n\r\n return re.sub(\"\\r\", self.RESPONSE_RETURN, a_string)\r\n else:\r\n return a_string\r\n\r\n def normalize_cmd(self, command):\r\n command = command.rstrip()\r\n command += self.RETURN\r\n return command\r\n\r\n def check_enable_mode(self, check_string=\"\"):\r\n self.write_channel(self.RETURN)\r\n output = self.read_until_prompt()\r\n return check_string in output\r\n\r\n def enable(self, cmd=\"\", pattern=\"ssword\", re_flags=re.IGNORECASE):\r\n output = \"\"\r\n msg = (\r\n \"Failed to enter enable mode. Please ensure you pass \"\r\n \"the 'secret' argument to ConnectHandler.\"\r\n )\r\n if not self.check_enable_mode():\r\n self.write_channel(self.normalize_cmd(cmd))\r\n try:\r\n output += self.read_until_prompt_or_pattern(\r\n pattern=pattern, re_flags=re_flags\r\n )\r\n self.write_channel(self.normalize_cmd(self.secret))\r\n output += self.read_until_prompt()\r\n except Net_ConnectTimeoutException:\r\n raise ValueError(msg)\r\n if not self.check_enable_mode():\r\n raise ValueError(msg)\r\n return output\r\n\r\n def exit_enable_mode(self, exit_command=\"\"):\r\n output = \"\"\r\n if self.check_enable_mode():\r\n self.write_channel(self.normalize_cmd(exit_command))\r\n output += self.read_until_prompt()\r\n if self.check_enable_mode():\r\n raise ValueError(\"Failed to exit enable mode.\")\r\n return output\r\n\r\n def check_config_mode(self, check_string=\"\", pattern=\"\"):\r\n self.write_channel(self.RETURN)\r\n # You can encounter an issue here (on router name changes) prefer delay-based solution\r\n if not pattern:\r\n output = self._read_channel_timing()\r\n else:\r\n output = self.read_until_pattern(pattern=pattern)\r\n return check_string in output\r\n\r\n def config_mode(self, config_command=\"\", pattern=\"\"):\r\n output = \"\"\r\n if not self.check_config_mode():\r\n self.write_channel(self.normalize_cmd(config_command))\r\n output = self.read_until_pattern(pattern=pattern)\r\n if not self.check_config_mode():\r\n raise ValueError(\"Failed to enter configuration mode.\")\r\n return output\r\n\r\n def exit_config_mode(self, exit_config=\"\", pattern=\"\"):\r\n output = \"\"\r\n if self.check_config_mode():\r\n self.write_channel(self.normalize_cmd(exit_config))\r\n output = self.read_until_pattern(pattern=pattern)\r\n if self.check_config_mode():\r\n raise ValueError(\"Failed to exit configuration mode\")\r\n log.debug(\"exit_config_mode: {}\".format(output))\r\n return output\r\n\r\n def send_config_from_file(self, config_file=None, **kwargs):\r\n with io.open(config_file, \"rt\", encoding=\"utf-8\") as cfg_file:\r\n return self.send_config_set(cfg_file, **kwargs)\r\n\r\n def send_config_set(\r\n self,\r\n config_commands=None,\r\n exit_config_mode=True,\r\n delay_factor=1,\r\n max_loops=150,\r\n strip_prompt=False,\r\n strip_command=False,\r\n config_mode_command=None,\r\n ):\r\n\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n if config_commands is None:\r\n return \"\"\r\n elif isinstance(config_commands, string_types):\r\n config_commands = (config_commands,)\r\n\r\n if not hasattr(config_commands, \"__iter__\"):\r\n raise ValueError(\"Invalid argument passed into send_config_set\")\r\n\r\n # Send config commands\r\n cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()\r\n output = self.config_mode(*cfg_mode_args)\r\n for cmd in config_commands:\r\n self.write_channel(self.normalize_cmd(cmd))\r\n if self.fast_cli:\r\n pass\r\n else:\r\n time.sleep(delay_factor * 0.05)\r\n\r\n # Gather output\r\n output += self._read_channel_timing(\r\n delay_factor=delay_factor, max_loops=max_loops\r\n )\r\n if exit_config_mode:\r\n output += self.exit_config_mode()\r\n output = self._sanitize_output(output)\r\n log.debug(\"{}\".format(output))\r\n return output\r\n\r\n def strip_ansi_escape_codes(self, string_buffer):\r\n log.debug(\"In strip_ansi_escape_codes\")\r\n log.debug(\"repr = {}\".format(repr(string_buffer)))\r\n\r\n code_position_cursor = chr(27) + r\"\\[\\d+;\\d+H\"\r\n code_show_cursor = chr(27) + r\"\\[\\?25h\"\r\n code_next_line = chr(27) + r\"E\"\r\n code_erase_line_end = chr(27) + r\"\\[K\"\r\n code_erase_line = chr(27) + r\"\\[2K\"\r\n code_erase_start_line = chr(27) + r\"\\[K\"\r\n code_enable_scroll = chr(27) + r\"\\[\\d+;\\d+r\"\r\n code_form_feed = chr(27) + r\"\\[1L\"\r\n code_carriage_return = chr(27) + r\"\\[1M\"\r\n code_disable_line_wrapping = chr(27) + r\"\\[\\?7l\"\r\n code_reset_mode_screen_options = chr(27) + r\"\\[\\?\\d+l\"\r\n code_reset_graphics_mode = chr(27) + r\"\\[00m\"\r\n code_erase_display = chr(27) + r\"\\[2J\"\r\n code_graphics_mode = chr(27) + r\"\\[\\d\\d;\\d\\dm\"\r\n code_graphics_mode2 = chr(27) + r\"\\[\\d\\d;\\d\\d;\\d\\dm\"\r\n code_graphics_mode3 = chr(27) + r\"\\[(3|4)\\dm\"\r\n code_graphics_mode4 = chr(27) + r\"\\[(9|10)[0-7]m\"\r\n code_get_cursor_position = chr(27) + r\"\\[6n\"\r\n code_cursor_position = chr(27) + r\"\\[m\"\r\n code_erase_display = chr(27) + r\"\\[J\"\r\n code_attrs_off = chr(27) + r\"\\[0m\"\r\n code_reverse = chr(27) + r\"\\[7m\"\r\n\r\n code_set = [\r\n code_position_cursor,\r\n code_show_cursor,\r\n code_erase_line,\r\n code_enable_scroll,\r\n code_erase_start_line,\r\n code_form_feed,\r\n code_carriage_return,\r\n code_disable_line_wrapping,\r\n code_erase_line_end,\r\n code_reset_mode_screen_options,\r\n code_reset_graphics_mode,\r\n code_erase_display,\r\n code_graphics_mode,\r\n code_graphics_mode2,\r\n code_graphics_mode3,\r\n code_graphics_mode4,\r\n code_get_cursor_position,\r\n code_cursor_position,\r\n code_erase_display,\r\n code_attrs_off,\r\n code_reverse,\r\n ]\r\n\r\n output = string_buffer\r\n for ansi_esc_code in code_set:\r\n output = re.sub(ansi_esc_code, \"\", output)\r\n\r\n # CODE_NEXT_LINE must substitute with return\r\n output = re.sub(code_next_line, self.RETURN, output)\r\n\r\n log.debug(\"new_output = {0}\".format(output))\r\n log.debug(\"repr = {0}\".format(repr(output)))\r\n\r\n return output\r\n\r\n def cleanup(self):\r\n \"\"\"Any needed cleanup before closing connection.\"\"\"\r\n pass\r\n\r\n def paramiko_cleanup(self):\r\n \"\"\"Cleanup Paramiko to try to gracefully handle SSH session ending.\"\"\"\r\n self.remote_conn_pre.close()\r\n del self.remote_conn_pre\r\n\r\n def disconnect(self):\r\n \"\"\"Try to gracefully close the SSH connection.\"\"\"\r\n try:\r\n self.cleanup()\r\n if self.protocol == \"ssh\":\r\n self.paramiko_cleanup()\r\n elif self.protocol == \"telnet\":\r\n self.remote_conn.close()\r\n except Exception:\r\n # There have been race conditions observed on disconnect.\r\n pass\r\n finally:\r\n self.remote_conn_pre = None\r\n self.remote_conn = None\r\n self.close_session_log()\r\n\r\n def commit(self):\r\n \"\"\"Commit method for platforms that support this.\"\"\"\r\n raise AttributeError(\"Network device does not support 'commit()' method\")\r\n\r\n def save_config(self, *args, **kwargs):\r\n \"\"\"Not Implemented\"\"\"\r\n raise NotImplementedError\r\n\r\n def open_session_log(self, filename, mode=\"write\"):\r\n \"\"\"Open the session_log file.\"\"\"\r\n if mode == \"append\":\r\n self.session_log = open(filename, mode=\"ab\")\r\n else:\r\n self.session_log = open(filename, mode=\"wb\")\r\n self._session_log_close = True\r\n\r\n def close_session_log(self):\r\n \"\"\"Close the session_log file (if it is a file that we opened).\"\"\"\r\n if self.session_log is not None and self._session_log_close:\r\n self.session_log.close()\r\n self.session_log = None\r\n\r\nclass TerminalServer(BaseConnection):\r\n \"\"\"Generic Terminal Server driver.\r\n\r\n Allow direct write_channel / read_channel operations without session_preparation causing\r\n an exception.\r\n \"\"\"\r\n\r\n def session_preparation(self):\r\n \"\"\"Do nothing here; base_prompt is not set; paging is not disabled.\"\"\"\r\n pass\r\n\r\nclass TerminalServerSSH(TerminalServer):\r\n \"\"\"Generic Terminal Server driver SSH.\"\"\"\r\n pass\r\n\r\nclass BaseFileTransfer(object):\r\n \"\"\"Class to manage SCP file transfer and associated SSH control channel.\"\"\"\r\n def __init__(\r\n self, ssh_conn, source_file, dest_file, file_system=None, direction=\"put\"\r\n ):\r\n self.ssh_ctl_chan = ssh_conn\r\n self.source_file = source_file\r\n self.dest_file = dest_file\r\n self.direction = direction\r\n\r\n auto_flag = (\r\n \"cisco_ios\" in ssh_conn.device_type\r\n or \"cisco_xe\" in ssh_conn.device_type\r\n or \"cisco_xr\" in ssh_conn.device_type\r\n )\r\n if not file_system:\r\n if auto_flag:\r\n self.file_system = self.ssh_ctl_chan._autodetect_fs()\r\n else:\r\n raise ValueError(\"Destination file system not specified\")\r\n else:\r\n self.file_system = file_system\r\n\r\n if direction == \"put\":\r\n self.source_md5 = self.file_md5(source_file)\r\n self.file_size = os.stat(source_file).st_size\r\n elif direction == \"get\":\r\n self.source_md5 = self.remote_md5(remote_file=source_file)\r\n self.file_size = self.remote_file_size(remote_file=source_file)\r\n else:\r\n raise ValueError(\"Invalid direction specified\")\r\n\r\n def __enter__(self):\r\n \"\"\"Context manager setup\"\"\"\r\n self.establish_scp_conn()\r\n return self\r\n\r\n def __exit__(self, exc_type, exc_value, traceback):\r\n \"\"\"Context manager cleanup.\"\"\"\r\n self.close_scp_chan()\r\n\r\n def establish_scp_conn(self):\r\n \"\"\"Establish SCP connection.\"\"\"\r\n self.scp_conn = SCPConn(self.ssh_ctl_chan)\r\n\r\n def close_scp_chan(self):\r\n \"\"\"Close the SCP connection to the remote network device.\"\"\"\r\n self.scp_conn.close()\r\n self.scp_conn = None\r\n\r\n def remote_space_available(self, search_pattern=r\"(\\d+) \\w+ free\"):\r\n \"\"\"Return space available on remote device.\"\"\"\r\n remote_cmd = \"dir {}\".format(self.file_system)\r\n remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd)\r\n match = re.search(search_pattern, remote_output)\r\n if \"kbytes\" in match.group(0) or \"Kbytes\" in match.group(0):\r\n return int(match.group(1)) * 1000\r\n return int(match.group(1))\r\n\r\n def _remote_space_available_unix(self, search_pattern=\"\"):\r\n \"\"\"Return space available on *nix system (BSD/Linux).\"\"\"\r\n self.ssh_ctl_chan._enter_shell()\r\n remote_cmd = \"/bin/df -k {}\".format(self.file_system)\r\n remote_output = self.ssh_ctl_chan.send_command(\r\n remote_cmd, expect_string=r\"[\\$#]\"\r\n )\r\n\r\n # Try to ensure parsing is correct:\r\n # Filesystem 1K-blocks Used Avail Capacity Mounted on\r\n # /dev/bo0s3f 1264808 16376 1147248 1% /cf/var\r\n remote_output = remote_output.strip()\r\n output_lines = remote_output.splitlines()\r\n\r\n # First line is the header; second is the actual file system info\r\n header_line = output_lines[0]\r\n filesystem_line = output_lines[1]\r\n\r\n if \"Filesystem\" not in header_line or \"Avail\" not in header_line.split()[3]:\r\n # Filesystem 1K-blocks Used Avail Capacity Mounted on\r\n msg = \"Parsing error, unexpected output from {}:\\n{}\".format(\r\n remote_cmd, remote_output\r\n )\r\n raise ValueError(msg)\r\n\r\n space_available = filesystem_line.split()[3]\r\n if not re.search(r\"^\\d+$\", space_available):\r\n msg = \"Parsing error, unexpected output from {}:\\n{}\".format(\r\n remote_cmd, remote_output\r\n )\r\n raise ValueError(msg)\r\n\r\n self.ssh_ctl_chan._return_cli()\r\n return int(space_available) * 1024\r\n\r\n def local_space_available(self):\r\n \"\"\"Return space available on local filesystem.\"\"\"\r\n destination_stats = os.statvfs(\".\")\r\n return destination_stats.f_bsize * destination_stats.f_bavail\r\n\r\n def verify_space_available(self, search_pattern=r\"(\\d+) \\w+ free\"):\r\n \"\"\"Verify sufficient space is available on destination file system (return boolean).\"\"\"\r\n if self.direction == \"put\":\r\n space_avail = self.remote_space_available(search_pattern=search_pattern)\r\n elif self.direction == \"get\":\r\n space_avail = self.local_space_available()\r\n if space_avail > self.file_size:\r\n return True\r\n return False\r\n\r\n def check_file_exists(self, remote_cmd=\"\"):\r\n \"\"\"Check if the dest_file already exists on the file system (return boolean).\"\"\"\r\n if self.direction == \"put\":\r\n if not remote_cmd:\r\n remote_cmd = \"dir {}/{}\".format(self.file_system, self.dest_file)\r\n remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)\r\n search_string = r\"Directory of .*{0}\".format(self.dest_file)\r\n if (\r\n \"Error opening\" in remote_out\r\n or \"No such file or directory\" in remote_out\r\n or \"Path does not exist\" in remote_out\r\n ):\r\n return False\r\n elif re.search(search_string, remote_out, flags=re.DOTALL):\r\n return True\r\n else:\r\n raise ValueError(\"Unexpected output from check_file_exists\")\r\n elif self.direction == \"get\":\r\n return os.path.exists(self.dest_file)\r\n\r\n def _check_file_exists_unix(self, remote_cmd=\"\"):\r\n \"\"\"Check if the dest_file already exists on the file system (return boolean).\"\"\"\r\n if self.direction == \"put\":\r\n self.ssh_ctl_chan._enter_shell()\r\n remote_cmd = \"ls {}\".format(self.file_system)\r\n remote_out = self.ssh_ctl_chan.send_command(\r\n remote_cmd, expect_string=r\"[\\$#]\"\r\n )\r\n self.ssh_ctl_chan._return_cli()\r\n return self.dest_file in remote_out\r\n elif self.direction == \"get\":\r\n return os.path.exists(self.dest_file)\r\n\r\n def remote_file_size(self, remote_cmd=\"\", remote_file=None):\r\n \"\"\"Get the file size of the remote file.\"\"\"\r\n if remote_file is None:\r\n if self.direction == \"put\":\r\n remote_file = self.dest_file\r\n elif self.direction == \"get\":\r\n remote_file = self.source_file\r\n if not remote_cmd:\r\n remote_cmd = \"dir {}/{}\".format(self.file_system, remote_file)\r\n remote_out = self.ssh_ctl_chan.send_command(remote_cmd)\r\n # Strip out \"Directory of flash:/filename line\r\n remote_out = re.split(r\"Directory of .*\", remote_out)\r\n remote_out = \"\".join(remote_out)\r\n # Match line containing file name\r\n escape_file_name = re.escape(remote_file)\r\n pattern = r\".*({}).*\".format(escape_file_name)\r\n match = re.search(pattern, remote_out)\r\n if match:\r\n line = match.group(0)\r\n # Format will be 26 -rw- 6738 Jul 30 2016 19:49:50 -07:00 filename\r\n file_size = line.split()[2]\r\n if \"Error opening\" in remote_out or \"No such file or directory\" in remote_out:\r\n raise IOError(\"Unable to find file on remote system\")\r\n else:\r\n return int(file_size)\r\n\r\n def _remote_file_size_unix(self, remote_cmd=\"\", remote_file=None):\r\n \"\"\"Get the file size of the remote file.\"\"\"\r\n if remote_file is None:\r\n if self.direction == \"put\":\r\n remote_file = self.dest_file\r\n elif self.direction == \"get\":\r\n remote_file = self.source_file\r\n remote_file = \"{}/{}\".format(self.file_system, remote_file)\r\n if not remote_cmd:\r\n remote_cmd = \"ls -l {}\".format(remote_file)\r\n\r\n self.ssh_ctl_chan._enter_shell()\r\n remote_out = self.ssh_ctl_chan.send_command(remote_cmd, expect_string=r\"[\\$#]\")\r\n self.ssh_ctl_chan._return_cli()\r\n\r\n if \"No such file or directory\" in remote_out:\r\n raise IOError(\"Unable to find file on remote system\")\r\n\r\n escape_file_name = re.escape(remote_file)\r\n pattern = r\"^.* ({}).*$\".format(escape_file_name)\r\n match = re.search(pattern, remote_out, flags=re.M)\r\n if match:\r\n # Format: -rw-r--r-- 1 pyclass wheel 12 Nov 5 19:07 /var/tmp/test3.txt\r\n line = match.group(0)\r\n file_size = line.split()[4]\r\n return int(file_size)\r\n\r\n raise ValueError(\r\n \"Search pattern not found for remote file size during SCP transfer.\"\r\n )\r\n\r\n def file_md5(self, file_name):\r\n \"\"\"Compute MD5 hash of file.\"\"\"\r\n with open(file_name, \"rb\") as f:\r\n file_contents = f.read()\r\n file_hash = hashlib.md5(file_contents).hexdigest()\r\n return file_hash\r\n\r\n @staticmethod\r\n def process_md5(md5_output, pattern=r\"=\\s+(\\S+)\"):\r\n match = re.search(pattern, md5_output)\r\n if match:\r\n return match.group(1)\r\n else:\r\n raise ValueError(\"Invalid output from MD5 command: {}\".format(md5_output))\r\n\r\n def compare_md5(self):\r\n \"\"\"Compare md5 of file on network device to md5 of local file.\"\"\"\r\n if self.direction == \"put\":\r\n remote_md5 = self.remote_md5()\r\n return self.source_md5 == remote_md5\r\n elif self.direction == \"get\":\r\n local_md5 = self.file_md5(self.dest_file)\r\n return self.source_md5 == local_md5\r\n\r\n def remote_md5(self, base_cmd=\"verify /md5\", remote_file=None):\r\n \"\"\"Calculate remote MD5 and returns the hash.\r\n\r\n This command can be CPU intensive on the remote device.\r\n \"\"\"\r\n if remote_file is None:\r\n if self.direction == \"put\":\r\n remote_file = self.dest_file\r\n elif self.direction == \"get\":\r\n remote_file = self.source_file\r\n remote_md5_cmd = \"{} {}/{}\".format(base_cmd, self.file_system, remote_file)\r\n dest_md5 = self.ssh_ctl_chan.send_command(remote_md5_cmd, max_loops=1500)\r\n dest_md5 = self.process_md5(dest_md5)\r\n return dest_md5\r\n\r\n def transfer_file(self):\r\n \"\"\"SCP transfer file.\"\"\"\r\n if self.direction == \"put\":\r\n self.put_file()\r\n elif self.direction == \"get\":\r\n self.get_file()\r\n\r\n def get_file(self):\r\n \"\"\"SCP copy the file from the remote device to local system.\"\"\"\r\n source_file = \"{}/{}\".format(self.file_system, self.source_file)\r\n self.scp_conn.scp_get_file(source_file, self.dest_file)\r\n self.scp_conn.close()\r\n\r\n def put_file(self):\r\n \"\"\"SCP copy the file from the local system to the remote device.\"\"\"\r\n destination = \"{}/{}\".format(self.file_system, self.dest_file)\r\n self.scp_conn.scp_transfer_file(self.source_file, destination)\r\n # Must close the SCP connection to get the file written (flush)\r\n self.scp_conn.close()\r\n\r\n def verify_file(self):\r\n \"\"\"Verify the file has been transferred correctly.\"\"\"\r\n return self.compare_md5()\r\n\r\n def enable_scp(self, cmd=None):\r\n \"\"\"\r\n Enable SCP on remote device.\r\n\r\n Defaults to Cisco IOS command\r\n \"\"\"\r\n if cmd is None:\r\n cmd = [\"ip scp server enable\"]\r\n elif not hasattr(cmd, \"__iter__\"):\r\n cmd = [cmd]\r\n self.ssh_ctl_chan.send_config_set(cmd)\r\n\r\n def disable_scp(self, cmd=None):\r\n \"\"\"\r\n Disable SCP on remote device.\r\n\r\n Defaults to Cisco IOS command\r\n \"\"\"\r\n if cmd is None:\r\n cmd = [\"no ip scp server enable\"]\r\n elif not hasattr(cmd, \"__iter__\"):\r\n cmd = [cmd]\r\n self.ssh_ctl_chan.send_config_set(cmd)\r\n\r\nclass CiscoFileTransfer(BaseFileTransfer):\r\n pass\r\n\r\nclass LinuxFileTransfer(CiscoFileTransfer):\r\n \"\"\"\r\n Linux SCP File Transfer driver.\r\n\r\n Mostly for testing purposes.\r\n \"\"\"\r\n def __init__(\r\n self, ssh_conn, source_file, dest_file, file_system=\"/var/tmp\", direction=\"put\"\r\n ):\r\n return super(LinuxFileTransfer, self).__init__(\r\n ssh_conn=ssh_conn,\r\n source_file=source_file,\r\n dest_file=dest_file,\r\n file_system=file_system,\r\n direction=direction,\r\n )\r\n\r\n def remote_space_available(self, search_pattern=\"\"):\r\n \"\"\"Return space available on remote device.\"\"\"\r\n return self._remote_space_available_unix(search_pattern=search_pattern)\r\n\r\n def check_file_exists(self, remote_cmd=\"\"):\r\n \"\"\"Check if the dest_file already exists on the file system (return boolean).\"\"\"\r\n return self._check_file_exists_unix(remote_cmd=remote_cmd)\r\n\r\n def remote_file_size(self, remote_cmd=\"\", remote_file=None):\r\n \"\"\"Get the file size of the remote file.\"\"\"\r\n return self._remote_file_size_unix(\r\n remote_cmd=remote_cmd, remote_file=remote_file\r\n )\r\n\r\n def remote_md5(self, base_cmd=\"md5sum\", remote_file=None):\r\n if remote_file is None:\r\n if self.direction == \"put\":\r\n remote_file = self.dest_file\r\n elif self.direction == \"get\":\r\n remote_file = self.source_file\r\n remote_md5_cmd = \"{} {}/{}\".format(base_cmd, self.file_system, remote_file)\r\n dest_md5 = self.ssh_ctl_chan.send_command(\r\n remote_md5_cmd, max_loops=750, delay_factor=5\r\n )\r\n dest_md5 = self.process_md5(dest_md5)\r\n return dest_md5\r\n\r\n @staticmethod\r\n def process_md5(md5_output, pattern=r\"^(\\S+)\\s+\"):\r\n return super(LinuxFileTransfer, LinuxFileTransfer).process_md5(\r\n md5_output, pattern=pattern\r\n )\r\n\r\n def enable_scp(self, cmd=None):\r\n raise NotImplementedError\r\n\r\n def disable_scp(self, cmd=None):\r\n raise NotImplementedError\r\n\r\nclass CiscoBaseConnection(BaseConnection):\r\n \"\"\"Base Class for cisco-like behavior.\"\"\"\r\n def check_enable_mode(self, check_string=\"#\"):\r\n \"\"\"Check if in enable mode. Return boolean.\"\"\"\r\n return super(CiscoBaseConnection, self).check_enable_mode(\r\n check_string=check_string\r\n )\r\n\r\n def enable(self, cmd=\"enable\", pattern=\"ssword\", re_flags=re.IGNORECASE):\r\n \"\"\"Enter enable mode.\"\"\"\r\n return super(CiscoBaseConnection, self).enable(\r\n cmd=cmd, pattern=pattern, re_flags=re_flags\r\n )\r\n\r\n def exit_enable_mode(self, exit_command=\"disable\"):\r\n \"\"\"Exits enable (privileged exec) mode.\"\"\"\r\n return super(CiscoBaseConnection, self).exit_enable_mode(\r\n exit_command=exit_command\r\n )\r\n\r\n def check_config_mode(self, check_string=\")#\", pattern=\"\"):\r\n \"\"\"\r\n Checks if the device is in configuration mode or not.\r\n\r\n Cisco IOS devices abbreviate the prompt at 20 chars in config mode\r\n \"\"\"\r\n return super(CiscoBaseConnection, self).check_config_mode(\r\n check_string=check_string, pattern=pattern\r\n )\r\n\r\n def config_mode(self, config_command=\"config term\", pattern=\"\"):\r\n \"\"\"\r\n Enter into configuration mode on remote device.\r\n\r\n Cisco IOS devices abbreviate the prompt at 20 chars in config mode\r\n \"\"\"\r\n if not pattern:\r\n pattern = re.escape(self.base_prompt[:16])\r\n return super(CiscoBaseConnection, self).config_mode(\r\n config_command=config_command, pattern=pattern\r\n )\r\n\r\n def exit_config_mode(self, exit_config=\"end\", pattern=\"#\"):\r\n \"\"\"Exit from configuration mode.\"\"\"\r\n return super(CiscoBaseConnection, self).exit_config_mode(\r\n exit_config=exit_config, pattern=pattern\r\n )\r\n\r\n\r\n def telnet_login(\r\n self,\r\n pri_prompt_terminator=r\"#\\s*$\",\r\n alt_prompt_terminator=r\">\\s*$\",\r\n username_pattern=r\"(?:user:|username|login|user name)\",\r\n pwd_pattern=r\"assword\",\r\n delay_factor=5,\r\n max_loops=20,\r\n ):\r\n \"\"\"Telnet login. Can be username/password or just password.\"\"\"\r\n delay_factor = self.select_delay_factor(delay_factor)\r\n time.sleep(1 * delay_factor)\r\n\r\n output = \"\"\r\n return_msg = \"\"\r\n i = 1\r\n while i <= max_loops:\r\n try:\r\n output = self.read_channel()\r\n return_msg += output\r\n\r\n # Search for username pattern / send username\r\n if re.search(username_pattern, output, flags=re.I):\r\n self.write_channel(self.username + self.TELNET_RETURN)\r\n time.sleep(1 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n\r\n # Search for password pattern / send password\r\n if re.search(pwd_pattern, output, flags=re.I):\r\n self.write_channel(self.password + self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(\r\n pri_prompt_terminator, output, flags=re.M\r\n ) or re.search(alt_prompt_terminator, output, flags=re.M):\r\n return return_msg\r\n\r\n # Support direct telnet through terminal server\r\n if re.search(r\"initial configuration dialog\\? \\[yes/no\\]: \", output):\r\n self.write_channel(\"no\" + self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n count = 0\r\n while count < 15:\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(r\"ress RETURN to get started\", output):\r\n output = \"\"\r\n break\r\n time.sleep(2 * delay_factor)\r\n count += 1\r\n\r\n # Check for device with no password configured\r\n if re.search(r\"assword required, but none set\", output):\r\n self.remote_conn.close()\r\n msg = \"Login failed - Password required, but none set: {}\".format(\r\n self.host\r\n )\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n # Check if proper data received\r\n if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(\r\n alt_prompt_terminator, output, flags=re.M\r\n ):\r\n return return_msg\r\n\r\n self.write_channel(self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n i += 1\r\n except EOFError:\r\n self.remote_conn.close()\r\n msg = \"Login failed: {}\".format(self.host)\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n # Last try to see if we already logged in\r\n self.write_channel(self.TELNET_RETURN)\r\n time.sleep(0.5 * delay_factor)\r\n output = self.read_channel()\r\n return_msg += output\r\n if re.search(pri_prompt_terminator, output, flags=re.M) or re.search(\r\n alt_prompt_terminator, output, flags=re.M\r\n ):\r\n return return_msg\r\n\r\n self.remote_conn.close()\r\n msg = \"Login failed: {}\".format(self.host)\r\n raise Net_ConnectAuthenticationException(msg)\r\n\r\n def cleanup(self):\r\n \"\"\"Gracefully exit the SSH session.\"\"\"\r\n try:\r\n self.exit_config_mode()\r\n except Exception:\r\n pass\r\n # Always try to send final 'exit' regardless of whether exit_config_mode works or not.\r\n self._session_log_fin = True\r\n self.write_channel(\"exit\" + self.RETURN)\r\n\r\n def _autodetect_fs(self, cmd=\"dir\", pattern=r\"Directory of (.*)/\"):\r\n \"\"\"Autodetect the file system on the remote device. Used by SCP operations.\"\"\"\r\n if not self.check_enable_mode():\r\n raise ValueError(\"Must be in enable mode to auto-detect the file-system.\")\r\n output = self.send_command_expect(cmd)\r\n match = re.search(pattern, output)\r\n if match:\r\n file_system = match.group(1)\r\n # Test file_system\r\n cmd = \"dir {}\".format(file_system)\r\n output = self.send_command_expect(cmd)\r\n if \"% Invalid\" in output or \"%Error:\" in output:\r\n raise ValueError(\r\n \"An error occurred in dynamically determining remote file \"\r\n \"system: {} {}\".format(cmd, output)\r\n )\r\n else:\r\n return file_system\r\n\r\n raise ValueError(\r\n \"An error occurred in dynamically determining remote file \"\r\n \"system: {} {}\".format(cmd, output)\r\n )\r\n\r\n def save_config(\r\n self,\r\n cmd=\"copy running-config startup-config\",\r\n confirm=False,\r\n confirm_response=\"\",\r\n ):\r\n \"\"\"Saves Config.\"\"\"\r\n self.enable()\r\n if confirm:\r\n output = self.send_command_timing(command_string=cmd)\r\n if confirm_response:\r\n output += self.send_command_timing(confirm_response)\r\n else:\r\n # Send enter by default\r\n output += self.send_command_timing(self.RETURN)\r\n else:\r\n # Some devices are slow so match on trailing-prompt if you can\r\n output = self.send_command(command_string=cmd)\r\n return output\r\n\r\nclass CiscoSSHConnection(CiscoBaseConnection):\r\n pass\r\n\r\nclass Net_ConnectTimeoutException(SSHException):\r\n \"\"\"SSH session timed trying to connect to the device.\"\"\"\r\n pass\r\n\r\nclass LinuxSSH(CiscoSSHConnection):\r\n\r\n def session_preparation(self):\r\n \"\"\"Prepare the session after the connection has been established.\"\"\"\r\n self.ansi_escape_codes = True\r\n return super(LinuxSSH, self).session_preparation()\r\n\r\n def _enter_shell(self):\r\n \"\"\"Already in shell.\"\"\"\r\n return \"\"\r\n\r\n def _return_cli(self):\r\n \"\"\"The shell is the CLI.\"\"\"\r\n return \"\"\r\n\r\n def disable_paging(self, *args, **kwargs):\r\n \"\"\"Linux doesn't have paging by default.\"\"\"\r\n return \"\"\r\n\r\n def set_base_prompt(\r\n self,\r\n pri_prompt_terminator=LINUX_PROMPT_PRI,\r\n alt_prompt_terminator=LINUX_PROMPT_ALT,\r\n delay_factor=1,\r\n ):\r\n \"\"\"Determine base prompt.\"\"\"\r\n return super(LinuxSSH, self).set_base_prompt(\r\n pri_prompt_terminator=pri_prompt_terminator,\r\n alt_prompt_terminator=alt_prompt_terminator,\r\n delay_factor=delay_factor,\r\n )\r\n\r\n def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):\r\n \"\"\"Can't exit from root (if root)\"\"\"\r\n if self.username == \"root\":\r\n exit_config_mode = False\r\n return super(LinuxSSH, self).send_config_set(\r\n config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs\r\n )\r\n\r\n def check_config_mode(self, check_string=LINUX_PROMPT_ROOT):\r\n \"\"\"Verify root\"\"\"\r\n return self.check_enable_mode(check_string=check_string)\r\n\r\n def config_mode(self, config_command=\"sudo su\"):\r\n \"\"\"Attempt to become root.\"\"\"\r\n return self.enable(cmd=config_command)\r\n\r\n def exit_config_mode(self, exit_config=\"exit\"):\r\n return self.exit_enable_mode(exit_command=exit_config)\r\n\r\n def check_enable_mode(self, check_string=LINUX_PROMPT_ROOT):\r\n \"\"\"Verify root\"\"\"\r\n return super(LinuxSSH, self).check_enable_mode(check_string=check_string)\r\n\r\n def exit_enable_mode(self, exit_command=\"exit\"):\r\n \"\"\"Exit enable mode.\"\"\"\r\n delay_factor = self.select_delay_factor(delay_factor=0)\r\n output = \"\"\r\n if self.check_enable_mode():\r\n self.write_channel(self.normalize_cmd(exit_command))\r\n time.sleep(0.3 * delay_factor)\r\n self.set_base_prompt()\r\n if self.check_enable_mode():\r\n raise ValueError(\"Failed to exit enable mode.\")\r\n return output\r\n\r\n def enable(self, cmd=\"sudo su\", pattern=\"ssword\", re_flags=re.IGNORECASE):\r\n \"\"\"Attempt to become root.\"\"\"\r\n delay_factor = self.select_delay_factor(delay_factor=0)\r\n output = \"\"\r\n if not self.check_enable_mode():\r\n self.write_channel(self.normalize_cmd(cmd))\r\n time.sleep(0.3 * delay_factor)\r\n try:\r\n output += self.read_channel()\r\n if re.search(pattern, output, flags=re_flags):\r\n self.write_channel(self.normalize_cmd(self.secret))\r\n self.set_base_prompt()\r\n except socket.timeout:\r\n raise Net_ConnectTimeoutException(\r\n \"Timed-out reading channel, data not available.\"\r\n )\r\n if not self.check_enable_mode():\r\n msg = (\r\n \"Failed to enter enable mode. Please ensure you pass \"\r\n \"the 'secret' argument to ConnectHandler.\"\r\n )\r\n raise ValueError(msg)\r\n return output\r\n\r\n def cleanup(self):\r\n \"\"\"Try to Gracefully exit the SSH session.\"\"\"\r\n self._session_log_fin = True\r\n self.write_channel(\"exit\" + self.RETURN)\r\n\r\n def save_config(self, *args, **kwargs):\r\n \"\"\"Not Implemented\"\"\"\r\n raise NotImplementedError\r\n\r\n\r\n########################################################################################################################\r\n# Text Format Syntaxes\r\n########################################################################################################################\r\n\r\n\r\ndef write_bytes(out_data, encoding=\"ascii\"):\r\n \"\"\"Write Python2 and Python3 compatible byte stream.\"\"\"\r\n if sys.version_info[0] >= 3:\r\n if isinstance(out_data, type(\"\")):\r\n if encoding == \"utf-8\":\r\n return out_data.encode(\"utf-8\")\r\n else:\r\n return out_data.encode(\"ascii\", \"ignore\")\r\n elif isinstance(out_data, type(b\"\")):\r\n return out_data\r\n else:\r\n if isinstance(out_data, type(\"\")):\r\n if encoding == \"utf-8\":\r\n return out_data.encode(\"utf-8\")\r\n else:\r\n return out_data.encode(\"ascii\", \"ignore\")\r\n elif isinstance(out_data, type(str(\"\"))):\r\n return out_data\r\n msg = \"Invalid value for out_data neither unicode nor byte string: {}\".format(\r\n out_data\r\n )\r\n raise ValueError(msg)\r\n\r\nclass CopyableRegexObject(object):\r\n \"\"\"Like a re.RegexObject, but can be copied.\"\"\"\r\n\r\n def __init__(self, pattern):\r\n self.pattern = pattern\r\n self.regex = re.compile(pattern)\r\n\r\n def match(self, *args, **kwargs):\r\n return self.regex.match(*args, **kwargs)\r\n\r\n def sub(self, *args, **kwargs):\r\n return self.regex.sub(*args, **kwargs)\r\n\r\n def __copy__(self):\r\n return CopyableRegexObject(self.pattern)\r\n\r\n def __deepcopy__(self, unused_memo):\r\n return self.__copy__()\r\n\r\nclass Error(Exception):\r\n \"\"\"The base error class.\"\"\"\r\n\r\nclass Usage(Error):\r\n \"\"\"Command line format error.\"\"\"\r\n\r\ndef EncloseAnsiText(text):\r\n \"\"\"Enclose ANSI/SGR escape sequences with ANSI_START and ANSI_END.\"\"\"\r\n return sgr_re.sub(lambda x: ANSI_START + x.group(1) + ANSI_END, text)\r\n\r\ndef clitable_to_dict(cli_table):\r\n \"\"\"Converts TextFSM cli_table object to list of dictionaries.\"\"\"\r\n objs = []\r\n for row in cli_table:\r\n temp_dict = {}\r\n for index, element in enumerate(row):\r\n temp_dict[cli_table.header[index].lower()] = element\r\n objs.append(temp_dict)\r\n return objs\r\n\r\ndef get_template_dir():\r\n \"\"\"Find and return the ntc-templates/templates dir.\"\"\"\r\n try:\r\n template_dir = os.path.expanduser(os.environ[\"NET_TEXTFSM\"])\r\n index = os.path.join(template_dir, \"index\")\r\n if not os.path.isfile(index):\r\n # Assume only base ./ntc-templates specified\r\n template_dir = os.path.join(template_dir, \"templates\")\r\n except KeyError:\r\n # Construct path ~/ntc-templates/templates\r\n home_dir = os.path.expanduser(\"~\")\r\n template_dir = os.path.join(home_dir, \"ntc-templates\", \"templates\")\r\n\r\n index = os.path.join(template_dir, \"index\")\r\n if not os.path.isdir(template_dir) or not os.path.isfile(index):\r\n msg = \"\"\"\r\nValid ntc-templates not found, please install https://github.com/networktocode/ntc-templates\r\nand then set the NET_TEXTFSM environment variable to point to the ./ntc-templates/templates\r\ndirectory.\"\"\"\r\n raise ValueError(msg)\r\n return os.path.abspath(template_dir)\r\n\r\ndef get_structured_data(raw_output, platform, command):\r\n \"\"\"Convert raw CLI output to structured data using TextFSM template.\"\"\"\r\n template_dir = get_template_dir()\r\n index_file = os.path.join(template_dir, \"index\")\r\n textfsm_obj = clitable.CliTable(index_file, template_dir)\r\n attrs = {\"Command\": command, \"Platform\": platform}\r\n try:\r\n # Parse output through template\r\n textfsm_obj.ParseCmd(raw_output, attrs)\r\n structured_data = clitable_to_dict(textfsm_obj)\r\n output = raw_output if structured_data == [] else structured_data\r\n return output\r\n except CliTableError:\r\n return raw_output\r\n\r\ndef get_structured_data_genie(raw_output, platform, command):\r\n if not sys.version_info >= (3, 4):\r\n raise ValueError(\"Genie requires Python >= 3.4\")\r\n\r\n if not GENIE_INSTALLED:\r\n msg = (\r\n \"\\nGenie and PyATS are not installed. Please PIP install both Genie and PyATS:\\n\"\r\n \"pip install genie\\npip install pyats\\n\"\r\n )\r\n raise ValueError(msg)\r\n\r\n if \"cisco\" not in platform:\r\n return raw_output\r\n\r\n genie_device_mapper = {\r\n \"cisco_ios\": \"ios\",\r\n \"cisco_xe\": \"iosxe\",\r\n \"cisco_xr\": \"iosxr\",\r\n \"cisco_nxos\": \"nxos\",\r\n \"cisco_asa\": \"asa\",\r\n }\r\n\r\n os = None\r\n # platform might be _ssh, _telnet, _serial strip that off\r\n if platform.count(\"_\") > 1:\r\n base_platform = platform.split(\"_\")[:-1]\r\n base_platform = \"_\".join(base_platform)\r\n else:\r\n base_platform = platform\r\n\r\n os = genie_device_mapper.get(base_platform)\r\n if os is None:\r\n return raw_output\r\n\r\n # Genie specific construct for doing parsing (based on Genie in Ansible)\r\n device = Device(\"new_device\", os=os)\r\n device.custom.setdefault(\"abstraction\", {})\r\n device.custom[\"abstraction\"][\"order\"] = [\"os\"]\r\n device.cli = AttrDict({\"execute\": None})\r\n try:\r\n # Test of whether their is a parser for the given command (will return Exception if fails)\r\n get_parser(command, device)\r\n parsed_output = device.parse(command, output=raw_output)\r\n return parsed_output\r\n except Exception:\r\n return raw_output\r\n\r\nclass Error(Exception):\r\n \"\"\"Base class for errors.\"\"\"\r\n\r\nclass IndexTableError(Error):\r\n \"\"\"General INdexTable error.\"\"\"\r\n\r\nclass CliTableError(Error):\r\n \"\"\"General CliTable error.\"\"\"\r\n\r\n# Net_Connect Modules\r\nclass SSHException(Exception):\r\n \"\"\"\r\n Exception raised by failures in SSH2 protocol negotiation or logic errors.\r\n \"\"\"\r\n pass\r\n\r\nclass AuthenticationException(SSHException):\r\n \"\"\"\r\n Exception raised when authentication failed for some reason. It may be\r\n possible to retry with different credentials. (Other classes specify more\r\n specific reasons.)\r\n .. versionadded:: 1.6\r\n \"\"\"\r\n pass\r\n\r\nclass PasswordRequiredException(AuthenticationException):\r\n \"\"\"\r\n Exception raised when a password is needed to unlock a private key file.\r\n \"\"\"\r\n pass\r\n\r\nclass BadAuthenticationType(AuthenticationException):\r\n \"\"\"\r\n Exception raised when an authentication type (like password) is used, but\r\n the server isn't allowing that type. (It may only allow public-key, for\r\n example.)\r\n .. versionadded:: 1.1\r\n \"\"\"\r\n allowed_types = []\r\n\r\n # TODO 3.0: remove explanation kwarg\r\n def __init__(self, explanation, types):\r\n # TODO 3.0: remove this supercall unless it's actually required for\r\n # pickling (after fixing pickling)\r\n AuthenticationException.__init__(self, explanation, types)\r\n self.explanation = explanation\r\n self.allowed_types = types\r\n\r\n def __str__(self):\r\n return \"{}; allowed types: {!r}\".format(\r\n self.explanation, self.allowed_types\r\n )\r\n\r\nclass PartialAuthentication(AuthenticationException):\r\n \"\"\"\r\n An internal exception thrown in the case of partial authentication.\r\n \"\"\"\r\n\r\n allowed_types = []\r\n\r\n def __init__(self, types):\r\n AuthenticationException.__init__(self, types)\r\n self.allowed_types = types\r\n\r\n def __str__(self):\r\n return \"Partial authentication; allowed types: {!r}\".format(\r\n self.allowed_types\r\n )\r\n\r\nclass ChannelException(SSHException):\r\n \"\"\"\r\n Exception raised when an attempt to open a new `.Channel` fails.\r\n\r\n :param int code: the error code returned by the server\r\n\r\n .. versionadded:: 1.6\r\n \"\"\"\r\n def __init__(self, code, text):\r\n SSHException.__init__(self, code, text)\r\n self.code = code\r\n self.text = text\r\n\r\n def __str__(self):\r\n return \"ChannelException({!r}, {!r})\".format(self.code, self.text)\r\n\r\nclass BadHostKeyException(SSHException):\r\n def __init__(self, hostname, got_key, expected_key):\r\n SSHException.__init__(self, hostname, got_key, expected_key)\r\n self.hostname = hostname\r\n self.key = got_key\r\n self.expected_key = expected_key\r\n\r\n def __str__(self):\r\n msg = (\r\n \"Host key for server '{}' does not match: got '{}', expected '{}'\"\r\n ) # noqa\r\n return msg.format(\r\n self.hostname,\r\n self.key.get_base64(),\r\n self.expected_key.get_base64(),\r\n )\r\n\r\nclass ProxyCommandFailure(SSHException):\r\n def __init__(self, command, error):\r\n SSHException.__init__(self, command, error)\r\n self.command = command\r\n self.error = error\r\n\r\n def __str__(self):\r\n return 'ProxyCommand(\"{}\") returned nonzero exit status: {}'.format(\r\n self.command, self.error\r\n )\r\n\r\nclass NoValidConnectionsError(socket.error):\r\n def __init__(self, errors):\r\n \"\"\"\r\n :param dict errors:\r\n The errors dict to store, as described by class docstring.\r\n \"\"\"\r\n addrs = sorted(errors.keys())\r\n body = \", \".join([x[0] for x in addrs[:-1]])\r\n tail = addrs[-1][0]\r\n if body:\r\n msg = \"Unable to connect to port {0} on {1} or {2}\"\r\n else:\r\n msg = \"Unable to connect to port {0} on {2}\"\r\n super(NoValidConnectionsError, self).__init__(\r\n None, msg.format(addrs[0][1], body, tail) # stand-in for errno\r\n )\r\n self.errors = errors\r\n\r\n def __reduce__(self):\r\n return (self.__class__, (self.errors,))\r\n\r\nclass Error(Exception):\r\n \"\"\"Base class for errors.\"\"\"\r\n\r\nclass IndexTableError(Error):\r\n \"\"\"General INdexTable error.\"\"\"\r\n\r\nclass CliTableError(Error):\r\n \"\"\"General CliTable error.\"\"\"\r\n\r\nclass IndexTable(object):\r\n def __init__(self, preread=None, precompile=None, file_path=None):\r\n self.index = None\r\n self.compiled = None\r\n if file_path:\r\n self._index_file = file_path\r\n self._index_handle = open(self._index_file, \"r\")\r\n self._ParseIndex(preread, precompile)\r\n\r\n def __del__(self):\r\n \"\"\"Close index handle.\"\"\"\r\n if hasattr(self, \"_index_handle\"):\r\n self._index_handle.close()\r\n\r\n def __len__(self):\r\n \"\"\"Returns number of rows in table.\"\"\"\r\n return self.index.size\r\n\r\n def __copy__(self):\r\n \"\"\"Returns a copy of an IndexTable object.\"\"\"\r\n clone = IndexTable()\r\n if hasattr(self, \"_index_file\"):\r\n # pylint: disable=protected-access\r\n clone._index_file = self._index_file\r\n clone._index_handle = self._index_handle\r\n\r\n clone.index = self.index\r\n clone.compiled = self.compiled\r\n return clone\r\n\r\n def __deepcopy__(self, memodict=None):\r\n \"\"\"Returns a deepcopy of an IndexTable object.\"\"\"\r\n clone = IndexTable()\r\n if hasattr(self, \"_index_file\"):\r\n # pylint: disable=protected-access\r\n clone._index_file = copy.deepcopy(self._index_file)\r\n clone._index_handle = open(clone._index_file, \"r\")\r\n\r\n clone.index = copy.deepcopy(self.index)\r\n clone.compiled = copy.deepcopy(self.compiled)\r\n return clone\r\n\r\n def _ParseIndex(self, preread, precompile):\r\n self.index = texttable.TextTable()\r\n self.index.CsvToTable(self._index_handle)\r\n\r\n if preread:\r\n for row in self.index:\r\n for col in row.header:\r\n row[col] = preread(col, row[col])\r\n\r\n self.compiled = copy.deepcopy(self.index)\r\n\r\n for row in self.compiled:\r\n for col in row.header:\r\n if precompile:\r\n row[col] = precompile(col, row[col])\r\n if row[col]:\r\n row[col] = copyable_regex_object.CopyableRegexObject(row[col])\r\n\r\n def GetRowMatch(self, attributes):\r\n \"\"\"Returns the row number that matches the supplied attributes.\"\"\"\r\n for row in self.compiled:\r\n try:\r\n for key in attributes:\r\n # Silently skip attributes not present in the index file.\r\n # pylint: disable=E1103\r\n if (\r\n key in row.header\r\n and row[key]\r\n and not row[key].match(attributes[key])\r\n ):\r\n # This line does not match, so break and try next row.\r\n raise StopIteration()\r\n return row.row\r\n except StopIteration:\r\n pass\r\n return 0\r\n\r\nclass SCPConn(object):\r\n \"\"\"\r\n Establish a secure copy channel to the remote network device.\r\n\r\n Must close the SCP connection to get the file to write to the remote filesystem\r\n \"\"\"\r\n def __init__(self, ssh_conn):\r\n self.ssh_ctl_chan = ssh_conn\r\n self.establish_scp_conn()\r\n\r\n def establish_scp_conn(self):\r\n \"\"\"Establish the secure copy connection.\"\"\"\r\n ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()\r\n self.scp_conn = self.ssh_ctl_chan._build_ssh_client()\r\n self.scp_conn.connect(**ssh_connect_params)\r\n self.scp_client = scp.SCPClient(self.scp_conn.get_transport())\r\n\r\n def scp_transfer_file(self, source_file, dest_file):\r\n \"\"\"Put file using SCP (for backwards compatibility).\"\"\"\r\n self.scp_client.put(source_file, dest_file)\r\n\r\n def scp_get_file(self, source_file, dest_file):\r\n \"\"\"Get file using SCP.\"\"\"\r\n self.scp_client.get(source_file, dest_file)\r\n\r\n def scp_put_file(self, source_file, dest_file):\r\n \"\"\"Put file using SCP.\"\"\"\r\n self.scp_client.put(source_file, dest_file)\r\n\r\n def close(self):\r\n \"\"\"Close the SCP connection.\"\"\"\r\n self.scp_conn.close()\r\n\r\nclass Net_ConnectAuthenticationException(AuthenticationException):\r\n \"\"\"SSH authentication exception based on Paramiko AuthenticationException.\"\"\"\r\n pass\r\n\r\nclass TelnetConnection(BaseConnection):\r\n pass\r\n\r\nclass TerminalServerTelnet(TerminalServer):\r\n \"\"\"Generic Terminal Server driver telnet.\"\"\"\r\n def telnet_login(self, *args, **kwargs):\r\n # Disable automatic handling of username and password when using terminal server driver\r\n pass\r\n\r\n def std_login(self, *args, **kwargs):\r\n return super(TerminalServerTelnet, self).telnet_login(*args, **kwargs)\r\n\r\n","sub_path":"F5_Volume_Utilization_V6/roles/f5_Volume_Utlilization/packages/Modules_Frame.py","file_name":"Modules_Frame.py","file_ext":"py","file_size_in_byte":88241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"82745208","text":"import numpy as np\nimport os\nimport sys\nimport math\nimport copy\nfrom skimage.exposure import adjust_gamma\nfrom skimage import io\nfrom scipy.ndimage import gaussian_filter\nfrom scipy import ndimage as ndi\nfrom skimage.morphology import disk, closing, watershed\nfrom skimage.filters import median, rank, threshold_otsu, gaussian\nfrom skimage.segmentation import random_walker\nfrom skimage.restoration import denoise_bilateral, estimate_sigma\nfrom skimage.feature import peak_local_max\nfrom skimage.transform import hough_circle, hough_circle_peaks\nfrom skimage.draw import circle_perimeter\nfrom skimage import measure\nfrom scipy.stats import iqr\nfrom scipy.ndimage.morphology import binary_fill_holes\nfrom skimage.segmentation import active_contour\nfrom skimage import measure\n\nfrom lib.math_funcs import *\nfrom lib.render import *\n\n\ndtype2bits = {'uint8': 8,\n\t\t\t 'uint16': 16,\n\t\t\t 'uint32': 32}\n\ndtype2range = { 'uint8': 255,\n\t\t\t\t'uint16': 65535,\n\t\t\t\t'uint32': 4294967295,\n\t\t\t\t'uint64': 18446744073709551615}\n\ndef gamma_stabilize(image, alpha_clean = 5, floor_method = 'min'):\n\t\"\"\"Normalizes the luma curve. floor intensity becomes 0 and max allowed by the bit number - 1\n\tBorrowed from Andrei's Imagepipe\n\n\t:param image: [np.ndarray]\n\t:param alpha_clean: [int] size of features that would be removed if surrounded by a majority of\n\t:param floor_method: [str] ['min', '1q', '5p', 'median'] method of setting the floor intensity. 1q is first quartile, 1p is the first percentile\n\t:return: [np.ndarray]\n\t\"\"\"\n\tbits = dtype2bits[image.dtype.name]\n\tif floor_method == 'min':\n\t\tinner_min = np.min(image)\n\telif floor_method == '1q':\n\t\tinner_min = np.percentile(image, 25)\n\telif floor_method == '5p':\n\t\tinner_min = np.percentile(image, 5)\n\telif floor_method == 'median':\n\t\tinner_min = np.median(image)\n\telse:\n\t\traise PipeArgError('floor_method can only be one of the three types: min, 1q, 5p or median')\n\tstabilized = (image - inner_min) / (float(2 ** bits) - inner_min)\n\tstabilized[stabilized < alpha_clean*np.median(stabilized)] = 0\n\treturn stabilized\n\n\ndef sum_projection(image, axis = 0):\n\t'''Axis is defined as the index of the image.shape output.\n\tBy default it is the Z axis (z,x,y)\n\tTakes a 3d image, and sums it along a defined axis to form a 2d Image\n\n\t:param image: [np.ndarray] 3d stack image in [np.ndarray] format\n\t:param axis: [int] axis to sum along, z = 0, x = 1, y = 2\n\t:return: [np.ndarray] returns 2d image in the shape x,y summed along z axis (by default)\n\t'''\n\ttry:\n\t\treturn np.sum(image, axis)\n\texcept ValueError:\n\t\tif not((axis >= 0 or axis <= 2) and isinstance(axis, int)):\n\t\t\tprint(\"Axis value invalid\")\n\t\telse:\n\t\t\tprint(\"Image input faulty\")\n\t\traise Exception\n\n\ndef max_projection(image, axis = 0):\n\t'''Axis is defined as the index of the image.shape output.\n\tBy default it is the Z axis (z,x,y)\n\tTakes a 3d image, and projects it along a defined axis to form a 2d Image\n\tTakes the max value for each pixel along (default) x,y plane, and projects it\n\tto one plane\n\n\t:param image: [np.ndarray] 3d stack image in format\n\t:param axis: [int] axis to sum along, z = 0, x = 1, y = 2\n\t:return: [np.ndarray] returns 2d image in the shape x,y\n\t'''\n\ttry:\n\t\treturn np.amax(image, axis)\n\texcept ValueError:\n\t\tif not((axis >= 0 or axis <= 2) and isinstance(axis, int)):\n\t\t\tprint(\"Axis value invalid\")\n\t\telse:\n\t\t\tprint(\"Image input faulty\")\n\t\traise Exception\n\n\ndef avg_projection(image, axis = 0):\n\t'''Axis is defined as the index of the image.shape output.\n\tBy default it is the Z axis (z,x,y)\n\tTakes a 3d image, and projects it along a defined axis to form a 2d Image\n\tTakes the average value for each pixel in the (default) x,y plane along the\n\tz axis\n\n\t:param image: [np.ndarray] 3d stack image in format\n\t:param axis: [int] axis to sum along, z = 0, x = 1, y = 2\n\t:return: [np.ndarray] returns 2d image in the shape x,y\n\t'''\n\ttry:\n\t\t# print axis\n\t\tz, x, y = image.shape\n\t\treturn np.sum(image, axis)//z\n\texcept ValueError:\n\t\tif not((axis >= 0 or axis <= 2) and isinstance(axis, int)):\n\t\t\tprint(\"Axis value invalid\")\n\t\telse:\n\t\t\tprint(\"Image input faulty\")\n\t\traise Exception\n\n\ndef disk_hole(image, radius, pinhole = False):\n\t'''Returns either an image of a pinhole or a circle in the\n\tmiddle for removing high frequency/ low frequency noise using FFT\n\tsame dimensions as input image\n\tPinhole = True : pinhole filter, or high pass filter. Filters out low frequency\n\tcontent to yield edges\n\tPinhole = False: single dot filter, preserves low frequency content\n\n\t:param image: [np.ndarray] 2d input image (filter will be applied eventually), used to get dims\n\t:param radius: [int] radius of pinhole/pinpoint\n\t:param pinhole: [bool] determines whether the filter will be a pinhole or pinpoint\n\t:return: [np.ndarray] 2d filter of same size of 2d image input\n\t'''\n\tx, y = image.shape\n\tstructuring_element = np.zeros((x, y), dtype = long)\n\tcenter = x//2\n\n\tfor rows in xrange(x):\n\t\tfor cols in xrange(y):\n\t\t\tif (rows - center + 0.5) ** 2 + (cols - center + 0.5) ** 2 <= radius ** 2:\n\t\t\t\tstructuring_element[rows, cols] = 1\n\tif pinhole:\n\t\treturn 1 - structuring_element\n\telse:\n\t\treturn structuring_element\n\n\ndef smooth(image, smoothing_px = 0.5, threshold = 1):\n\t\"\"\"Gaussian smoothing of the image\n\tBorrowed from Andrei's Imagepipe\n\n\t:param image: [np.ndarray] Input image\n\t:param smoothing_px: [float] size of smoothing pixel\n\t:param threshold: [int] threshold to filter image intensity\n\t:return: [np.ndarray]\n\t\"\"\"\n\t# print \"> Filtering image with Gaussian filter\"\n\tif len(image.shape) > 2:\n\t\tfor i in range(0, image.shape[0]):\n\t\t\timage[i, :, :] = gaussian_filter(image[i, :, :],\n\t\t\t\t\t\t\t\t\t\t\t smoothing_px, mode='constant')\n\t\t\timage[image < threshold * np.mean(image)] = 0\n\telse:\n\t\timage = gaussian_filter(image, smoothing_px, mode='constant')\n\t\timage[image < threshold * np.mean(image)] = 0\n\treturn image\n\n\ndef smooth_tripleD(image, smoothing_px = 0.5, stdevs = 1):\n\t\"\"\"Gaussian smoothing of the image\n\tBorrowed from Andrei's Imagepipe\n\n\t:param image: [np.ndarray] 3d Input image\n\t:param smoothing_px: [float] size of smoothing pixel\n\t:param threshold: [float] threshold to filter image intensity\n\t:return: [np.ndarray]\n\t\"\"\"\n\t# print \"> Filtering image with Gaussian filter\"\n\tif len(image.shape) > 2:\n\t\tfor i in range(0, image.shape[0]):\n\t\t\timage[i, :, :] = gaussian_filter(image[i, :, :],\n\t\t\t\t\t\t\t\t\t\t\t smoothing_px, mode='constant')\n\t\t\timage[image < mean + stdev * stdevs] = 0\n\telse:\n\t\timage = gaussian_filter(image, smoothing_px, mode='constant')\n\t\tmean, stdev = px_hist_stats_n0(image)\n\t\timage[image < mean + stdev * stdevs] = 0\n\treturn image\n\n\ndef fft_ifft(image, struct_element):\n\t'''Performs a fast fourier transform, removes certain frequencies highlighted by\n\tthe structuring element, and returns the inverse fourier transform back.\n\tHelper function disk_hole\n\n\t:param image: [np.ndarray] Image to be filtered\n\t:param struct_element: [np.ndarray] filter to be applied to image in frequency space, should be same dimension as input image\n\t:return: [np.ndarray] filtered image\n\t'''\n\t# print \"> Performing FFT>filter>IFFT transform\"\n\n\tfft_transform = np.fft.fft2(image)\n\tf_shift = np.fft.fftshift(fft_transform)\n\n\t# magnitude_spectrum = 20*np.log(np.abs(f_shift))\n\t# view_2d_img(magnitude_spectrum)\n\t# view_2d_img(struct_element)\n\n\tf_shift_filtered = f_shift * struct_element\n\n\t# magnitude_spectrum_filtered = 20*np.log(np.abs(f_shift_filtered))\n\t# view_2d_img(magnitude_spectrum_filtered)\n\n\tf_inv_shift = np.fft.ifftshift(f_shift_filtered)\n\trecovered_img = np.fft.ifft2(f_inv_shift)\n\trecovered_img = np.abs(recovered_img)\n\treturn recovered_img\n\n\ndef bandpass_disk(image, r_range = (10, 200), pinhole = False):\n\t'''\n\tCreates a bandpass disk for filtering FFT images, creates either a solid\n\ttorus filter or negative image of that\n\n\t:param image: [np.ndarray] image that filter will be applied to\n\t:param r_range: [tuple] (inner, outer) radius of bandpass filter\n\t:param pinhole: [bool] torus (true) or inverse torus (false) filter\n\t:return: [np.ndarray] bandpass filter structuring element\n\t'''\n\touter = disk_hole(image, r_range[1], pinhole)\n\tinner = disk_hole(image, r_range[0], pinhole)\n\tstructuring_element = outer - inner\n\treturn structuring_element\n\n\ndef median_layers(image, struct_disk_r = 5):\n\t'''\n\tApplies median filter over multiple layer of a 3d stack image\n\n\t:param image: [np.ndarray] input image\n\t:param struct_disk_r: [float] size of median filter kernel\n\t:return: [np.ndarray] de-noised median filtered image\n\t'''\n\tfor i in range(0, image.shape[0]):\n\t\timage[i, :, :] = median(image[i, :, :], disk(struct_disk_r))\n\treturn image\n\n\ndef img_type_2uint8(base_image, func = 'floor'):\n\t'''\n\tConverts a given image type to a uint8 image\n\tRounding is done either via 'floor', 'ceiling', or 'fix' functions in numpy\n\n\t:param base_image: [np.ndarray] input image\n\t:param func: [str] function used for scaling image pixel intensity\n\t:return: [np.ndarray] uint8 image\n\t'''\n\t# print \"> Converting Image to uin8\"\n\ttry:\n\t\tbi_max_val = global_max(base_image)\n\t\tbi_min_val = global_min(base_image)\n\t\tdt_max = dtype2range['uint8']\n\t\tdt_min = 0\n\n\t\t# scaled = dt_min * (1 - ((base_image - bi_min_val) / (bi_max_val - bi_min_val))) + dt_max * ((base_image - bi_min_val)/(bi_max_val - bi_min_val))\n\t\tscaled = (base_image - bi_min_val) * ((dt_max - dt_min) / (bi_max_val - bi_min_val)) + dt_min\n\n\t\tif func == 'floor':\n\t\t\tpre_int = np.floor(scaled)\n\t\telif func == 'ceiling':\n\t\t\tpre_int = np.ceil(scaled)\n\t\telif func == 'fix':\n\t\t\tpre_int = np.fix(scaled)\n\t\telse:\n\t\t\traise IOError\n\n\t\treturn np.uint8(pre_int)\n\texcept IOError:\n\t\tprint(\"Function '{}' not recognized \".format(func))\n\t\traise Exception\n\n\ndef binarize_image(base_image, _dilation = 0, feature_size = 2):\n\t'''\n\tBinarizes an image using local otsu and random walker\n\tBorrowed from Andrei's Imagepipe\n\n\t:param base_image: [np.ndarray] input image\n\t:param _dilation: [float] amount of dilation to implement in Binarization\n\t:param feature_size: [float] size of the structuring disk for random Walker\n\t:return: [np.ndarray] binarized image\n\t'''\n\tprint(\"> Binarizing Image...\")\n\tif np.percentile(base_image, 99) < 0.20:\n\t\tif np.percentile(base_image, 99) > 0:\n\t\t\tmult = 0.20 / np.percentile(base_image, 99) # poissonean background assumptions\n\t\telse:\n\t\t\tmult = 1000. / np.sum(base_image)\n\t\tbase_image = base_image * mult\n\t\tbase_image[base_image > 1] = 1\n\n\tclustering_markers = np.zeros(base_image.shape, dtype=np.uint8)\n\tselem2 = disk(feature_size)\n\tprint('> Performing Local Otsu')\n\tlocal_otsu = rank.otsu(base_image, selem2)\n\t# view_2d_img(local_otsu)\n\tclustering_markers[base_image < local_otsu * 0.9] = 1\n\tclustering_markers[base_image > local_otsu * 1.1] = 2\n\tprint(\"> Performing Random Walker Binarization\")\n\tbinary_labels = random_walker(base_image, clustering_markers, beta = 10, mode = 'bf') - 1\n\n\tif _dilation:\n\t\tselem = disk(_dilation)\n\t\tbinary_labels = dilation(binary_labels, selem)\n\treturn binary_labels\n\n# Depreciated\ndef hough_num_circles(input_binary_img, min_r = 15, max_r = 35, step = 2):\n\t'''\n\tHelper function for cell_split\n\tRuns hough transform on a cell cluster in a binary image to determine where\n\tindividual cells may lie. Does not take in a whole binary image, only takes in a contour converted\n\tto a binary image for a single cluster\n\n\t:param input_binary_img: [np.ndarray] Input binary image of the single cell group\n\t:param min_r: [float] minimum radius acceptable for a cell\n\t:param max_r: [float] maximum radius acceptable for a cell\n\t:param step: [float] rate at which minimum radius will be stepped up to maximum radius size\n\t:return: [np.ndarray] cropped and split version of input binary image\n\t'''\n\tprint(\"> Performing Hough cell splitting\")\n\t# Create a list of radii to test and perform hough transform to recover circle centers (x,y) and radii\n\though_radii = np.arange(min_r, max_r, 2)\n\though_res = hough_circle(input_binary_img, hough_radii)\n\taccums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii, total_num_peaks = 3)\n\tcircles = zip(cy, cx, radii);\n\t# remove any circles too close to each other\n\n\tno_duplicates = crop_close(circles, max_sep = 10)\n\n\t# HYPOTHETICAL # of cells\n\tN_cells = len(no_duplicates)\n\t# view_2d_img(input_binary_img)\n\tprint(\"\\t> Number cells in subsection: {}\".format(N_cells))\n\t# print no_duplicates\n\tif N_cells > 1:\n\t\t# Set initial radius to 1\n\t\tfor rows in no_duplicates:\n\t\t\trows[-1] == 1\n\t\t# Create mask to divide both cells\n\t\t# Grow circle size until there is a collision followed by no more collisions\n\t\tactual_mask = np.zeros_like(input_binary_img)\n\t\t# Create Conditions for Whileloop\n\t\tcollision = False\n\t\tend_collision = False\n\t\tstop_condition = False\n\t\tn = 0\n\t\tmax_iter = 100\n\n\t\t# while end_collision == False or n < 10:\n\t\twhile (n < max_iter and stop_condition == False):\n\t\t\t# Create empty mask to grow\n\t\t\tmask = np.zeros_like(input_binary_img)\n\t\t\tfor center_y, center_x, radius in no_duplicates:\n\t\t\t\t# Create mask for each circle in no_duplicates\n\t\t\t\tsub_mask = np.zeros_like(input_binary_img)\n\t\t\t\t# List of coodinates for perimeter of a circle and remove any negative points to prevent edge looparound\n\t\t\t\tcircy, circx = circle_perimeter(center_y, center_x, radius)\n\t\t\t\tno_negs = remove_neg_pts(zip(circy, circx))\n\t\t\t\tfor y, x in no_negs:\n\t\t\t\t\t# for each circle point, if it falls within the dimensions of the submask, plot it.\n\t\t\t\t\tif y < sub_mask.shape[0] and x < sub_mask.shape[1]:\n\t\t\t\t\t\tsub_mask[y, x] = 1\n\t\t\t\t# Append submask to growing mask after dilation (aka making the circle boundaries wide as fuck)\n\t\t\t\tmask += dilation(sub_mask, disk(2))\n\t\t\t# Determine if there is a collision between circles (max element in grow mask is more than just one submask)\n\t\t\t# montage_n_x((actual_mask, mask))\n\t\t\t# print np.amax(mask.flatten())\n\t\t\tif np.amax(mask.flatten()) > 1:\n\t\t\t\tcollision = True\n\t\t\t\t# collision_pt = np.where(mask >= 2)\n\t\t\t\tmask[mask < 2] = 0\n\t\t\t\t# view_2d_img(mask)\n\t\t\t\tactual_mask += mask\n\t\t\t\tactual_mask[actual_mask != 0 ] = 1\n\t\t\t# montage_n_x((actual_mask, mask))\n\t\t\tif collision == True and np.amax(mask.flatten()) <= 1:\n\t\t\t\tend_collision = True\n\t\t\t\tstop_condition = True\n\n\t\t\t# Grow circle radius by 8% per\n\t\t\tfor rows in no_duplicates:\n\t\t\t\trows[-1] *= 1.08\n\t\t\t\trows[-1] = np.int(rows[-1])\n\t\t\tn += 1\n\t\t\t# print n, collision, end_collision, stop_condition\n\t\tif stop_condition == False:\n\t\t\t# montage_n_x((actual_mask, actual_mask + input_binary_img, filled_cells, filled_cells * (1 - actual_mask)))\n\t\t\treturn np.ones_like(input_binary_img)\n\t\t\t# return binary_fill_holes(input_binary_img).astype(int)\n\t\telse:\n\t\t\t# Fill edges to create mask\n\t\t\t# filled_cells = binary_fill_holes(input_binary_img).astype(int)\n\t\t\t# montage_n_x((actual_mask, actual_mask + input_binary_img, filled_cells, filled_cells * (1 - actual_mask)))\n\t\t\t# view_2d_img(filled_cells * (1 - dm))\n\t\t\t# return filled_cells * (1 - actual_mask)\n\t\t\treturn actual_mask\n\telse:\n\t\t# view_2d_img(input_binary_img)\n\t\treturn np.ones_like(input_binary_img)\n\t\t# return binary_fill_holes(input_binary_img).astype(int)\n\n\t# Uncomment for visualization\n\t# montage_n_x((input_binary_img, filled_cells, dm, filled_cells * (1 - dm)))\n\t# for center_y, center_x, radius in no_duplicates:\n\t# \tcircy, circx = circle_perimeter(center_y, center_x, radius)\n\t# \tinput_binary_img[circy, circx] = 10\n\t# view_2d_img(input_binary_img)\n\n\ndef just_label(binary_image):\n\t'''\n\tJust labels a binary image (segments everything)\n\n\t:params binary_image: [np.ndarray] input image\n\t:return: [np.ndarray] segmented image\n\t'''\n\tlabeled_field, object_no = ndi.label(binary_image, structure = np.ones((3, 3)))\n\treturn labeled_field\n\n\ndef label_and_correct(binary_channel, pre_binary, min_px_radius = 10, max_px_radius = 100, min_intensity = 0, mean_diff = 10):\n\t\"\"\"\n\tLabelling of a binary image, with constraints on minimal feature size, minimal intensity of area\n\t covered by a binary label or minimal mean difference from background\n\n\t:param binary_channel: [np.ndarray] input image\n\t:param pre_binary: [np.ndarray] used to compute total intensity\n\t:param min_px_radius: [float] minimal feature size\n\t:param min_intensity: [float] minimal total intensity\n\t:param mean_diff: [float] minimal (multiplicative) difference from the background\n\t:return: [np.ndarray]\n\t\"\"\"\n\tlabeled_field, object_no = ndi.label(binary_channel, structure = np.ones((3, 3)))\n\n\t# prebinary_px = pre_binary.flatten()\n\t# n_bins = int(2 * iqr(prebinary_px) * (len(prebinary_px) ** (1/3)))\n\t# n, bin_edge = np.histogram(prebinary_px, n_bins)\n\t# peak_max_indx = np.argmax(n)\n\t# background_val = (bin_edge[peak_max_indx] + bin_edge[peak_max_indx + 1]) / 2\n\tbackground_mean = np.mean(pre_binary[labeled_field == 0])\n\tfor label in range(1, object_no+1):\n\t\tmask = labeled_field == label\n\t\tpx_radius = np.sqrt(np.sum((mask).astype(np.int8)))\n\t\ttotal_intensity = np.sum(pre_binary[mask])\n\t\tlabel_mean = np.mean(pre_binary[labeled_field == label])\n\t\tif px_radius < min_px_radius or total_intensity < min_intensity or label_mean < mean_diff * background_mean or px_radius > max_px_radius:\n\t\t\tlabeled_field[labeled_field == label] = 0\n\t# dbg.label_and_correct_debug(labeled_field)\n\treturn labeled_field\n\n\ndef cell_split(input_img, contours, min_area = 100, max_area = 3500, min_peri = 100, max_peri = 1500):\n\t'''\n\tFunction finds individual cluster of cells that have a contour fall within the bounds of area and perimeter\n\tand attempts to divide them by their constituents\n\n\t:param input_img: [np.ndarray] binary input image containing all segmented cells\n\t:param contours: [list] of [lists] a list of list of points for each of the contours for each cell\n\t:param min_area: [float] minimum acceptable area for a cell\n\t:param max_area: [float] max acceptable area for a cell\n\t:param min_peri: [float] minimum acceptable perimeter for a cell\n\t:param max_peri: [float] maximum acceptable perimeter for a cell\n\t:return: [np.ndarray] full image with cell clusters split\n\t'''\n\tprint(\"> Starting Cell Split\")\n\toutput = np.zeros_like(input_img)\n\toutput[input_img > 0] = 1\n\tfor item_contour in contours:\n\t\t# remove cells that have a low circumference or too high circumference\n\t\tcontour_len = item_contour.shape[0]\n\t\tcontour_img = binary_fill_holes(points2img(item_contour)).astype(int)\n\t\tcontour_area = sum(contour_img.flatten())\n\t\tif contour_len >= min_peri and contour_len <= max_peri and contour_area >= min_area and contour_area <= max_area:\n\t\t# if item_contour.shape[0] >= 100 and item_contour.shape[0] <= 350:\n\t\t\t# holding = points2img(item_contour)\n\t\t\t# holding_fill = binary_fill_holes(holding).astype(int)\n\t\t\t# if sum(holding_fill.flatten()) > 100:\n\t\t\tsplit_cells_mask = hough_num_circles(contour_img)\n\n\t\t\ttlx, tly, brx, bry = location(item_contour)\n\t\t\tif array_all_ones(split_cells_mask):\n\t\t\t\tfor x in xrange(tlx, brx + 1):\n\t\t\t\t\tfor y in xrange(tly, bry + 1):\n\t\t\t\t\t\toutput[y, x] = output[y, x] * split_cells_mask[y - tly, x - tlx]\n\t\t\t\t# output[tly - 1:bry + 1, tlx - 1:brx + 1] = output[tly - 1:bry + 1, tlx - 1:brx + 1] * split_cells_mask\n\t\t\t\t# montage_n_x((output,output[tly-1:bry+1,tlx-1:brx+1], split_cells_mask, output[tly-1:bry+1,tlx-1:brx+1] * split_cells_mask))\n\t\t\telse:\n\t\t\t\td_contour_img = dilation(contour_img, disk(1))\n\t\t\t\tspecific_mask = split_cells_mask + d_contour_img\n\t\t\t\tspecific_mask[specific_mask < 2] = 0\n\t\t\t\tspecific_mask[specific_mask >= 2] = 1\n\t\t\t\tfor x in xrange(tlx, brx + 1):\n\t\t\t\t\tfor y in xrange(tly, bry + 1):\n\t\t\t\t\t\toutput[y, x] = output[y, x] * (1- specific_mask[y - tly, x - tlx])\n\n\n\treturn label_and_correct(output, input_img)\n\n\ndef rm_eccentric(input_img, min_eccentricity, max_ecc, min_area, max_area):\n\t'''Evaluates the eccentricity of single cells within an image with multiple cells, and throws away any cells that exhibit odd eccentricity\n\tAlso chucks any cells that have an area larger than max_area\n\n\t:param input_img: [np.ndarray] segmented binary image\n\t:param min_eccentricity: [float] minimum acceptable eccentricity\n\t:param max_area: [float] maximum area acceptable for a cell\n\t'''\n\n\tmax_cells = np.amax(input_img.flatten())\n\toutput_img = copy.deepcopy(input_img)\n\tfor x in xrange(max_cells):\n\t\tmask = np.zeros_like(input_img)\n\t\tmask[output_img == x + 1] = 1\n\n\t\t_, area, _, eccentricity = get_contour_details(mask)\n\n\t\tif eccentricity < min_eccentricity or eccentricity > max_ecc and area < min_area or area > max_area:\n\t\t\toutput_img[output_img == x + 1] = 0\n\treturn output_img\n\n\ndef improved_watershed(binary_base, intensity, expected_separation = 10):\n\t\"\"\"\n\tImproved watershed method that takes in account minimum intensity as well as minimal size of\n\tseparation between the elements\n\tBorrowed from Andrei's Imagepipe\n\n\t:param binary_base: [np.ndarray] support for watershedding\n\t:param intensity: [np.ndarray] intensity value used to exclude watershed points with too low of intensity\n\t:param expected_separation: [float] expected minimal separation (in pixels) between watershed centers\n\t:return: [np.ndarray]\n\t\"\"\"\n\tprint(\"> Performing Improved Watershed\")\n\t# sel_elem = disk(2)\n\t#\n\t# # changed variable name for \"labels\"\n\t# post_closing_labels = closing(binary_base, sel_elem)\n\n\tdistance = ndi.distance_transform_edt(binary_base)\n\tlocal_maxi = peak_local_max(distance,\n\t\t\t\t\t\t\t\tindices = False, # we want the image mask, not peak position\n\t\t\t\t\t\t\t\tmin_distance = expected_separation, # about half of a bud with our size\n\t\t\t\t\t\t\t\tthreshold_abs = 10, # allows to clear the noise\n\t\t\t\t\t\t\t\tlabels = binary_base)\n\t# we fuse the labels that are close together that escaped the min distance in local_maxi\n\tlocal_maxi = ndi.convolve(local_maxi, np.ones((5, 5)), mode = 'constant', cval = 0.0)\n\t# finish the watershed\n\tstruct = np.ones((3, 3))\n\tstruct[0,0] = 0\n\tstruct[0,2] = 0\n\tstruct[2,0] = 0\n\tstruct[2,2] = 0\n\texpanded_maxi_markers = ndi.label(local_maxi, structure = struct)[0]\n\tsegmented_cells_labels = watershed(-distance, expanded_maxi_markers, mask = binary_base)\n\n\tunique_segmented_cells_labels = np.unique(segmented_cells_labels)\n\tunique_segmented_cells_labels = unique_segmented_cells_labels[1:]\n\taverage_apply_mask_list = []\n\t# Gimick fix\n\t# intensity_array = intensity * np.ones_like(segmented_cells_labels)\n\tfor cell_label in unique_segmented_cells_labels:\n\t\tmy_mask = segmented_cells_labels == cell_label\n\t\tapply_mask = segmented_cells_labels[my_mask]\n\t\taverage_apply_mask = np.mean(intensity[my_mask])\n\t\tif average_apply_mask < 0.005:\n\t\t\taverage_apply_mask = 0\n\t\t\tsegmented_cells_labels[segmented_cells_labels == cell_label] = 0\n\t\taverage_apply_mask_list.append(average_apply_mask)\n\t# x_labels = ['cell13', 'cell1', 'cell7', 'cell2', 'cell14', 'cell6', 'cell3', 'cell5', 'cell4', 'cell11', 'cell12', 'cell8', 'cell10', 'cell9']\n\t# dbg.improved_watershed_debug(segmented_cells_labels, intensity)\n\t# dbg.improved_watershed_plot_intensities(x_labels, average_apply_mask_list.sort())\n\treturn segmented_cells_labels\n\n\ndef get_contour_details(input_img):\n\t'''\n\tInput image must have only one cell in it with one contour, function extracts\n\tarea, perimeter, radius, eccentricity from a given cell. radius is an\n\tapproximation, assuming the cell is circular\n\t:param input_img: input image (binary) of just a single cell. Cannot contain\n\t\t\t\t\t\tmultiple cells or multiple contours\n\t:return: radius, area, perimeter, and eccentricity in that order\n\t'''\n\tcontours = measure.find_contours(input_img,\n\t\t\t\t\t\t\t\t\t\tlevel = 0.5,\n\t\t\t\t\t\t\t\t\t\tfully_connected = 'low',\n\t\t\t\t\t\t\t\t\t\tpositive_orientation = 'low')\n\tPoint_set = Point_set2D(contours[0])\n\tradius = (Point_set.shoelace() / math.pi) ** 0.5\n\teccentricity = (4 * math.pi * Point_set.shoelace()) / (Point_set.perimeter() ** 2)\n\treturn radius, Point_set.shoelace(), Point_set.perimeter(), eccentricity\n\n\ndef hist_peak(image):\n\t'''\n\tReturns the peak histogram count for a given image\n\n\t:param image: 2d-3d image for generating histogram map\n\t:return: peak histogram value\n\t'''\n\tpx_dataset = image.flatten()\n\tn_bins = int(2 * iqr(px_dataset) * (len(px_dataset)) ** (1/3))\n\tn, bin_edges = np.histogram(px_dataset, n_bins)\n\tpeak_max_indx = np.argmax(n)\n\treturn (bin_edges[peak_max_indx] + bin_edges[peak_max_indx]) / 2\n\n\ndef get_bounding_img(binary_img, condition):\n\t'''\n\tGiven a binary image, reduces the image down to the size where it only isolates the binary elements.\n\tBinary features must be presented as greater than 0 in a numpy array (2d and 3d compatible)\n\t:param binary_img: [np.ndarray] Image before reduction\n\t:return: [np.ndarray] reduced minimum bounding box image\n\t'''\n\tdims = len(binary_img.shape)\n\tpos_coord = np.where(binary_img == condition)\n\tmins = np.amin(pos_coord, axis = 1)\n\tmaxs = np.amax(pos_coord, axis = 1) + 1\n\n\tif dims == 3:\n\t\tz_min = mins[0]\n\t\tz_max = maxs[0]\n\t\tx_min = mins[1]\n\t\tx_max = maxs[1]\n\t\ty_min = mins[2]\n\t\ty_max = maxs[2]\n\t\treturn binary_img[z_min:z_max, x_min:x_max, y_min:y_max]\n\telif dims == 2:\n\t\tx_min = mins[1]\n\t\tx_max = maxs[1]\n\t\ty_min = mins[2]\n\t\ty_max = maxs[2]\n\t\treturn binary_img[x_min:x_max, y_min:y_max]\t\n\telse:\n\t\traise ValueError\n\n\ndef write_stats(before_image, after_image, UID, filename, read_path, write_path, img_type = \"cell\"):\n\t'''\n\tGiven two segmented binary images, determine the difference between the\n\tcells present on both images and save differences and cell stats to a file\n\t:param before_image: [np.ndarray] Image before cell deletion or addition\n\t:param after_image: [np.ndarray] Image after cell deletion or addition\n\t:param UID: [str] unique UID for the image, should be the same between the two Images\n\t:param filename: [str] name of the datafile to be written to\n\t:param write_path: [str] location of the datafile containing data\n\t'''\n\twrite_file = open(os.path.join(write_path, filename),'a')\n\t# write_file.write(\"cell\\tUID\\tcell_num\\tcell_updated_num\\tdeleted\\tRadius\\tArea\\tPerimeter\\tEccentricity\\tread_path\\n\")\n\tdeletion = True\n\tbefore_cells = np.amax(before_image.flatten())\n\tafter_cells = np.amax(after_image.flatten())\n\tif after_cells > before_cells:\n\t\tdeletion = False\n\tmax_cells = np.maximum(before_cells, after_cells)\n\tfor cell_index in xrange(max_cells):\n\t\tcurrent_label = cell_index + 1\n\t\tafter_label = current_label\n\t\tif deletion:\n\t\t\tmask = np.zeros_like(before_image)\n\t\t\tmask[before_image == current_label] = current_label\n\t\telse:\n\t\t\tmask = np.zeros_like(after_image)\n\t\t\tmask[after_image == current_label] = current_label\n\t\tradius, area, perimeter, E = get_contour_details(mask)\n\t\tcell_isolation = after_image * mask\n\n\t\tcell_delete = False\n\t\tif np.amax(cell_isolation.flatten()) != current_label:\n\t\t\tif np.amax(cell_isolation.flatten()) == 0:\n\t\t\t\tafter_label = 0\n\t\t\t\tcell_delete = True\n\t\t\telse:\n\t\t\t\tafter_label = int(np.amax(cell_isolation.flatten()) / current_label)\n\t\twrite_file.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(img_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tUID,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcurrent_label,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tafter_label,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcell_delete,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tradius,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tarea,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tperimeter,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tread_path))\n\twrite_file.close()\n\n\ndef global_max(img_2d):\n\t'''Returns the maximum pixel value within a 2-3d image'''\n\treturn np.amax(img_2d.flatten())\n\n\ndef global_min(img_2d):\n\t'''\n\tReturns the minimum pixel value within a 2-3d image\n\t'''\n\treturn np.amin(img_2d.flatten())\n\n\ndef properties(image):\n\t'''Prints some of an image's properties into the console directly'''\n\tprint(\">Image Properties\")\n\tprint(\"Dimensions: {}\".format(image.shape))\n\tprint(\"Format: {}\".format(image.dtype.name))\n\tprint(\"Global Max: {}\\tGlobal Min: {}\".format(global_max(image), global_min(image)))\n\n\ndef euclid_dist_nD(p0, p1):\n\treturn np.sum((p1 - p0) ** 2) ** 0.5\n\n\nclass Point_set2D(object):\n\tdef __init__(self, point_list):\n\t\tself.point_list = np.array([[float(coordinate) for coordinate in point] for point in point_list])\n\n\n\tdef num_pts(self):\n\t\treturn len(self.point_list)\n\n\n\tdef center_mass(self):\n\t\treturn np.sum(self.point_list, 0) / self.num_pts()\n\n\n\tdef perimeter(self):\n\t\tperi_distance = 0\n\t\tfor pt_indx in xrange(self.num_pts()):\n\t\t\tperi_distance += euclid_dist_nD(self.point_list[pt_indx],\n\t\t\t\t\t\t\t\t\t\t\tself.point_list[pt_indx - 1])\n\t\treturn peri_distance\n\n\n\tdef shoelace(self):\n\t\tarea = 0\n\t\tfor pt in xrange(len(self.point_list)):\n\t\t\tarea += self.point_list[pt - 1][0] * self.point_list[pt][1]\n\t\t\tarea -= self.point_list[pt - 1][1] * self.point_list[pt][0]\n\t\treturn abs(area) / 2.0\n","sub_path":"lib/processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":28190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"481823284","text":"## Data Extraction ##\n\nimport numpy as np\nimport h5py\n\n# Finding Specific Tissue\ndef findSpecificTissue(folder_name,tissue,testing_label):\n\n data = h5py.File(folder_name + tissue + '.mat')\n label_map = np.array(data[testing_label])\n RamanMap = np.array(data['map_t' + tissue])\n\n return label_map,RamanMap\n\n# Finding the unique keys for all the tissue files - to identify callable keys when pre-processing data\ndef findUniqueKeys(folder_name):\n\n unique_keys = []\n\n for x in range(3,72):\n\n # For the tissues with only a single task\n try:\n mat = h5py.File(folder_name + str(x) + '.mat')\n\n for item in list(mat.keys()):\n unique_keys.append(item)\n\n except OSError:\n print(x, 'OSError')\n\n except KeyError:\n print(x, 'KeyError')\n\n # For the tissues with multiple task\n try:\n\n for y in range(1,3):\n mat = h5py.File(folder_name + str(x) + '.mat')\n\n for item in list(mat.keys()):\n unique_keys.append(item)\n\n except OSError:\n print(x, y, 'OSError')\n\n except KeyError:\n print(x, y, 'KeyError')\n\n return np.unique(unique_keys)\n\n# Given an input key, this function will return the tissues which contain that key\ndef findTissue(folder_name,key):\n\n tissue = []\n\n for x in range(3,72):\n\n try:\n mat = h5py.File(folder_name + str(x) + '.mat')\n\n if key in list(mat.keys()):\n tissue.append()\n\n except OSError:\n print(x, 'OSError')\n\n except KeyError:\n print(x, 'KeyError')\n\n return tissue\n\n# This function converts the ones in the matrix to the index - to be one hot encoded later\ndef convert(matrix,index):\n\n for x in range(matrix.shape[0]):\n for y in range(matrix.shape[1]):\n if matrix[x,y] == 1:\n matrix[x,y] = index\n\n return matrix\n\n# Returns 3 lists - Map of labels indicated , Raman Data, Tissues Used\n# Map of label - in the form of a list of 2D matrices\n# Raman Data - in the form of a list of 3D matrices\ndef preProcessAllLabels(folder_name):\n\n # Initializing variables\n known_labels = ['bcc','dermis','epi']\n label = []\n RamanData = []\n tissues_used = []\n\n for x in range(3, 72):\n\n for y in range(0,3):\n\n if y == 0:\n folder_number = str(x)\n\n else:\n folder_number = str(x) + '_' + str(y)\n\n try:\n # Opening file and obtaining keys\n mat = h5py.File(folder_name + folder_number + '.mat')\n keys = list(mat.keys())\n\n # Checking just for aforementioned keys in all the files\n present_labels = [item for item in keys if item in known_labels]\n\n # # Only if bcc is within the image do we take the rest of the data\n # if 'bcc' in present_labels:\n\n label_map = np.zeros(mat[present_labels[0]].shape)\n\n for key in present_labels:\n\n if key == 'bcc':\n\n temp = convert(np.array(mat[key]), 1)\n label_map = label_map + temp\n\n elif key == 'dermis':\n\n temp = convert(np.array(mat[key]),2)\n label_map = label_map + temp\n\n elif key == 'epi':\n\n temp = convert(np.array(mat[key]),3)\n label_map = label_map + temp\n\n\n RamanMap = np.array(mat['map_t' + folder_number])\n\n # Cheking for dimension mismatch\n # If there is no dimension mismatch organise data to be raman input and BCC/NonBCC cell output\n if label_map.shape[0] == RamanMap.shape[1] and label_map.shape[1] == RamanMap.shape[2]:\n label.append(label_map)\n RamanData.append(RamanMap)\n tissues_used.append(folder_number)\n\n except OSError:\n print(x, OSError)\n\n # This is due to the tissue not having any of the keys\n except KeyError:\n print(x, KeyError)\n\n except IndexError:\n print(x, IndexError)\n\n # This error is due to different keys having different shapes\n except ValueError:\n print(x, ValueError)\n\n return label, RamanData, tissues_used\n\n\n# This is for the tissues with multiple tasks\n# Returns 3 lists - Map of Label, Raman Data, Tissues Used\n# Map of Label - in the form of a list of 2D matrices\n# Raman Data - in the form of a list of 3D matrices\ndef preProcessBCC(folder_name,testing_label):\n\n # Initializing variables\n label = []\n RamanData = []\n tissues_used = []\n\n for x in range(3, 72):\n\n for y in range(0,3):\n\n if y == 0:\n folder_number = str(x)\n\n else:\n folder_number = str(x) + '_' + str(y)\n\n try:\n # Opening file and obtaining keys\n mat = h5py.File(folder_name + folder_number +'.mat')\n keys = list(mat.keys())\n\n # Checking just for BCC data in all the files\n if testing_label in keys:\n label_map = np.array(mat[testing_label])\n RamanMap = np.array(mat['map_t' + folder_number])\n\n else:\n continue\n\n # Cheking for dimension mismatch\n # If there is no dimension mismatch organise data to be raman input and BCC/NonBCC cell output\n if label_map.shape[0] == RamanMap.shape[1] and label_map.shape[1] == RamanMap.shape[2]:\n label.append(label_map)\n RamanData.append(RamanMap)\n tissues_used.append(folder_number)\n\n except OSError:\n print(x, 'OSError')\n\n except KeyError:\n print(x, 'KeyError')\n\n except IndexError:\n print(x, 'IndexError')\n\n return label, RamanData, tissues_used","sub_path":"Algorithms/process_data/obtaining_data.py","file_name":"obtaining_data.py","file_ext":"py","file_size_in_byte":6131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"639976605","text":"from generator import random_handler as ran\nimport sympy as sym\nimport math\nimport random\nfrom generator import constants_conversions as c\nfrom mathsub import differential_calculus_engine as engine\nfrom mathsub import algebra_engine\n\nx, y, z, t = sym.symbols('x y z t', real = True)#generic variables\n\ndef ask():\n ask_words = ['Find', 'Determine', 'Calculate', 'Compute', 'Evaluate']\n return random.choice(ask_words)\n\ndef parse(string_input):\n string_input = str(string_input)\n return string_input.replace('**', '^').replace('*', ' ') \n\n\n\nclass continuity_piecewise_function_linear_linear():\n def __init__(self):\n\n piecewise = engine.ContinuousPiecewise()\n piecewise.init_random(parts = 2, type = 'line.line')\n\n self.question = f\"\"\"The piecewise function {piecewise.function} is continuous. Determine the values inside the function that makes the function continuous.\"\"\"\n self.answer = f\"\"\"ANSWERS GENERATED ABOVE\"\"\"\n\nclass continuity_piecewise_function_parabola_linear():\n def __init__(self):\n\n piecewise = engine.ContinuousPiecewise()\n piecewise.init_random(parts = 2, type = 'parabola.line')\n\n self.question = f\"\"\"The piecewise function {piecewise.function} is continuous. Determine the values inside the function that makes the function continuous.\"\"\"\n self.answer = f\"\"\"ANSWERS GENERATED ABOVE\"\"\"\n\nclass discontinuity_piecewise_function_point():\n def __init__(self):\n\n piecewise = engine.PointDiscontinuity()\n piecewise.init_random()\n\n self.question = f\"\"\"Identify what type of discontinuity the function {piecewise.function} has.\"\"\"\n self.answer = f\"\"\"{piecewise.type}, discontinuous at x = {piecewise.point_of_discontinuity}\"\"\"\n\nclass discontinuity_piecewise_function_jump():\n def __init__(self):\n\n piecewise = engine.JumpDiscontinuity()\n piecewise.init_random()\n\n self.question = f\"\"\"Identify what type of discontinuity the function {piecewise.function} has.\"\"\"\n self.answer = f\"\"\"{piecewise.type}, discontinuous at x = {piecewise.point_of_discontinuity} with a magnitude of {piecewise.magnitude}.\"\"\"\n\n# class first_derivative_explicit():\n# def __init__(self):\n\n# problem = engine.DerivativeExplicit()\n# problem.init_random()\n\n# self.question = f\"\"\"Differentiate {problem.function_string}.\"\"\"\n# self.answer = f\"\"\"{problem.derivative()}\"\"\"\n\nclass Derivative_explicit():\n def __init__(self):\n BATTERIES = []\n CHOICES = []\n suffix = ''\n prefix = ''\n for i in range(4):\n #battery = engine.Some_class_from_engine\n battery = engine.Derivative_explicit()\n #data = battery.Some_attribute_from_battery \n data = parse(battery.derivative())\n BATTERIES.append(battery)\n CHOICES.append(prefix + str(data) + suffix) \n main = BATTERIES[0]\n CHOICES[0] = str(CHOICES[0]) + ' #'\n random.shuffle(CHOICES)\n #edit below\n self.question = f\"\"\"{ask()} the first derivative of the function f(x) = {parse(main.function)}.\"\"\"\n\n self.answer = f\"\"\"A. {CHOICES[0]}\nB. {CHOICES[1]}\nC. {CHOICES[2]}\nD. {CHOICES[3]}\"\"\" \n\nclass first_derivative_explicit_yofx_xoft_dydt():\n def __init__(self):\n\n problem = engine.DerivativeExplicit_yofx_xoft_dydt()\n problem.init_random()\n\n self.question = f\"\"\"If y(x) = {problem.y_of_x} and x(t) = {problem.x_of_t}, determine the value of dy/dt at t = {problem.t}.\"\"\"\n self.answer = f\"\"\"{problem.dydt_at_t}\"\"\"\n\nclass first_derivative_explicit_xoft_yoft_dydx():\n def __init__(self):\n\n problem = engine.DerivativeExplicit_xoft_yoft_dydx()\n problem.init_random()\n\n self.question = f\"\"\"If x(t) = {problem.x_of_t}, and y(t) = {problem.y_of_t}, determine the value of dy/dx at t = {problem.t}.\"\"\"\n self.answer = f\"\"\"{problem.dydx_at_t}\"\"\"\n\nclass first_derivative_implicit():\n def __init__(self):\n\n problem = engine.DerivativeImplicit_Bivariable()\n problem.init_random()\n\n self.question = f\"\"\"For the function {problem.expression} = 0, determine the value of dy/dx.\"\"\"\n self.answer = f\"\"\"{problem.dydx}\"\"\"\n\nclass second_derivative_implicit():\n def __init__(self):\n\n problem = engine.DerivativeImplicit_Bivariable()\n problem.init_random()\n\n self.question = f\"\"\"For the function {problem.expression} = 0, determine the value of d^2y/dx^2.\"\"\"\n self.answer = f\"\"\"{problem.dydx}\"\"\"\n\nclass tangent_line_from_conic_section():\n def __init__(self):\n\n problem = engine.TangentLine_from_ConicSection()\n problem.init_random()\n\n self.question = f\"\"\"For the graph of the function {problem.general_string}, determine the equation of the line tangent to the curve at the point {problem.point_of_tangency.string}.\"\"\"\n self.answer = f\"\"\"{problem.tangent_line.string}\"\"\"\n\nclass normal_line_from_conic_section():\n def __init__(self):\n\n problem = engine.NormalLine_from_ConicSection()\n problem.init_random()\n\n self.question = f\"\"\"For the graph of the function {problem.general_string}, determine the equation of the line normal to the curve at the point {problem.point_of_tangency.string}.\"\"\"\n self.answer = f\"\"\"{problem.normal_line.string}\"\"\"\n\nclass polynomial_critical_numbers():\n def __init__(self):\n tryagain = True\n while tryagain:\n try:\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n WORDING_LIST = ['critical points', 'relative extrema']\n\n self.question = f\"\"\"Determine the {random.choice(WORDING_LIST)} of the function f(x) = {problem.polynomial.expression}.\"\"\"\n \n points_string = \"\"\n\n for i in range(len(problem.critical_points)):\n points_string = points_string + problem.critical_points[i].string + ' '\n\n self.answer = f\"\"\"{points_string}\"\"\"\n tryagain = False\n except:\n pass\n\nclass polynomial_relative_maxima():\n def __init__(self):\n tryagain = True\n while tryagain:\n try:\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n\n self.question = f\"\"\"Determine the relative maxima of the function f(x) = {problem.polynomial.expression}.\"\"\"\n \n points_string = \"\"\n\n for i in range(len(problem.relative_maxima)):\n points_string = points_string + problem.relative_maxima[i].string + ' '\n\n self.answer = f\"\"\"{points_string}\"\"\" \n tryagain = False\n except:\n tryagain = True \n\nclass polynomial_relative_minima():\n def __init__(self):\n\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n\n self.question = f\"\"\"Determine the relative minima of the function f(x) = {problem.polynomial.expression}.\"\"\"\n \n points_string = \"\"\n\n for i in range(len(problem.relative_minima)):\n points_string = points_string + problem.relative_minima[i].string + ' '\n\n self.answer = f\"\"\"{points_string}\"\"\" \n\nclass polynomial_increasing_interval():\n def __init__(self):\n\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n\n self.question = f\"\"\"Determine the interval that the function f(x) = {problem.polynomial.expression} is increasing\"\"\"\n \n self.answer = f\"\"\"{problem.interval_increasing}\"\"\"\n\nclass polynomial_decreasing_interval():\n def __init__(self):\n\n problem = engine.RelativeExtrema_Polynomials()\n problem.init_random()\n\n\n self.question = f\"\"\"Determine the interval that the function f(x) = {problem.polynomial.expression} is decreasing\"\"\"\n \n self.answer = f\"\"\"{problem.interval_decreasing}\"\"\"\n\nclass product_of_two_numbers_x_y():\n def __init__(self):\n\n problem = engine.ProductOfTwoNumbers_x_y()\n problem.init_random()\n\n\n self.question = f\"\"\"Among those positive real numbers u and v whose sum is {problem.sum_of_numbers}, find the choice of u and v that makes their product P as much as possible\"\"\"\n \n self.answer = f\"\"\"{problem.number1}, {problem.number2}\"\"\" \n\nclass product_of_two_numbers_xsquared_y():\n def __init__(self):\n\n problem = engine.ProductOfTwoNumbers_xsquared_y()\n problem.init_random()\n\n\n self.question = f\"\"\"Divide the number {problem.sum_of_numbers} into two parts such that the product P of one part and the square of the other is a maximum.\"\"\"\n \n self.answer = f\"\"\"{problem.number1}, {problem.number2}\"\"\" \n\nclass paper_with_margins():\n def __init__(self):\n\n paper = engine.PaperWithMargins()\n paper.init_random()\n\n self.question = f\"\"\"A sheet of paper for a poster is to be {paper.area} cm^2 in area. The margins at the top and bottom are to be {paper.margin_length_one_side} cm and at the sides to be {paper.margin_width_one_side} cm. What should be the dimensions of the sheet to maximize the printed area?\"\"\"\n self.answer = f\"\"\"{paper.length} cm x {paper.width} cm\"\"\"\n\nclass ships_moving_at_axis():\n def __init__(self):\n\n ships = engine.MovingAtAxis()\n ships.init_random()\n\n self.question = f\"\"\"At t = 0, Ship B is {ships.B_initial_distance_from_A} miles due east of another ship A. Ship B is then sailing due west at {ships.B_velocity} miles per hpour, and A is sailing due south at {ships.A_velocity} miles per hour. If they continue on their respective courses, when will they be nearest one another, and how near?\"\"\"\n self.answer = f\"\"\"{ships.time_nearest} hours, {ships.distance_nearest} miles\"\"\"\n\nclass can_with_minimum_area_open():\n def __init__(self):\n\n can = engine.CanWithMinimumArea_Open()\n can.init_random()\n\n self.question = f\"\"\"A cylinder container with circular base is to hold {can.volume} cm^3. Find its dimensions so that the amount (surface area) of metal required is minimum when the container is an open can.\"\"\"\n self.answer = f\"\"\"radius: {can.radius} cm, height: {can.height} cm\"\"\"\n\n\nclass can_with_minimum_area_closed():\n def __init__(self):\n\n can = engine.CanWithMinimumArea_Closed()\n can.init_random()\n\n self.question = f\"\"\"A cylinder container with circular base is to hold {can.volume} cm^3. Find its dimensions so that the amount (surface area) of metal required is minimum when the container is an closed can.\"\"\"\n self.answer = f\"\"\"radius: {can.radius} cm, height: {can.height} cm\"\"\"\n \nclass manufacturing_items():\n def __init__(self):\n\n plant = engine.Manufacturing()\n plant.init_random()\n\n self.question = f\"\"\"The total cost of producing x radio sets per day is PHP {plant.cost_function}, and the price per set at which they may be sold is PHP {plant.price_function}. What should be the daily output to obtain a maximum total profit?\"\"\"\n\n self.answer = f\"\"\"{plant.items_at_profit_max} items\"\"\"\n\n\nclass man_in_rowboat():\n def __init__(self):\n\n boat = engine.ManInRowBoat()\n boat.init_random()\n\n self.question = f\"\"\"A man in a rowboat at P, {boat.PA_distance} miles from the nearest point A on a straight shorem wishes to reach a point B, {boat.AB_distance} miles from A along the shore, in shortest time. Where should he land if he can row {boat.row_speed} miles per hour and walk {boat.walk_speed} miles per hour?\"\"\"\n\n self.answer = f\"\"\"{boat.distance_at_time_smallest} miles from point A, {boat.time_smallest} hours\"\"\"\n\nclass rectangular_fence():\n def __init__(self):\n\n fence = engine.RectangularFence()\n fence.init_random()\n\n self.question = f\"\"\"A given rectangular area that is {fence.area} m^2 is to be fenced off in a field that lies along a stright river. If no fencing is need along the river, determine the least amount of fencing required.\"\"\"\n self.answer = f\"\"\"{fence.perimeter} m\"\"\"\n\nclass wall_and_beam_and_building():\n def __init__(self):\n\n structure = engine.WallAndBuilding()\n structure.init_random()\n\n self.question = f\"\"\"A wall of a building is to be braced by a beam that must pass over parallel wall {structure.wall_height} ft high and {structure.wall_distance} ft from the building. Find the length of the shortest beam that can be used.\"\"\"\n self.answer = f\"\"\"{structure.beam_length} ft\"\"\"\n\n\n\n#some new codes -----\nclass Constructor():\n def __init__(self, engine_class_instances):\n #Battery - a single instance of a set of givens, and an answer for a certain problem\n\n BATTERIES = []\n CHOICES = []\n suffix = ''\n prefix = ''\n for i in range(4):\n\n #battery = engine.Some_class_from_engine\n battery = engine_class_instances[i]\n\n #data = battery.Some_attribute_from_battery \n data = parse(battery.answer)\n\n BATTERIES.append(battery)\n CHOICES.append(prefix + str(data) + suffix) \n main = BATTERIES[0]\n CHOICES[0] = str(CHOICES[0]) + ' #'\n random.shuffle(CHOICES)\n #edit below\n self.question = main.question\n self.answer = f\"\"\"A. {CHOICES[0]}\nB. {CHOICES[1]}\nC. {CHOICES[2]}\nD. {CHOICES[3]}\"\"\" \n\nclass first_derivative():\n def __init__(self):\n instance_list = [\n engine.first_derivative(), \n engine.first_derivative(),\n engine.first_derivative(),\n engine.first_derivative() \n ]\n constructed = Constructor(instance_list)\n self.question = constructed.question\n self.answer = constructed.answer \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\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\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\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\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\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\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\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":"mathsub/differential_calculus.py","file_name":"differential_calculus.py","file_ext":"py","file_size_in_byte":14089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"521463828","text":"from pi_trees_ros.pi_trees_ros import *\nfrom pi_trees_lib.task_setup import *\n\nimport GlobalData\nimport CheckRefboxCommand\nimport SkillBook\nimport InPlay\n\n\nclass KickoffEnemy(Selector):\n def __init__(self, name):\n super(KickoffEnemy , self).__init__(name)\n\n self.prepare = Prepare('Prepare enemy kickoff')\n self.execute = Execute('Execute enemy kickoff')\n\n # add parent tasks\n self.add_child(self.prepare)\n self.add_child(self.execute)\n\nclass Prepare(ParallelAll):\n def __init__(self, name):\n super(Prepare, self).__init__(name)\n\n self.is_kickoff_enemy = CheckRefboxCommand.IsKICKOFF_ENEMY('Is Kickoff enemy')\n self.defence = SkillBook.StayAroundBall('Stay Around Ball')\n\n self.add_child(self.is_kickoff_enemy)\n self.add_child(self.defence)\n\nclass Execute(ParallelAll):\n def __init__(self, name):\n super(Execute, self).__init__(name)\n\n self.is_normal_start = CheckRefboxCommand.IsNORMAL_START('is_normal_start')\n self.move = Move('Move')\n\n self.add_child(self.is_normal_start)\n self.add_child(self.move)\n\nclass Move(Sequence):\n def __init__(self, name):\n super(Move, self).__init__(name)\n\n self.wait_inplay = SkillBook.WaitInplay('wait inplay')\n self.stay = SkillBook.StayAroundBall('StayAroundBall')\n\n self.positioning = ParallelSelector('positioning')\n self.positioning.add_child(self.wait_inplay)\n self.positioning.add_child(self.stay)\n\n self.inplay = InPlay.InPlay('inplay')\n\n self.add_child(self.positioning)\n self.add_child(self.inplay)\n","sub_path":"roots_decision_making/scripts/KickoffEnemy.py","file_name":"KickoffEnemy.py","file_ext":"py","file_size_in_byte":1663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"132220515","text":"from django.conf.urls import url\nfrom .views import (CreateBlogAPIView, UpdateBlogStatusAPIView, SelfBlogListView, BlogListView, GetBlogDetailsAPIView)\n\nurlpatterns = [\n url('createBlog', CreateBlogAPIView.as_view()),\n url('updateBlog/(?P.+)', UpdateBlogStatusAPIView.as_view()),\n url('getSelfBlogList', SelfBlogListView.as_view()),\n url('getBlogList', BlogListView.as_view()),\n url('getBlogDetails/(?P.+)', GetBlogDetailsAPIView.as_view())\n]\n","sub_path":"django_blog_session/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"290384566","text":"__author__ = 'Igor Maculan '\nimport logging\n\nfrom pushbullet import Listener, PushBullet\n\n\nlogging.basicConfig(level=logging.DEBUG)\n\nAPI_KEY = '' # YOUR API KEY\n\nHTTP_PROXY_HOST = None\nHTTP_PROXY_PORT = None\n\n\ndef on_push(message):\n print ('received push:' + str(message))\n\ndef main():\n\tpb = PushBullet(API_KEY)\n\ts = Listener(pb,on_push = on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT)\n\ttry:\n\t\ts.run_forever()\n\texcept KeyboardInterrupt:\n\t\ts.close()\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"example/listener_example.py","file_name":"listener_example.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"574625933","text":"from tkinter import *\r\nfrom tkinter import font, colorchooser, filedialog, messagebox, ttk\r\nimport os\r\nfrom fpdf import FPDF\r\n\r\nmain_application=Tk()\r\nmain_application.geometry('1200x800')\r\nmain_application.title('Vinayak Text Editor')\r\nmain_application.iconbitmap('icons2/v.ico')\r\n\r\n\r\n#*********************Main Menu****************************\r\nmain_menu=Menu()\r\n\r\n#Code for printing File icons\r\nnew_icon=PhotoImage(file='icons2/new.png')\r\nopen_icon=PhotoImage(file='icons2/open.png')\r\nsave_icon=PhotoImage(file='icons2/save.png')\r\nsave_as_icon=PhotoImage(file='icons2/save_as.png')\r\npdf_icon=PhotoImage(file='icons2/pdf.png')\r\nexit_icon=PhotoImage(file='icons2/exit.png')\r\n\r\n#Write as many terms as to be shown in the main menu bar\r\nfile=Menu(main_menu, tearoff=False) #iF tearoff flase not used, then it can be make apart from the text editor by clicking on the line shown in GUI\r\n\r\n\r\n\r\n#Code for adding edit icons\r\ncut_icon=PhotoImage(file='icons2/cut.png')\r\ncopy_icon=PhotoImage(file='icons2/copy.png')\r\npaste_icon=PhotoImage(file='icons2/paste.png')\r\nclear_all_icon=PhotoImage(file='icons2/clear_all.png')\r\nfind_icon=PhotoImage(file='icons2/find.png') #Can add undo, redoo later on\r\n\r\n\r\nedit=Menu(main_menu, tearoff=False)\r\n\r\n#Code for adding view icons\r\ntoolbar_icon=PhotoImage(file='icons2/tool_bar.png')\r\nstatusbar_icon=PhotoImage(file='icons2/status_bar.png')\r\n\r\nview=Menu(main_menu, tearoff=False)\r\n\r\n#Code for adding theme icons\r\nlight_default_icon=PhotoImage(file='icons2/light_default.png')\r\nlight_plus_icon=PhotoImage(file='icons2/light_plus.png')\r\ndark_icon=PhotoImage(file='icons2/dark.png')\r\nred_icon=PhotoImage(file='icons2/red.png')\r\nmonokai_icon=PhotoImage(file='icons2/monokai.png')\r\nnight_blue_icon=PhotoImage(file='icons2/night_blue.png')\r\nyellow_icon=PhotoImage(file='icons2/yellow.png')\r\n\r\ncolor_theme=Menu(main_menu, tearoff=False)\r\ntheme_choice=StringVar()\r\n\r\n#Code for adding color commands\r\ncolor_icons=(light_default_icon, light_plus_icon, dark_icon, red_icon, monokai_icon, night_blue_icon, yellow_icon)\r\n\r\ncolor_dict={\r\n 'Light Default':('#000000', '#ffffff'),\r\n 'Light Plus': ('#474747', '#e0e0e0'),\r\n 'Dark': ('#c4c4c4', '2d2d2d'),\r\n 'Red': ('#2d2d2d', '#ffe8e8'),\r\n 'Monokai': ('#d3b774', '#474747'),\r\n 'Night Blue': ('#ededed', '#6b9dc2'),\r\n 'Yellow': ('#ffff00', '#000000')\r\n}\r\n\r\n#Cascade all these (for displaying it on GUI)\r\nmain_menu.add_cascade(label='File', menu=file)\r\nmain_menu.add_cascade(label='Edit', menu=edit)\r\nmain_menu.add_cascade(label='View', menu=view)\r\nmain_menu.add_cascade(label='Color Theme', menu=color_theme)\r\n\r\n#*********************Main Menu End************************\r\n\r\n#*********************Toolbar****************************\r\n\r\ntool_bar=Label(main_application)\r\ntool_bar.pack(side=TOP, fill=X) #For filling screen horizontally, fill=X, filling vertically, fill=Y, filling both, fill=both\r\n\r\n#Setting font style\r\nfont_tuples=font.families()\r\nfont_family=StringVar()\r\nfont_box=ttk.Combobox(tool_bar, width=30, textvariable=font_family, state='readonly')\r\nfont_box['values']=font_tuples\r\nfont_box.current(font_tuples.index('Arial'))\r\nfont_box.grid(row=0, column=0, padx=5)\r\n\r\n#Setting size box\r\nsize_var=IntVar()\r\nfont_size=ttk.Combobox(tool_bar, width=14, textvariable=size_var, state='readonly')\r\nfont_size['values']=tuple(range(8, 81)) # (8, 81, 2) -> Size range starts from 8 and goes till 81 with the margin of 2\r\nfont_size.current(4)\r\nfont_size.grid(row=0, column=1, padx=5)\r\n\r\n#Taking Toolbar Icons\r\nbold_icon=PhotoImage(file='icons2/bold.png')\r\nitalic_icon=PhotoImage(file='icons2/italic.png')\r\nunderline_icon=PhotoImage(file='icons2/underline.png')\r\nfont_color_icon=PhotoImage(file='icons2/font_color.png')\r\nalign_left_icon=PhotoImage(file='icons2/align_left.png')\r\nalign_right_icon=PhotoImage(file='icons2/align_right.png')\r\nalign_center_icon=PhotoImage(file='icons2/align_center.png')\r\n\r\n#Creating Bold button\r\nbold_btn=ttk.Button(tool_bar, image=bold_icon)\r\nbold_btn.grid(row=0, column=2, padx=5)\r\n\r\n#Creating Italic Button\r\nitalic_btn=ttk.Button(tool_bar, image=italic_icon)\r\nitalic_btn.grid(row=0, column=3, padx=5)\r\n\r\n#Creating underline Button\r\nunderline_btn=ttk.Button(tool_bar, image=underline_icon)\r\nunderline_btn.grid(row=0, column=4, padx=5)\r\n\r\n#Creating font color button\r\nfont_color_btn=ttk.Button(tool_bar, image=font_color_icon)\r\nfont_color_btn.grid(row=0, column=5, padx=5)\r\n\r\n#Creating align left button\r\nalign_left_btn=ttk.Button(tool_bar, image=align_left_icon)\r\nalign_left_btn.grid(row=0, column=6, padx=5)\r\n\r\n#Creating align right button\r\nalign_right_btn=ttk.Button(tool_bar, image=align_right_icon)\r\nalign_right_btn.grid(row=0, column=7, padx=5)\r\n\r\n#Creating align left button\r\nalign_center_btn=ttk.Button(tool_bar, image=align_center_icon)\r\nalign_center_btn.grid(row=0, column=8, padx=5)\r\n\r\n#*********************Toolbar End************************\r\n\r\n#*********************Text Editor****************************\r\n\r\ntext_editor=Text(main_application)\r\ntext_editor.config(wrap='word', relief=FLAT)\r\n\r\n#Craeting scrollbar\r\nscroll_bar=Scrollbar(main_application)\r\nscroll_bar.config(command=text_editor.yview)\r\nscroll_bar.pack(side=RIGHT, fill=Y)\r\n\r\n#Setting focus so that the user starts writing directly in the editor\r\ntext_editor.focus_set()\r\ntext_editor.pack(fill=BOTH, expand=True)\r\ntext_editor.config(yscrollcommand=scroll_bar.set)\r\n\r\n#Font Family & Font Size Functionality\r\ncurrent_font_family='Arial'\r\ncurrent_font_size=12\r\ntext_editor.configure(font=('Arial', '12'))\r\n\r\n#Creating function for changing font\r\ndef change_font(event=None):\r\n global current_font_family\r\n current_font_family=font_family.get() #What user selects goes in font_family\r\n text_editor.configure(font=(current_font_family, current_font_size))\r\n\r\n#Creating function for font size\r\ndef change_font_size(event=None): #Writing event as None so that if no value is passed, ten also it shows no error\r\n global current_font_size\r\n current_font_size = size_var.get() # What user selects goes in font_family\r\n text_editor.configure(font=(current_font_family, current_font_size))\r\n\r\nfont_size.bind(\"<>\", change_font_size) #Binding font size\r\nfont_box.bind(\"<>\", change_font) #Binding font style\r\n\r\n##Buttons Functionalities\r\n\r\n#Bold Button function\r\ndef change_bold():\r\n text_property=font.Font(font=text_editor['font'])\r\n text_property.bind('', bold_btn)\r\n if text_property.actual()['weight']=='normal':\r\n text_editor.configure(font=(current_font_family, current_font_size, 'bold'))\r\n if text_property.actual()['weight']=='bold':\r\n text_editor.configure(font=(current_font_family, current_font_size, 'normal'))\r\n\r\n#italic button function\r\ndef change_italic():\r\n text_property=font.Font(font=text_editor['font'])\r\n if text_property.actual()['slant']=='italic':\r\n text_editor.configure(font=(current_font_family, current_font_size, 'roman'))\r\n if text_property.actual()['slant']=='roman':\r\n text_editor.configure(font=(current_font_family, current_font_size, 'italic'))\r\n\r\n\r\n#Underline button function\r\ndef change_underline():\r\n text_property = font.Font(font=text_editor['font'])\r\n if text_property.actual()['underline'] == 0:\r\n text_editor.configure(font=(current_font_family, current_font_size, 'underline'))\r\n if text_property.actual()['underline'] == 1:\r\n text_editor.configure(font=(current_font_family, current_font_size, 'normal'))\r\n\r\n#Binding Bold, italic, underline functions with app\r\nunderline_btn.configure(command=change_underline)\r\nitalic_btn.configure(command=change_italic)\r\nbold_btn.configure(command=change_bold)\r\n\r\n#Font Color functionality\r\ndef change_font_color():\r\n color_var=colorchooser.askcolor()\r\n text_editor.configure(fg=color_var[1])\r\n\r\nfont_color_btn.configure(command=change_font_color)\r\n\r\n#Align functionality\r\ndef align_left():\r\n text_content=text_editor.get(1.0, 'end') #Select all written text\r\n text_editor.tag_config('left', justify=LEFT)\r\n text_editor.delete(1.0, END)\r\n text_editor.insert(INSERT, text_content, 'left')\r\n\r\ndef align_center():\r\n text_content=text_editor.get(1.0, 'end') #Select all written text\r\n text_editor.tag_config('center', justify=CENTER)\r\n text_editor.delete(1.0, END)\r\n text_editor.insert(INSERT, text_content, 'center')\r\n\r\ndef align_right():\r\n text_content=text_editor.get(1.0, 'end') #Select all written text\r\n text_editor.tag_config('right', justify=RIGHT)\r\n text_editor.delete(1.0, END)\r\n text_editor.insert(INSERT, text_content, 'right')\r\n\r\nalign_left_btn.configure(command=align_left)\r\nalign_right_btn.configure(command=align_right)\r\nalign_center_btn.configure(command=align_center)\r\n#*********************Text Editor End************************\r\n\r\n#*********************Status Bar****************************\r\n\r\nstatus_bar=ttk.Label(main_application, text='Status Bar')\r\nstatus_bar.pack(side=BOTTOM)\r\n\r\n#Printing character and words\r\ntext_changed=False\r\ndef changed(event=None):\r\n global text_changed\r\n if text_editor.edit_modified():\r\n text_changed=True\r\n words=len(text_editor.get(1.0, 'end-1c').split())\r\n characters=len(text_editor.get(1.0, 'end-1c').replace(' ', '')) #Replace used for not counting space as character\r\n status_bar.config(text=f'Characters: {characters} Words: {words}')\r\n text_editor.edit_modified(False)\r\n\r\ntext_editor.bind('<>', changed)\r\n#*********************Status Bar End************************\r\n\r\n#*********************Main Menu Functionality****************************\r\n\r\n#Variable\r\nurl=''\r\n\r\n#New Functionality\r\ndef new_file(event=None):\r\n global url\r\n url=''\r\n MsgBox = messagebox.askquestion('Exit Application', 'Are you sure you want to create new file?', icon='warning')\r\n if MsgBox == 'yes':\r\n text_editor.delete(1.0, END)\r\n else:\r\n text_editor.delete(1.0, 1.0)\r\n\r\n#Open Functionality\r\ndef open_file(event=None):\r\n global url\r\n url=filedialog.askopenfilename(initialdir=os.getcwd(), title='Select File', filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n\r\n #url1=docx2txt.process()\r\n\r\n try:\r\n with open(url, 'r') as fr:\r\n text_editor.delete(1., END)\r\n text_editor.insert(1.0, fr.read())\r\n except FileNotFoundError:\r\n return text_editor.delete(1.0, 1.0)\r\n except:\r\n return text_editor.delete(1.0, 1.0)\r\n main_application.title(os.path.basename(url))\r\n\r\npdf=FPDF()\r\ndef pdf_create():\r\n global url, text_changed\r\n try:\r\n mbox = messagebox.askyesno('Confirmation', 'Do you want to make pdf of same file?')\r\n if mbox is True:\r\n if url:\r\n f = text_editor.get(1.0, END)\r\n for x in f:\r\n pdf.cell(200, 10, txt=x, ln=1, align='C')\r\n pdf.output(url + '.pdf')\r\n else:\r\n content2 = str(text_editor.get(1.0, END))\r\n url = filedialog.asksaveasfile(mode='w', defaultextension='.txt',\r\n filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n url.write(content2)\r\n f = text_editor.get(1.0, END)\r\n for x in f:\r\n pdf.cell(200, 10, txt=x, ln=1, align='C')\r\n pdf.output(url+'.pdf')\r\n elif mbox is False:\r\n url = filedialog.askopenfilename(initialdir=os.getcwd(), title='Select File',\r\n filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n try:\r\n with open(url, 'r') as fr:\r\n text_editor.delete(1., END)\r\n text_editor.insert(1.0, fr.read())\r\n f = text_editor.get(1.0, END)\r\n for x in f:\r\n pdf.cell(200, 10, txt=x, ln=1, align='C')\r\n pdf.output(url + '.pdf')\r\n except FileNotFoundError:\r\n return text_editor.delete(1.0, 1.0)\r\n except:\r\n return\r\n\r\n #global url\r\n #MsgBox = messagebox.askquestion('Exit Application', 'Are you sure you want to create new file?', icon='warning')\r\n #if MsgBox == 'yes':\r\n #f = open_file('')\r\n #else:\r\n #text_editor.delete(1.0, 1.0)\r\n f= text_editor.get(1.0, 'end-1c')\r\n for x in f:\r\n pdf.cell(200, 10, txt=x, ln=1, align='C')\r\n pdf.output(\"name.pdf\")\r\n\r\n#Save Functionality\r\ndef save_file(event=None):\r\n global url\r\n try:\r\n if url:\r\n content=str(text_editor.get(1.0, END))\r\n with open(url, 'w', encoding='utf-8') as fw:\r\n fw.write(content)\r\n else:\r\n url=filedialog.asksaveasfile(mode='w', defaultextension='.txt', filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n content2=text_editor.get(1.0, END)\r\n url.write(content2)\r\n url.close()\r\n except:\r\n return\r\n\r\n#Save As Functionality\r\ndef save_as_file(event=None):\r\n global url\r\n try:\r\n content=text_editor.get(1.0, END)\r\n url = filedialog.asksaveasfile(mode='w', defaultextension='.txt', filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n url.write(content)\r\n url.close()\r\n except:\r\n return\r\n\r\n#Exit Functionality\r\ndef exit_file(event=None):\r\n global url, text_changed\r\n try:\r\n if text_changed:\r\n mbox=messagebox.askyesnocancel('Warning', 'Do you want to save the file?')\r\n if mbox is True:\r\n if url:\r\n content=text_editor.get(1.0, END)\r\n with open(url, 'w', encoding='utf-8') as fw:\r\n fw.write(content)\r\n main_application.destroy()\r\n else:\r\n content2=str(text_editor.get(1.0, END))\r\n url = filedialog.asksaveasfile(mode='w', defaultextension='.txt', filetypes=(('Text File', '*.txt'), ('All files', '*.*')))\r\n url.write(content2)\r\n url.close()\r\n main_application.destroy()\r\n elif mbox is False:\r\n main_application.destroy()\r\n else:\r\n main_application.destroy()\r\n except:\r\n return\r\n\r\n#Code for adding file commands\r\nfile.add_command(label='New', image=new_icon, compound=LEFT, accelerator='Ctrl+N', command=new_file)\r\nfile.add_command(label='Open', image=open_icon, compound=LEFT, accelerator='Ctrl+O', command=open_file)\r\nfile.add_command(label='Save', image=save_icon, compound=LEFT, accelerator='Ctrl+S', command=save_file)\r\nfile.add_command(label='Save As', image=save_as_icon, compound=LEFT, accelerator='Ctrl+Alt+S', command=save_as_file)\r\nfile.add_command(label='Export to PDF', image=pdf_icon, compound=LEFT, accelerator='Ctrl+R', command=pdf_create)\r\nfile.add_command(label='Exit', image=exit_icon, compound=LEFT, accelerator='Ctrl+Q', command=exit_file)\r\n\r\n#Find functionaity\r\ndef find_file(event=None):\r\n def find():\r\n word=find_input.get()\r\n text_editor.tag_remove('match', '1.0', END)\r\n matches=0\r\n if word:\r\n start_pos='1.0'\r\n while True:\r\n start_pos=text_editor.search(word, start_pos, stopindex=END)\r\n if not start_pos:\r\n break\r\n end_pos=f'{start_pos}+{len(word)}c'\r\n text_editor.tag_add('match', start_pos, end_pos)\r\n matches+=1\r\n start_pos=end_pos\r\n text_editor.tag_config('match', foreground='red', background='yellow')\r\n\r\n def replace():\r\n word=find_input.get()\r\n replace_txt=replace_input.get()\r\n content=text_editor.get(1.0, END)\r\n new_content=content.replace(word, replace_txt)\r\n text_editor.delete(1.0, END)\r\n text_editor.insert(1.0, new_content)\r\n\r\n def exit():\r\n find_dialog.destroy()\r\n\r\n find_dialog=Toplevel()\r\n find_dialog.geometry('400x200+500+200')\r\n find_dialog.resizable(0,0) #So that it can't be resized\r\n find_frame=ttk.LabelFrame(find_dialog, text='Find/Replace')\r\n find_frame.pack(pady=20)\r\n text_find_label=ttk.Label(find_frame, text='Find: ')\r\n text_replace_label=ttk.Label(find_frame, text='Replace: ')\r\n find_input=ttk.Entry(find_frame, width=30)\r\n replace_input=ttk.Entry(find_frame, width=30)\r\n find_btn=ttk.Button(find_frame, text='Find', command=find)\r\n replace_btn=ttk.Button(find_frame, text='Replace', command=replace)\r\n exit_btn=ttk.Button(find_frame, text='Exit', command=exit)\r\n text_find_label.grid(row=0, column=0, padx=4, pady=8)\r\n text_replace_label.grid(row=1, column=0, padx=4, pady=8)\r\n find_input.grid(row=0, column=1, padx=4, pady=8)\r\n replace_input.grid(row=1, column=1, padx=4, pady=8)\r\n replace_btn.grid(row=2, column=0, padx=3, pady=8)\r\n find_btn.grid(row=2, column=1, padx=3, pady=8)\r\n exit_btn.grid(row=2, column=2, padx=3, pady=8)\r\n find_dialog.mainloop()\r\n\r\n#Code for adding edit commands\r\nedit.add_command(label='Cut', image=cut_icon, compound=LEFT, accelerator='Ctrl+X', command=lambda :text_editor.event_generate(\"\"))\r\nedit.add_command(label='Copy', image=copy_icon, compound=LEFT, accelerator='Ctrl+C', command=lambda :text_editor.event_generate(\"\"))\r\nedit.add_command(label='Paste', image=paste_icon, compound=LEFT, accelerator='Ctrl+V', command=lambda :text_editor.event_generate(\"\"))\r\nedit.add_command(label='Clear All', image=clear_all_icon, compound=LEFT, command=lambda :text_editor.delete(1.0, END))\r\nedit.add_command(label='Find', image=find_icon, compound=LEFT, accelerator='Ctrl+F', command=find_file)\r\n\r\n#View check button\r\nshow_statusbar=BooleanVar()\r\nshow_statusbar.set(True)\r\nshow_toolbar=BooleanVar()\r\nshow_toolbar.set(True)\r\n\r\ndef hide_toolbar():\r\n global show_toolbar\r\n if show_toolbar:\r\n tool_bar.pack_forget()\r\n show_toolbar=False\r\n else:\r\n text_editor.pack_forget()\r\n status_bar.pack_forget()\r\n tool_bar.pack(side=TOP, fill=X)\r\n text_editor.pack(fill=BOTH, expand=True)\r\n status_bar.pack(side=BOTTOM)\r\n show_toolbar=True\r\n\r\ndef hide_statusbar():\r\n global show_statusbar\r\n if show_statusbar:\r\n status_bar.pack_forget()\r\n show_statusbar=False\r\n else:\r\n status_bar.pack(side=BOTTOM)\r\n show_statusbar=True\r\n\r\n#Code for adding view check boxes\r\nview.add_checkbutton(label='Toolbar', onvalue=True, offvalue=0, variable=show_toolbar, image=toolbar_icon, compound=LEFT, command=hide_toolbar)\r\nview.add_checkbutton(label='Satus Bar', onvalue=1, offvalue=False, variable=show_statusbar, image=statusbar_icon, compound=LEFT, command=hide_statusbar)\r\n\r\n#Color theme\r\ndef change_theme():\r\n chosen_theme=theme_choice.get()\r\n color_tuple=color_dict.get(chosen_theme)\r\n fg_color, bg_color=color_tuple[0], color_tuple[1]\r\n text_editor.config(background=bg_color, fg=fg_color)\r\n\r\ncount=0\r\nfor i in color_dict:\r\n color_theme.add_radiobutton(label=i, image=color_icons[count], variable=theme_choice, compound=LEFT, command=change_theme)\r\n count+=1\r\n\r\n#**********************Bind shortcut Keys*****************************\r\nmain_application.bind(\"\", new_file)\r\nmain_application.bind(\"\", open_file)\r\nmain_application.bind(\"\", save_file)\r\nmain_application.bind(\"\", save_as_file)\r\nmain_application.bind(\"\", pdf_create)\r\nmain_application.bind(\"\", exit_file)\r\nmain_application.bind(\"\", find_file)\r\n\r\n#*********************Main Menu Functionality End************************\r\nmain_application.config(menu=main_menu)\r\nmain_application.mainloop()","sub_path":"texteditor.py","file_name":"texteditor.py","file_ext":"py","file_size_in_byte":19771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"491125252","text":"import TransportEquation1DCenteredImplicit\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom math import log10, sqrt\nimport sys\nimport time, json\n\n \ndef test_validation1DTransportEquationCenteredImplicit(cfl,isSmooth):\n start = time.time()\n #### 1D regular grid\n meshList=[50,100,200,400,800]\n meshType=\"1D regular grid\"\n testColor=\"Green\"\n nbMeshes=len(meshList)\n mesh_size_tab=meshList\n mesh_name='RegularGrid'\n\n a=0. ; b=1.\n error_u_tab=[0]*nbMeshes\n sol_u=[0]*nbMeshes\n total_var_u=[0]*nbMeshes\n min_u=[0]*nbMeshes\n max_u=[0]*nbMeshes\n time_tab=[0]*nbMeshes\n\n plt.close('all')\n i=0\n\n # Storing of numerical errors, mesh sizes and solution\n for nx in meshList:\n min_u[i], max_u[i], sol_u[i], total_var_u[i], error_u_tab[i], time_tab[i] = TransportEquation1DCenteredImplicit.solve(nx,cfl,a,b,isSmooth)\n assert max_u[i]>-1e-5 and max_u[i]<1+1e-5\n error_u_tab[i]=log10(error_u_tab[i])\n time_tab[i]=log10(time_tab[i])\n i=i+1\n \n end = time.time()\n\n # Plot of solution\n plt.close()\n for i in range(nbMeshes):\n plt.plot(np.linspace(a,b,meshList[i]), sol_u[i], label= str(mesh_size_tab[i]) + ' cells')\n plt.legend()\n plt.xlabel('x')\n plt.ylabel('u')\n plt.title('Plot of the numerical solution of the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_PlotOfSolution.png\") \n else:\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_PlotOfSolution.png\") \n plt.close()\n\n # Plot of maximal value\n plt.close()\n plt.plot(mesh_size_tab, max_u, label='Maximum value')\n plt.legend()\n plt.xlabel('Number of cells')\n plt.ylabel('Max |u|')\n plt.title('Maximum velocity norm of the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_MaxSolution.png\")\n else:\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_MaxSolution.png\")\n \n # Plot of total variation\n plt.close()\n plt.plot(mesh_size_tab, total_var_u, label='Total variation')\n plt.legend()\n plt.xlabel('Number of cells')\n plt.ylabel('Var(u)')\n plt.title('Total variation for the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_TotalVariation.png\")\n else:\n plt.savefig(mesh_name+\"_1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_TotalVariation.png\")\n \n for i in range(nbMeshes):\n mesh_size_tab[i]=log10(mesh_size_tab[i])\n \n # Least square linear regression\n # Find the best a,b such that f(x)=ax+b best approximates the convergence curve\n # The vector X=(a,b) solves a symmetric linear system AX=B with A=(a1,a2\\\\a2,a3), B=(b1,b2)\n a1=np.dot(mesh_size_tab,mesh_size_tab)\n a2=np.sum(mesh_size_tab)\n a3=nbMeshes\n \n det=a1*a3-a2*a2\n assert det!=0, 'test_validation1DTransportEquationCenteredImplicit() : Make sure you use distinct meshes and at least two meshes'\n\n b1u=np.dot(error_u_tab,mesh_size_tab) \n b2u=np.sum(error_u_tab)\n au=( a3*b1u-a2*b2u)/det\n bu=(-a2*b1u+a1*b2u)/det\n \n print(\"Implicit Centered scheme for Transport Equation on 1D regular grid : scheme order is \", -au)\n \n # Plot of convergence curve\n plt.close()\n plt.plot(mesh_size_tab, error_u_tab, label='log(|error|)')\n plt.plot(mesh_size_tab, a*np.array(mesh_size_tab)+b,label='least square slope : '+'%.3f' % a)\n plt.legend()\n plt.xlabel('log(Number of cells)')\n plt.ylabel('log(|error u|)')\n plt.title('Convergence of finite volumes for the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_ConvergenceCurve.png\")\n else:\n plt.savefig(mesh_name+\"1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_ConvergenceCurve.png\")\n \n # Plot of computational time\n plt.close()\n plt.plot(mesh_size_tab, time_tab, label='log(cpu time)')\n plt.legend()\n plt.xlabel('log(Number of cells)')\n plt.ylabel('log(cpu time)')\n plt.title('Computational time of finite volumes for the transport equation \\n with implicit centered scheme on a 1D regular grid')\n if(isSmooth):\n plt.savefig(mesh_name+\"1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Smooth_ComputationalTime.png\")\n else:\n plt.savefig(mesh_name+\"1DTransportEquationCenteredImplicit_CFL\"+str(cfl)+\"_Stiff_ComputationalTime.png\")\n\n plt.close('all')\n\n convergence_synthesis={}\n\n convergence_synthesis[\"PDE_model\"]=\"Transport_Equation\"\n convergence_synthesis[\"PDE_is_stationary\"]=False\n convergence_synthesis[\"PDE_search_for_stationary_solution\"]=True\n convergence_synthesis[\"Numerical_method_name\"]=\"Centered scheme\"\n convergence_synthesis[\"Numerical_method_space_discretization\"]=\"Finite volumes\"\n convergence_synthesis[\"Numerical_method_time_discretization\"]=\"Implicit\"\n convergence_synthesis[\"Initial_data\"]=\"sine\"\n convergence_synthesis[\"Boundary_conditions\"]=\"Periodic\"\n convergence_synthesis[\"Numerical_parameter_cfl\"]=cfl\n convergence_synthesis[\"Space_dimension\"]=2\n convergence_synthesis[\"Mesh_dimension\"]=2\n convergence_synthesis[\"Mesh_names\"]=meshList\n convergence_synthesis[\"Mesh_type\"]=meshType\n convergence_synthesis[\"Mesh_description\"]=mesh_name\n convergence_synthesis[\"Mesh_sizes\"]=mesh_size_tab\n convergence_synthesis[\"Mesh_cell_type\"]=\"1D regular grid\"\n convergence_synthesis[\"Numerical_ersolution\"]=max_u\n convergence_synthesis[\"Scheme_order\"]=-au\n convergence_synthesis[\"Test_color\"]=testColor\n convergence_synthesis[\"Computational_time\"]=end-start\n\n with open('Convergence_1DTransportEquationCenteredImplicit_'+mesh_name+'.json', 'w') as outfile: \n json.dump(convergence_synthesis, outfile)\n\nif __name__ == \"\"\"__main__\"\"\":\n if len(sys.argv) >2 :\n cfl = float(sys.argv[1])\n isSmooth = bool(int(sys.argv[2]))\n test_validation1DTransportEquationCenteredImplicit(cfl,isSmooth)\n else :\n test_validation1DTransportEquationCenteredImplicit(0.99,True)\n\n","sub_path":"tests/validation/TransportEquation1D/1DTransportCenteredImplicit/test_validation1DTransportEquationCenteredImplicit.py","file_name":"test_validation1DTransportEquationCenteredImplicit.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"264677598","text":"\n\nfrom xai.brain.wordbase.nouns._making import _MAKING\n\n#calss header\nclass _MAKINGS(_MAKING, ):\n\tdef __init__(self,): \n\t\t_MAKING.__init__(self)\n\t\tself.name = \"MAKINGS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"making\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_makings.py","file_name":"_makings.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"187401315","text":"from psychopy import core, visual, event, data, gui # basic psychopy stuff\nimport numpy as np # for math stuff\n\n##############################################\n# settings\n##############################################\n\ncondfile = \"conditions.csv\" # replace with absolute path\ndur_fix = 0.5\ndur_stim = 0.125\ndur_mask = None # random\ndur_iti = 0.5\n\n##############################################\n# pre-experiment dialog\n##############################################\n\n# define questions for prompt\nsession_data = {\n 'sub_initials': 'abc',\n 'sub_number': 0\n}\n# display dialog; data is stored in session_data\n\n# *****************\n# task: create a pre-experiment dialog\n# *****************\n\n##############################################\n# load conditions file and initialize handlers\n##############################################\n\n# import formatted file containing info for each trial\nconditions = data.importConditions(condfile)\n# this lets us loop through all conditions\ntrial_handler = data.TrialHandler(conditions, name='horsezeb',\n nReps=1, method='random')\n# this handles behavioral data\nexp_handler = data.ExperimentHandler(name='horsezeb',\n dataFileName='data/{}'.format(session_data['sub_initials']))\n# allow exp_handler to retrieve trial information from trial_handler\nexp_handler.addLoop(trial_handler)\n\n##############################################\n# initialize window\n##############################################\n\n# create the main window using a normed coordinate system\nwin = visual.Window((1280,1024), fullscr=False, units='height')\n\n##############################################\n# prepare + present instructions\n##############################################\n\ninstructions_message = \"\"\"this is the world-famous zebra-horse discrimination task.\nin each trial, press A if you saw a zebra, L if you saw a horse.\"\"\"\n\nmessage = visual.TextStim(win, text=instructions_message, height=0.03)\n\nmessage.draw()\nwin.flip()\nevent.waitKeys() # press any key to continue\nwin.flip() # clear screen\n\n##############################################\n# initialize stimuli/messages\n##############################################\n\nfix = visual.TextStim(win, text=\"+\", height=0.1)\nstim = None # ************** task: initialize\nprobe1 = visual.TextStim(win, text='zebra or horse?', pos=(0,0), height=0.05)\nprobe2 = visual.TextStim(win, text='press A for zebra, L for horse',\n pos=(0,-0.15), height=0.03)\n\nresp_clock = core.Clock() # for measuring response times\n\n##############################################\n# main loop\n##############################################\n\nwhile trial_handler.getFutureTrial(): # loop through all conditions\n trial = trial_handler.next() # retrieve info for current trial\n print(trial)\n\n ### whatever happens each trial goes here ###\n\n # *****************\n # task: implement the trial sequence here\n # *****************\n\n exp_handler.nextEntry() # next row in results csv\n\n##############################################\n# exp finished\n##############################################\n\n# *****************\n# task: create a finish message\n# *****************\n\nevent.waitKeys() # close after any key press\ncore.quit()\n","sub_path":"experiment1/exp1Base.py","file_name":"exp1Base.py","file_ext":"py","file_size_in_byte":3194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"387277178","text":"import re\nimport string\nfrom pymorphy2.tokenizers import simple_word_tokenize\nfrom pymorphy2 import MorphAnalyzer\n\n\nstopwoards = set(string.punctuation) | {'_','—','–','−','_tem'}\nmorph= MorphAnalyzer()\nsent_tokenize = re.compile(\"[.,?!'\\'\\n]\").split\n\ndef best_parser(token,parses):\n for p in parses:\n if token.istitle() and {'Geox', 'Name', 'Surn', 'Patr'} & p.tag.grammemes:#если с большой буквы и входит в теги одушевл.: #Geox-георгрифия,Name-имя,Surn-фамилия\n return p#оставляем в той же форме #Patr-отчество\n if p.tag.POS == 'NPRO': #если местоимение(NPRO-местоимение)\n return p\n return parses[0]\n\n\n#приведение в нормальную форму\ndef normal_form(p):\n if {'Patr', 'Surn'} & p.tag.grammemes:#если это Фамилия или отчество\n #print(p.word)\n #print(p.inflect({'sing', 'nomn'}).word)\n return p.inflect({'sing', 'nomn'}).word #склоняет в sign-единственное число,nomn-именительный падеж и возвращает\n return p.normal_form #слово приводит в нормальную\n\n#ф-ия нормализации слова:\ndef normalized(tokens):\n #нормализуем каждый токен в зависимости от надобности\n parser = [\n #print(morph.parse(w))\n best_parser(w, morph.parse(w))\n for w in tokens\n if w.lower() not in stopwoards\n ]\n\n #убирает токены,которые не соответсвуют частям речи\n parser = [\n p for p in parser\n #if p.tag.POS not in {'PNCT', 'LATN', 'CONJ', 'NUMB', 'PREP'}#CONJ-союз,#PNCT-пунктуация,NUMB-число,LATN-токен состоит из лат.букв\n #if not {'PNCT', 'CONJ', 'NUMB,real', 'NUMB', 'NUMB,intg', 'PREP', 'UNKN'} & p.tag.grammemes\n if not {'PNCT', 'CONJ', 'NUMB,real', 'NUMB', 'NUMB,intg', 'PREP'} & p.tag.grammemes\n ]\n #возвращает нормальную форму слова,приведенного в нижний регистр\n #print(normal_form(p).lower() for p in parser)\n return [normal_form(p).lower() for p in parser]\n\n\n#Ф-ИЯ ДЛЯ РАЗБИЕНИЯ СТРОКИ НА ТОКЕНЫ И ПЕРЕДАЧА В Ф-ИЮ НОРМАЛИЗАЦИИ\n#делит единую строку на отдельные строки,а так же\n#убирает из строки разделители,которые заданы регулярным выражением sent_tokenize с помощью библиотеки re.\n#После чего убирает из начала и конца строки пробелы(sent.strip()) с пом. библиотеки string и ее метода strip\n#и передает в ф-ию нормализации список из токенов с пом. библиотеки pymorphy2 и метода simple_word_tokenize\n# пример:\n#вход(book)-\" Я ничего не понимаю, может быть\"\n#параметр передаваем в ф-ию normalized: ['Я', 'ничего', 'не', 'понимаю'],['может', 'быть']\n''''\ndef get_sents(book):\n return [\n normalized(simple_word_tokenize(sent.strip()))\n for sent in sent_tokenize(book) if sent.strip()\n #normalized(simple_word_tokenize(book))\n ]\n'''\n\ndef get_sents(input_data):\n return [\n normalized(simple_word_tokenize(sent))\n for sent in input_data\n ]\n\n\n\nif __name__ == \"__main__\":\n while 1:\n print(\"Введите текстр\")\n text = input()\n print(get_sents([text]))","sub_path":"Classificator/Learn_neiro/lemmatization.py","file_name":"lemmatization.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"127227281","text":"#!/usr/bin/env python3\n\"\"\"\nTakes a cifti map ('dscalar.nii') and outputs a csv of results\n\nUsage:\n ciftify_statclust_report [options] \n\nArguments:\n Input map.\n\nOptions:\n --min-threshold MIN the largest value [default: -2.85] to consider for being a minimum\n --max-threshold MAX the smallest value [default: 2.85] to consider for being a maximum\n --area-threshold MIN threshold [default: 20] for surface cluster area, in mm^2\n --surface-distance MM minimum distance in mm [default: 20] between extrema of the same type.\n --volume-distance MM minimum distance in mm [default: 20] between extrema of the same type.\n\n --outputbase prefix Output prefix (with path) to output documents\n --no-cluster-dlabel Do not output a dlabel map of the clusters\n --output-peaks Also output an additional output of peak locations\n\n --left-surface GII Left surface file (default is HCP S1200 Group Average)\n --right-surface GII Right surface file (default is HCP S1200 Group Average)\n --left-surf-area GII Left surface vertex areas file (default is HCP S1200 Group Average)\n --right-surf-area GII Right surface vertex areas file (default is HCP S1200 Group Average)\n\n --debug Debug logging\n -n,--dry-run Dry run\n -h, --help Prints this message\n\nDETAILS\nNote: at the moment generates separate outputs for surface.\nUses -cifti-separate in combination with FSL's clusterize to get information from\nthe subcortical space.\n\nOutputs a cluster report csv with the following headings:\n + clusterID: Integer for the cluster this peak is from (corresponds to dlabel.nii)\n + cluster_name: the cluster label\n + by default this will be \"LABEL_\" but this be changed\n in the .dlabel.nii file using connectome-workbench\n + mean_value: the average value for this cluster within the input dscalar.nii map\n + area: the surface area of the cluster (on the specified surface)\n + DKT_overlap: a list of DKT freesurfer anatomical atlas (aparc) atlas labels\n that overlap with this cluster and the percent overlap of each label\n + Yeo7_overlap: a list of the Yeo et al 2011 7 network labels that overlap\n with this cluster and the percent overlap of each label\n + MMP_overlap: The labels from the Glasser et al (2016) Multi-Modal Parcellation\n that overlap with this cluster and the percent overlap of each label\n\nIf the '--output-peaks' flag is indicated, an addtional table will be output\nwith several headings:\n + clusterID: Integer for the cluster this peak is from (corresponds to dlabel.nii)\n + hemisphere: Hemisphere the peak is in (L or R)\n + vertex: The vertex id\n + x,y,z: The nearest x,y,z coordinates to the vertex\n + value: The intensity (value) at that vertex in the func.dscalar.nii\n + DKT: The label from the freesurfer anatomical atlas (aparc) at the vertex\n + DKT_overlap: The proportion of the cluster (clusterID) that overlaps with the DKT atlas label\n + Yeo7: The label from the Yeo et al 2011 7 network atlas at this peak vertex\n + Yeo7_overlap: The proportion of the cluster (clusterID) that overlaps with this Yeo7 network label\n + MMP: The label from the Glasser et al (2016) Multi-Modal Parcellation\n + MMP_overlap: The proportion of the cluster (clusterID) that overlaps with the MMP atlas label\n\nIf no surfaces of surface area files are given. The midthickness surfaces from\nthe HCP S1200 Group Mean will be used, as well as it's vertex-wise\nsurface area infomation.\n\nDefault name for the output csv taken from the input file.\ni.e. func.dscalar.nii --> func_peaks.csv\n\nUnless the '--no-cluster-dlabel' flag is given, a map of the clusters with be\nbe written to the same folder as the outputcsv to aid in visualication of the results.\nThis dlable map with have a name ending in '_clust.dlabel.nii'.\n(i.e. func_peaks.csv & func_clust.dlabel.nii)\n\nAtlas References:\nYeo, BT. et al. 2011. 'The Organization of the Human Cerebral Cortex\nEstimated by Intrinsic Functional Connectivity.' Journal of Neurophysiology\n106 (3): 1125-65.\n\nDesikan, RS.et al. 2006. 'An Automated Labeling System for Subdividing the\nHuman Cerebral Cortex on MRI Scans into Gyral Based Regions of Interest.'\nNeuroImage 31 (3): 968-80.\n\nGlasser, MF. et al. 2016. 'A Multi-Modal Parcellation of Human Cerebral Cortex.'\nNature 536 (7615): 171-78.\n\nWritten by Erin W Dickie, Last updated August 27, 2017\n\"\"\"\nfrom docopt import docopt\nimport os, sys\nimport numpy as np\nimport pandas as pd\nimport logging\nimport logging.config\nimport ciftify.niio\nimport ciftify.report\nimport ciftify.utils\nfrom ciftify.meants import NibInput\n\nconfig_path = os.path.join(os.path.dirname(ciftify.config.find_ciftify_global()), 'bin', \"logging.conf\")\nlogging.config.fileConfig(config_path, disable_existing_loggers=False)\nlogger = logging.getLogger(os.path.basename(__file__))\n\ndef load_LR_vertex_areas(surf_settings):\n ''' loads the vertex areas and stacks the dataframes'''\n surf_va_L = ciftify.niio.load_gii_data(surf_settings.L.vertex_areas)\n surf_va_R = ciftify.niio.load_gii_data(surf_settings.R.vertex_areas)\n surf_va_LR = np.vstack((surf_va_L, surf_va_R))\n return(surf_va_LR)\n\n\ndef report_atlas_overlap(df, label_data, atlas, surf_va_LR, min_percent_overlap = 5):\n # read the atlas\n atlas_data, atlas_dict = ciftify.niio.load_LR_label(atlas['path'],\n int(atlas['map_number']))\n # write an overlap report to the outputfile\n o_col = '{}_overlap'.format(atlas['name'])\n df[o_col] = \"\"\n for pd_idx in df.index.get_values():\n df.loc[pd_idx, o_col] = ciftify.report.get_label_overlap_summary(\n pd_idx, label_data, atlas_data, atlas_dict, surf_va_LR,\n min_percent_overlap = min_percent_overlap)\n return(df)\n\n\ndef run_ciftify_dlabel_report(arguments, tmpdir):\n\n dscalar_in = NibInput(arguments[''])\n surf_distance = arguments['--surface-distance']\n\n outputbase = arguments['--outputbase']\n dont_output_clusters = arguments['--no-cluster-dlabel']\n output_peaktable = arguments['--output-peaks']\n\n surf_settings = ciftify.report.CombinedSurfaceSettings(arguments, tmpdir)\n atlas_settings = ciftify.report.define_atlas_settings()\n\n ## if not outputname is given, create it from the input dscalar map\n if not outputbase:\n outputbase = os.path.join(os.path.dirname(dscalar_in.path), dscalar_in.base)\n ciftify.utils.check_output_writable(outputbase, exit_on_error = True)\n\n clusters_dscalar = clusterise_dscalar_input(dscalar_in.path,\n arguments,\n surf_settings,\n tmpdir)\n\n if dont_output_clusters:\n cluster_dlabel = os.path.join(tmpdir, 'clust.dlabel.nii')\n else:\n cluster_dlabel = '{}_clust.dlabel.nii'.format(outputbase)\n empty_labels = os.path.join(tmpdir, 'empty_labels.txt')\n ciftify.utils.run('touch {}'.format(empty_labels))\n ciftify.utils.run(['wb_command', '-cifti-label-import',\n clusters_dscalar, empty_labels, cluster_dlabel])\n\n ## load the data\n label_data, label_dict = ciftify.niio.load_LR_label(cluster_dlabel, map_number = 1)\n\n ## define the outputcsv\n outputcsv = '{}_statclust_report.csv'.format(outputbase)\n logger.info('Output table: {}'.format(outputcsv))\n\n ## load the vertex areas\n surf_va_LR = load_LR_vertex_areas(surf_settings)\n\n ## assert that the dimensions match\n if not (label_data.shape[0] == surf_va_LR.shape[0]):\n logger.error('label file vertices {} not equal to vertex areas {}'\n ''.format(label_data.shape[0], surf_va_LR.shape[0]))\n sys.exit(1)\n\n ## use the label dict to start the report dataframe\n df = pd.DataFrame.from_dict(label_dict, orient = \"index\")\n df['label_idx'] = df.index\n df = df.rename(index=str, columns={0: \"label_name\"})\n\n\n # calculate a column of the surface area for row ROIs\n df['area'] = -999\n for pd_idx in df.index.get_values():\n df.loc[pd_idx, 'area'] = ciftify.report.calc_cluster_area(pd_idx,\n label_data, surf_va_LR)\n\n for atlas in atlas_settings.values():\n df = report_atlas_overlap(df, label_data, atlas,\n surf_va_LR, min_percent_overlap = 5)\n\n df.to_csv(outputcsv)\n\n if output_peaktable:\n write_statclust_peaktable(dscalar_in.path, clusters_dscalar, outputbase,\n arguments, surf_settings, atlas_settings)\n\nclass ThresholdArgs:\n '''little class that holds the user aguments about thresholds'''\n def __init__(self, arguments):\n self.max = arguments([])\n area_threshold = arguments['--area-threshold']\n self.volume_distance = arguments['--volume-distance']\n min_threshold = arguments['--min-threshold']\n max_threshold = arguments['--max-threshold']\n area_threshold = arguments['--area-thratlas_settingseshold']\n\ndef clusterise_dscalar_input(data_file, arguments, surf_settings, tmpdir):\n '''runs wb_command -cifti-find-clusters twice\n returns the path to the output\n '''\n ## also run clusterize with the same settings to get clusters\n pcluster_dscalar = os.path.join(tmpdir,'pclusters.dscalar.nii')\n\n wb_cifti_clusters(data_file, pcluster_dscalar, surf_settings,\n arguments['--max-threshold'],\n arguments['--area-threshold'],\n less_than = False, starting_label=1)\n\n ## load both cluster files to determine the max value\n pos_clust_data = ciftify.niio.load_concat_cifti_surfaces(pcluster_dscalar)\n max_pos = int(np.max(pos_clust_data))\n\n ## now get the negative clusters\n ncluster_dscalar = os.path.join(tmpdir,'nclusters.dscalar.nii')\n wb_cifti_clusters(data_file, ncluster_dscalar, surf_settings,\n arguments['--min-threshold'],\n arguments['--area-threshold'],\n less_than = True, starting_label=max_pos + 1)\n\n ## add the positive and negative together to make one cluster map\n clusters_out = os.path.join(tmpdir,'clusters.dscalar.nii')\n ciftify.utils.run(['wb_command', '-cifti-math \"(x+y)\"',\n clusters_out,\n '-var','x',pcluster_dscalar, '-var','y',ncluster_dscalar])\n return clusters_out\n\ndef wb_cifti_clusters(input_cifti, output_cifti, surf_settings,\n value_threshold, minimun_size,less_than, starting_label=1):\n '''runs wb_command -cifti-find-clusters'''\n wb_arglist = ['wb_command', '-cifti-find-clusters',\n input_cifti,\n str(value_threshold), str(minimun_size),\n str(value_threshold), str(minimun_size),\n 'COLUMN',\n output_cifti,\n '-left-surface', surf_settings.L.surface,\n '-corrected-areas', surf_settings.L.vertex_areas,\n '-right-surface', surf_settings.R.surface,\n '-corrected-areas', surf_settings.R.vertex_areas,\n '-start', str(starting_label)]\n if less_than : wb_arglist.append('-less-than')\n cinfo = ciftify.niio.cifti_info(input_cifti)\n if cinfo['maps_to_volume']: wb_arglist.append('-merged-volume')\n ciftify.utils.run(wb_arglist)\n\ndef write_statclust_peaktable(data_file, clusters_dscalar, outputbase,\n arguments, surf_settings, atlas_settings):\n '''runs the old peak table functionality\n\n Parameters\n ----------\n data_file : filepath\n path to the dscalar map input\n clusters_dscalar : filepath\n path to the cluster file created with same settings\n outputbase :\n the prefix for the outputfile\n arguments : dict\n the user args dictionary to pull the thresholds from\n surf_settings : dict\n the dictionary of paths to the surface files,\n created by ciftify.report.CombinedSurfaceSettings\n altas_settings : dict\n dictionary of paths and settings related to the atlases to use for overlaps\n comparison. Created by ciftify.report.define_atlas_settings()\n\n Outputs\n -------\n writes a csv to _cortex_peaks.csv\n '''\n with ciftify.utils.TempDir() as ex_tmpdir:\n ## run FSL's cluster on the subcortical bits\n ## now to run FSL's cluster on the subcortical bits\n cinfo = ciftify.niio.cifti_info(data_file)\n if cinfo['maps_to_volume']:\n subcortical_vol = os.path.join(ex_tmpdir, 'subcortical.nii.gz')\n ciftify.utils.run(['wb_command', '-cifti-separate', data_file, 'COLUMN', '-volume-all', subcortical_vol])\n fslcluster_cmd = ['cluster',\n '--in={}'.format(subcortical_vol),\n '--thresh={}'.format(arguments['--max-threshold']),\n '--peakdist={}'.format(arguments['--volume-distance'])]\n peak_table = ciftify.utils.get_stdout(fslcluster_cmd)\n with open(\"{}_subcortical_peaks.csv\".format(outputbase), \"w\") as text_file:\n text_file.write(peak_table.replace('/t',','))\n else:\n logger.info('No subcortical volume data in {}'.format(data_file))\n\n ## run wb_command -cifti-extrema to find the peak locations\n extrema_dscalar = os.path.join(ex_tmpdir,'extrema.dscalar.nii')\n ciftify.utils.run(['wb_command','-cifti-extrema',\n data_file,\n str(arguments['--surface-distance']),\n str(arguments['--volume-distance']),\n 'COLUMN',\n extrema_dscalar,\n '-left-surface', surf_settings.L.surface,\n '-right-surface', surf_settings.R.surface,\n '-threshold',\n str(arguments['--min-threshold']),\n str(arguments['--max-threshold'])])\n\n ## multiply the cluster labels by the extrema to get the labeled exteama\n lab_extrema_dscalar = os.path.join(ex_tmpdir,'lab_extrema.dscalar.nii')\n ciftify.utils.run(['wb_command', '-cifti-math \"(abs(x*y))\"',\n lab_extrema_dscalar,\n '-var','x',clusters_dscalar, '-var','y',extrema_dscalar])\n\n ## run left and right dfs... then concatenate them\n dfL = build_hemi_results_df(surf_settings.L, atlas_settings,\n data_file, lab_extrema_dscalar, clusters_dscalar)\n dfR = build_hemi_results_df(surf_settings.R, atlas_settings,\n data_file, lab_extrema_dscalar, clusters_dscalar)\n df = dfL.append(dfR, ignore_index = True)\n\n ## write the table out to the outputcsv\n output_columns = ['clusterID','hemisphere','vertex', 'peak_value', 'area']\n decimals_out = {\"clusterID\":0, 'peak_value':3, 'area':0}\n for atlas in atlas_settings.keys():\n atlas_name = atlas_settings[atlas]['name']\n output_columns.append(atlas_name)\n output_columns.append('{}_overlap'.format(atlas_name))\n decimals_out['{}_overlap'.format(atlas_name)] = 3\n\n df = df.round(decimals_out)\n df.to_csv(\"{}_cortex_peaks.csv\".format(outputbase),\n columns = output_columns,index=False)\n\n\n\ndef build_hemi_results_df(surf_settings, atlas_settings,\n input_dscalar, extreama_dscalar, clusters_dscalar):\n\n ## read in the extrema file from above\n extrema_array = ciftify.niio.load_hemisphere_data(extreama_dscalar, surf_settings.wb_structure)\n vertices = np.nonzero(extrema_array)[0] # indices - vertex id for peaks in hemisphere\n\n ## read in the original data for the value column\n input_data_array = ciftify.niio.load_hemisphere_data(input_dscalar, surf_settings.wb_structure)\n\n ## load both cluster indices\n clust_array = ciftify.niio.load_hemisphere_data(clusters_dscalar, surf_settings.wb_structure)\n\n ## load the coordinates\n coords = ciftify.niio.load_surf_coords(surf_settings.surface)\n surf_va = ciftify.niio.load_gii_data(surf_settings.vertex_areas)\n\n ## put all this info together into one pandas dataframe\n df = pd.DataFrame({\"clusterID\": np.reshape(extrema_array[vertices],(len(vertices),)),\n \"hemisphere\": surf_settings.hemi,\n \"vertex\": vertices,\n 'peak_value': [round(x,3) for x in np.reshape(input_data_array[vertices],(len(vertices),))]})\n\n ## look at atlas overlap\n for atlas in atlas_settings.keys():\n df = calc_atlas_overlap(df, surf_settings.wb_structure, clust_array, surf_va, atlas_settings[atlas])\n\n return(df)\n\ndef calc_atlas_overlap(df, wb_structure, clust_label_array, surf_va, atlas_settings):\n '''\n calculates the surface area column of the peaks table\n needs hemisphere specific inputs\n '''\n\n ## load atlas\n atlas_label_array, atlas_dict = ciftify.niio.load_hemisphere_labels(atlas_settings['path'],\n wb_structure,\n map_number = atlas_settings['map_number'])\n\n atlas_prefix = atlas_settings['name']\n\n ## create new cols to hold the data\n df[atlas_prefix] = pd.Series('not_calculated', index = df.index)\n overlap_col = '{}_overlap'.format(atlas_prefix)\n df[overlap_col] = pd.Series(-99.0, index = df.index)\n\n for pd_idx in df.index.tolist():\n ## atlas interger label is the integer at the vertex\n atlas_label = atlas_label_array[df.loc[pd_idx, 'vertex']]\n\n ## the atlas column holds the labelname for this label\n df.loc[pd_idx, atlas_prefix] = atlas_dict[atlas_label]\n\n overlap_area = ciftify.report.calc_overlapping_area(\n df.loc[pd_idx, 'clusterID'], clust_label_array,\n atlas_label, atlas_label_array,\n surf_va)\n\n ## overlap area is the area of the overlaping region over the total cluster area\n clust_area = ciftify.report.calc_cluster_area(\n df.loc[pd_idx, 'clusterID'],\n clust_label_array,\n surf_va)\n\n df.loc[pd_idx, overlap_col] = overlap_area/clust_area\n\n return(df)\n\ndef main():\n arguments = docopt(__doc__)\n\n logger.setLevel(logging.WARNING)\n\n if arguments['--debug']:\n logger.setLevel(logging.DEBUG)\n logging.getLogger('ciftify').setLevel(logging.DEBUG)\n\n ## set up the top of the log\n logger.info('{}{}'.format(ciftify.utils.ciftify_logo(),\n ciftify.utils.section_header('Starting ciftify_statclust_report')))\n\n ciftify.utils.log_arguments(arguments)\n\n with ciftify.utils.TempDir() as tmpdir:\n logger.info('Creating tempdir:{} on host:{}'.format(tmpdir,\n os.uname()[1]))\n ret = run_ciftify_dlabel_report(arguments, tmpdir)\n\nif __name__ == '__main__':\n main()\n","sub_path":"ciftify/bin/ciftify_statclust_report.py","file_name":"ciftify_statclust_report.py","file_ext":"py","file_size_in_byte":18720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"418175493","text":"import copy\nimport os\n\nimport numpy as np\nimport pytest\nimport scipy.sparse as sp\nfrom scipy.spatial.distance import cdist as scipy_cdist\n\nfrom jina import Document, DocumentArray\nfrom jina.math.dimensionality_reduction import PCA\nfrom jina.types.arrays.memmap import DocumentArrayMemmap\n\n\n@pytest.fixture()\ndef doc_lists():\n d1 = Document(embedding=np.array([0, 0, 0]))\n d2 = Document(embedding=np.array([3, 0, 0]))\n d3 = Document(embedding=np.array([1, 0, 0]))\n d4 = Document(embedding=np.array([2, 0, 0]))\n\n d1_m = Document(embedding=np.array([1, 0, 0]))\n d2_m = Document(embedding=np.array([2, 0, 0]))\n d3_m = Document(embedding=np.array([0, 0, 1]))\n d4_m = Document(embedding=np.array([0, 0, 2]))\n d5_m = Document(embedding=np.array([0, 0, 3]))\n\n return [d1, d2, d3, d4], [d1_m, d2_m, d3_m, d4_m, d5_m]\n\n\n@pytest.fixture\ndef docarrays_for_embedding_distance_computation(doc_lists):\n D1, D2 = doc_lists\n da1 = DocumentArray(D1)\n da2 = DocumentArray(D2)\n return da1, da2\n\n\n@pytest.fixture\ndef docarrays_for_embedding_distance_computation_sparse():\n d1 = Document(embedding=sp.csr_matrix([0, 0, 0]))\n d2 = Document(embedding=sp.csr_matrix([3, 0, 0]))\n d3 = Document(embedding=sp.csr_matrix([1, 0, 0]))\n d4 = Document(embedding=sp.csr_matrix([2, 0, 0]))\n\n d1_m = Document(embedding=sp.csr_matrix([1, 0, 0]))\n d2_m = Document(embedding=sp.csr_matrix([2, 0, 0]))\n d3_m = Document(embedding=sp.csr_matrix([0, 0, 1]))\n d4_m = Document(embedding=sp.csr_matrix([0, 0, 2]))\n d5_m = Document(embedding=sp.csr_matrix([0, 0, 3]))\n\n D1 = DocumentArray([d1, d2, d3, d4])\n D2 = DocumentArray([d1_m, d2_m, d3_m, d4_m, d5_m])\n return D1, D2\n\n\n@pytest.fixture\ndef embeddings():\n return np.array([[1, 0, 0], [2, 0, 0], [3, 0, 0]])\n\n\ndef doc_lists_to_doc_arrays(\n doc_lists, tmpdir, first_memmap, second_memmap, buffer_pool_size\n):\n doc_list1, doc_list2 = doc_lists\n\n tmpdir1, tmpdir2 = tmpdir / '1', tmpdir / '2'\n\n D1 = (\n DocumentArray()\n if not first_memmap\n else DocumentArrayMemmap(tmpdir1, buffer_pool_size=buffer_pool_size)\n )\n D1.extend(doc_list1)\n D2 = (\n DocumentArray()\n if not second_memmap\n else DocumentArrayMemmap(tmpdir2, buffer_pool_size=buffer_pool_size)\n )\n D2.extend(doc_list2)\n return D1, D2\n\n\n@pytest.mark.parametrize('buffer_pool_size', [1000, 3])\n@pytest.mark.parametrize('first_memmap', [True, False])\n@pytest.mark.parametrize('second_memmap', [True, False])\n@pytest.mark.parametrize(\n 'limit, batch_size', [(1, None), (2, None), (None, None), (1, 1), (1, 2), (2, 1)]\n)\ndef test_matching_retrieves_correct_number(\n doc_lists, limit, batch_size, first_memmap, second_memmap, tmpdir, buffer_pool_size\n):\n D1, D2 = doc_lists_to_doc_arrays(\n doc_lists,\n tmpdir,\n first_memmap,\n second_memmap,\n buffer_pool_size=buffer_pool_size,\n )\n D1.match(D2, metric='sqeuclidean', limit=limit, batch_size=batch_size)\n for m in D1.get_attributes('matches'):\n if limit is None:\n assert len(m) == len(D2)\n else:\n assert len(m) == limit\n\n\n@pytest.mark.parametrize('metric', ['sqeuclidean', 'cosine'])\ndef test_matching_same_results_with_sparse(\n docarrays_for_embedding_distance_computation,\n docarrays_for_embedding_distance_computation_sparse,\n metric,\n):\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_sp, D2_sp = docarrays_for_embedding_distance_computation_sparse\n\n # use match with numpy arrays\n D1.match(D2, metric=metric)\n distances = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances.extend([d.scores[metric].value])\n\n # use match with sparse arrays\n D1_sp.match(D2_sp, metric=metric)\n distances_sparse = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances_sparse.extend([d.scores[metric].value])\n\n np.testing.assert_equal(distances, distances_sparse)\n\n\n@pytest.mark.parametrize('metric', ['sqeuclidean', 'cosine'])\ndef test_matching_same_results_with_batch(\n docarrays_for_embedding_distance_computation,\n metric,\n):\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_batch = copy.deepcopy(D1)\n D2_batch = copy.deepcopy(D2)\n\n # use match without batches\n D1.match(D2, metric=metric)\n distances = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances.extend([d.scores[metric].value])\n\n # use match with batches\n D1_batch.match(D2_batch, metric=metric, batch_size=10)\n\n distances_batch = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances_batch.extend([d.scores[metric].value])\n\n np.testing.assert_equal(distances, distances_batch)\n\n\n@pytest.mark.parametrize('metric', ['euclidean', 'cosine'])\ndef test_matching_scipy_cdist(\n docarrays_for_embedding_distance_computation,\n metric,\n):\n def scipy_cdist_metric(X, Y, *args):\n return scipy_cdist(X, Y, metric=metric)\n\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_scipy = copy.deepcopy(D1)\n\n # match with our custom metric\n D1.match(D2, metric=metric)\n distances = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances.extend([d.scores[metric].value])\n\n # match with callable cdist function from scipy\n D1_scipy.match(D2, metric=scipy_cdist_metric)\n distances_scipy = []\n for m in D1.get_attributes('matches'):\n for d in m:\n distances_scipy.extend([d.scores[metric].value])\n\n np.testing.assert_equal(distances, distances_scipy)\n\n\n@pytest.mark.parametrize('buffer_pool_size', [1000, 3])\n@pytest.mark.parametrize('first_memmap', [True, False])\n@pytest.mark.parametrize('second_memmap', [True, False])\n@pytest.mark.parametrize(\n 'normalization, metric',\n [\n (None, 'sqeuclidean'),\n ((0, 1), 'sqeuclidean'),\n (None, 'euclidean'),\n ((0, 1), 'euclidean'),\n (None, 'cosine'),\n ((0, 1), 'cosine'),\n ],\n)\n@pytest.mark.parametrize('use_scipy', [True, False])\ndef test_matching_retrieves_closest_matches(\n doc_lists,\n tmpdir,\n normalization,\n metric,\n use_scipy,\n first_memmap,\n second_memmap,\n buffer_pool_size,\n):\n \"\"\"\n Tests if match.values are returned 'low to high' if normalization is True or 'high to low' otherwise\n \"\"\"\n D1, D2 = doc_lists_to_doc_arrays(\n doc_lists,\n tmpdir,\n first_memmap,\n second_memmap,\n buffer_pool_size=buffer_pool_size,\n )\n D1.match(\n D2, metric=metric, limit=3, normalization=normalization, use_scipy=use_scipy\n )\n expected_sorted_values = [\n D1[0].matches[i].scores['sqeuclidean'].value for i in range(3)\n ]\n if normalization:\n assert min(expected_sorted_values) >= 0\n assert max(expected_sorted_values) <= 1\n else:\n assert expected_sorted_values == sorted(expected_sorted_values)\n\n\n@pytest.mark.parametrize(\n 'normalization, metric',\n [\n (None, 'sqeuclidean'),\n ((0, 1), 'sqeuclidean'),\n (None, 'euclidean'),\n ((0, 1), 'euclidean'),\n (None, 'cosine'),\n ((0, 1), 'cosine'),\n ],\n)\n@pytest.mark.parametrize('use_scipy', [True, False])\ndef test_docarray_match_docarraymemmap(\n docarrays_for_embedding_distance_computation,\n normalization,\n metric,\n tmpdir,\n use_scipy,\n):\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_ = copy.deepcopy(D1)\n D2_ = copy.deepcopy(D2)\n D1.match(\n D2, metric=metric, limit=3, normalization=normalization, use_scipy=use_scipy\n )\n values_docarray = [m.scores[metric].value for d in D1 for m in d.matches]\n\n D2memmap = DocumentArrayMemmap(tmpdir)\n D2memmap.extend(D2_)\n D1_.match(\n D2memmap,\n metric=metric,\n limit=3,\n normalization=normalization,\n use_scipy=use_scipy,\n )\n values_docarraymemmap = [m.scores[metric].value for d in D1_ for m in d.matches]\n\n np.testing.assert_equal(values_docarray, values_docarraymemmap)\n\n\n@pytest.mark.parametrize(\n 'normalization, metric',\n [\n (None, 'hamming'),\n ((0, 1), 'hamming'),\n (None, 'minkowski'),\n ((0, 1), 'minkowski'),\n (None, 'jaccard'),\n ((0, 1), 'jaccard'),\n ],\n)\ndef test_scipy_dist(\n docarrays_for_embedding_distance_computation, normalization, metric, tmpdir\n):\n D1, D2 = docarrays_for_embedding_distance_computation\n D1_ = copy.deepcopy(D1)\n D2_ = copy.deepcopy(D2)\n D1.match(D2, metric=metric, limit=3, normalization=normalization, use_scipy=True)\n values_docarray = [m.scores[metric].value for d in D1 for m in d.matches]\n\n D2memmap = DocumentArrayMemmap(tmpdir)\n D2memmap.extend(D2_)\n D1_.match(\n D2memmap, metric=metric, limit=3, normalization=normalization, use_scipy=True\n )\n values_docarraymemmap = [m.scores[metric].value for d in D1_ for m in d.matches]\n\n np.testing.assert_equal(values_docarray, values_docarraymemmap)\n\n\n@pytest.mark.parametrize('buffer_pool_size', [1000, 3])\n@pytest.mark.parametrize('first_memmap', [True, False])\n@pytest.mark.parametrize('second_memmap', [True, False])\ndef test_2arity_function(\n first_memmap, second_memmap, doc_lists, tmpdir, buffer_pool_size\n):\n def dotp(x, y, *args):\n return np.dot(x, np.transpose(y))\n\n D1, D2 = doc_lists_to_doc_arrays(\n doc_lists,\n tmpdir,\n first_memmap,\n second_memmap,\n buffer_pool_size=buffer_pool_size,\n )\n D1.match(D2, metric=dotp, use_scipy=True)\n\n for d in D1:\n for m in d.matches:\n assert 'dotp' in m.scores\n\n\n@pytest.mark.parametrize('whiten', [True, False])\ndef test_pca_projection(embeddings, whiten):\n n_components = 2\n n_features = embeddings.shape[1]\n pca = PCA(n_components=n_components, whiten=whiten)\n assert pca.e_values is None\n assert pca.w is None\n embeddings_transformed = pca.fit_transform(embeddings)\n assert len(pca.e_values) == n_features\n assert pca.w.shape[0] == n_features\n assert embeddings_transformed.shape[1] == n_components\n\n\ndef test_pca_plot_generated(embeddings, tmpdir):\n doc_array = DocumentArray([Document(embedding=x) for x in embeddings])\n file_path = os.path.join(tmpdir, 'pca_plot.png')\n doc_array.visualize(output=file_path)\n assert os.path.exists(file_path)\n\n\ndef test_match_inclusive():\n \"\"\"Call match function, while the other :class:`DocumentArray` is itself\n or have same :class:`Document`.\n \"\"\"\n # The document array da1 match with itself.\n da1 = DocumentArray(\n [\n Document(embedding=np.array([1, 2, 3])),\n Document(embedding=np.array([1, 0, 1])),\n Document(embedding=np.array([1, 1, 2])),\n ]\n )\n\n da1.match(da1)\n assert len(da1) == 3\n traversed = da1.traverse_flat(traversal_paths=['m', 'mm', 'mmm'])\n assert len(traversed) == 9\n # The document array da2 shares same documents with da1\n da2 = DocumentArray([Document(embedding=np.array([4, 1, 3])), da1[0], da1[1]])\n da1.match(da2)\n assert len(da2) == 3\n traversed = da1.traverse_flat(traversal_paths=['m', 'mm', 'mmm'])\n assert len(traversed) == 9\n\n\ndef test_match_inclusive_dam(tmpdir):\n \"\"\"Call match function, while the other :class:`DocumentArray` is itself\n or have same :class:`Document`.\n \"\"\"\n # The document array da1 match with itself.\n dam = DocumentArrayMemmap(tmpdir)\n dam.extend(\n [\n Document(embedding=np.array([1, 2, 3])),\n Document(embedding=np.array([1, 0, 1])),\n Document(embedding=np.array([1, 1, 2])),\n ]\n )\n\n dam.match(dam)\n assert len(dam) == 3\n traversed = dam.traverse_flat(traversal_paths=['m', 'mm', 'mmm'])\n assert len(list(traversed)) == 9\n # The document array da2 shares same documents with da1\n da2 = DocumentArray([Document(embedding=np.array([4, 1, 3])), dam[0], dam[1]])\n dam.match(da2)\n assert len(da2) == 3\n traversed = dam.traverse_flat(traversal_paths=['m', 'mm', 'mmm'])\n assert len(list(traversed)) == 9\n\n\n@pytest.mark.parametrize('exclude_self, num_matches', [(True, 1), (False, 2)])\ndef test_match_exclude_self(exclude_self, num_matches):\n da1 = DocumentArray(\n [\n Document(id='1', embedding=np.array([1, 2])),\n Document(id='2', embedding=np.array([3, 4])),\n ]\n )\n da2 = DocumentArray(\n [\n Document(id='1', embedding=np.array([1, 2])),\n Document(id='2', embedding=np.array([3, 4])),\n ]\n )\n da1.match(da2, exclude_self=exclude_self)\n for d in da1:\n assert len(d.matches) == num_matches\n\n\n@pytest.fixture()\ndef get_pair_document_array():\n da1 = DocumentArray(\n [\n Document(id='1', embedding=np.array([1, 2])),\n Document(id='2', embedding=np.array([3, 4])),\n ]\n )\n da2 = DocumentArray(\n [\n Document(id='1', embedding=np.array([1, 2])),\n Document(id='2', embedding=np.array([3, 4])),\n Document(id='3', embedding=np.array([4, 5])),\n ]\n )\n yield da1, da2\n\n\n@pytest.mark.parametrize(\n 'limit, expect_len, exclude_self',\n [\n (2, 2, True),\n (1, 1, True),\n (3, 2, True),\n (2, 2, False),\n (1, 1, False),\n (3, 3, False),\n ],\n)\ndef test_match_exclude_self_limit_2(\n get_pair_document_array, exclude_self, limit, expect_len\n):\n da1, da2 = get_pair_document_array\n da1.match(da2, exclude_self=exclude_self, limit=limit)\n for d in da1:\n assert len(d.matches) == expect_len\n\n\n@pytest.mark.parametrize(\n 'lhs, rhs',\n [\n (DocumentArray(), DocumentArray()),\n (\n DocumentArray(\n [\n Document(embedding=np.array([3, 4])),\n Document(embedding=np.array([4, 5])),\n ]\n ),\n DocumentArray(\n [\n Document(embedding=np.array([3, 4])),\n Document(embedding=np.array([4, 5])),\n ]\n ),\n ),\n (\n DocumentArray(),\n DocumentArray(\n [\n Document(embedding=np.array([3, 4])),\n Document(embedding=np.array([4, 5])),\n ]\n ),\n ),\n (\n (\n DocumentArray(\n [\n Document(embedding=np.array([3, 4])),\n Document(embedding=np.array([4, 5])),\n ]\n )\n ),\n DocumentArray(),\n ),\n (None, DocumentArray()),\n (DocumentArray(), None),\n ],\n)\ndef test_match_none(lhs, rhs):\n if lhs is not None:\n lhs.match(rhs)\n if rhs is not None:\n rhs.match(lhs)\n\n\n@pytest.fixture()\ndef get_two_docarray():\n d1 = Document(embedding=np.array([0, 0, 0]))\n d1c1 = Document(embedding=np.array([0, 1, 0]))\n\n d2 = Document(embedding=np.array([1, 0, 0]))\n d2c1 = Document(embedding=np.array([1, 1, 0]))\n d2c2 = Document(embedding=np.array([1, 0, 1]))\n\n d3 = Document(embedding=np.array([2, 1, 1]))\n d3c1 = Document(embedding=np.array([2, 1, 0]))\n d3c2 = Document(embedding=np.array([2, 0, 1]))\n d3c3 = Document(embedding=np.array([2, 0, 0]))\n\n d4 = Document(embedding=np.array([3, 1, 1]))\n d4c1 = Document(embedding=np.array([3, 1, 0]))\n d4c2 = Document(embedding=np.array([3, 0, 1]))\n d4c3 = Document(embedding=np.array([3, 0, 0]))\n d4c4 = Document(embedding=np.array([3, 1, 1]))\n\n d1.chunks.extend([d1c1])\n d2.chunks.extend([d2c1, d2c2])\n d3.chunks.extend([d3c1, d3c2, d3c3])\n d4.chunks.extend([d4c1, d4c2, d4c3, d4c4])\n\n da1 = DocumentArray([d1, d2])\n da2 = DocumentArray([d3, d4])\n yield da1, da2\n\n\ndef test_match_with_traversal_path(get_two_docarray):\n da1, da2 = get_two_docarray\n da1.match(da2, traversal_rdarray=['c'])\n assert len(da1[0].matches) == len(da2[0].chunks) + len(da2[1].chunks)\n\n da2.match(da1, traversal_rdarray=['c'])\n assert len(da2[0].matches) == len(da1[0].chunks) + len(da1[1].chunks)\n\n\ndef test_match_on_two_sides_chunks(get_two_docarray):\n da1, da2 = get_two_docarray\n da2.match(da1, traversal_ldarray=['c'], traversal_rdarray=['c'])\n assert len(da2[0].matches) == 0\n assert len(da2[0].chunks[0].matches) == len(da1[0].chunks) + len(da1[1].chunks)\n\n da1.match(da2, traversal_ldarray=['c'], traversal_rdarray=['c'])\n assert len(da1[0].matches) == 0\n assert len(da1[0].chunks[0].matches) == len(da2[0].chunks) + len(da2[1].chunks)\n","sub_path":"tests/unit/types/arrays/test_neural_ops.py","file_name":"test_neural_ops.py","file_ext":"py","file_size_in_byte":16736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"491189538","text":"from os import listdir\nfrom PIL import Image\nimport os.path\nimport numpy as np\nimport glob\nimport tensorflow.keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Activation, Flatten\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\n\npath_new_benign = r'/home/shah/PycharmProjects/FYP-Part1/dataset/benign'\npath_new_malware = r'/home/shah/PycharmProjects/FYP-Part1/dataset/malware'\n\nh = 256 #height of image\nw = 256 #width of image\n\n#be careful with using this function, it will consume memory, access to disk and time for Benign\nimages = []\nfor f in listdir(path_new_benign):\n with open(os.path.join(path_new_benign, f), 'rb') as img_set:\n img_arr = img_set.read(h*w)\n while img_arr:\n if len(img_arr) == h*w and img_arr not in images:\n images.append(img_arr)\n img_arr = img_set.read(h*w)\n\n#be careful with using this function, it will consume memory, access to disk and time for Malware\nimages2 = []\nfor f in listdir(path_new_malware):\n with open(os.path.join(path_new_malware, f), 'rb') as img_set2:\n img_arr2 = img_set2.read(h*w)\n while img_arr2:\n if len(img_arr2) == h*w and img_arr2 not in images2:\n images2.append(img_arr2)\n img_arr2 = img_set2.read(h*w)\n\n#And you can save them into png files for Benign\ncount = 0\nfor img in images:\n png = Image.fromarray(np.reshape(list(img), (h,w)).astype('float32'), mode='L')\n png.save('images/benign/image_l%d.png'%count)\n count += 1\n\n#And you can save them into png files for Malware\ncount2 = 0\nfor img2 in images2:\n png = Image.fromarray(np.reshape(list(img2), (h,w)).astype('float32'), mode='L')\n png.save('images/malware/image_l%d.png'%count)\n count += 1\n\n\n# reshape images to fit into the CNN model for Benign\nimg_list = np.zeros(shape=(len(images), h, w, 1), dtype=np.uint8)\nfor j in range(len(images)):\n img_list[j, :, :, 0] = np.reshape(list(images[j]), (h, w))\n\nimg_list = img_list.astype('float32')\nimg_list /= 255\n\n# reshape images2 to fit into the CNN model for Malware\nimg_list2 = np.zeros(shape=(len(images2), h, w, 1), dtype=np.uint8)\nfor j in range(len(images2)):\n img_list2[j, :, :, 0] = np.reshape(list(images2[j]), (h, w))\n\nimg_list2 = img_list2.astype('float32')\nimg_list2 /= 255\n\n\n\nmodel = Sequential()\n#Conv2D Layers\nmodel.add(Conv2D(12, (25, 25), padding='same',input_shape=img_list.shape[1:], activation = 'relu'))\nmodel.add(Conv2D(12, (25, 25), activation = 'relu'))\n#Max Pooling Layer\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n#Conv2D Layer\nmodel.add(Conv2D(12, (13, 13), padding='same', activation = 'relu'))\nmodel.add(Conv2D(12, (13, 13), activation = 'relu'))\n#Max Pooling\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n#Flattening Layer\nmodel.add(Flatten())\n#Dense Layer\nmodel.add(Dense(1024, activation = 'relu'))\nmodel.add(Dense(1, activation = 'sigmoid'))\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['binary_accuracy'])\nmodel.summary()\n\n\n\n#\n#\n#Change the parameters to whatever suits you\nbenign_images = r'images/benign'\nmalicious_images = r'images/malware'\n\n\nbatch_size = 5\nepochs = 100\nlabels = [0 for _ in benign_images] + [1 for _ in malicious_images]\nmodel.fit(benign_images + malicious_images, labels, batch_size = batch_size, epochs = epochs,\n validation_split = 0.25,\n shuffle = True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"368217506","text":"\"\"\"Scraps NY Times website and sends interesting news to my Telegram, based on keyworks\"\"\"\nimport urllib.request\nimport http.cookiejar\nimport os.path as PATH\nfrom telegram import Telegram\nfrom bs4 import BeautifulSoup\n\nCJ = http.cookiejar.CookieJar()\n\nURL = \"https://www.nytimes.com\"\nPAGE = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(CJ)).open(URL)\nSOUP = BeautifulSoup(PAGE.read())\nALLNEWS = SOUP.find_all('h2', class_='story-heading')\nALLNEWS += SOUP.find_all('h3', class_='story-heading')\nALLNEWS += SOUP.find_all('a', class_='story-link')\nTOKEN = '284151617:AAHrYeAUdA-MJW2D9aTJsn5643356Kkwe18'\nBOT_ID = 284151617\nMY_ID = 71247486\nBOT = Telegram(TOKEN, BOT_ID, MY_ID)\nKEYWORDS = ('mets', 'giants', 'cern', 'knicks', 'boxing', 'mma', 'ufc',\n 'portugal', 'physics', 'chess', 'nasa', 'health',\n 'literature', 'science', 'math', 'linux', 'tech',\n 'snowden', 'manning','photography')\n\nCACHE = []\n\nFILENAME = '/home/pi/Scripts/.news_cache'\nif not PATH.exists(FILENAME):\n NEWFILE = open(FILENAME, 'w+').close()\nSHOWN = open(FILENAME, 'r+')\n\ndef to_write(link):\n \"\"\"Function to determine if a news is new or not\"\"\"\n SHOWN.seek(0)\n new = True\n for line in SHOWN:\n if link in line:\n new = False\n break\n return new\n\ndef fetcher():\n \"\"\"This functions checks if a particular news is in the keywords and sends it in case it is\"\"\"\n news = [str(new).lower() for new in ALLNEWS]\n for story in news:\n for word in KEYWORDS:\n if word in story:\n news_list = str(story).split('\"')\n for item in news_list:\n item = str(item)\n if 'www.nytimes.com/' in item:\n if item not in CACHE and to_write(item):\n BOT.message(item)\n CACHE.append(item)\n SHOWN.write(item + '\\n')\n\nfetcher()\nSHOWN.close()\n","sub_path":"nyt.py","file_name":"nyt.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"356067577","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[5]:\n\n\nimport numpy as np\ndef puntodos(i,j,k): \n if k>=int(n/2)**2+2*int(n/2)+2:#caso base\n return z\n elif j=0):#SUBIENDO\n z[i][j]=k\n if(j>0):\n k=k+1\n z[n-1-i-j][j]=k\n if(i>0):\n puntodos(i-1,j+1,k+1)\n elif j>=int(n/2) and (i<=int(n/2)):#BAJANDO\n z[i][j]=k\n k=k+1\n if j-i==i and k= 0:\n for optimizer in six.itervalues(self._optimizers):\n optimizer.target.to_gpu(device)\n\n self.converter = converter\n self.loss_func = loss_func\n self.device = device\n self.iteration = 0\n\n self.loss_scale = loss_scale\n if loss_scale is not None:\n for optimizer in six.itervalues(self._optimizers):\n optimizer.set_loss_scale(loss_scale)\n\n self.auto_new_epoch = auto_new_epoch\n if auto_new_epoch:\n for o in six.itervalues(self._optimizers):\n o.use_auto_new_epoch = True\n\n def first_iter(self):\n self.f_val=True\n\n def update(self):\n #print(\"#1:{0}\".format(self._iterators['main'].next()))\n '''\n if(self._iterators['main'].is_new_epoch is True or self.f_val is True):\n self.update_core()\n self.f_val=False\n else:\n self.update_vat()\n '''\n #1\n #print(\"#1:{0}\".format(self._iterators['main'].current_position))\n #self.update_core()\n #print(\"#2:{0}\".format(self._iterators['main'].current_position))\n #iterator=self._iterators['main']\n\n self.update_vat()\n #print(\"#3:{0}\".format(self._iterators['main'].current_position))\n #print(self.iteration)\n #print(iterator.epoch)\n #print(iterator.epoch_detail)\n #print(iterator.previous_epoch_detail)\n self.iteration += 1\n #print(self._iterators['main'].is_new_epoch)\n\n\n def update_vat(self):\n iterator=self._iterators['main']\n batch = iterator.next()\n\n iterator_ul=self._iterators_ul['main']\n batch_ul = iterator_ul.next()\n #print(batch)\n in_arrays = self.converter(batch, self.device)\n in_arrays_ul = self.converter(batch_ul, self.device)\n #print(in_arrays)\n optimizer = self._optimizers['main']\n loss_func = optimizer.target\n #print(in_arrays[0] )\n #optimizer.zero_grads()\n #optimizer.cleargrad()\n #optimizer.update(loss_func, in_arrays[0])\n\n\n #print(np.sum(in_arrays[0][0]))\n #print(in_arrays_ul[0].shape)\n\n if isinstance(in_arrays, tuple):\n #optimizer.update(loss_func, *in_arrays)\n loss_l=loss_func(*in_arrays)\n elif isinstance(in_arrays, dict):\n #optimizer.update(loss_func, **in_arrays)\n loss_l=loss_func(**in_arrays)\n else:\n #optimizer.update(loss_func, in_arrays)\n loss_l=loss_func(in_arrays)\n\n #print(in_arrays_ul[0])\n #optimizer.update(loss_func, in_arrays_ul[0])\n loss_ul=loss_func(in_arrays_ul[0])\n loss_total=loss_l+loss_ul\n loss_func.cleargrads()\n loss_total.backward()\n #print(self.iteration)\n #print(optimizer.alpha)\n\n if(self.iteration >= 500 and self.iteration % 500 == 0):\n #print(\"alpha change\")\n optimizer.alpha *= 0.9\n\n optimizer.update()\n\n #print(iterator.is_new_epoch)\n if self.auto_new_epoch and iterator.is_new_epoch:\n optimizer.new_epoch(auto=True)\n #optimizer.zero_grads()\n #optimizer.cleargrad()\n\n\ndef vat_loss_function(\n x, t, normalize=True, cache_score=True, class_weight=None,\n ignore_label=-1, reduce='mean', enable_double_backprop=False):\n '''\n if enable_double_backprop:\n return _double_backward_softmax_cross_entropy(\n x, t, normalize, class_weight, ignore_label, reduce)\n else:\n return SoftmaxCrossEntropy(\n normalize, cache_score, class_weight, ignore_label, reduce)(x, t)\n '''\n if t is not None:\n #h = self.predict(x)\n loss = F.softmax_cross_entropy(x, t)\n chainer.report({'loss': loss, 'accuracy': F.accuracy(x, t)}, self)\n return loss\n else:\n #return vat(self, distance, x, self.eps)\n return vat(self,distance, x, 1.0)\n","sub_path":"lib/vat.py","file_name":"vat.py","file_ext":"py","file_size_in_byte":9982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"480812158","text":"#! /bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 6 11:20:44 2017\n\n@author: tipputa\n\"\"\"\n\nimport pandas as pd\nimport sys, os\nimport createOrthologousGenes as createOrtho\nimport createCircos as createCircos\nimport timeRecord as recorder\n\nuseage = \"\"\"\n\nError: please input the absolute PATH of output and genbank directories .\n\nUsage: \n python runAllProcess.py \n e.g: python runAllProcess.py ~/study/ ~/study/gb/\n\"\"\"\n\nif __name__ == '__main__':\n timeRecorder = []\n recordAll = recorder.timeRecord()\n\n if len(sys.argv)==3:\n RootDir = sys.argv[1] + \"/\"\n gbDir = sys.argv[2] + \"/\"\n \n else: \n print(useage)\n quit()\n \n os.chdir(RootDir)\n createOrtho.runs(timeRecorder, RootDir, gbDir)\n df = pd.read_csv(RootDir + '/data/all_blast_results.tsv', delimiter = \"\\t\")\n createCircos.runs(df, timeRecorder, RootDir, gbDir)\n recordAll.fin(\"All process\", timeRecorder)\n print(\"\\n\\nFin.\")\n pd.Series(timeRecorder).to_csv(RootDir + \"Calculation_times.txt\", header = None, index = None)\n","sub_path":"bin_singularity/runAllProcess.py","file_name":"runAllProcess.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"329600619","text":"import os\r\nfrom collections import Counter\r\nfrom typing import Optional, Any\r\n\r\nimport numpy as np\r\nfrom PIL import Image\r\nfrom matplotlib import pyplot as plt\r\nfrom sklearn.cluster import KMeans\r\n\r\n\r\ndef rgb2hex(rgb):\r\n hex = \"#{:02x}{:02x}{:02x}\".format(int(rgb[0]), int(rgb[1]), int(rgb[2]))\r\n # hex = f\"#{rgb[0]}{}{}\"\r\n return hex\r\n\r\n\r\nrgb = [0, 1, 2]\r\nhex = [\"#\"]\r\n[hex.append(f\"{c:}\") for c in rgb]\r\n''.join(hex)\r\n\r\nPATH = \"./SOLO1.jpg\"\r\nWIDTH = 128\r\nHEIGHT = 128\r\nCLUSTERS = 6\r\n\r\nimage: Optional[Any] = Image.open(PATH)\r\n\r\nvar = image.size\r\n\r\nprint(\"Loaded {f} image. Size: {s:.2f} KB. Dimensions: ({d})\".format(\r\n f=image.format, s=os.path.getsize(PATH) / 1024, d=image.size))\r\n\r\nimage\r\n\r\n\r\n# DADOS E DIMENSÕES DA IMAGEM FOI APRESENTADA NA TELA\r\n# EM SEGUIDA A FUNÇÃO VAI CALCULAR OS DADOS - MINERAR\r\n\r\ndef calculate_new_size(image):\r\n if image.width >= image.height:\r\n wpercent = (WIDTH / float(image.width))\r\n hsize = int((float(image.height) * float(wpercent)))\r\n new_width, new_height = WIDTH, hsize\r\n else:\r\n hpercent = (HEIGHT / float(image.height))\r\n wsize = int((float(image.width) * float(hpercent)))\r\n new_width, new_height = wsize, HEIGHT\r\n\r\n image.resize((new_width, new_height), Image.ANTIALIAS)\r\n return image, new_width, new_height\r\n\r\n\r\n# AGORA A APRENDIZAGEM DE MAQUINA (MACHINE LEARNING) A FUNÇÃO DEVE AGRUPAR SIMILARES\r\n\r\nnew_image, new_width, new_height = calculate_new_size(image)\r\nprint(f\"New dimensions: {new_width}x{new_height}\")\r\nimg_array = np.array(new_image)\r\nimg_vector = img_array.reshape((img_array.shape[0] * img_array.shape[1], 3))\r\nnew_image\r\n\r\nmodel = KMeans(n_clusters=CLUSTERS)\r\nlabels = model.fit_predict(img_vector)\r\nlabel_counts = Counter(labels)\r\nmodel.cluster_centers_\r\n\r\ntotal_count = sum(label_counts.values())\r\ntotal_count\r\n\r\nhex_colors = [rgb2hex(center) for center in model.cluster_centers_]\r\nhex_colors\r\n\r\nhex_colors\r\n\r\n# AGRUPOU NAS CORES ACIMA EM FORMATO HEX - '#a89679', '#968468', '#c7c4c7', '#645c53', '#827158', '#afabab' \r\n# PRECISO QUE DÊ EM MUNSELL TIPO - colour.xyY_to_munsell_colour([0.38736945, 0.35751656, 0.59362000]) DANDO ISSO '4.2YR 8.1/5.3'\r\n\r\nlist(zip(hex_colors, list(label_counts.values())))\r\n\r\n# FEZ UMA LISTA ASSOCIANDO A QUANTIDADE DE PIXEL, ACREDITO QUE SEJA ISSO. / DE SIMILARES PREDOMINANTES\r\n\r\nplt.figure(figsize=(14, 8))\r\n\r\nplt.subplot(221)\r\n\r\nplt.imshow(image)\r\n\r\nplt.axis('off')\r\n\r\nplt.subplot(222)\r\n\r\nplt.pie(label_counts.values(), labels=hex_colors, colors=[color / 255 for color in model.cluster_centers_],\r\n autopct='%1.1f%%',\r\n shadow=True, startangle=90)\r\n\r\nplt.axis('equal')\r\n\r\nplt.title('CORES DO SOLO')\r\n\r\nplt.show()","sub_path":"detector de cor ML.py","file_name":"detector de cor ML.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"381537865","text":"#!/usr/bin/python3\n# coding: utf-8\n\nimport os\nimport smtplib\nfrom email import encoders\nfrom email.header import Header\nfrom email.mime.text import MIMEText\nfrom email.utils import parseaddr\nfrom email.utils import formataddr\n\n\ndef format_addr(s):\n name, addr = parseaddr(s)\n return formataddr((Header(name, \"utf-8\").encode(), addr))\n\n\ndef send_mail(to_list, content):\n from_email = \"newsmonitor@126.com\"\n from_email_pwd = os.getenv('email_pass')\n smtp_server = \"smtp.126.com\"\n msg = MIMEText(\n content,\n \"html\", \"utf-8\")\n msg[\"From\"] = format_addr(\"%s\" % (from_email))\n msg[\"To\"] = ','.join([format_addr(\"%s\" % (to_email))\n for to_email in to_list])\n msg[\"Subject\"] = Header(\"python email\", \"utf-8\").encode()\n\n server = smtplib.SMTP(smtp_server, 25)\n server.set_debuglevel(1)\n server.login(from_email, from_email_pwd)\n server.sendmail(from_email, to_list, msg.as_string())\n server.close()\n\n\nif __name__ == '__main__':\n content = 'hello hello, send by python
'\n send_mail(['newsmonitor@126.com'], content)\n","sub_path":"__mail.py","file_name":"__mail.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"412054162","text":"# Character recognition software is\n# widely used to digitise printed texts.\n# Thus the texts can be edited, searched\n# and stored on a computer.\n#\n# When documents (especially pretty old\n# ones written with a typewriter), are\n# digitised character recognition softwares\n# often make mistakes.\n#\n# Your task is correct the errors in the\n# digitised text. You only have to handle\n# the following mistakes:\n#\n# S is misinterpreted as 5\n# O is misinterpreted as 0\n# I is misinterpreted as 1\n# The test cases contain numbers only by mistake.\n\ndef correct(string):\n\n mapping = {\n \"0\": \"O\",\n \"1\": \"I\",\n \"5\": \"S\"\n }\n\n new_string = \"\"\n\n for c in string:\n if c in mapping:\n c = mapping[c]\n new_string += c\n else:\n new_string += c\n\n return new_string\n\nprint(correct(\"L0ND0N\"),\"LONDON\");\nprint(correct(\"DUBL1N\"),\"DUBLIN\");\nprint(correct(\"51NGAP0RE\"),\"SINGAPORE\");\nprint(correct(\"BUDAPE5T\"),\"BUDAPEST\");\nprint(correct(\"PAR15\"),\"PARIS\");\n","sub_path":"8 kyu/18_09_20_correct_the_mistakes_of_the_character_recognition_software.py","file_name":"18_09_20_correct_the_mistakes_of_the_character_recognition_software.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"462236548","text":"import json\n\nimport arrow\nimport dateutil\nimport dateutil.parser\n\n\nclass Tick:\n def __init__(self, time, price, volume=0, bids=None, asks=None, contract=None,\n source=None,\n exchange_time=None,\n amount=None,\n **kwargs):\n\n # internally use python3's datetime\n if isinstance(time, arrow.Arrow):\n time = time.datetime\n assert time.tzinfo\n self.contract = contract\n self.source = source\n self.time = time\n self.price = price\n self.volume = volume\n self.amount = amount\n self.bids = []\n self.asks = []\n self.exchange_time = exchange_time\n if bids:\n self.bids = sorted(bids, key=lambda x: -x['price'])\n if asks:\n self.asks = sorted(asks, key=lambda x: x['price'])\n for item in self.bids:\n assert 'price' in item and 'volume' in item and len(item) == 2\n for item in self.asks:\n assert 'price' in item and 'volume' in item and len(item) == 2\n # self.asks = asks\n\n # last as an candidate of last\n @property\n def last(self):\n return self.price\n\n @last.setter\n def last(self, value):\n self.price = value\n\n @property\n def bid1(self):\n if self.bids:\n return self.bids[0]['price']\n return None\n\n @property\n def ask1(self):\n if self.asks:\n return self.asks[0]['price']\n return None\n\n @property\n def weighted_middle(self):\n a = self.bids[0]['price'] * self.asks[0]['volume']\n b = self.asks[0]['price'] * self.bids[0]['volume']\n return (a + b) / (self.asks[0]['volume'] + self.bids[0]['volume'])\n\n def get_interest_side(self, bs):\n if bs == 's':\n return self.bids\n if bs == 'b':\n return self.asks\n\n def __str__(self):\n return '<{} {}.{:03d} {}/{} {} {}>'.format(self.contract,\n self.time.strftime('%H:%M:%S'),\n self.time.microsecond // 1000,\n self.bid1,\n self.ask1,\n self.last,\n self.volume)\n\n def __repr__(self):\n return str(self)\n\n @staticmethod\n def init_with_dict(dct):\n return Tick(dct['time'], dct['price'], dct['volume'], dct['bids'], dct['asks'])\n\n def to_dict(self):\n dct = {'time': self.time.isoformat(), 'price': self.price, 'volume': self.volume, 'asks': self.asks,\n 'bids': self.bids}\n if self.exchange_time:\n dct['exchange_time'] = self.exchange_time.isoformat()\n if self.contract:\n dct['symbol'] = self.contract\n return dct\n\n # @staticmethod\n # def from_dct(dct):\n # # con = ContractApi.get_by_symbol(dct['symbol'])\n # con = dct['symbol']\n # return Tick(time=dateutil.parser.parse(dct['time']), price=dct['price'], bids=dct['bids'], asks=dct['asks'],\n # contract=con, volume=dct['volume'])\n\n def to_mongo_dict(self):\n dct = {'time': self.time, 'price': self.price, 'volume': self.volume, 'asks': self.asks, 'bids': self.bids}\n if self.contract:\n dct['contract'] = self.contract\n return dct\n\n def to_short_list(self):\n b = ','.join(['{},{}'.format(x['price'], x['volume']) for x in self.bids])\n a = ','.join(['{},{}'.format(x['price'], x['volume']) for x in self.asks])\n lst = [self.contract, self.time.timestamp(), self.price, self.volume, b, a]\n return lst\n\n @staticmethod\n def from_short_list(lst):\n if isinstance(lst[0], str):\n # convert string to contract\n # lst[0] = ContractApi.get_by_symbol(lst[0])\n lst[0] = lst[0]\n bids, asks = lst[4], lst[5]\n bids = [{'price': float(p), 'volume': float(v)} for p, v in zip(bids.split(',')[::2], bids.split(',')[1::2])]\n asks = [{'price': float(p), 'volume': float(v)} for p, v in zip(asks.split(',')[::2], asks.split(',')[1::2])]\n\n time = arrow.Arrow.fromtimestamp(lst[1]).datetime\n return Tick(contract=lst[0], time=time, price=lst[2], volume=lst[3], bids=bids, asks=asks)\n\n def to_ws_str(self):\n lst = self.to_short_list()\n return json.dumps(lst)\n\n @classmethod\n def from_dict(cls, dict_or_str):\n if isinstance(dict_or_str, str):\n return cls.from_dict(json.loads(dict_or_str))\n d = dict_or_str\n t = Tick(time=arrow.get(d['time']),\n # contract=ContractApi.get_by_symbol(d['contract']),\n contract=d['contract'],\n volume=d['volume'],\n asks=d['asks'],\n bids=d['bids'],\n price=d['last'],\n source=d.get('source', None),\n )\n return t\n\n def bs1(self, bs):\n if bs == 'b':\n return self.bid1\n else:\n return self.ask1\n","sub_path":"onetoken/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"30864710","text":"# each method in class takes instance as the first argument\n# below is converting regular method to class method\nclass Employee :\n\t\n\tnum_of_employees = 0\n\traise_amount = 1.4\n\n\tdef __init__(self,first,last,pay):\n\t\tself.first = first\n\t\tself.last = last\n\t\tself.pay = pay\n\t\tself.email = first+'.'+last+'@company.com'\n\t\tEmployee.num_of_employees += 1\n\n\n\tdef fullname(self) :\n\t\treturn '{} {}'.format(self.first,self.last)\n\n\tdef apply_raise(self):\n\t\tself.pay = int(self.pay * self.raise_amount)\n\t\t# we can also access self.raise_amount\n\n\t@classmethod\n\tdef set_raise_amt(cls,amount):\n\t\tcls.raise_amount = amount\n\n\t\n\nemp_1 = Employee('Pranav','Kamat',60000)\nemp_2 = Employee('Gayatri','Kamat',50000)\nprint(\"total number of employees is \")\nprint(Employee.num_of_employees)\n\nEmployee.set_raise_amt(1.5)\nprint(Employee.raise_amount)\nprint(emp_1.raise_amount)\nprint(emp_2.raise_amount)\n\n# even emp_1.set_raise_amt(1.6) works same unexpectadly\n\n","sub_path":"OOPS/methods.py","file_name":"methods.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"208210897","text":"from copy import deepcopy\nfrom scipy import linalg as spla\nimport numpy as np\nimport pycufsm.analysis\n\n# Originally developed for MATLAB by Benjamin Schafer PhD et al\n# Ported to Python by Brooks Smith MEng, PE, CPEng\n#\n# Each function within this file was originally its own separate file.\n# Original MATLAB comments, especially those retaining to authorship or\n# change history, have been generally retained unaltered\n\n\ndef base_column(\n nodes_base, elements, props, length, b_c, m_a, el_props, node_props, n_main_nodes,\n n_corner_nodes, n_sub_nodes, n_global_modes, n_dist_modes, n_local_modes, dof_perm, r_x, r_z,\n r_ys, d_y\n):\n # this routine creates base vectors for a column with length length for all the\n # specified longitudinal terms in m_a\n\n # assumptions\n # orthogonalization is not performed unless the user wants\n # orthogonalization is done by solving the eigen-value problem within each sub-space\n # normalization is not done\n\n # input data\n # nodes, elements, props - basic data\n # b_c: ['S-S'] a string specifying boundary conditions to be analyzed:\n #'S-S' simply-pimply supported boundary condition at loaded edges\n #'C-C' clamped-clamped boundary condition at loaded edges\n #'S-C' simply-clamped supported boundary condition at loaded edges\n #'C-F' clamped-free supported boundary condition at loaded edges\n #'C-bulk' clamped-guided supported boundary condition at loaded edges\n # m_a - longitudinal terms (half-wave numbers)\n\n # output data\n # b_v_l - base vectors (each column corresponds to a certain mode)\n # assemble for each half-wave number m_i on its diagonal\n # b_v_l = diag(b_v_m)\n # for each half-wave number m_i, b_v_m\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof: other modes\n # n_global_modes, n_dist_modes, n_local_modes - number of bulk, D, L modes, respectively\n #\n\n # S. Adany, Aug 28, 2006\n # B. Schafer, Aug 29, 2006\n # Z. Li, Dec 22, 2009\n # Z. Li, June 2010\n\n # construct the base for all the longitudinal terms\n n_nodes = len(nodes_base)\n n_dof_m = 4*n_nodes\n total_m = len(m_a)\n b_v_l = np.zeros((n_dof_m*total_m, n_dof_m*total_m))\n for i, m_i in enumerate(m_a):\n # to create r_p constraint matrix for the rest of planar DOFs\n r_p = constr_planar_xz(\n nodes_base, elements, props, node_props, dof_perm, m_i, length, b_c, el_props\n )\n b_v_m = base_vectors(\n d_y=d_y,\n elements=elements,\n el_props=el_props,\n length=length,\n m_i=m_i,\n node_props=node_props,\n n_main_nodes=n_main_nodes,\n n_corner_nodes=n_corner_nodes,\n n_sub_nodes=n_sub_nodes,\n n_global_modes=n_global_modes,\n n_dist_modes=n_dist_modes,\n n_local_modes=n_local_modes,\n r_x=r_x,\n r_z=r_z,\n r_p=r_p,\n r_ys=r_ys,\n dof_perm=dof_perm\n )\n b_v_l[(n_dof_m*i):n_dof_m*(i + 1), (n_dof_m*i):n_dof_m*(i + 1)] = b_v_m\n\n return b_v_l\n\n\ndef base_update(\n gbt_con, b_v_l, length, m_a, nodes, elements, props, n_global_modes, n_dist_modes,\n n_local_modes, b_c, el_props\n):\n # this routine optionally makes orthogonalization and normalization of base vectors\n\n # assumptions\n # orthogonalization is done by solving the EV problem for each sub-space\n # three options for normalization is possible, set by 'gbt_con['norm']' parameter\n\n # input data\n # gbt_con['o_space'] - by gbt_con, choices of ST/O mode\n # 1: ST basis\n # 2: O space (null space of GDL) with respect to k_global\n # 3: O space (null space of GDL) with respect to kg_global\n # 4: O space (null space of GDL) in vector sense\n # gbt_con['norm'] - by gbt_con, code for normalization (if normalization is done at all)\n # 0: no normalization,\n # 1: vector norm\n # 2: strain energy norm\n # 3: work norm\n # b_v_l - natural base vectors for length (each column corresponds to a certain mode)\n # for each half-wave number m_i\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof_m: other modes\n # length - length\n # m_a, nodes, elements, props - as usual\n # n_global_modes, n_dist_modes, n_local_modes - nr of modes\n # b_c - boundary condition, 'S-S','C-C',...etc., as usual\n # gbt_con['couple'] - by gbt_con, coupled basis vs uncoupled basis for general B.C.\n # especially for non-simply supported B.C.\n # 1: uncoupled basis, the basis will be block diagonal\n # 2: coupled basis, the basis is fully spanned\n # gbt_con['orth'] - by gbt_con, natural basis vs modal basis\n # 1: natural basis\n # 2: modal basis, axial orthogonality\n # 3: modal basis, load dependent orthogonality\n\n # output data\n # b_v - output base vectors (maybe natural, orthogonal or normalized,\n # depending on the selected options)\n\n # S. Adany, Oct 11, 2006\n # Z. Li modified on Jul 10, 2009\n # Z. Li, June 2010\n\n n_nodes = len(nodes[:, 1])\n n_dof_m = 4*n_nodes\n total_m = len(m_a) # Total number of longitudinal terms m_i\n b_v = np.zeros((n_dof_m*total_m, n_dof_m*total_m))\n\n if gbt_con['couple'] == 1:\n # uncoupled basis\n for i, m_i in enumerate(m_a):\n b_v_m = b_v_l[n_dof_m*i:n_dof_m*(i + 1), n_dof_m*i:n_dof_m*(i + 1)]\n # k_global/kg_global\n if gbt_con['norm'] == 2 or gbt_con['norm'] == 3 \\\n or gbt_con['o_space'] == 2 or gbt_con['o_space'] == 3 \\\n or gbt_con['orth'] == 2 or gbt_con['orth'] == 3:\n # axial loading or real loading by either gbt_con['orth'] = 2 or gbt_con['orth'] = 3\n if gbt_con['orth'] == 1 or gbt_con['orth'] == 2:\n nodes_base = deepcopy(nodes)\n nodes_base[:, 7] = np.ones_like(nodes[:, 7]) # set u_p stress to 1.0 (axial)\n [k_global, kg_global] = create_k_globals(\n m_i=m_i,\n nodes=nodes_base,\n elements=elements,\n el_props=el_props,\n props=props,\n length=length,\n b_c=b_c\n )\n else:\n [k_global, kg_global] = create_k_globals(\n m_i=m_i,\n nodes=nodes,\n elements=elements,\n el_props=el_props,\n props=props,\n length=length,\n b_c=b_c\n )\n\n # orthogonalization/normalization begins\n #\n if gbt_con['orth'] == 2 or gbt_con['orth'] == 3 \\\n or gbt_con['o_space'] == 2 or gbt_con['o_space'] == 3 or gbt_con['o_space'] == 4:\n # indices\n if gbt_con['o_space'] == 1:\n dof_index = np.zeros((5, 2))\n dof_index[3, 0] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 1] = n_global_modes + n_dist_modes + n_local_modes + n_nodes - 1\n dof_index[4, 0] = n_global_modes + n_dist_modes + n_local_modes + n_nodes - 1\n dof_index[4, 1] = n_dof_m\n else:\n dof_index = np.zeros((4, 2))\n dof_index[3, 0] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 1] = n_dof_m\n dof_index[0, 0] = 0\n dof_index[0, 1] = n_global_modes\n dof_index[1, 0] = n_global_modes\n dof_index[1, 1] = n_global_modes + n_dist_modes\n dof_index[2, 0] = n_global_modes + n_dist_modes\n dof_index[2, 1] = n_global_modes + n_dist_modes + n_local_modes\n\n # define vectors for other modes, gbt_con['o_space'] = 2, 3, 4\n if gbt_con['o_space'] == 2:\n a_matrix = spla.null_space(b_v_m[:, dof_index[0, 0]:dof_index[2, 1]].conj().T)\n b_v_m[:, dof_index[3, 0]:dof_index[3, 1]] = np.linalg.solve(k_global, a_matrix)\n if gbt_con['o_space'] == 3:\n a_matrix = spla.null_space(b_v_m[:, dof_index[0, 0]:dof_index[2, 1]].conj().T)\n b_v_m[:, dof_index[3, 0]:dof_index[3, 1]] = np.linalg.solve(kg_global, a_matrix)\n if gbt_con['o_space'] == 4:\n a_matrix = spla.null_space(b_v_m[:, dof_index[0, 0]:dof_index[2, 1]].conj().T)\n b_v_m[:, dof_index[3, 0]:dof_index[3, 1]] = a_matrix\n\n # orthogonalization for modal basis 2/3 + normalization for normals 2/3\n for dof_sub in dof_index:\n dof_sub1 = int(dof_sub[1])\n dof_sub0 = int(dof_sub[0])\n if dof_sub[1] >= dof_sub[0]:\n k_global_sub \\\n = b_v_m[:, dof_sub0:dof_sub1].conj().T @ \\\n k_global @ b_v_m[:, dof_sub0:dof_sub1]\n kg_global_sub \\\n = b_v_m[:, dof_sub0:dof_sub1].conj().T @ \\\n kg_global @ b_v_m[:, dof_sub0:dof_sub1]\n [eigenvalues, eigenvectors] = spla.eig(a=k_global_sub, b=kg_global_sub)\n lf_sub = np.real(eigenvalues)\n indexsub = np.argsort(lf_sub)\n lf_sub = lf_sub[indexsub]\n eigenvectors = np.real(eigenvectors[:, indexsub])\n if gbt_con['norm'] == 2 or gbt_con['norm'] == 3:\n if gbt_con['norm'] == 2:\n s_matrix = eigenvectors.conj().T @ k_global_sub @ eigenvectors\n\n if gbt_con['norm'] == 3:\n s_matrix = eigenvectors.conj().T @ kg_global_sub @ eigenvectors\n\n s_matrix = np.diag(s_matrix)\n for j in range(0, int(dof_sub[1] - dof_sub[0])):\n eigenvectors[:, j] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n eigenvectors[:, j].conj().T,\n np.sqrt(s_matrix).conj().T\n )\n )\n )\n\n b_v_m[:, dof_sub0:dof_sub1] \\\n = b_v_m[:, dof_sub0:dof_sub1] @ eigenvectors\n\n # normalization for gbt_con['o_space'] = 1\n if (gbt_con['norm'] == 2 or gbt_con['norm'] == 3) and gbt_con['o_space'] == 1:\n for j in range(0, n_dof_m):\n if gbt_con['norm'] == 2:\n b_v_m[:, j] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v_m[:, j].conj().T,\n np.sqrt(b_v_m[:, j].conj().T @ k_global @ b_v_m[:, j]).conj().T\n )\n )\n )\n\n if gbt_con['norm'] == 3:\n b_v_m[:, j] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v_m[:, j].conj().T,\n np.sqrt(b_v_m[:, j].conj().T @ kg_global @ b_v_m[:, j]).conj().T\n )\n )\n )\n\n # normalization for gbt_con['norm'] 1\n if gbt_con['norm'] == 1:\n for j in range(0, n_dof_m):\n b_v_m[:, j] = b_v_m[:, j]/np.sqrt(b_v_m[:, j].conj().T @ b_v_m[:, j])\n\n b_v[n_dof_m*i:n_dof_m*(i + 1), n_dof_m*i:n_dof_m*(i + 1)] = b_v_m\n\n else:\n # coupled basis\n # k_global/kg_global\n if gbt_con['norm'] == 2 or gbt_con['norm'] == 3 \\\n or gbt_con['o_space'] == 2 or gbt_con['o_space'] == 3 \\\n or gbt_con['orth'] == 2 or gbt_con['orth'] == 3:\n # axial loading or real loading by either gbt_con['orth'] = 2 or gbt_con['orth'] = 3\n if gbt_con['orth'] == 1 or gbt_con['orth'] == 2:\n nodes_base = deepcopy(nodes)\n nodes_base[:, 7] = np.ones_like(nodes[:, 7]) # set u_p stress to 1.0 (axial)\n else:\n nodes_base = nodes\n\n # ZERO OUT THE GLOBAL MATRICES\n k_global = np.zeros((4*n_nodes*total_m, 4*n_nodes*total_m))\n kg_global = np.zeros((4*n_nodes*total_m, 4*n_nodes*total_m))\n\n # ASSEMBLE THE GLOBAL STIFFNESS MATRICES\n for i, elem in enumerate(elements):\n # Generate element stiffness matrix (k_local) in local coordinates\n thick = elem[3]\n b_strip = el_props[i, 1]\n mat_num = int(elem[4])\n row = int((np.argwhere(props[:, 0] == mat_num)).reshape(1))\n mat = props[row]\n stiff_x = mat[1]\n stiff_y = mat[2]\n nu_x = mat[3]\n nu_y = mat[4]\n bulk = mat[5]\n k_l = pycufsm.analysis.klocal(\n stiff_x=stiff_x,\n stiff_y=stiff_y,\n nu_x=nu_x,\n nu_y=nu_y,\n bulk=bulk,\n thick=thick,\n length=length,\n b_strip=b_strip,\n b_c=b_c,\n m_a=m_a\n )\n # Generate geometric stiffness matrix (kg_local) in local coordinates\n node_i = int(elem[1])\n node_j = int(elem[2])\n ty_1 = nodes_base[node_i][7]*thick\n ty_2 = nodes_base[node_j][7]*thick\n kg_l = pycufsm.analysis.kglocal(\n length=length, b_strip=b_strip, ty_1=ty_1, ty_2=ty_2, b_c=b_c, m_a=m_a\n )\n # Transform k_local and kg_local into global coordinates\n alpha = el_props[i, 2]\n [k_local, kg_local] = pycufsm.analysis.trans(\n alpha=alpha, k_local=k_l, kg_local=kg_l, m_a=m_a\n )\n\n # Add element contribution of k_local to full matrix k_global\n # and kg_local to kg_global\n [k_global, kg_global] = pycufsm.analysis.assemble(\n k_global=k_global,\n kg_global=kg_global,\n k_local=k_local,\n kg_local=kg_local,\n node_i=node_i,\n node_j=node_j,\n n_nodes=n_nodes,\n m_a=m_a\n )\n\n # orthogonalization/normalization begins\n if gbt_con['orth'] == 2 or gbt_con['orth'] == 3 \\\n or gbt_con['o_space'] == 2 or gbt_con['o_space'] == 3 or gbt_con['o_space'] == 4:\n # indices\n dof_index[0, 0] = 0\n dof_index[0, 1] = n_global_modes\n dof_index[1, 0] = n_global_modes\n dof_index[1, 1] = n_global_modes + n_dist_modes\n dof_index[2, 0] = n_global_modes + n_dist_modes\n dof_index[2, 1] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 0] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 1] = n_dof_m\n\n n_other_modes = n_dof_m - (n_global_modes + n_dist_modes + n_local_modes)\n\n b_v_gdl = np.zeros(((len(m_a) + 1)*(n_global_modes + n_dist_modes + n_local_modes), 1))\n b_v_g = np.zeros(((len(m_a) + 1)*n_global_modes, 1))\n b_v_d = np.zeros(((len(m_a) + 1)*n_dist_modes, 1))\n b_v_l = np.zeros(((len(m_a) + 1)*n_local_modes, 1))\n b_v_o = np.zeros(((len(m_a) + 1)*n_other_modes, 1))\n for i, m_i in enumerate(m_a):\n # considering length-dependency on base vectors\n b_v_m = b_v_l[:, n_dof_m*i:n_dof_m*(i + 1)] # n_dof_m*i:n_dof_m*(i+1)\n b_v_gdl[:, i * (n_global_modes + n_dist_modes + n_local_modes):(i + 1) *\n (n_global_modes+n_dist_modes+n_local_modes)] \\\n = b_v_m[:, dof_index[1, 1]:dof_index[3, 2]]\n b_v_g[:, i*n_global_modes:(i + 1)*n_global_modes] = b_v_m[:,\n dof_index[1,\n 1]:dof_index[1,\n 2]]\n b_v_d[:, i*n_dist_modes:(i + 1)*n_dist_modes] = b_v_m[:, dof_index[2,\n 1]:dof_index[2,\n 2]]\n b_v_l[:, i*n_local_modes:(i + 1)*n_local_modes] = b_v_m[:,\n dof_index[3,\n 1]:dof_index[3,\n 2]]\n b_v_o[:, i*n_other_modes:(i + 1)*n_other_modes] = b_v_m[:,\n dof_index[4,\n 1]:dof_index[4,\n 2]]\n #\n\n # define vectors for other modes, gbt_con['o_space'] = 3 only\n if gbt_con['o_space'] == 3:\n a_matrix = spla.null_space(b_v_gdl.conj().T)\n b_v_o = np.linalg.solve(k_global, a_matrix)\n for i, m_i in enumerate(m_a):\n b_v[:, i*n_dof_m+dof_index[3, 0]:i*n_dof_m+dof_index[3, 1]] \\\n = b_v_o[:, i*n_other_modes+1:(i+1)*n_other_modes]\n\n # define vectors for other modes, gbt_con['o_space'] = 4 only\n if gbt_con['o_space'] == 4:\n a_matrix = spla.null_space(b_v_gdl.conj().T)\n b_v_o = np.linalg.solve(kg_global, a_matrix)\n for i, m_i in enumerate(m_a):\n b_v[:, i*n_dof_m+dof_index[3, 0]:i*n_dof_m+dof_index[3, 1]] \\\n = b_v_o[:, i*n_other_modes+1:(i+1)*n_other_modes]\n\n # define vectors for other modes, gbt_con['o_space'] = 5 only\n if gbt_con['o_space'] == 5:\n a_matrix = spla.null_space(b_v_gdl.conj().T)\n for i, m_i in enumerate(m_a):\n b_v[:, i*n_dof_m+dof_index[3, 0]:i*n_dof_m+dof_index[3, 1]] \\\n = a_matrix[:, i*n_other_modes+1:(i+1)*n_other_modes]\n\n # orthogonalization + normalization for normals 2/3\n for i_sub, dof_sub in enumerate(dof_index):\n if dof_sub[2] >= dof_sub[1]:\n if i_sub == 1:\n k_global_sub = b_v_g.conj().T*k_global*b_v_g\n kg_global_sub = b_v_g.conj().T*kg_global*b_v_g\n elif i_sub == 2:\n k_global_sub = b_v_d.conj().T*k_global*b_v_d\n kg_global_sub = b_v_d.conj().T*kg_global*b_v_d\n elif i_sub == 3:\n k_global_sub = b_v_l.conj().T*k_global*b_v_l\n kg_global_sub = b_v_l.conj().T*kg_global*b_v_l\n elif i_sub == 4:\n k_global_sub = b_v_o.conj().T*k_global*b_v_o\n kg_global_sub = b_v_o.conj().T*kg_global*b_v_o\n\n [eigenvalues, eigenvectors] = spla.eig(a=k_global_sub, b=kg_global_sub)\n lf_sub = np.real(eigenvalues)\n indexsub = np.argsort(lf_sub)\n lf_sub = lf_sub[indexsub]\n eigenvectors = np.real(eigenvectors[:, indexsub])\n if gbt_con['norm'] == 2 or gbt_con['norm'] == 3:\n if gbt_con['norm'] == 2:\n s_matrix = eigenvectors.conj().T @ k_global_sub @ eigenvectors\n if gbt_con['norm'] == 3:\n s_matrix = eigenvectors.conj().T @ kg_global_sub @ eigenvectors\n s_matrix = np.diag(s_matrix)\n for i in range(0, (dof_sub[1] - dof_sub[0])*total_m):\n eigenvectors[:, i] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n eigenvectors[:, i].conj().T,\n np.sqrt(s_matrix).conj().T\n )\n )\n )\n\n if i_sub == 1:\n b_v_orth = b_v_g @ eigenvectors\n elif i_sub == 2:\n b_v_orth = b_v_d @ eigenvectors\n elif i_sub == 3:\n b_v_orth = b_v_l @ eigenvectors\n elif i_sub == 4:\n b_v_orth = b_v_o @ eigenvectors\n\n for i, m_i in enumerate(m_a):\n if i_sub == 1:\n b_v[:, i*n_dof_m+dof_sub[1]:i*n_dof_m+dof_sub[2]] \\\n = b_v_orth[:, i*n_global_modes+1:(i+1)*n_global_modes]\n elif i_sub == 2:\n b_v[:, i*n_dof_m+dof_sub[1]:i*n_dof_m+dof_sub[2]] \\\n = b_v_orth[:, i*n_dist_modes+1:(i+1)*n_dist_modes]\n elif i_sub == 3:\n b_v[:, i*n_dof_m+dof_sub[1]:i*n_dof_m+dof_sub[2]] \\\n = b_v_orth[:, i*n_local_modes+1:(i+1)*n_local_modes]\n elif i_sub == 4:\n b_v[:, i*n_dof_m+dof_sub[1]:i*n_dof_m+dof_sub[2]] \\\n = b_v_orth[:, i*n_other_modes+1:(i+1)*n_other_modes]\n\n # normalization for gbt_con['o_space'] = 1\n if (gbt_con['norm'] == 2 or gbt_con['norm'] == 3) and (gbt_con['o_space'] == 1):\n for i in range(0, n_dof_m*total_m):\n if gbt_con['norm'] == 2:\n b_v[:, i] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v[:, i].conj().T,\n np.sqrt(b_v[:, i].conj().T @ k_global @ b_v[:, i]).conj().T\n )\n )\n )\n\n if gbt_con['norm'] == 3:\n b_v[:, i] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v[:, i].conj().T,\n np.sqrt(b_v[:, i].conj().T @ kg_global @ b_v[:, i]).conj().T\n )\n )\n )\n\n # normalization for gbt_con['norm'] 1\n if gbt_con['norm'] == 1:\n for i in range(0, n_dof_m*total_m):\n b_v[:, i] = np.transpose(\n np.conj(\n np.linalg.lstsq(\n b_v[:, i].conj().T,\n np.sqrt(b_v[:, i].conj().T @ b_v[:, i]).conj().T\n )\n )\n )\n # b_v[n_dof_m*i:n_dof_m*(i+1),n_dof_m*i:n_dof_m*(i+1)] = b_v_m\n return b_v\n\n\ndef mode_select(b_v, n_global_modes, n_dist_modes, n_local_modes, gbt_con, n_dof_m, m_a):\n # this routine selects the required base vectors\n # b_v_red forms a reduced space for the calculation, including the\n # selected modes only\n # b_v_red itself is the final constraint matrix for the selected modes\n #\n #\n # input data\n # b_v - base vectors (each column corresponds to a certain mode)\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof: other modes\n # n_global_modes, n_dist_modes, n_local_modes - number of global, distortional\n # and local buckling modes, respectively\n # gbt_con['glob'] - indicator which global modes are selected\n # gbt_con['dist'] - indicator which dist. modes are selected\n # gbt_con['local'] - indicator whether local modes are selected\n # gbt_con['other'] - indicator whether other modes are selected\n # n_dof_m: 4*n_nodes, total DOF for a singal longitudinal term\n\n # output data\n # b_v_red - reduced base vectors (each column corresponds to a certain mode)\n\n #\n # note:\n # for all if_* indicator: 1 if selected, 0 if eliminated\n #\n #\n # S. Adany, Mar 22, 2004\n # BWS May 2004\n # modifed on Jul 10, 2009 by Z. Li for general b_c\n # Z. Li, June 2010\n\n n_m = int(\n sum(gbt_con['glob']) + sum(gbt_con['dist']) + sum(gbt_con['local']) + sum(gbt_con['other'])\n )\n b_v_red = np.zeros((len(b_v), (len(m_a) + 1)*n_m))\n for i in range(0, len(m_a)):\n # b_v_m = b_v[n_dof_m*i:n_dof_m*(i+1),n_dof_m*i:n_dof_m*(i+1)]\n n_other_modes = n_dof_m - n_global_modes - n_dist_modes - n_local_modes # nr of other modes\n #\n nmo = 0\n b_v_red_m = np.zeros((len(b_v), n_m))\n for j in range(0, n_global_modes):\n if gbt_con['glob'][j] == 1:\n b_v_red_m[:, nmo] = b_v[:, n_dof_m*i + j]\n nmo = nmo + 1\n\n for j in range(0, n_dist_modes):\n if gbt_con['dist'][j] == 1:\n b_v_red_m[:, nmo] = b_v[:, n_dof_m*i + n_global_modes + j]\n nmo = nmo + 1\n\n # if gbt_con['local'] == 1\n # b_v_red[:,(nmo+1):(nmo+n_local_modes)]\n # = b_v[:,(n_global_modes+n_dist_modes+1):(n_global_modes+\n # n_dist_modes+n_local_modes)]\n # nmo = nmo+n_local_modes\n # end\n for j in range(0, n_local_modes):\n if gbt_con['local'][j] == 1:\n b_v_red_m[:, nmo] = b_v[:, n_dof_m*i + n_global_modes + n_dist_modes + j]\n nmo = nmo + 1\n\n for j in range(0, n_other_modes):\n if gbt_con['other'][j] == 1:\n b_v_red_m[:,\n nmo] = b_v[:,\n n_dof_m*i + n_global_modes + n_dist_modes + n_local_modes + j]\n nmo = nmo + 1\n\n # if gbt_con['other'] == 1\n # n_other_modes = len(b_v[:, 1])-n_global_modes - n_dist_modes - n_local_modes\n # # nr of other modes\n # b_v_red[:,(nmo+1):(nmo+n_other_modes)]\n # = b_v[:,(n_global_modes+n_dist_modes+n_local_modes+1):(n_global_modes+\n # n_dist_modes+n_local_modes+n_other_modes)]\n # # b_v_red[:,(nmo+1)] = b_v[:,(n_global_modes+n_dist_modes+n_local_modes+1)]\n # end\n b_v_red[:, nmo*i:nmo*(i + 1)] = b_v_red_m\n\n return b_v_red\n\n\ndef constr_user(nodes, constraints, m_a):\n #\n # this routine creates the constraints matrix, r_user_matrix, as defined by the user\n #\n #\n # input/output data\n # nodes - same as elsewhere throughout this program\n # constraints - same as 'constraints' throughout this program\n # m_a - longitudinal terms to be included for this length\n\n # r_user_matrix - the constraints matrix (in other words: base vectors) so that\n # displ_orig = r_user_matrix * displ_new\n\n # S. Adany, Feb 26, 2004\n # Z. Li, Aug 18, 2009 for general b.c.\n # Z. Li, June 2010\n\n n_nodes = len(nodes[:, 1])\n n_dof_m = 4*n_nodes\n dof_reg = np.ones((n_dof_m, 1))\n r_user_matrix = np.eye(n_dof_m*len(m_a))\n for i in range(0, len(m_a)):\n #\n r_user_m_matrix = np.eye(n_dof_m)\n # to consider free DOFs\n for j in range(0, n_nodes):\n for k in range(3, 7):\n if nodes[j, k] == 0:\n if k == 3:\n dof_e = j*2 + 1 - 1\n elif k == 5:\n dof_e = (j + 1)*2 - 1\n elif k == 4:\n dof_e = n_nodes*2 + j*2 + 1 - 1\n elif k == 6:\n dof_e = n_nodes*2 + (j + 1)*2 - 1\n\n dof_reg[dof_e, 0] = 0\n\n # to consider master-slave constraints\n for j in range(0, len(constraints)):\n if len(constraints[j, :]) >= 5:\n # nr of eliminated DOF\n node_e = constraints[j, 0]\n if constraints[j, 1] == 0:\n dof_e = node_e*2 + 1 - 1\n elif constraints[j, 1] == 2:\n dof_e = (node_e + 1)*2 - 1\n elif constraints[j, 1] == 1:\n dof_e = n_nodes*2 + node_e*2 + 1 - 1\n elif constraints[j, 1] == 3:\n dof_e = n_nodes*2 + (node_e + 1)*2 - 1\n\n # nr of kept DOF\n node_k = constraints[j, 3]\n if constraints[j, 4] == 0:\n dof_k = node_k*2 + 1 - 1\n elif constraints[j, 4] == 2:\n dof_k = (node_k + 1)*2 - 1\n elif constraints[j, 4] == 1:\n dof_k = n_nodes*2 + node_k*2 + 1 - 1\n elif constraints[j, 4] == 3:\n dof_k = n_nodes*2 + (node_k + 1)*2 - 1\n\n # to modify r_user_matrix\n r_user_m_matrix[:, dof_k] = r_user_m_matrix[:, dof_k] \\\n + constraints[j, 2]*r_user_m_matrix[:, dof_e]\n dof_reg[dof_e, 0] = 0\n\n # to eliminate columns from r_user_matrix\n k = -1\n r_u_matrix = np.zeros_like(r_user_m_matrix)\n for j in range(0, n_dof_m):\n if dof_reg[j, 0] == 1:\n k = k + 1\n r_u_matrix[:, k] = r_user_m_matrix[:, j]\n\n r_user_m_matrix = r_u_matrix[:, 0:k]\n r_user_matrix[i*n_dof_m:(i + 1)*n_dof_m, i*k:(i + 1)*k] = r_user_m_matrix\n\n return r_user_matrix\n\n\ndef mode_constr(nodes, elements, node_props, main_nodes, meta_elements):\n #\n # this routine creates the constraint matrices necessary for mode\n # separation/classification for each specified half-wave number m_i\n #\n # assumptions\n # GBT-like assumptions are used\n # the cross-section must not be closed and must not contain closed parts\n #\n # must check whether 'Warp' works well for any open section !!!\n #\n #\n # input/output data\n # nodes, elements, props - same as elsewhere throughout this program\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m_i-el_i-1, m_i-el_i-2, ...]\n # meta_elements [meta-elements] - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n #\n #\n # notes:\n # m-el_i-? is positive if the starting nodes of m-el_i-? coincides with\n # the given m-nodes, otherwise negative\n # nodes types: 1-corner, 2-edge, 3-sub\n # sub-nodes numbers are the original one, of course\n #\n # S. Adany, Mar 10, 2004\n # Z. Li, Jul 10, 2009\n\n # to create r_x and r_z constraint matrices\n [r_x, r_z] = constr_xz_y(main_nodes, meta_elements)\n #\n # to create r_ys constraint matrix for the y DOFs of sub-nodes\n r_ys = constr_ys_ym(nodes, main_nodes, meta_elements, node_props)\n #\n # to create r_yd for y DOFs of main nodes for distortional buckling\n r_yd = constr_yd_yg(nodes, elements, node_props, r_ys, len(main_nodes))\n #\n # to create r_ud for y DOFs of indefinite main nodes\n r_ud = constr_yu_yd(main_nodes, meta_elements)\n\n return r_x, r_z, r_yd, r_ys, r_ud\n\n\ndef y_dofs(\n nodes, elements, main_nodes, n_main_nodes, n_dist_modes, r_yd, r_ud, sect_props, el_props\n):\n\n # this routine creates y-DOFs of main nodes for global buckling and\n # distortional buckling, however:\n # only involves single half-wave number m_i\n #\n # assumptions\n # GBT-like assumptions are used\n # the cross-section must not be closed and must not contain closed parts\n\n # input data\n # nodes, elements - same as elsewhere throughout this program\n # main_nodes [main nodes] - nodes of 'meta' cross-section\n # n_main_nodes, n_corner_nodes, n_sub_nodes\n # - number of main nodes, corner nodes and sub-nodes, respectively\n # n_dist_modes, n_local_modes - number of distortional and local buckling modes, respectively\n # r_yd, r_ud - constraint matrices\n #\n # output data\n # d_y - y-DOFs of main nodes for global buckling and distortional buckling\n # (each column corresponds to a certain mode)\n #\n #\n # S. Adany, Mar 10, 2004, modified Aug 29, 2006\n # Z. Li, Dec 22, 2009\n\n w_o = np.zeros((len(nodes), 2))\n w_o[int(elements[0, 1]), 0] = int(elements[0, 1])\n w_no = 0\n\n # compute the unit warping\n # code from cutwp_prop2:232-249\n for _ in range(0, len(elements)):\n i = 0\n while (np.any(w_o[:, 0] == elements[i, 1]) and np.any(w_o[:, 0] == elements[i, 2])) \\\n or (not np.any(w_o[:, 0] == elements[i, 1]) \\\n and not np.any(w_o[:, 0] == elements[i, 2])):\n i = i + 1\n s_n = int(elements[i, 1])\n f_n = int(elements[i, 2])\n p_o = ((nodes[s_n, 1] - sect_props['x0']) \\\n * (nodes[f_n, 2] - sect_props['y0']) \\\n - (nodes[f_n, 1] - sect_props['x0']) \\\n * (nodes[s_n, 2] - sect_props['y0'])) \\\n / el_props[i, 1]\n if w_o[s_n, 0] == 0:\n w_o[s_n, 0] = s_n\n w_o[s_n, 1] = w_o[f_n, 1] - p_o*el_props[i, 1]\n elif w_o[int(elements[i, 2]), 1] == 0:\n w_o[f_n, 0] = f_n\n w_o[f_n, 1] = w_o[s_n, 1] + p_o*el_props[i, 1]\n w_no = w_no + 1 / (2*sect_props['A']) * (w_o[s_n, 1] + w_o[f_n, 1]) \\\n * elements[i, 3] * el_props[i, 1]\n w_n = w_no - w_o[:, 1]\n # coord. transform. to the principal axes\n phi = sect_props['phi']\n rot = np.array([\n [np.cos(phi), -np.sin(phi)],\n [np.sin(phi), np.cos(phi)],\n ])\n centre_of_gravity = [\n sect_props['cx'],\n sect_props['cy'],\n ] @ rot\n\n # CALCULATION FOR GLOBAL AND DISTORTIONAL BUCKLING MODES\n #\n # to create y-DOFs of main nodes for global buckling\n d_y = np.zeros((n_main_nodes, 4))\n for i, m_node in enumerate(main_nodes):\n xz_i = [m_node[1], m_node[2]] @ rot\n d_y[i, 0] = 1\n d_y[i, 1] = xz_i[1] - centre_of_gravity[1]\n d_y[i, 2] = xz_i[0] - centre_of_gravity[0]\n d_y[i, 3] = w_n[int(m_node[3])]\n\n # for i = 1:4\n # d_y[:, i] = d_y[:, i]/norm(d_y[:, i])\n # end\n # to count the nr of existing global modes\n n_global_modes = 4\n ind = np.ones(4)\n for i in range(0, 4):\n if np.nonzero(d_y[:, i]) == []:\n ind[i] = 0\n n_global_modes = n_global_modes - 1\n\n # to eliminate zero columns from d_y\n sdy = d_y\n d_y = np.zeros((len(sdy), int(sum(ind))))\n k = 0\n for i in range(0, 4):\n if ind[i] == 1:\n d_y[:, k] = sdy[:, i]\n k = k + 1\n\n # to create y-DOFs of main nodes for distortional buckling\n if n_dist_modes > 0:\n d_y = np.concatenate((d_y, np.zeros((len(d_y), n_dist_modes))), axis=1)\n # junk = spla.null_space((r_yd*d_y(:, 1:(n_global_modes+1))).conj().T)\n # junk3 = junk.conj().T*r_yd*junk\n r_chol = np.linalg.cholesky(r_yd).T\n junk = spla.null_space((r_chol @ d_y[:, 0:n_global_modes]).conj().T)\n junk2 = np.linalg.solve(r_chol, junk)\n\n j_junk1 = spla.null_space(junk2.conj().T)\n j_junk2 = spla.null_space(r_ud.conj().T)\n nj1 = len(j_junk1[0])\n nj2 = len(j_junk2[0])\n j_junk3 = j_junk1\n j_junk3[:, nj1:nj1 + nj2] = j_junk2\n j_junk4 = spla.null_space(j_junk3.conj().T)\n\n # d_y(:,(n_global_modes+2):(n_global_modes+1+n_dist_modes)) = j_junk4\n junk3 = j_junk4.conj().T @ r_yd @ j_junk4\n # junk3 = junk2.conj().T*junk2\n #\n [_, eigenvectors] = spla.eig(junk3)\n # eigenvalues = diag(eigenvalues)\n # [eigenvalues, index] = sort(eigenvalues)\n # eigenvectors = eigenvectors[:, index]\n d_y[:, n_global_modes:n_global_modes + n_dist_modes] = j_junk4 @ eigenvectors\n\n return d_y, n_global_modes\n\n\ndef base_vectors(\n d_y, elements, el_props, length, m_i, node_props, n_main_nodes, n_corner_nodes, n_sub_nodes,\n n_global_modes, n_dist_modes, n_local_modes, r_x, r_z, r_p, r_ys, dof_perm\n):\n #\n # this routine creates the base vectors for global, dist., local and other modes\n #\n # assumptions\n # GBT-like assumptions are used\n # the cross-section must not be closed and must not contain closed parts\n #\n # must check whether 'Warp' works well for any open section !!!\n #\n #\n # input data\n # elements, el_props - same as elsewhere throughout this program\n # length, m_i - member length and number of half-waves, respectively\n # main_nodes [main nodes] - nodes of 'meta' cross-section\n # meta_elements [meta-elements] - elements of 'meta' cross-section\n # node_props - some properties of the nodes\n # n_main_nodes, n_corner_nodes, n_sub_nodes\n # - number of main nodes, corner nodes and sub-nodes, respectively\n # n_dist_modes, n_local_modes - number of distortional and local buckling modes, respectively\n # r_x, r_z, r_p, r_ys, - constraint matrices\n # dof_perm - permutation matrix to re-order the DOFs\n #\n # output data\n # n_other_modes - nr of other modes\n # b_v_m - base vectors for single half-wave number m_i\n # (each column corresponds to a certain mode)\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof: other modes\n #\n # note:\n # more details on the input variables can be found in the routines called\n # in this routine\n #\n\n # S. Adany, Mar 10, 2004, modified Aug 29, 2006\n # Z. Li, Dec 22, 2009\n\n # DATA PREPARATION\n k_m = m_i*np.pi/length\n n_node_props = len(node_props)\n n_dof = 4*n_node_props # nro of DOFs\n n_edge_nodes = n_main_nodes - n_corner_nodes\n # zero out\n b_v_m = np.zeros((n_dof, n_dof))\n\n # CALCULATION FOR GLOBAL AND DISTORTIONAL BUCKLING MODES\n # to add global and dist y DOFs to base vectors\n b_v_m = d_y[:, 0:n_global_modes + n_dist_modes]\n b_v_m = np.concatenate((b_v_m, np.zeros((n_dof - len(b_v_m), len(b_v_m[0])))), axis=0)\n #\n # to add x DOFs of corner nodes to the base vectors\n # r_x = r_x/k_m\n b_v_m[n_main_nodes:n_main_nodes + n_corner_nodes, 0:n_global_modes\n + n_dist_modes] = r_x @ b_v_m[0:n_main_nodes, 0:n_global_modes + n_dist_modes]\n #\n # to add z DOFs of corner nodes to the base vectors\n # r_z = r_z/k_m\n b_v_m[n_main_nodes + n_corner_nodes:n_main_nodes + 2*n_corner_nodes, 0:n_global_modes\n + n_dist_modes] = r_z @ b_v_m[0:n_main_nodes, 0:n_global_modes + n_dist_modes]\n #\n # to add other planar DOFs to the base vectors\n b_v_m[n_main_nodes + 2*n_corner_nodes:n_dof - n_sub_nodes, 0:n_global_modes\n + n_dist_modes] = r_p @ b_v_m[n_main_nodes:n_main_nodes + 2*n_corner_nodes,\n 0:n_global_modes + n_dist_modes]\n #\n # to add y DOFs of sub-nodes to the base vector\n b_v_m[n_dof - n_sub_nodes:n_dof, 0:n_global_modes\n + n_dist_modes] = r_ys @ b_v_m[0:n_main_nodes, 0:n_global_modes + n_dist_modes]\n #\n # division by k_m\n b_v_m[n_main_nodes:n_dof - n_sub_nodes,\n 0:n_global_modes + n_dist_modes] = b_v_m[n_main_nodes:n_dof - n_sub_nodes,\n 0:n_global_modes + n_dist_modes]/k_m\n #\n # norm base vectors\n for i in range(0, n_global_modes + n_dist_modes):\n b_v_m[:, i] = b_v_m[:, i]/np.linalg.norm(b_v_m[:, i])\n\n # CALCULATION FOR LOCAL BUCKLING MODES\n n_globdist_modes = n_global_modes + n_dist_modes # nr of global and dist. modes\n b_v_m = np.concatenate((b_v_m, np.zeros((len(b_v_m), n_local_modes))), axis=1)\n # np.zeros\n b_v_m[0:n_dof,\n n_globdist_modes:n_globdist_modes + n_local_modes] = np.zeros((n_dof, n_local_modes))\n\n # rot DOFs for main nodes\n b_v_m[3*n_main_nodes:4*n_main_nodes,\n n_globdist_modes:n_globdist_modes + n_main_nodes] = np.eye(n_main_nodes)\n #\n # rot DOFs for sub nodes\n if n_sub_nodes > 0:\n b_v_m[4*n_main_nodes + 2*n_sub_nodes:4*n_main_nodes + 3*n_sub_nodes, n_globdist_modes\n + n_main_nodes:n_globdist_modes + n_main_nodes + n_sub_nodes] = np.eye(n_sub_nodes)\n\n # x, z DOFs for edge nodes\n k = 0\n for i in range(0, n_node_props):\n if node_props[i, 3] == 2:\n el_i = np.nonzero(\n np.any(elements[:, 1] == i) or np.any(elements[:, 2] == i)\n ) # adjacent element\n alfa = el_props[el_i, 2]\n b_v_m[n_main_nodes + 2*n_corner_nodes + k,\n n_globdist_modes + n_main_nodes + n_sub_nodes + k] = -np.sin(alfa) # x\n b_v_m[n_main_nodes + 2*n_corner_nodes + n_edge_nodes + k,\n n_globdist_modes + n_main_nodes + n_sub_nodes + k] = np.cos(alfa) # z\n k = k + 1\n\n # x, z DOFs for sub-nodes\n if n_sub_nodes > 0:\n k = 0\n for i in range(0, n_node_props):\n if node_props[i, 3] == 3:\n el_i = np.nonzero(\n np.any(elements[:, 1] == i) or np.any(elements[:, 2] == i)\n ) # adjacent element\n alfa = el_props[el_i[0], 2]\n b_v_m[4*n_main_nodes + k, n_globdist_modes + n_main_nodes + n_sub_nodes\n + n_edge_nodes + k] = -np.sin(alfa) # x\n b_v_m[4*n_main_nodes + n_sub_nodes + k, n_globdist_modes + n_main_nodes\n + n_sub_nodes + n_edge_nodes + k] = np.cos(alfa) # z\n k = k + 1\n\n # CALCULATION FOR OTHER BUCKLING MODES\n #\n # # first among the \"others\": uniform y\n # b_v_m[1:n_main_nodes,(n_globdist_modes+n_local_modes+1)]\n # = np.zeros(n_main_nodes, 1)+np.sqrt(1 / (n_main_nodes+n_sub_nodes))\n # b_v_m[(n_dof-n_sub_nodes+1):n_dof,(n_globdist_modes+n_local_modes+1)]\n # = np.zeros(n_sub_nodes, 1)+np.sqrt(1 / (n_main_nodes+n_sub_nodes))\n #\n ## old way\n # n_other_modes = n_dof - n_globdist_modes - n_local_modes\n # n_elements = len(elements[:, 1])\n # b_v_m[1:n_dof,(n_globdist_modes+n_local_modes+1):(n_globdist_modes+\n # n_local_modes+2*n_elements)] = np.zeros(n_dof, 2*n_elements)\n # temp_elem = elements[:, 2:3]\n # for i = 1:n_elements\n # #\n # alfa = el_props[i, 3]\n # #\n # # find nodes on the one side of the current element\n # n_nod = 1\n # nods=[]\n # nods(1) = elements[i, 2]\n # temp_elem = elements[:, 2:3]\n # temp_elem[i, 1] = 0\n # temp_elem[i, 2] = 0\n # new = 1\n # while new>0\n # new = 0\n # for j = 1:n_elements\n # for k_local = 1:len(nods)\n # if (nods(k_local) == temp_elem[j, 1])\n # n_nod = n_nod+1\n # new = new+1\n # nods(n_nod) = temp_elem[j, 2]\n # temp_elem[j, 1] = 0\n # temp_elem[j, 2] = 0\n #\n # if (nods(k_local) == temp_elem[j, 2])\n # n_nod = n_nod+1\n # new = new+1\n # nods(n_nod) = temp_elem[j, 1]\n # temp_elem[j, 1] = 0\n # temp_elem[j, 2] = 0\n #\n # #\n # # create the base-vectors for membrane SHEAR modes\n # s = np.sqrt(1/n_nod)\n # for j = 1:n_nod\n # old_dof_y = 2 * (nods[j])\n # b_v_m[old_dof_y,(n_globdist_modes+n_local_modes+i)] = s\n #\n # # create the base-vectors for membrane TRANSVERSE modes\n # for j = 1:n_nod\n # old_dof_x = 2 * (nods[j])-1\n # old_dof_z = 2*n_node_props+2 * (nods[j])-1\n # b_v_m[old_dof_x,(n_globdist_modes+n_local_modes+n_elements+i)] = s*np.cos(alfa)\n # b_v_m[old_dof_z,(n_globdist_modes+n_local_modes+n_elements+i)] = s*np.sin(alfa)\n #\n #\n # end\n ## new way\n n_elements = len(elements)\n b_v_m = np.concatenate((b_v_m, np.zeros((len(b_v_m), 2*n_elements))), axis=1)\n for i, elem in enumerate(elements):\n alfa = el_props[i, 2]\n\n # find nodes on the one side of the current element\n n_nod1 = int(elem[1])\n n_nod2 = int(elem[2])\n\n # create the base-vectors for membrane SHEAR modes\n b_v_m[(n_nod1 - 1)*2, n_globdist_modes + n_local_modes + i] = 0.5\n b_v_m[(n_nod2 - 1)*2, n_globdist_modes + n_local_modes + i] = -0.5\n\n # create the base-vectors for membrane TRANSVERSE modes\n b_v_m[(n_nod1 - 1)*2, n_globdist_modes + n_local_modes + n_elements + i] = -0.5*np.cos(alfa)\n b_v_m[(n_nod2 - 1)*2, n_globdist_modes + n_local_modes + n_elements + i] = 0.5*np.cos(alfa)\n b_v_m[2*n_node_props + (n_nod1 - 1)*2,\n n_globdist_modes + n_local_modes + n_elements + i] = 0.5*np.sin(alfa)\n b_v_m[2*n_node_props + (n_nod2 - 1)*2,\n n_globdist_modes + n_local_modes + n_elements + i] = -0.5*np.sin(alfa)\n\n # RE_ORDERING DOFS\n b_v_m[:, 0:n_globdist_modes\n + n_local_modes] = dof_perm @ b_v_m[:, 0:n_globdist_modes + n_local_modes]\n\n return b_v_m\n\n\ndef constr_xz_y(main_nodes, meta_elements):\n # this routine creates the constraint matrix, Rxz, that defines relationship\n # between x, z displacements DOFs [for internal main nodes, referred also as corner nodes]\n # and the longitudinal y displacements DOFs [for all the main nodes]\n # if GBT-like assumptions are used\n #\n # to make this routine length-independent, Rxz is not multiplied here by\n # (1/k_m), thus it has to be multiplied outside of this routine!\n #\n # additional assumption: cross section is opened!\n #\n #\n # input/output data\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements [meta-elements] - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n #\n # note:\n # m-el_i-? is positive if the starting nodes of m-el_i-? coincides with\n # the given m-nodes, otherwise negative\n #\n # S. Adany, Feb 05, 2004\n #\n #\n # to calculate some data of main elements (stored in meta_elements_data)\n meta_elements_data = np.zeros((len(meta_elements), 5))\n for i, m_elem in enumerate(meta_elements):\n node1 = int(m_elem[1])\n node2 = int(m_elem[2])\n x_1 = main_nodes[node1, 1]\n x_2 = main_nodes[node2, 1]\n z_1 = main_nodes[node1, 2]\n z_2 = main_nodes[node2, 2]\n b_i = np.sqrt((x_2 - x_1)**2 + (z_2 - z_1)**2)\n a_i = np.arctan2(z_2 - z_1, x_2 - x_1)\n s_i = (z_2 - z_1)/b_i\n c_i = (x_2 - x_1)/b_i\n meta_elements_data[i, 0] = b_i # elements width, b_strip\n meta_elements_data[i, 1] = 1/meta_elements_data[i, 0] # 1/b_strip\n meta_elements_data[i, 2] = a_i # elements inclination\n meta_elements_data[i, 3] = s_i # np.sin\n meta_elements_data[i, 4] = c_i # np.cos\n # meta_elements_data[i, 5] = s_i/b_i # np.sin/b_strip\n # meta_elements_data[i, 6] = c_i/b_i # np.cos/b_strip\n\n # to count the number of corner nodes, and of main nodes\n n_main_nodes = len(main_nodes[:, 0])\n n_corner_nodes = 0\n for m_node in main_nodes:\n if m_node[4] > 1:\n n_corner_nodes = n_corner_nodes + 1\n\n r_x = np.zeros((n_corner_nodes, n_main_nodes))\n r_z = np.zeros((n_corner_nodes, n_main_nodes))\n k = 0\n for i, m_node in enumerate(main_nodes):\n if m_node[4] > 1:\n # to select two non-parallel meta-elements (elem1, elem2)\n elem1 = int(m_node[5])\n elem1_flag = int(round((m_node[5] - elem1)*10))\n j = 6\n while np.sin(meta_elements_data[int(np.real(m_node[j])), 2]\n - meta_elements_data[elem1, 2]) == 0:\n j = j + 1\n\n elem2 = int(m_node[j])\n elem2_flag = int(round((m_node[j] - elem2)*10))\n\n # to define main-nodes that play (order: main_nodes1, main_nodes2, main_nodes3)\n main_nodes2 = int(i)\n main_nodes1 = int(meta_elements[elem1, elem1_flag])\n main_nodes3 = int(meta_elements[elem2, elem2_flag])\n\n # to calculate elements of Rxz matrix\n r_1 = meta_elements_data[elem1, 1]\n alfa1 = meta_elements_data[elem1, 2]\n sin1 = meta_elements_data[elem1, 3]\n cos1 = meta_elements_data[elem1, 4]\n if elem1_flag == 2:\n alfa1 = alfa1 - np.pi\n sin1 = -sin1\n cos1 = -cos1\n\n r_2 = meta_elements_data[elem2, 1]\n alfa2 = meta_elements_data[elem2, 2]\n sin2 = meta_elements_data[elem2, 3]\n cos2 = meta_elements_data[elem2, 4]\n if elem2 == 1:\n alfa2 = alfa2 - np.pi\n sin2 = -sin2\n cos2 = -cos2\n\n det = np.sin(alfa2 - alfa1)\n\n # to form Rxz matrix\n r_x[k, main_nodes1] = sin2*r_1/det\n r_x[k, main_nodes2] = (-sin1*r_2 - sin2*r_1)/det\n r_x[k, main_nodes3] = sin1*r_2/det\n\n r_z[k, main_nodes1] = -cos2*r_1/det\n r_z[k, main_nodes2] = (cos1*r_2 + cos2*r_1)/det\n r_z[k, main_nodes3] = -cos1*r_2/det\n\n k = k + 1\n\n return r_x, r_z\n\n\ndef constr_planar_xz(nodes, elements, props, node_props, dof_perm, m_i, length, b_c, el_props):\n #\n # this routine creates the constraint matrix, r_p, that defines relationship\n # between x, z DOFs of any non-corner nodes + teta DOFs of all nodes,\n # and the x, z displacements DOFs of corner nodes\n # if GBT-like assumptions are used\n #\n #\n # input/output data\n # nodes, elements, props - same as elsewhere throughout this program\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n # dof_perm - permutation matrix, so that\n # (orig-displacements-vect) = (dof_perm) � (new-displacements - vector)\n #\n # S. Adany, Feb 06, 2004\n # Z. Li, Jul 10, 2009\n #\n # to count corner-, edge- and sub-nodes\n n_node_props = len(node_props)\n n_corner_nodes = 0\n n_edge_nodes = 0\n n_sub_nodes = 0\n for n_prop in node_props:\n if n_prop[3] == 1:\n n_corner_nodes = n_corner_nodes + 1\n\n if n_prop[3] == 2:\n n_edge_nodes = n_edge_nodes + 1\n\n if n_prop[3] == 3:\n n_sub_nodes = n_sub_nodes + 1\n\n n_main_nodes = n_corner_nodes + n_edge_nodes # nr of main nodes\n\n n_dof = 4*n_node_props # nro of DOFs\n\n # to create the full global stiffness matrix (for transverse bending)\n k_global = kglobal_transv(nodes, elements, props, m_i, length, b_c, el_props)\n\n # to re-order the DOFs\n k_global = dof_perm.conj().T @ k_global @ dof_perm\n\n # to have partitions of k_global\n k_global_pp = k_global[n_main_nodes + 2*n_corner_nodes:n_dof - n_sub_nodes,\n n_main_nodes + 2*n_corner_nodes:n_dof - n_sub_nodes]\n k_global_pc = k_global[n_main_nodes + 2*n_corner_nodes:n_dof - n_sub_nodes,\n n_main_nodes:n_main_nodes + 2*n_corner_nodes]\n\n # to form the constraint matrix\n #[r_p]=-inv(k_global_pp) * k_global_pc\n\n r_p = -np.linalg.solve(k_global_pp, k_global_pc)\n\n return r_p\n\n\ndef constr_yd_yg(nodes, elements, node_props, r_ys, n_main_nodes):\n #\n # this routine creates the constraint matrix, r_yd, that defines relationship\n # between base vectors for distortional buckling,\n # and base vectors for global buckling,\n # but for y DOFs of main nodes only\n #\n #\n # input/output data\n # nodes, elements - same as elsewhere throughout this program\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n # r_ys - constrain matrix, see function 'constr_ys_ym'\n # n_main_nodes - nr of main nodes\n #\n # S. Adany, Mar 04, 2004\n #\n n_nodes = len(nodes)\n a_matrix = np.zeros((n_nodes, n_nodes))\n for elem in elements:\n node1 = int(elem[1])\n node2 = int(elem[2])\n d_x = nodes[node2, 1] - nodes[node1, 1]\n d_z = nodes[node2, 2] - nodes[node1, 2]\n d_area = np.sqrt(d_x*d_x + d_z*d_z)*elem[3]\n ind = np.nonzero(node_props[:, 0] == node1)\n node1 = int(node_props[ind, 1])\n ind = np.nonzero(node_props[:, 0] == node2)\n node2 = int(node_props[ind, 1])\n a_matrix[node1, node1] = a_matrix[node1, node1] + 2*d_area\n a_matrix[node2, node2] = a_matrix[node2, node2] + 2*d_area\n a_matrix[node1, node2] = a_matrix[node1, node2] + d_area\n a_matrix[node2, node1] = a_matrix[node2, node1] + d_area\n\n r_ysm = np.zeros((n_nodes, n_main_nodes))\n r_ysm[0:n_main_nodes, 0:n_main_nodes] = np.eye(n_main_nodes)\n r_ysm[n_main_nodes:n_nodes, 0:n_main_nodes] = r_ys\n r_yd = r_ysm.conj().T @ a_matrix @ r_ysm\n\n return r_yd\n\n\ndef constr_ys_ym(nodes, main_nodes, meta_elements, node_props):\n # this routine creates the constraint matrix, r_ys, that defines relationship\n # between y DOFs of sub-nodes,\n # and the y displacements DOFs of main nodes\n # by linear interpolation\n #\n #\n # input/output data\n # nodes - same as elsewhere throughout this program\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements [meta-elements] - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n #\n # S. Adany, Feb 06, 2004\n #\n n_sub_nodes = 0\n for n_prop in node_props:\n if n_prop[3] == 3:\n n_sub_nodes = n_sub_nodes + 1\n\n n_main_nodes = len(main_nodes)\n\n r_ys = np.zeros((n_sub_nodes, n_main_nodes))\n\n for m_elem in meta_elements:\n if m_elem[3] > 0:\n nod1 = int(main_nodes[int(m_elem[1]), 3])\n nod3 = int(main_nodes[int(m_elem[2]), 3])\n x_1 = nodes[nod1, 1]\n x_3 = nodes[nod3, 1]\n z_1 = nodes[nod1, 2]\n z_3 = nodes[nod3, 2]\n b_m = np.sqrt((x_3 - x_1)**2 + (z_3 - z_1)**2)\n n_new1 = int(node_props[nod1, 1])\n n_new3 = int(node_props[nod3, 1])\n for j in range(0, int(m_elem[3])):\n nod2 = int(m_elem[j + 4])\n x_2 = nodes[nod2, 1]\n z_2 = nodes[nod2, 2]\n b_s = np.sqrt((x_2 - x_1)**2 + (z_2 - z_1)**2)\n n_new2 = int(node_props[nod2, 1])\n r_ys[n_new2 - n_main_nodes, n_new1] = (b_m - b_s)/b_m\n r_ys[n_new2 - n_main_nodes, n_new3] = b_s/b_m\n\n return r_ys\n\n\ndef constr_yu_yd(main_nodes, meta_elements):\n #\n # this routine creates the constraint matrix, r_ud, that defines relationship\n # between y displacements DOFs of indefinite main nodes\n # and the y displacements DOFs of definite main nodes\n # (definite main nodes = those main nodes which unambiguously define the y displacements pattern\n # indefinite main nodes = those nodes the y DOF of which can be calculated\n # from the y DOF of definite main nodes\n # note: for open sections with one single branch only there are no indefinite nodes)\n #\n # important assumption: cross section is opened!\n #\n #\n # input/output data\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements [meta-elements] - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n #\n # note:\n # m-el_i-? is positive if the starting nodes of m-el_i-? coincides with\n # the given m-nodes, otherwise negative\n #\n # S. Adany, Mar 10, 2004\n #\n #\n # to calculate some data of main elements (stored in meta_elements_data)\n meta_elements_data = np.zeros((len(meta_elements), 5))\n for i, m_elem in enumerate(meta_elements):\n node1 = int(m_elem[1])\n node2 = int(m_elem[2])\n x_1 = main_nodes[node1, 1]\n x_2 = main_nodes[node2, 1]\n z_1 = main_nodes[node1, 2]\n z_2 = main_nodes[node2, 2]\n b_i = np.sqrt((x_2 - x_1)**2 + (z_2 - z_1)**2)\n a_i = np.arctan2(z_2 - z_1, x_2 - x_1)\n s_i = (z_2 - z_1)/b_i\n c_i = (x_2 - x_1)/b_i\n meta_elements_data[i, 0] = b_i # elements width, b_strip\n meta_elements_data[i, 1] = 1/meta_elements_data[i, 0] # 1/b_strip\n meta_elements_data[i, 2] = a_i # elements inclination\n meta_elements_data[i, 3] = s_i # np.sin\n meta_elements_data[i, 4] = c_i # np.cos\n # meta_elements_data[i, 5] = s_i/b_i # np.sin/b_strip\n # meta_elements_data[i, 6] = c_i/b_i # np.cos/b_strip\n\n # to count the number of corner nodes, and of main nodes\n n_main_nodes = len(main_nodes)\n n_corner_nodes = 0\n for m_node in main_nodes:\n if m_node[4] > 1:\n n_corner_nodes = n_corner_nodes + 1\n\n # to register definite and indefinite nodes\n node_reg = np.ones((n_main_nodes, 1))\n for i, m_node in enumerate(main_nodes):\n if m_node[4] > 2:\n # to select two non-parallel meta-elements (elem1, elem2)\n elem1 = int(np.real(m_node[5]))\n j = 6\n while np.sin(meta_elements_data[int(np.real(m_node[j])), 2]\n - meta_elements_data[elem1, 2]) == 0:\n j = j + 1\n\n elem2 = int(np.real(m_node[j]))\n\n # to set far nodes of adjacent unselected elements to indefinite (node_reg == 0)\n for j in range(1, m_node[4]):\n elem3 = int(np.real(m_node[j + 5]))\n if elem3 != elem2:\n if meta_elements[elem3, 1] != i:\n node_reg[int(meta_elements[elem3, 1])] = 0\n else:\n node_reg[int(meta_elements[elem3, 2])] = 0\n\n # to create r_ud matrix\n r_ud = np.zeros((n_main_nodes, n_main_nodes))\n\n # for definite nodes\n for i in range(0, n_main_nodes):\n if node_reg[i] == 1:\n r_ud[i, i] = 1\n\n # for indefinite nodes\n for i, m_node in enumerate(main_nodes):\n if m_node[4] > 2:\n # to select the two meta-elements that play (elem1, elem2)\n elem1 = int(m_node[5])\n elem1_flag = m_node[5] - elem1\n j = 6\n while np.sin(meta_elements_data[int(np.real(m_node[j])), 2]\n - meta_elements_data[elem1, 2]) == 0:\n j = j + 1\n\n elem2 = int(m_node[j])\n elem2_flag = m_node[j] - elem2\n\n # to define main-nodes that play (order: main_nodes1, main_nodes2, main_nodes3)\n main_nodes2 = int(i)\n if elem1_flag == 0.1:\n main_nodes1 = int(meta_elements[elem1, 2])\n else:\n main_nodes1 = int(meta_elements[elem1, 1])\n\n if elem2_flag == 0.1:\n main_nodes3 = int(meta_elements[elem2, 2])\n else:\n main_nodes3 = int(meta_elements[elem2, 1])\n\n # to calculate data necessary for r_ud\n r_1 = meta_elements_data[elem1, 1]\n alfa1 = meta_elements_data[elem1, 2]\n sin1 = meta_elements_data[elem1, 3]\n cos1 = meta_elements_data[elem1, 4]\n if elem1 > 0:\n alfa1 = alfa1 - np.pi\n sin1 = -sin1\n cos1 = -cos1\n\n r_2 = meta_elements_data[elem2, 1]\n alfa2 = meta_elements_data[elem2, 2]\n sin2 = meta_elements_data[elem2, 3]\n cos2 = meta_elements_data[elem2, 4]\n if elem2 < 0:\n alfa2 = alfa2 - np.pi\n sin2 = -sin2\n cos2 = -cos2\n\n det = np.sin(alfa2 - alfa1)\n\n r_mat = np.array([[r_1, -r_1, 0], [0, r_2, -r_2]])\n c_s = np.array([[sin2, -sin1], [-cos2, cos1]])\n csr = c_s @ r_mat/det\n\n for j in range(1, main_nodes[i, 4]):\n elem3 = int(m_node[j + 5])\n elem3_flag = m_node[j + 5] - elem3\n if elem3 != elem2:\n if meta_elements[elem3, 1] != i:\n main_nodes4 = int(meta_elements[elem3, 1])\n else:\n main_nodes4 = int(meta_elements[elem3, 2])\n\n r_3 = meta_elements_data[elem3, 1]\n alfa3 = meta_elements_data[elem3, 2]\n sin3 = meta_elements_data[elem3, 3]\n cos3 = meta_elements_data[elem3, 4]\n if elem3_flag == 0.2:\n alfa3 = alfa3 - np.pi\n sin3 = -sin3\n cos3 = -cos3\n\n rud = -1/r_3*np.array([cos3, sin3]) @ csr\n rud[0, 1] = rud[0, 1] + 1\n r_ud[main_nodes4, main_nodes1] = rud[0, 0]\n r_ud[main_nodes4, main_nodes2] = rud[0, 1]\n r_ud[main_nodes4, main_nodes3] = rud[0, 2]\n\n # to completely eliminate indefinite nodes from r_ud (if necessary)\n k = 1\n while k == 1:\n k = 0\n for i in range(0, n_main_nodes):\n if node_reg[i] == 0:\n if np.nonzero(r_ud[:, i]):\n k = 1\n indices = np.nonzero(r_ud[:, i])\n for ind in indices:\n r_ud[ind, :] = r_ud[ind, :] + r_ud[i, :]*r_ud[ind, i]\n r_ud[ind, i] = 0\n\n return r_ud\n\n\ndef base_properties(nodes, elements):\n # this routine creates all the data for defining the base vectors from the\n # cross section properties\n #\n # input data\n # nodes, elements- basic data#\n # output data\n # main_nodes - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements,\n # nodes type]\n # n_global_modes, n_dist_modes, n_local_modes, n_other_modes\n # - number of bulk, D, L, O modes, respectively\n # n_main_nodes, n_corner_nodes, n_sub_nodes\n # - number of main nodes, corner nodes and sub-nodes, respectively\n # dof_perm - permutation matrix, so that\n # (orig-displacements-vect) = (dof_perm) � (new-displacements-vector)\n #\n # S. Adany, Aug 28, 2006\n # B. Schafer, Aug 29, 2006\n # Z. Li, Dec 22, 2009\n\n [main_nodes, meta_elements, node_props] = meta_elems(nodes=nodes, elements=elements)\n [n_main_nodes, n_corner_nodes, n_sub_nodes] = node_class(node_props=node_props)\n [n_dist_modes, n_local_modes] = mode_nr(n_main_nodes, n_corner_nodes, n_sub_nodes, main_nodes)\n dof_perm = dof_ordering(node_props)\n\n return main_nodes, meta_elements, node_props, n_main_nodes, \\\n n_corner_nodes, n_sub_nodes, n_dist_modes, n_local_modes, dof_perm\n\n\ndef meta_elems(nodes, elements):\n # this routine re-organises the basic input data\n # to eliminate internal subdividing nodes\n # to form meta-elements (corner-to-corner or corner-to-free edge)\n # to identify main nodes (corner nodes and free edge nodes)\n #\n # important assumption: cross section is opened!\n #\n # input/output data\n # nodes, elements - same as elsewhere throughout this program\n # main_nodes - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # meta_elements - array of\n # [nr, main-nodes-1, main-nodes-2, nr of sub-nodes, sub-no-1, sub-nod-2, ...]\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n #\n # note:\n # m-el_i-? is positive if the starting nodes of m-el_i-? coincides with\n # the given m-nodes, otherwise negative\n # nodes types: 1-corner, 2-edge, 3-sub\n # sub-nodes numbers are the original ones, of course\n #\n # S. Adany, Feb 06, 2004\n #\n n_nodes = len(nodes)\n #\n # to count nr of elements connecting to each nodes\n # + register internal nodes to be eliminated\n # + set nodes type (node_props[:, 4])\n node_props = np.zeros((n_nodes, 4))\n node_props[:, 0] = nodes[:, 0]\n for i in range(0, n_nodes):\n els = []\n for j, elem in enumerate(elements):\n if elem[1] == i or elem[2] == i:\n els.append(j) # zli: element no. containing this nodes\n\n node_props[i, 2] = len(els)\n if len(els) == 1:\n node_props[i, 3] = 2\n\n if len(els) >= 2:\n node_props[i, 3] = 1\n\n if len(els) == 2:\n n_1 = i\n n_2 = int(elements[els[0], 1])\n # zli: the first nodes of the first elements containing this nodes\n if n_2 == n_1:\n n_2 = int(elements[els[0], 2])\n\n n_3 = int(elements[els[1], 1])\n if n_3 == n_1:\n n_3 = int(elements[els[1], 2])\n\n a_1 = np.arctan2(nodes[n_2, 2] - nodes[n_1, 2], nodes[n_2, 1] - nodes[n_1, 1]) #?\n a_2 = np.arctan2(nodes[n_1, 2] - nodes[n_3, 2], nodes[n_1, 1] - nodes[n_3, 1])\n if abs(a_1 - a_2) < 1E-7:\n node_props[i, 2] = 0\n node_props[i, 3] = 3\n\n # to create meta-elements (with the original nodes numbers)\n meta_elements_temp = np.zeros((len(elements), 5))\n meta_elements_temp[:, 0:3] = elements[:, 0:3]\n for i in range(0, n_nodes):\n if node_props[i, 2] == 0:\n els = []\n for j, m_elem in enumerate(meta_elements_temp):\n if m_elem[1] == i or m_elem[2] == i:\n els.append(j)\n\n node1 = int(meta_elements_temp[els[0], 1])\n if node1 == i:\n node1 = int(meta_elements_temp[els[0], 2])\n\n node2 = int(meta_elements_temp[els[1], 1])\n if node2 == i:\n node2 = int(meta_elements_temp[els[1], 2])\n\n meta_elements_temp[els[0], 1] = node1\n meta_elements_temp[els[0], 2] = node2\n meta_elements_temp[els[1], 1] = -1\n meta_elements_temp[els[1], 2] = -1\n meta_elements_temp[els[0], 3] = meta_elements_temp[els[0], 3] + 1 # zli:\n if 3 + meta_elements_temp[els[0], 3] >= len(meta_elements_temp[0]):\n meta_elements_temp = np.c_[meta_elements_temp, np.zeros(len(meta_elements_temp))]\n meta_elements_temp[els[0],\n int(3\n + meta_elements_temp[els[0], 3])] = i # zli:deleted elements no.\n\n # to eliminate disappearing elements (nodes numbers are still the original ones!)\n n_meta_elements = 0 # nr of meta-elements\n meta_elements = []\n for m_elem_t in meta_elements_temp:\n if m_elem_t[1] != -1 and m_elem_t[2] != -1:\n meta_elements.append(m_elem_t)\n meta_elements[-1][0] = n_meta_elements\n n_meta_elements = n_meta_elements + 1\n meta_elements = np.array(meta_elements)\n\n # to create array of main-nodes\n #(first and fourth columns assign the new vs. original numbering,\n # + node_assign tells the original vs. new numbering)\n n_main_nodes = 0 # nr of main nodes\n main_nodes = []\n for i, node in enumerate(nodes):\n if node_props[i, 2] != 0:\n main_nodes.append([n_main_nodes, node[1], node[2], i, node_props[i, 2]])\n node_props[i, 1] = n_main_nodes\n n_main_nodes = n_main_nodes + 1\n main_nodes = np.array(main_nodes)\n\n # to re-number nodes in the array meta_elements (only for main nodes, of course)\n for i, n_props in enumerate(node_props):\n if node_props[i, 2] != 0:\n for m_elem in meta_elements:\n if m_elem[1] == i:\n m_elem[1] = n_props[1]\n\n if m_elem[2] == i:\n m_elem[2] = n_props[1]\n\n # to assign meta-elements to main-nodes\n for i in range(0, n_main_nodes):\n k = 5\n for j, m_elem in enumerate(meta_elements):\n if m_elem[1] == i:\n if len(main_nodes[0]) <= k:\n main_nodes = np.c_[main_nodes, np.zeros(n_main_nodes)]\n main_nodes[i, k] = j + 0.2\n k = k + 1\n\n if m_elem[2] == i:\n if len(main_nodes[0]) <= k:\n main_nodes = np.c_[main_nodes, np.zeros(n_main_nodes)]\n main_nodes[i, k] = j + 0.1\n k = k + 1\n\n # to finish node_assign with the new numbers of subdividing nodes\n n_sub_nodes = 0 # nr of subdividing nodes\n for n_prop in node_props:\n if n_prop[2] == 0:\n n_prop[1] = n_main_nodes + n_sub_nodes\n n_sub_nodes = n_sub_nodes + 1\n\n return main_nodes, meta_elements, node_props\n\n\ndef mode_nr(n_main_nodes, n_corner_nodes, n_sub_nodes, main_nodes):\n #\n # this routine determines the number of distortional and local buckling modes\n # if GBT-like assumptions are used\n #\n #\n # input/output data\n # n_main_nodes, n_sub_nodes - number of main nodes and sub_nodes, respectively\n # main_nodes [main nodes] - array of\n # [nr, x, z, orig nodes nr, nr of adj meta-elements, m-el_i-1, m-el_i-2, ...]\n # n_dist_modes, n_local_modes - number of distortional and local buckling modes, respectively\n #\n # S. Adany, Feb 09, 2004\n #\n #\n # to count the number of distortional modes\n n_dist_modes = n_main_nodes - 4\n for i in range(0, n_main_nodes):\n if main_nodes[i, 4] > 2:\n n_dist_modes = n_dist_modes - (main_nodes[i, 4] - 2)\n\n if n_dist_modes < 0:\n n_dist_modes = 0\n\n # to count the number of local modes\n n_edge_nodes = n_main_nodes - n_corner_nodes # nr of edge nodes\n n_local_modes = n_main_nodes + 2*n_sub_nodes + n_edge_nodes\n\n return n_dist_modes, n_local_modes\n\n\ndef dof_ordering(node_props):\n # this routine re-orders the DOFs,\n # according to the need of forming shape vectors for various buckling modes\n #\n # input/output data\n # node_props - array of [original nodes nr, new nodes nr, nr of adj elements, nodes type]\n # dof_perm - permutation matrix, so that\n # (orig-displacements-vect) = (dof_perm) � (new-displacements-vector)\n #\n # notes:\n # (1) nodes types: 1-corner, 2-edge, 3-sub\n # (2) the re-numbering of long. displacements. DOFs of main nodes, which may be\n # necessary for dist. buckling, is not included here but handled\n # separately when forming Ry constraint matrix\n #\n # S. Adany, Feb 06, 2004\n #\n #\n # to count corner-, edge- and sub-nodes\n n_node_props = len(node_props)\n n_corner_nodes = 0\n n_edge_nodes = 0\n n_sub_nodes = 0\n for n_prop in node_props:\n if n_prop[3] == 1:\n n_corner_nodes = n_corner_nodes + 1\n if n_prop[3] == 2:\n n_edge_nodes = n_edge_nodes + 1\n if n_prop[3] == 3:\n n_sub_nodes = n_sub_nodes + 1\n\n n_main_nodes = n_corner_nodes + n_edge_nodes # nr of main nodes\n\n # to form permutation matrix\n dof_perm = np.zeros((4*n_node_props, 4*n_node_props))\n\n # x DOFs\n i_c = 0\n i_e = 0\n i_s = 0\n for i, n_prop in enumerate(node_props):\n if n_prop[3] == 1: # corner nodes\n dof_perm[2*i, n_main_nodes + i_c] = 1\n i_c = i_c + 1\n if n_prop[3] == 2: # edge nodes\n dof_perm[2*i, n_main_nodes + 2*n_corner_nodes + i_e] = 1\n i_e = i_e + 1\n if n_prop[3] == 3: # sub nodes\n dof_perm[2*i, 4*n_main_nodes + i_s] = 1\n i_s = i_s + 1\n\n # y DOFs\n i_c = 0\n i_s = 0\n for i, n_prop in enumerate(node_props):\n if n_prop[3] == 1 or n_prop[3] == 2: # corner or edge nodes\n dof_perm[2*i + 1, i_c] = 1\n i_c = i_c + 1\n if n_prop[3] == 3: # sub nodes\n dof_perm[2*i + 1, 4*n_main_nodes + 3*n_sub_nodes + i_s] = 1\n i_s = i_s + 1\n\n # z DOFs\n i_c = 0\n i_e = 0\n i_s = 0\n for i, n_prop in enumerate(node_props):\n if n_prop[3] == 1: # corner nodes\n dof_perm[2*n_node_props + 2*i, n_main_nodes + n_corner_nodes + i_c] = 1\n i_c = i_c + 1\n if n_prop[3] == 2: # edge nodes\n dof_perm[2*n_node_props + 2*i, n_main_nodes + 2*n_corner_nodes + n_edge_nodes + i_e] = 1\n i_e = i_e + 1\n if n_prop[3] == 3: # sub nodes\n dof_perm[2*n_node_props + 2*i, 4*n_main_nodes + n_sub_nodes + i_s] = 1\n i_s = i_s + 1\n\n # teta DOFs\n i_c = 0\n i_s = 0\n for i, n_prop in enumerate(node_props):\n if n_prop[3] == 1 or n_prop[3] == 2: # corner or edge nodes\n dof_perm[2*n_node_props + 2*i + 1, 3*n_main_nodes + i_c] = 1\n i_c = i_c + 1\n if n_prop[3] == 3: # sub nodes\n dof_perm[2*n_node_props + 2*i + 1, 4*n_main_nodes + 2*n_sub_nodes + i_s] = 1\n i_s = i_s + 1\n\n return dof_perm\n\n\ndef create_k_globals(m_i, nodes, elements, el_props, props, length, b_c):\n # called from base_update, while only single longitudinal term m_i involved\n #\n # created on Aug 28, 2006, by S. Adany\n # modified on Jul 10, 2009 by Z. Li\n\n # MATRIX SIZES\n n_nodes = len(nodes)\n\n # ZERO OUT THE GLOBAL MATRICES\n k_global = np.zeros((n_nodes*4, n_nodes*4))\n kg_global = np.zeros((n_nodes*4, n_nodes*4))\n\n # ASSEMBLE THE GLOBAL STIFFNESS MATRICES\n for i, elem in enumerate(elements):\n thick = elem[3]\n b_strip = el_props[i, 1]\n mat_num = int(elem[4])\n row = int((np.argwhere(props[:, 0] == mat_num)).reshape(1))\n mat = props[row]\n stiff_x = mat[1]\n stiff_y = mat[2]\n nu_x = mat[3]\n nu_y = mat[4]\n bulk = mat[5]\n k_l = klocal_m(\n stiff_x=stiff_x,\n stiff_y=stiff_y,\n nu_x=nu_x,\n nu_y=nu_y,\n bulk=bulk,\n thick=thick,\n length=length,\n b_strip=b_strip,\n b_c=b_c,\n m_i=m_i\n )\n # Generate geometric stiffness matrix (kg_local) in local coordinates\n node_i = int(elem[1])\n node_j = int(elem[2])\n ty_1 = nodes[node_i, 7]*thick\n ty_2 = nodes[node_j, 7]*thick\n kg_l = kglocal_m(length=length, b_strip=b_strip, ty_1=ty_1, ty_2=ty_2, b_c=b_c, m_i=m_i)\n # Transform k_local and kg_local into global coordinates\n alpha = el_props[i, 2]\n [k_local, kg_local] = trans_m(alpha, k_l, kg_l)\n\n # Add element contribution of k_local to full matrix k_global and kg_local to kg_global\n [k_global, kg_global] = assemble_m(\n k_global=k_global,\n kg_global=kg_global,\n k_local=k_local,\n kg_local=kg_local,\n node_i=node_i,\n node_j=node_j,\n n_nodes=n_nodes\n )\n\n return k_global, kg_global\n\n\ndef klocal_m(stiff_x, stiff_y, nu_x, nu_y, bulk, thick, length, b_strip, m_i, b_c):\n # assemble local elastic stiffness matrix for a single longitudinal term m_i\n #\n # created on Jul 10, 2009 by Z. Li\n\n # Generate element stiffness matrix (k_local) in local coordinates\n e_1 = stiff_x/(1 - nu_x*nu_y)\n e_2 = stiff_y/(1 - nu_x*nu_y)\n d_x = stiff_x*thick**3/(12*(1 - nu_x*nu_y))\n d_y = stiff_y*thick**3/(12*(1 - nu_x*nu_y))\n d_1 = nu_x*stiff_y*thick**3/(12*(1 - nu_x*nu_y))\n d_xy = bulk*thick**3/12\n #\n # k_local = sparse(np.zeros(8*m_i, 8*m_i))\n z_0 = np.zeros((4, 4))\n i = m_i\n j = m_i\n km_mp = np.zeros((4, 4))\n kf_mp = np.zeros((4, 4))\n u_m = i*np.pi\n u_p = j*np.pi\n c_1 = u_m/length\n c_2 = u_p/length\n #\n [i_1, i_2, i_3, i_4, i_5] = pycufsm.analysis.bc_i1_5(b_c, i, j, length)\n #\n # assemble the matrix of Km_mp\n km_mp[0, 0] = e_1*i_1/b_strip + bulk*b_strip*i_5/3\n km_mp[0, 1] = e_2*nu_x*(-1/2/c_2)*i_3 - bulk*i_5/2/c_2\n km_mp[0, 2] = -e_1*i_1/b_strip + bulk*b_strip*i_5/6\n km_mp[0, 3] = e_2*nu_x*(-1/2/c_2)*i_3 + bulk*i_5/2/c_2\n\n km_mp[1, 0] = e_2*nu_x*(-1/2/c_1)*i_2 - bulk*i_5/2/c_1\n km_mp[1, 1] = e_2*b_strip*i_4/3/c_1/c_2 + bulk*i_5/b_strip/c_1/c_2\n km_mp[1, 2] = e_2*nu_x*(1/2/c_1)*i_2 - bulk*i_5/2/c_1\n km_mp[1, 3] = e_2*b_strip*i_4/6/c_1/c_2 - bulk*i_5/b_strip/c_1/c_2\n\n km_mp[2, 0] = -e_1*i_1/b_strip + bulk*b_strip*i_5/6\n km_mp[2, 1] = e_2*nu_x*(1/2/c_2)*i_3 - bulk*i_5/2/c_2\n km_mp[2, 2] = e_1*i_1/b_strip + bulk*b_strip*i_5/3\n km_mp[2, 3] = e_2*nu_x*(1/2/c_2)*i_3 + bulk*i_5/2/c_2\n\n km_mp[3, 0] = e_2*nu_x*(-1/2/c_1)*i_2 + bulk*i_5/2/c_1\n km_mp[3, 1] = e_2*b_strip*i_4/6/c_1/c_2 - bulk*i_5/b_strip/c_1/c_2\n km_mp[3, 2] = e_2*nu_x*(1/2/c_1)*i_2 + bulk*i_5/2/c_1\n km_mp[3, 3] = e_2*b_strip*i_4/3/c_1/c_2 + bulk*i_5/b_strip/c_1/c_2\n km_mp = km_mp*thick\n #\n #\n # assemble the matrix of Kf_mp\n kf_mp[0, 0] = (5040*d_x*i_1 - 504*b_strip**2*d_1*i_2 - 504*b_strip**2*d_1*i_3 \\\n + 156*b_strip**4*d_y*i_4 + 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 1] = (2520*b_strip*d_x*i_1 - 462*b_strip**3*d_1*i_2 - 42*b_strip**3*d_1*i_3 \\\n + 22*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 2] = (-5040*d_x*i_1 + 504*b_strip**2*d_1*i_2 + 504*b_strip**2*d_1*i_3 \\\n + 54*b_strip**4*d_y*i_4 - 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 3] = (2520*b_strip*d_x*i_1 - 42*b_strip**3*d_1*i_2 - 42*b_strip**3*d_1*i_3 \\\n - 13*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[1, 0] = (2520*b_strip*d_x*i_1 - 462*b_strip**3*d_1*i_3 - 42*b_strip**3*d_1*i_2 \\\n + 22*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 1] = (1680*b_strip**2*d_x*i_1 - 56*b_strip**4*d_1*i_2 - 56*b_strip**4*d_1*i_3 \\\n + 4*b_strip**6*d_y*i_4 + 224*b_strip**4*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 2] = (-2520*b_strip*d_x*i_1 + 42*b_strip**3*d_1*i_2 + 42*b_strip**3*d_1*i_3 \\\n + 13*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 3] = (840*b_strip**2*d_x*i_1 + 14*b_strip**4*d_1*i_2 + 14*b_strip**4*d_1*i_3 \\\n - 3*b_strip**6*d_y*i_4 - 56*b_strip**4*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[2, 0] = kf_mp[0, 2]\n kf_mp[2, 1] = kf_mp[1, 2]\n kf_mp[2, 2] = (5040*d_x*i_1 - 504*b_strip**2*d_1*i_2 - 504*b_strip**2*d_1*i_3 \\\n + 156*b_strip**4*d_y*i_4 + 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[2, 3] = (-2520*b_strip*d_x*i_1 + 462*b_strip**3*d_1*i_2 + 42*b_strip**3*d_1*i_3 \\\n - 22*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[3, 0] = kf_mp[0, 3]\n kf_mp[3, 1] = kf_mp[1, 3]\n kf_mp[3, 2] = (-2520*b_strip*d_x*i_1 + 462*b_strip**3*d_1*i_3 + 42*b_strip**3*d_1*i_2 \\\n - 22*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3 # not symmetric\n kf_mp[3, 3] = (1680*b_strip**2*d_x*i_1 - 56*b_strip**4*d_1*i_2 - 56*b_strip**4*d_1*i_3 \\\n + 4*b_strip**6*d_y*i_4 + 224*b_strip**4*d_xy*i_5) / 420/b_strip**3\n\n # assemble the membrane and flexural stiffness matrices\n kmp = np.concatenate(\n (np.concatenate((km_mp, z_0), axis=1), np.concatenate((z_0, kf_mp), axis=1))\n )\n # add it into local element stiffness matrix by corresponding to m_i\n k_local = kmp\n\n return k_local\n\n\ndef kglocal_m(length, b_strip, m_i, ty_1, ty_2, b_c):\n # assemble local geometric stiffness matrix for a single longitudinal term m_i\n\n # created on Jul 10, 2009 by Z. Li\n\n # Generate geometric stiffness matrix (kg_local) in local coordinates\n # kg_local = sparse(np.zeros(8*m_i, 8*m_i))\n i = m_i\n j = m_i\n gm_mp = np.zeros((4, 4))\n z_0 = np.zeros((4, 4))\n gf_mp = np.zeros((4, 4))\n u_m = i*np.pi\n u_p = j*np.pi\n #\n [_, _, _, i_4, i_5] = pycufsm.analysis.bc_i1_5(b_c, i, j, length)\n #\n # assemble the matrix of gm_mp (symmetric membrane stability matrix)\n gm_mp[0, 0] = b_strip*(3*ty_1 + ty_2)*i_5/12\n gm_mp[0, 2] = b_strip*(ty_1 + ty_2)*i_5/12\n gm_mp[2, 0] = gm_mp[0, 2]\n gm_mp[1, 1] = b_strip*length**2*(3*ty_1 + ty_2)*i_4/12/u_m/u_p\n gm_mp[1, 3] = b_strip*length**2*(ty_1 + ty_2)*i_4/12/u_m/u_p\n gm_mp[3, 1] = gm_mp[1, 3]\n gm_mp[2, 2] = b_strip*(ty_1 + 3*ty_2)*i_5/12\n gm_mp[3, 3] = b_strip*length**2*(ty_1 + 3*ty_2)*i_4/12/u_m/u_p\n #\n # assemble the matrix of gf_mp (symmetric flexural stability matrix)\n gf_mp[0, 0] = (10*ty_1 + 3*ty_2)*b_strip*i_5/35\n gf_mp[0, 1] = (15*ty_1 + 7*ty_2)*b_strip**2*i_5/210/2\n gf_mp[1, 0] = gf_mp[0, 1]\n gf_mp[0, 2] = 9*(ty_1 + ty_2)*b_strip*i_5/140\n gf_mp[2, 0] = gf_mp[0, 2]\n gf_mp[0, 3] = -(7*ty_1 + 6*ty_2)*b_strip**2*i_5/420\n gf_mp[3, 0] = gf_mp[0, 3]\n gf_mp[1, 1] = (5*ty_1 + 3*ty_2)*b_strip**3*i_5/2/420\n gf_mp[1, 2] = (6*ty_1 + 7*ty_2)*b_strip**2*i_5/420\n gf_mp[2, 1] = gf_mp[1, 2]\n gf_mp[1, 3] = -(ty_1 + ty_2)*b_strip**3*i_5/140/2\n gf_mp[3, 1] = gf_mp[1, 3]\n gf_mp[2, 2] = (3*ty_1 + 10*ty_2)*b_strip*i_5/35\n gf_mp[2, 3] = -(7*ty_1 + 15*ty_2)*b_strip**2*i_5/420\n gf_mp[3, 2] = gf_mp[2, 3]\n gf_mp[3, 3] = (3*ty_1 + 5*ty_2)*b_strip**3*i_5/420/2\n # assemble the membrane and flexural stiffness matrices\n kg_mp = np.concatenate(\n (np.concatenate((gm_mp, z_0), axis=1), np.concatenate((z_0, gf_mp), axis=1))\n )\n # add it into local geometric stiffness matrix by corresponding to m_i\n kg_local = kg_mp\n return kg_local\n\n\ndef trans_m(alpha, k_local, kg_local):\n # transfer the local stiffness into global stiffness\n\n # created on Jul 10, 2009 by Z. Li\n gamma = np.array([[np.cos(alpha), 0, 0, 0, -np.sin(alpha), 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, np.cos(alpha), 0, 0, 0, -np.sin(alpha), 0], [0, 0, 0, 1, 0, 0, 0, 0],\n [np.sin(alpha), 0, 0, 0, np.cos(alpha), 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, np.sin(alpha), 0, 0, 0, np.cos(alpha), 0], [0, 0, 0, 0, 0, 0, 0, 1]])\n # extend to multi-m\n # for i = 1:m_i\n # gamma(8*(i-1)+1:8*i, 8*(i-1)+1:8*i) = gam\n # end\n #\n k_global = gamma @ k_local @ gamma.conj().T\n kg_global = gamma @ kg_local @ gamma.conj().T\n\n return k_global, kg_global\n\n\ndef assemble_m(k_global, kg_global, k_local, kg_local, node_i, node_j, n_nodes):\n # BWS\n # 1997\n # Add the element contribution to the global stiffness matrix for single\n # longitudinal term m_i\n\n # modifed on Jul 10, 2009 by Z. Li\n\n # Submatrices for the initial stiffness\n k11 = k_local[0:2, 0:2]\n k12 = k_local[0:2, 2:4]\n k13 = k_local[0:2, 4:6]\n k14 = k_local[0:2, 6:8]\n k21 = k_local[2:4, 0:2]\n k22 = k_local[2:4, 2:4]\n k23 = k_local[2:4, 4:6]\n k24 = k_local[2:4, 6:8]\n k31 = k_local[4:6, 0:2]\n k32 = k_local[4:6, 2:4]\n k33 = k_local[4:6, 4:6]\n k34 = k_local[4:6, 6:8]\n k41 = k_local[6:8, 0:2]\n k42 = k_local[6:8, 2:4]\n k43 = k_local[6:8, 4:6]\n k44 = k_local[6:8, 6:8]\n #\n # Submatrices for the geometric stiffness\n kg11 = kg_local[0:2, 0:2]\n kg12 = kg_local[0:2, 2:4]\n kg13 = kg_local[0:2, 4:6]\n kg14 = kg_local[0:2, 6:8]\n kg21 = kg_local[2:4, 0:2]\n kg22 = kg_local[2:4, 2:4]\n kg23 = kg_local[2:4, 4:6]\n kg24 = kg_local[2:4, 6:8]\n kg31 = kg_local[4:6, 0:2]\n kg32 = kg_local[4:6, 2:4]\n kg33 = kg_local[4:6, 4:6]\n kg34 = kg_local[4:6, 6:8]\n kg41 = kg_local[6:8, 0:2]\n kg42 = kg_local[6:8, 2:4]\n kg43 = kg_local[6:8, 4:6]\n kg44 = kg_local[6:8, 6:8]\n #\n k_2_matrix = np.zeros((4*n_nodes, 4*n_nodes))\n k_3_matrix = np.zeros((4*n_nodes, 4*n_nodes))\n #\n # The additional terms for k_global are stored in k_2_matrix\n skip = 2*n_nodes\n k_2_matrix[node_i*2:node_i*2 + 2, node_i*2:node_i*2 + 2] = k11\n k_2_matrix[node_i*2:node_i*2 + 2, node_j*2:node_j*2 + 2] = k12\n k_2_matrix[node_j*2:node_j*2 + 2, node_i*2:node_i*2 + 2] = k21\n k_2_matrix[node_j*2:node_j*2 + 2, node_j*2:node_j*2 + 2] = k22\n #\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k33\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k34\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k43\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k44\n #\n k_2_matrix[node_i*2:node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k13\n k_2_matrix[node_i*2:node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k14\n k_2_matrix[node_j*2:node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k23\n k_2_matrix[node_j*2:node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k24\n #\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, node_i*2:node_i*2 + 2] = k31\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, node_j*2:node_j*2 + 2] = k32\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, node_i*2:node_i*2 + 2] = k41\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, node_j*2:node_j*2 + 2] = k42\n k_global = k_global + k_2_matrix\n #\n # The additional terms for kg_global are stored in k_3_matrix\n k_3_matrix[node_i*2:node_i*2 + 2, node_i*2:node_i*2 + 2] = kg11\n k_3_matrix[node_i*2:node_i*2 + 2, node_j*2:node_j*2 + 2] = kg12\n k_3_matrix[node_j*2:node_j*2 + 2, node_i*2:node_i*2 + 2] = kg21\n k_3_matrix[node_j*2:node_j*2 + 2, node_j*2:node_j*2 + 2] = kg22\n #\n k_3_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = kg33\n k_3_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = kg34\n k_3_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = kg43\n k_3_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = kg44\n #\n k_3_matrix[node_i*2:node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = kg13\n k_3_matrix[node_i*2:node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = kg14\n k_3_matrix[node_j*2:node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = kg23\n k_3_matrix[node_j*2:node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = kg24\n #\n k_3_matrix[skip + node_i*2:skip + node_i*2 + 2, node_i*2:node_i*2 + 2] = kg31\n k_3_matrix[skip + node_i*2:skip + node_i*2 + 2, node_j*2:node_j*2 + 2] = kg32\n k_3_matrix[skip + node_j*2:skip + node_j*2 + 2, node_i*2:node_i*2 + 2] = kg41\n k_3_matrix[skip + node_j*2:skip + node_j*2 + 2, node_j*2:node_j*2 + 2] = kg42\n #\n kg_global = kg_global + k_3_matrix\n return k_global, kg_global\n\n\ndef kglobal_transv(nodes, elements, props, m_i, length, b_c, el_props):\n #\n # this routine creates the global stiffness matrix for planar displacements\n # basically the same way as in the main program, however:\n # only one half-wave number m_i is considered,\n # only w, teta terms are considered,\n # plus stiff_y = nu_x = nu_y = 0 is assumed\n # plus the longitudinal displacements. DOFs are explicitely eliminated\n # the multiplication by 'length' (member length) is not done here, must be done\n # outside of this routine\n #\n # input/output data\n # nodes, elements, props - same as elsewhere throughout this program\n # m_i - number of half waves\n # k_global_transv - global stiffness matrix (geometric not included)\n #\n # S. Adany, Feb 08, 2004\n # Z. Li, Jul 10, 2009\n #\n n_nodes = len(nodes)\n k_global_transv = np.zeros((4*n_nodes, 4*n_nodes))\n #\n for i, elem in enumerate(elements):\n thick = elem[3]\n b_strip = el_props[i, 1]\n mat_num = int(elem[4])\n row = int((np.argwhere(props[:, 0] == mat_num)).reshape(1))\n mat = props[row]\n stiff_x = mat[1]\n stiff_y = mat[2]\n nu_x = mat[3]\n nu_y = mat[4]\n bulk = mat[5]\n k_l = klocal_transv(\n stiff_x=stiff_x,\n stiff_y=stiff_y,\n nu_x=nu_x,\n nu_y=nu_y,\n bulk=bulk,\n thick=thick,\n length=length,\n b_strip=b_strip,\n b_c=b_c,\n m_i=m_i\n )\n\n # Transform k_local and kg_local into global coordinates\n alpha = el_props[i, 2]\n k_local = trans_single(alpha, k_l)\n\n # Add element contribution of k_local to full matrix k_global and kg_local to kg_global\n node_i = int(elem[1])\n node_j = int(elem[2])\n k_global_transv = assemble_single(\n k_global=k_global_transv,\n k_local=k_local,\n node_i=node_i,\n node_j=node_j,\n n_nodes=n_nodes\n )\n\n return k_global_transv\n\n\ndef klocal_transv(stiff_x, stiff_y, nu_x, nu_y, bulk, thick, length, b_strip, m_i, b_c):\n #\n # this routine creates the local stiffness matrix for bending terms\n # basically the same way as in the main program, however:\n # only for single half-wave number m_i\n # membrane strains practically zero, (membrane moduli are enlarged)\n # for bending, only transverse terms are considered, (practically: only\n # keeps the i_1 term, set i_2 through i_5 to be zero)\n # also different from the main program, here only involves one single\n # longitudinal term m_i.\n #\n # input/output data\n # nodes, elements, props - same as elsewhere throughout this program\n # k_global_transv - global stiffness matrix (geometric included)\n #\n # Z. Li, Jul 10, 2009\n\n e_1 = stiff_x/(1 - nu_x*nu_y)*100000000\n e_2 = stiff_y/(1 - nu_x*nu_y)\n d_x = stiff_x*thick**3/(12*(1 - nu_x*nu_y))\n d_y = stiff_y*thick**3/(12*(1 - nu_x*nu_y))\n d_1 = nu_x*stiff_y*thick**3/(12*(1 - nu_x*nu_y))\n d_xy = bulk*thick**3/12\n\n z_0 = np.zeros((4, 4))\n i = m_i\n j = m_i\n km_mp = np.zeros((4, 4))\n kf_mp = np.zeros((4, 4))\n u_m = i*np.pi\n u_p = j*np.pi\n c_1 = u_m/length\n c_2 = u_p/length\n\n [i_1, _, _, _, _] = pycufsm.analysis.bc_i1_5(b_c, i, j, length)\n i_2 = 0\n i_3 = 0\n i_4 = 0\n i_5 = 0\n\n # assemble in-plane stiffness matrix of Km_mp\n km_mp[0, 0] = e_1*i_1/b_strip + bulk*b_strip*i_5/3\n km_mp[0, 1] = e_2*nu_x*(-1/2/c_2)*i_3 - bulk*i_5/2/c_2\n km_mp[0, 2] = -e_1*i_1/b_strip + bulk*b_strip*i_5/6\n km_mp[0, 3] = e_2*nu_x*(-1/2/c_2)*i_3 + bulk*i_5/2/c_2\n\n km_mp[1, 0] = e_2*nu_x*(-1/2/c_1)*i_2 - bulk*i_5/2/c_1\n km_mp[1, 1] = e_2*b_strip*i_4/3/c_1/c_2 + bulk*i_5/b_strip/c_1/c_2\n km_mp[1, 2] = e_2*nu_x*(1/2/c_1)*i_2 - bulk*i_5/2/c_1\n km_mp[1, 3] = e_2*b_strip*i_4/6/c_1/c_2 - bulk*i_5/b_strip/c_1/c_2\n\n km_mp[2, 0] = -e_1*i_1/b_strip + bulk*b_strip*i_5/6\n km_mp[2, 1] = e_2*nu_x*(1/2/c_2)*i_3 - bulk*i_5/2/c_2\n km_mp[2, 2] = e_1*i_1/b_strip + bulk*b_strip*i_5/3\n km_mp[2, 3] = e_2*nu_x*(1/2/c_2)*i_3 + bulk*i_5/2/c_2\n\n km_mp[3, 0] = e_2*nu_x*(-1/2/c_1)*i_2 + bulk*i_5/2/c_1\n km_mp[3, 1] = e_2*b_strip*i_4/6/c_1/c_2 - bulk*i_5/b_strip/c_1/c_2\n km_mp[3, 2] = e_2*nu_x*(1/2/c_1)*i_2 + bulk*i_5/2/c_1\n km_mp[3, 3] = e_2*b_strip*i_4/3/c_1/c_2 + bulk*i_5/b_strip/c_1/c_2\n km_mp = km_mp*thick\n\n # assemble the bending stiffness matrix of Kf_mp\n kf_mp[0, 0] = (5040*d_x*i_1 - 504*b_strip**2*d_1*i_2 - 504*b_strip**2*d_1*i_3 \\\n + 156*b_strip**4*d_y*i_4 + 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 1] = (2520*b_strip*d_x*i_1 - 462*b_strip**3*d_1*i_2 - 42*b_strip**3*d_1*i_3 \\\n + 22*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 2] = (-5040*d_x*i_1 + 504*b_strip**2*d_1*i_2 + 504*b_strip**2*d_1*i_3 \\\n + 54*b_strip**4*d_y*i_4 - 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[0, 3] = (2520*b_strip*d_x*i_1 - 42*b_strip**3*d_1*i_2 - 42*b_strip**3*d_1*i_3 \\\n - 13*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[1, 0] = (2520*b_strip*d_x*i_1 - 462*b_strip**3*d_1*i_3 - 42*b_strip**3*d_1*i_2 \\\n + 22*b_strip**5*d_y*i_4 + 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 1] = (1680*b_strip**2*d_x*i_1 - 56*b_strip**4*d_1*i_2 - 56*b_strip**4*d_1*i_3 \\\n + 4*b_strip**6*d_y*i_4 + 224*b_strip**4*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 2] = (-2520*b_strip*d_x*i_1 + 42*b_strip**3*d_1*i_2 + 42*b_strip**3*d_1*i_3 \\\n + 13*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n kf_mp[1, 3] = (840*b_strip**2*d_x*i_1 + 14*b_strip**4*d_1*i_2 + 14*b_strip**4*d_1*i_3 \\\n - 3*b_strip**6*d_y*i_4 - 56*b_strip**4*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[2, 0] = kf_mp[0, 2]\n kf_mp[2, 1] = kf_mp[1, 2]\n kf_mp[2, 2] = (5040*d_x*i_1 - 504*b_strip**2*d_1*i_2 - 504*b_strip**2*d_1*i_3 \\\n + 156*b_strip**4*d_y*i_4 + 2016*b_strip**2*d_xy*i_5) / 420/b_strip**3\n kf_mp[2, 3] = (-2520*b_strip*d_x*i_1 + 462*b_strip**3*d_1*i_2 + 42*b_strip**3*d_1*i_3 \\\n - 22*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3\n\n kf_mp[3, 0] = kf_mp[0, 3]\n kf_mp[3, 1] = kf_mp[1, 3]\n kf_mp[3, 2] = (-2520*b_strip*d_x*i_1 + 462*b_strip**3*d_1*i_3 + 42*b_strip**3*d_1*i_2 \\\n - 22*b_strip**5*d_y*i_4 - 168*b_strip**3*d_xy*i_5) / 420/b_strip**3 # not symmetric\n kf_mp[3, 3] = (1680*b_strip**2*d_x*i_1 - 56*b_strip**4*d_1*i_2 - 56*b_strip**4*d_1*i_3 \\\n + 4*b_strip**6*d_y*i_4 + 224*b_strip**4*d_xy*i_5) / 420/b_strip**3\n\n # assemble the membrane and flexural stiffness matrices\n kmp = np.concatenate(\n (np.concatenate((km_mp, z_0), axis=1), np.concatenate((z_0, kf_mp), axis=1))\n )\n\n # local stiffness matrix:\n k_local = kmp\n return k_local\n\n\ndef assemble_single(k_global, k_local, node_i, node_j, n_nodes):\n #\n # this routine adds the element contribution to the global stiffness matrix\n # basically it does the same as routine 'assemble', however:\n # it does not care about kg_global (geom stiff matrix)\n # only involves single half-wave number m_i\n\n # S. Adany, Feb 06, 2004\n # Z. Li, Jul 10, 2009\n #\n # submatrices for the initial stiffness\n k11 = k_local[0:2, 0:2]\n k12 = k_local[0:2, 2:4]\n k13 = k_local[0:2, 4:6]\n k14 = k_local[0:2, 6:8]\n k21 = k_local[2:4, 0:2]\n k22 = k_local[2:4, 2:4]\n k23 = k_local[2:4, 4:6]\n k24 = k_local[2:4, 6:8]\n k31 = k_local[4:6, 0:2]\n k32 = k_local[4:6, 2:4]\n k33 = k_local[4:6, 4:6]\n k34 = k_local[4:6, 6:8]\n k41 = k_local[6:8, 0:2]\n k42 = k_local[6:8, 2:4]\n k43 = k_local[6:8, 4:6]\n k44 = k_local[6:8, 6:8]\n\n k_2_matrix = np.zeros((4*n_nodes, 4*n_nodes))\n\n # the additional terms for k_global are stored in k_2_matrix\n skip = 2*n_nodes\n k_2_matrix[node_i*2:node_i*2 + 2, node_i*2:node_i*2 + 2] = k11\n k_2_matrix[node_i*2:node_i*2 + 2, node_j*2:node_j*2 + 2] = k12\n k_2_matrix[node_j*2:node_j*2 + 2, node_i*2:node_i*2 + 2] = k21\n k_2_matrix[node_j*2:node_j*2 + 2, node_j*2:node_j*2 + 2] = k22\n\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k33\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k34\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k43\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k44\n\n k_2_matrix[node_i*2:node_i*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k13\n k_2_matrix[node_i*2:node_i*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k14\n k_2_matrix[node_j*2:node_j*2 + 2, skip + node_i*2:skip + node_i*2 + 2] = k23\n k_2_matrix[node_j*2:node_j*2 + 2, skip + node_j*2:skip + node_j*2 + 2] = k24\n\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, node_i*2:node_i*2 + 2] = k31\n k_2_matrix[skip + node_i*2:skip + node_i*2 + 2, node_j*2:node_j*2 + 2] = k32\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, node_i*2:node_i*2 + 2] = k41\n k_2_matrix[skip + node_j*2:skip + node_j*2 + 2, node_j*2:node_j*2 + 2] = k42\n k_global = k_global + k_2_matrix\n\n return k_global\n\n\ndef classify(props, nodes, elements, lengths, shapes, gbt_con, b_c, m_all, sect_props):\n # , clas_GDLO\n # MODAL CLASSIFICATION\n\n # input\n # props: [mat_num stiff_x stiff_y nu_x nu_y bulk] 6 x nmats\n # nodes: [nodes# x z dof_x dof_z dof_y dofrot stress] n_nodes x 8\n # elements: [elements# node_i node_j thick mat_num] n_elements x 5\n # lengths: lengths to be analyzed\n # shapes: array of mode shapes dof x lengths x mode\n # method:\n # method = 1 = vector norm\n # method = 2 = strain energy norm\n # method = 3 = work norm\n #\n #\n # output\n # clas: array or # classification\n\n # BWS August 29, 2006\n # modified SA, Oct 10, 2006\n # Z.Li, June 2010\n n_nodes = len(nodes)\n n_dof_m = 4*n_nodes\n\n # CLEAN UP INPUT\n # clean u_p 0's, multiple terms. or out-of-order terms in m_all\n m_all = pycufsm.analysis.m_sort(m_all)\n\n # FIND BASE PROPERTIES\n el_props = pycufsm.analysis.elem_prop(nodes=nodes, elements=elements)\n # set u_p stress to 1.0 for finding kg_global and k_global for axial modes\n nodes_base = deepcopy(nodes)\n nodes_base[:, 7] = np.ones_like(nodes[:, 7])\n\n # natural base first\n # properties all the longitudinal terms share\n [main_nodes, meta_elements, node_props, n_main_nodes, \\\n n_corner_nodes, n_sub_nodes, n_dist_modes, n_local_modes, dof_perm] \\\n = base_properties(nodes=nodes_base, elements=elements)\n [r_x, r_z, r_yd, r_ys, r_ud] = mode_constr(\n nodes=nodes_base,\n elements=elements,\n node_props=node_props,\n main_nodes=main_nodes,\n meta_elements=meta_elements\n )\n [d_y, n_global_modes] = y_dofs(\n nodes=nodes_base,\n elements=elements,\n main_nodes=main_nodes,\n n_main_nodes=n_main_nodes,\n n_dist_modes=n_dist_modes,\n r_yd=r_yd,\n r_ud=r_ud,\n sect_props=sect_props,\n el_props=el_props\n )\n\n # loop for the lengths\n n_lengths = len(lengths)\n l_i = 0 # length_index = one\n clas = []\n while l_i < n_lengths:\n length = lengths(l_i)\n # longitudinal terms included in the analysis for this length\n m_a = m_all[l_i]\n b_v_l = base_column(\n nodes_base=nodes_base,\n elements=elements,\n props=props,\n length=length,\n b_c=b_c,\n m_a=m_a,\n el_props=el_props,\n node_props=node_props,\n n_main_nodes=n_main_nodes,\n n_corner_nodes=n_corner_nodes,\n n_sub_nodes=n_sub_nodes,\n n_global_modes=n_global_modes,\n n_dist_modes=n_dist_modes,\n n_local_modes=n_local_modes,\n dof_perm=dof_perm,\n r_x=r_x,\n r_z=r_z,\n r_ys=r_ys,\n d_y=d_y\n )\n # orthonormal vectors\n b_v = base_update(\n gbt_con=gbt_con,\n b_v_l=b_v_l,\n length=length,\n m_a=m_a,\n nodes=nodes,\n elements=elements,\n props=props,\n n_global_modes=n_global_modes,\n n_dist_modes=n_dist_modes,\n n_local_modes=n_local_modes,\n b_c=b_c,\n el_props=el_props\n )\n\n # classification\n clas_modes = np.zeros((len(shapes([l_i][0])), 4))\n for mod in range(0, len(shapes[l_i][0])):\n clas_modes[mod, 0:4] = mode_class(\n b_v=b_v,\n displacements=shapes[l_i][:, mod],\n n_global_modes=n_global_modes,\n n_dist_modes=n_dist_modes,\n n_local_modes=n_local_modes,\n m_a=m_a,\n n_dof_m=n_dof_m,\n gbt_con=gbt_con\n )\n clas.append(clas_modes)\n l_i = l_i + 1 # length index = length index + one\n\n return clas\n\n\ndef mode_class(\n b_v, displacements, n_global_modes, n_dist_modes, n_local_modes, m_a, n_dof_m, gbt_con\n):\n #\n # to determine mode contribution in the current displacement\n\n # input data\n # b_v - base vectors (each column corresponds to a certain mode)\n # columns 1..n_global_modes: global modes\n # columns (n_global_modes+1)..(n_global_modes+n_dist_modes): dist. modes\n # columns (n_global_modes+n_dist_modes+1)\n # ..(n_global_modes+n_dist_modes+n_local_modes): local modes\n # columns (n_global_modes+n_dist_modes+n_local_modes+1)..n_dof: other modes\n # displacements - vector of nodal displacements\n # n_global_modes, n_dist_modes, n_local_modes\n # - number of global, distortional and local buckling modes, respectively\n # gbt_con['couple'] - by gbt_con, coupled basis vs uncoupled basis for general B.C.\n # especially for non-simply supported B.C.\n # 1: uncoupled basis, the basis will be block diagonal\n # 2: coupled basis, the basis is fully spanned\n\n # output data\n # clas_gdlo - array with the contributions of the modes in percentage\n # elem1: global, elem2: dist, elem3: local, elem4: other\n\n # S. Adany, Mar 10, 2004\n # Z. Li, June 2010\n\n total_m = len(m_a) # Total number of longitudinal terms m_i\n # indices\n dof_index = np.zeros((4, 2))\n dof_index[0, 0] = 0\n dof_index[0, 1] = n_global_modes\n dof_index[1, 0] = n_global_modes\n dof_index[1, 1] = n_global_modes + n_dist_modes\n dof_index[2, 0] = n_global_modes + n_dist_modes\n dof_index[2, 1] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 0] = n_global_modes + n_dist_modes + n_local_modes\n dof_index[3, 1] = n_dof_m\n\n if gbt_con['couple'] == 1:\n # uncoupled basis\n for i in range(0, len(m_a)):\n b_v_m = b_v[n_dof_m*i:n_dof_m*(i + 1), n_dof_m*i:n_dof_m*(i + 1)]\n\n # classification\n clas = np.linalg.lstsq(\n b_v_m[:, dof_index[0, 0]:dof_index[3, 1]], displacements[n_dof_m*i:n_dof_m*(i + 1)]\n )\n\n cl_gdlo = np.zeros((4, 5*n_modes))\n for j in range(0, 4):\n n_modes = dof_index[j, 1] - dof_index[i, 0]\n cl_gdlo[i, j*n_modes:j*n_modes + n_modes] = clas[dof_index[j, 0]:dof_index[j, 1]]\n\n # # L1 norm\n # for m_n = 1:4\n # clas_gdlo1(m_n) = sum(abs(cl_gdlo(m_n,:)))\n #\n # norm_sum = sum(clas_gdlo1)\n # clas_gdlo1 = clas_gdlo1/norm_sum*100\n\n # L2 norm\n for m_n in range(0, 4):\n clas_gdlo[m_n] = np.linalg.norm(cl_gdlo[m_n, :])\n\n norm_sum = sum(clas_gdlo)\n clas_gdlo = clas_gdlo/norm_sum*100\n else:\n # coupled basis\n # classification\n clas = np.linalg.lstsq(b_v, displacements)\n v_gdlo = np.zeros((4, (total_m + 1)*n_modes))\n for i in range(0, 4):\n for j in range(0, total_m):\n n_modes = dof_index[i, 2] - dof_index[i, 1] + 1\n v_gdlo[i, j*n_modes:j*n_modes+n_modes] \\\n = clas[j*n_dof_m + dof_index[i, 1]:j*n_dof_m + dof_index[i, 2]]\n\n # # L1 norm\n # clas_gdlo1(i) = sum(abs(v_gdlo(i,:)))\n # L2 norm\n clas_gdlo[i] = np.linalg.norm(v_gdlo[i, :])\n\n # # L1 norm\n # NormSum1 = sum(clas_gdlo1)\n # clas_gdlo1 = clas_gdlo1/NormSum1*100\n # L2 norm\n norm_sum = sum(clas_gdlo)\n clas_gdlo = clas_gdlo/norm_sum*100\n\n return clas_gdlo\n\n\ndef trans_single(alpha, k_local):\n #\n # this routine make the local-to-global co-ordinate transformation\n # basically it does the same as routine 'trans', however:\n # it does not care about kg_local (geom stiff matrix)\n # only involve one half-wave number m_i\n\n # S. Adany, Feb 06, 2004\n # Z. Li, Jul 10, 2009\n #\n gamma = np.array([[np.cos(alpha), 0, 0, 0, -np.sin(alpha), 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, np.cos(alpha), 0, 0, 0, -np.sin(alpha), 0], [0, 0, 0, 1, 0, 0, 0, 0],\n [np.sin(alpha), 0, 0, 0, np.cos(alpha), 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, np.sin(alpha), 0, 0, 0, np.cos(alpha), 0], [0, 0, 0, 0, 0, 0, 0, 1]])\n\n k_global = gamma @ k_local @ gamma.conj().T\n\n return k_global\n\n\ndef node_class(node_props):\n #this routine determines how many nodes of the various types exist\n #\n #input/output data\n # node_props - array of [original node nr, new node nr, nr of adj elems, node type]\n # nmno,ncno,nsno - number of main nodes, corner nodes and sub-nodes, respectively\n #\n #notes:\n # node types in node_props: 1-corner, 2-edge, 3-sub\n # sub-node numbers are the original one, of course\n #\n # S. Adany, Feb 09, 2004\n\n #to count corner-, edge- and sub-nodes\n n_corner_nodes = 0\n n_edge_nodes = 0\n n_sub_nodes = 0\n for n_prop in node_props:\n if n_prop[3] == 1:\n n_corner_nodes = n_corner_nodes + 1\n elif n_prop[3] == 2:\n n_edge_nodes = n_edge_nodes + 1\n elif n_prop[3] == 3:\n n_sub_nodes = n_sub_nodes + 1\n\n n_main_nodes = n_corner_nodes + n_edge_nodes #nr of main nodes\n\n return n_main_nodes, n_corner_nodes, n_sub_nodes\n","sub_path":"pycufsm/cfsm.py","file_name":"cfsm.py","file_ext":"py","file_size_in_byte":107704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"69435132","text":"\n\nfrom xai.brain.wordbase.nouns._sanctuary import _SANCTUARY\n\n#calss header\nclass _SANCTUARIES(_SANCTUARY, ):\n\tdef __init__(self,): \n\t\t_SANCTUARY.__init__(self)\n\t\tself.name = \"SANCTUARIES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"sanctuary\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_sanctuaries.py","file_name":"_sanctuaries.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"411276058","text":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras import backend as K\n\n\nclasses = 5\nepochs = 50\nbatch_size = 32\nimg_width, img_height = 200,200\nnb_train_samples = 500 # 5 classes\nnb_validation_samples = 150 # 5 classes\n\nmodel = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 3)))\nmodel.add(Conv2D(32, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu', name='fc1'))\nmodel.add(Dense(64, activation='relu', name='fc2'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(5, activation='softmax'))\nmodel.summary()\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='rmsprop',\n metrics=['accuracy'])\n\n\ntrain_data_dir = './data/train'\nvalidation_data_dir = './data/validation'\n\ntrain_datagen = ImageDataGenerator(\n rescale=2. / 255, #\n shear_range=0.2, #Shear angle in counter-clockwise direction as radians\n zoom_range=0.3, #[lower, upper] = [1-zoom_range, 1+zoom_range]\n rotation_range = 30,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(\n zoom_range=0.3,\n rotation_range = 30,\n rescale=1. / 255)\n\n\ntrain_generator = train_datagen.flow_from_directory(\n\ttrain_data_dir,\n\ttarget_size=(img_width, img_height),\n\tbatch_size=batch_size,\n\t#save_to_dir='./data/new_data/train',\n\tclass_mode='categorical')\n\nvalidation_generator = test_datagen.flow_from_directory(\n\tvalidation_data_dir,\n\ttarget_size=(img_width, img_height),\n\tbatch_size=batch_size ,\n\t#save_to_dir='./data/new_data/test',\n\tclass_mode='categorical')\n\nmodel.fit_generator(\n\ttrain_generator,\n\tsteps_per_epoch= batch_size,\n\tepochs=epochs,\n\tvalidation_data=validation_generator,\n\tvalidation_steps=batch_size) \n\nmodel.save('multi-vgg.h5')\n","sub_path":"multi-vgg.py","file_name":"multi-vgg.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"370318729","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom datetime import datetime\n\nfrom shipane_sdk.market_utils import MarketUtils\n\n\nclass OnlineQuantFollowingJob(object):\n def __init__(self, shipane_client, quant_client, name=None):\n self._log = logging.getLogger()\n self._shipane_client = shipane_client\n self._quant_client = quant_client\n self._name = name\n self._start_datatime = datetime.now()\n self._processed_transactions = []\n\n def __call__(self):\n if MarketUtils.is_closed():\n self._log.warning(\"********** 休市期间不跟单 **********\")\n if self._processed_transactions:\n del self._processed_transactions[:]\n return\n\n if not self._quant_client.is_login():\n self._log.info(\"登录 {}\".format(self._quant_client.name))\n self._quant_client.login()\n\n self._log.info(\"********** 开始跟单 **********\")\n try:\n all_transactions = self._quant_client.query()\n self._log.info(\"获取到 {} 条委托\".format(len(all_transactions)))\n\n transactions = []\n for transaction in all_transactions:\n if self._is_expired(transaction):\n continue\n transactions.append(transaction)\n \n self._log.info(\"获取到 {} 条有效委托\".format(len(transactions)))\n\n for tx in transactions:\n self._processed_transactions.append(tx)\n self._log.info(\"开始以 {}元 {} {}股 {}\".format(tx.price, tx.get_cn_action(), tx.amount, tx.symbol))\n response = self._shipane_client.execute(None,\n action=tx.action,\n symbol=tx.symbol,\n type='LIMIT',\n price=tx.price,\n amount=tx.amount)\n if response is not None:\n self._log.info(u'实盘易回复:\\nstatus_code: %d\\ntext: %s', response.status_code, response.text)\n else:\n self._log.error('实盘易未回复')\n except Exception as e:\n self._log.exception(\"跟单异常\")\n self._log.info(\"********** 结束跟单 **********\\n\")\n\n @property\n def name(self):\n return self._name\n\n def _is_expired(self, transaction):\n if transaction.completed_at < self._start_datatime:\n return True\n if transaction in self._processed_transactions:\n return True\n return False\n","sub_path":"shipane_sdk/jobs/online_quant_following.py","file_name":"online_quant_following.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"172668871","text":"'''\n\nYou are given n pairs of numbers.\nIn every pair, the first number is always smaller than the second number.\n\nNow, we define a pair (c, d) can follow another pair (a, b) if and only if b < c.\nChain of pairs can be formed in this fashion.\n\nGiven a set of pairs, find the length longest chain which can be formed.\nYou needn't use up all the given pairs. You can select pairs in any order.\n\nExample 1:\nInput: [[1,2], [2,3], [3,4]]\nOutput: 2\nExplanation: The longest chain is [1,2] -> [3,4]\nNote:\nThe number of given pairs will be in the range [1, 1000].\n'''\nimport operator\nclass Solution:\n def findLongestChain(self, pairs):\n \"\"\"\n :type pairs: List[List[int]]\n :rtype: int\n \"\"\"\n\n # pairs.sort()\n # dp = [1] * len(pairs)\n #\n # for j in range(len(pairs)):\n # for i in range(j):\n # if pairs[i][1] < pairs[j][0]:\n # dp[j] = max(dp[j], dp[i] + 1)\n #\n # return max(dp)\n\n cur, ans = float('-inf'), 0\n for x, y in sorted(pairs, key=operator.itemgetter(1)):\n if cur < x:\n cur = y\n ans += 1\n return ans\n\ns = Solution()\n\npairs = [[1,2], [2,3], [3,4], [5,18], [7,8], [9, 10]]\n\ns.findLongestChain(pairs)\n\n\n\n'''\nApproach #1: Dynamic Programming [Accepted]\nIntuition\n\nIf a chain of length k ends at some pairs[i], and pairs[i][1] < pairs[j][0], we can extend this chain to a chain of length k+1.\n\nAlgorithm\n\nSort the pairs by first coordinate, and let dp[i] be the length of the longest chain ending at pairs[i]. When i < j and pairs[i][1] < pairs[j][0], we can extend the chain, and so we have the candidate answer dp[j] = max(dp[j], dp[i] + 1).\n\n\nclass Solution(object): #Time Limit Exceeded\n def findLongestChain(self, pairs):\n pairs.sort()\n dp = [1] * len(pairs)\n\n for j in xrange(len(pairs)):\n for i in xrange(j):\n if pairs[i][1] < pairs[j][0]:\n dp[j] = max(dp[j], dp[i] + 1)\n\n return max(dp)\n\n\nComplexity Analysis\n\nTime Complexity: O(N^2)O(N\n2\n ) where NN is the length of pairs. There are two for loops, and N^2N\n2\n dominates the sorting step.\n\nSpace Complexity: O(N)O(N) for sorting and to store dp.\n\nApproach #2: Greedy [Accepted]\nIntuition\n\nWe can greedily add to our chain. Choosing the next addition to be the one with the lowest second coordinate is at least better than a choice with a larger second coordinate.\n\nAlgorithm\n\nConsider the pairs in increasing order of their second coordinate. We'll try to add them to our chain. If we can, by the above argument we know that it is correct to do so.\n\nclass Solution(object):\n def findLongestChain(self, pairs):\n cur, ans = float('-inf'), 0\n for x, y in sorted(pairs, key = operator.itemgetter(1)):\n if cur < x:\n cur = y\n ans += 1\n return ans\n\n\nComplexity Analysis\n\nTime Complexity: O(N \\log N)O(NlogN) where NN is the length of S. The complexity comes from the sorting step, but the rest of the solution does linear work.\n\nSpace Complexity: O(N)O(N). The additional space complexity of storing cur and ans, but sorting uses O(N)O(N) space. Depending on the implementation of the language used, sorting can sometimes use less space.\n\n'''","sub_path":"leetcode/646. Maximum Length of Pair Chain.py","file_name":"646. Maximum Length of Pair Chain.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"42543726","text":"sample_input = \"\"\"5\n-\n-+\n+-\n+++\n--+-\n\"\"\"\n\nsample_output = \"\"\"Case #1: 1\nCase #2: 1\nCase #3: 2\nCase #4: 0\nCase #5: 3\n\"\"\"\n\n\ndef do_one(line):\n def process_one(prev_data, pancake):\n count, prev_pancake = prev_data\n if ((prev_pancake == '' and pancake == '+') or\n pancake == prev_pancake):\n return prev_data\n return (count + 1, pancake)\n\n return reduce(process_one, line[::-1], (0, ''))[0]\n","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_maxpblum_problem2.py","file_name":"16_0_2_maxpblum_problem2.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"445278905","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File: _config.py\n# @Author: eswizardry\n# @Date: 2016-09-21 11:42:39\n# @Last Modified by: Bancha Rajainthong\n# @Last Modified time: 2016-09-25 15:54:52\n\nimport os\n\n# grab the folder where this scripts lives\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nDATABASE = 'flasktaskr.db'\nCSRF_ENABLED = True\nSECRET_KEY = 'my_precious'\n\n# define the full path for the database\nDATABASE_PATH = os.path.join(basedir, DATABASE)\n\n# the database uri\nSQLALCHEMY_DATABASE_URI = 'sqlite:///' + DATABASE_PATH\n","sub_path":"project/_config.py","file_name":"_config.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"30832240","text":"from functools import wraps\nimport json\n\nfrom .elasticsearch5.exceptions import RequestError, NotFoundError\n\n\ndef getkv(d):\n return list(d.items())[0]\n\n\ndef error_handle(func):\n @wraps(func)\n def wrapped(*args, **kwargs):\n try:\n result = func(*args, **kwargs)\n\n if 'deleted' in result and result['total'] == result['deleted']:\n return {'status_code': 200}\n\n if 'acknowledged' in result or '_id' in result:\n return {'status_code': 200}\n\n # bulk\n if isinstance(result, tuple):\n if not result[1]:\n return {'status_code': 200}\n else:\n return {'error_msg': result[1]}\n\n return result\n except (RequestError, NotFoundError) as e:\n error_msg = e.error\n error_code = e.status_code\n\n try:\n # 处理根据id删除文档错误\n error_msg = json.loads(error_msg)\n if not error_msg['found'] and '_id' in error_msg:\n error_msg = 'document_missing_exception'\n except:\n pass\n\n return {'status_code': error_code, 'error_msg': error_msg}\n except:\n raise\n\n return wrapped\n","sub_path":"es_sql5/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"45062739","text":"import sys\nimport sqlalchemy as sql\nimport pandas as pd\n\nfrom schools3.config import base_config\nfrom schools3.config.data import db_config, db_tables\n\n\nconfig = base_config.Config()\n\ndef get_years_for_grade(grade):\n engine = sql.create_engine(db_config.engine_url)\n all_snapshots = db_tables.clean_all_snapshots_table\n\n query = sql.select([\n sql.distinct(all_snapshots.c.school_year)\n ]).where(\n all_snapshots.c.grade == grade\n ).order_by(\n all_snapshots.c.school_year\n )\n\n return pd.read_sql(query, engine).school_year.to_list()\n\n\nconfig.label_windows = {\n 9: 3,\n 10: 2,\n 11: 1\n}\n\nconfig.update_frequency = 1\n\nconfig.years_per_grade = {k: get_years_for_grade(k) for k in range(9, 12)}\n\nsys.modules[__name__] = config\n","sub_path":"schools3/config/data/datasets/datasets_generator_config.py","file_name":"datasets_generator_config.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"114218907","text":"\n\ndef main():\n argument_spec = purefa_argument_spec()\n argument_spec.update(dict(host=dict(type='str', required=True), state=dict(type='str', default='present', choices=['absent', 'present']), protocol=dict(type='str', default='iscsi', choices=['fc', 'iscsi', 'nvme', 'mixed']), nqn=dict(type='list'), iqn=dict(type='list'), wwns=dict(type='list'), volume=dict(type='str'), lun=dict(type='int'), personality=dict(type='str', default='', choices=['hpux', 'vms', 'aix', 'esxi', 'solaris', 'hitachi-vsp', 'oracle-vm-server', 'delete', '']), preferred_array=dict(type='list')))\n module = AnsibleModule(argument_spec, supports_check_mode=True)\n array = get_system(module)\n if ((_is_cbs(module, array) and module.params['wwns']) or module.params['nqn']):\n module.fail_json(msg='Cloud block Store only support iSCSI as a protocol')\n api_version = array._list_available_rest_versions()\n if ((module.params['nqn'] is not None) and (NVME_API_VERSION not in api_version)):\n module.fail_json(msg='NVMe protocol not supported. Please upgrade your array.')\n state = module.params['state']\n host = get_host(module, array)\n if (module.params['lun'] and (not (1 <= module.params['lun'] <= 4095))):\n module.fail_json(msg='LUN ID of {0} is out of range (1 to 4095)'.format(module.params['lun']))\n if module.params['volume']:\n try:\n array.get_volume(module.params['volume'])\n except Exception:\n module.fail_json(msg='Volume {0} not found'.format(module.params['volume']))\n if module.params['preferred_array']:\n try:\n if (module.params['preferred_array'] != ['delete']):\n all_connected_arrays = array.list_array_connections()\n if (not all_connected_arrays):\n module.fail_json(msg='No target arrays connected to source array. Setting preferred arrays not possible.')\n else:\n current_arrays = [array.get()['array_name']]\n for current_array in range(0, len(all_connected_arrays)):\n if (all_connected_arrays[current_array]['type'] == 'sync-replication'):\n current_arrays.append(all_connected_arrays[current_array]['array_name'])\n for array_to_connect in range(0, len(module.params['preferred_array'])):\n if (module.params['preferred_array'][array_to_connect] not in current_arrays):\n module.fail_json(msg='Array {0} is not a synchronously connected array.'.format(module.params['preferred_array'][array_to_connect]))\n except Exception:\n module.fail_json(msg='Failed to get existing array connections.')\n if ((host is None) and (state == 'present')):\n make_host(module, array)\n elif (host and (state == 'present')):\n update_host(module, array)\n elif (host and (state == 'absent')):\n delete_host(module, array)\n elif ((host is None) and (state == 'absent')):\n module.exit_json(changed=False)\n","sub_path":"Data Set/bug-fixing-1/42144204f3ba83c4ce68c049a34fb15554718057--fix.py","file_name":"42144204f3ba83c4ce68c049a34fb15554718057--fix.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"83050145","text":"class Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n if len(text1) == 0 or len(text2) == 0:\n return 0\n lcs = [[-1 for _ in range(len(text2)+1)] for _ in range(len(text1)+1)]\n for i in range(len(text1)+1):\n for j in range(len(text2)+1):\n if i==0 or j==0:\n lcs[i][j] = 0\n elif text1[i-1] == text2[j-1]:\n lcs[i][j] = lcs[i-1][j-1]+1\n else:\n lcs[i][j] = max(lcs[i][j-1], lcs[i-1][j])\n \n\n \n return lcs[len(text1)][len(text2)]\n \n ","sub_path":"leetcode/30-day-challenge/April_2020/26-Longest-Common-Subsequence.py","file_name":"26-Longest-Common-Subsequence.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"544532950","text":"# location/admin.py\nfrom django.contrib import admin\nfrom location.models import Location\n\n\nclass LocationAdmin(admin.ModelAdmin):\n list_display = ('name_location', 'modified_by', 'modified', 'created_by', 'created', 'is_active')\n search_fields = ('name_location',)\n# list_filter = ('modified', 'created')\n# date_hierarchy = 'modified'\n ordering = ['name_location']\n\nadmin.site.register(Location, LocationAdmin)\n\n","sub_path":"location/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"425103203","text":"\n\ndef ecritureFichier(htmlText, fileNameOutput):\n try: \n FileReport = open(fileNameOutput,\"w\")\n FileReport.write(\" \".join(htmlText))\n FileReport.close()\n except IOError:\n print(\"error while writing scan repport\")\n\n\n#creation d un rapport au format html\n\ndef generateReport(result, fileNameOutput):\n head = \" Scan Report Scan Report Total hosts : totalhosts Up hosts : uphosts
\"\n bottom = \"\t \t \t \t \t \"\n templateMachine = \"\t
Nmap scan report for NameMachine (IpMachine) \tHost is MachineState
Mac address : MacAdress
\tPORT STATE SERVICE VERSION
\t\"\n templatePortText = \"PortNumber PortState PortService PortSVersion \"\n \n\n \n \n htmlText = list()\n \n uphosts=0\n totalhosts=0\n \n \n #on regarde dans le dictionnaire result les ips scannees et on complete les templates htmls\n try:\n for host in result:\n\n \n uphosts+=int(result[host]['res']['nmap']['scanstats']['uphosts'] )\n totalhosts+=int(result[host]['res']['nmap']['scanstats']['totalhosts'] ) \n \n for sousHost in result[host][\"res\"][\"scan\"]:\n \n \n temptemplateMachine = templateMachine.replace(\"NameMachine\", result[host][\"res\"][\"scan\"][sousHost][\"hostnames\"][0][\"name\"]+\" \"+result[host][\"res\"][\"scan\"][sousHost][\"hostnames\"][0][\"type\"] )\n temptemplateMachine = temptemplateMachine.replace(\"IpMachine\", sousHost)\n temptemplateMachine = temptemplateMachine.replace(\"MachineState\",result[host][\"res\"][\"scan\"][sousHost][\"status\"][\"state\"] + \" reason : \" + result[host][\"res\"][\"scan\"][sousHost][\"status\"][\"reason\"])\n if \"mac\" in result[host][\"res\"][\"scan\"][sousHost][\"addresses\"] and result[host][\"res\"][\"scan\"][sousHost][\"addresses\"][\"mac\"] != '':\n temptemplateMachine = temptemplateMachine.replace(\"MacAdress\", result[host][\"res\"][\"scan\"][sousHost][\"addresses\"][\"mac\"])\n else:\n temptemplateMachine = temptemplateMachine.replace(\"MacAdress\", \"Not found\")\n try:\n for port in result[host][\"res\"][\"scan\"][sousHost][\"tcp\"]: \n temptemplatePortText = templatePortText.replace(\"PortNumber\",str(port))\n temptemplatePortText=temptemplatePortText.replace(\"PortState\",result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"state\"])\n temptemplatePortText=temptemplatePortText.replace(\"PortService\",result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"name\"] + \" \" +result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"product\"])\n temptemplatePortText=temptemplatePortText.replace(\"PortSVersion\",result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"version\"]+\" \"+result[host][\"res\"][\"scan\"][sousHost][\"tcp\"][port][\"extrainfo\"])\n temptemplateMachine = temptemplateMachine.replace(\"#ici\t\", temptemplatePortText + \"#ici\t\")\n except Exception as ex:\n if 'tcp' not in result[host][\"res\"][\"scan\"][sousHost]:\n temptemplateMachine = temptemplateMachine.replace(\"#ici\t\", \"No open Ports\" ) \n # pas de ports ouverts pour un scan, c est normal \n pass\n temptemplateMachine = temptemplateMachine.replace(\"#ici\t\", \"\") \n htmlText.append(temptemplateMachine)\n \n except Exception as ex:\n print(\"error while reading scan results\") \n print(ex)\n\n htmlText.insert(0,head.replace(\"totalhosts\",str(totalhosts) ).replace(\"uphosts\",str(uphosts) ) )\n htmlText.append(bottom)\n ecritureFichier(htmlText, fileNameOutput)\n \n\n\n\n","sub_path":"report_generator.py","file_name":"report_generator.py","file_ext":"py","file_size_in_byte":4197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"392560304","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n\n def DFS(self, node, pv, d):\n if not node:\n return\n\n if node.val - pv == 1:\n d += 1\n self.longest = max(self.longest, d)\n else:\n d = 1\n\n self.DFS(node.left, node.val, d)\n self.DFS(node.right, node.val, d)\n\n def longestConsecutive(self, root):\n self.longest = 1\n if not root:\n return 0\n self.DFS(root.left, root.val, 1)\n self.DFS(root.right, root.val, 1)\n return self.longest\n\n\ntestClass = Solution()\n\n\nHead = TreeNode(1)\nHead.right = TreeNode(3)\nHead.right.right = TreeNode(4)\nHead.right.right.right = TreeNode(5)\nHead.right.left = TreeNode(2)\n\n\nprint(testClass.longestConsecutive(Head))\n","sub_path":"298-binary-tree-longest-consecutive-sequence/298.py","file_name":"298.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"577492243","text":"#With GUI Support. Input the Image and enter the value to rescale the image.\r\nfrom tkinter import *\r\nfrom tkinter.filedialog import *\r\nfrom tkinter import messagebox\r\nfrom PIL import Image\r\n\r\n#-------------------------------------------------------------------------------------------------\r\nroot = Tk()\r\nroot.title(\"Image Size Reducer\")\r\n\r\n#List to hold the list of Images\r\nimage_list = []\r\nstrScaleValue = StringVar()\r\n#Global variable to hold the output directory\r\nglobal_outputFolder = \"\"\r\n#-------------------------------------------------------------------------------------------------\r\ndef browseImage():\r\n imageFiles = askopenfilenames(filetypes=(('Image File ', '*.JPEG *.JPG *.PNG *.GIF'), ('Other formats', '*.TIFF *.BMP')))\r\n for image in imageFiles:\r\n image_list.append(image)\r\n listbox.insert(END, image.split('/')[-1])\r\n\r\ndef setOutDir():\r\n global global_outputFolder\r\n global_outputFolder = askdirectory()\r\n\r\ndef resizeImage():\r\n try:\r\n if len(image_list) == 0:\r\n messagebox.showerror(\"Error\", \"No Image file found!\")\r\n elif (strScaleValue.get() == \"\" or int(strScaleValue.get()) < 5 or int(strScaleValue.get()) > 100):\r\n messagebox.showerror(\"Error\", \"Enter the Resize value between 5 and 100\")\r\n else:\r\n global global_outputFolder\r\n if global_outputFolder == \"\":\r\n messagebox.showerror(\"Error\", \"Output Folder not Set!\")\r\n else:\r\n fun_Resize()\r\n except:\r\n messagebox.showerror(\"Exception\", \"Error:{0} and {1}\".format(sys.exc_info()[0].__name__, sys.exc_info()[1]))\r\n\r\ndef fun_Resize():\r\n for image in image_list:\r\n outputImagefile = global_outputFolder + '/'+ \"Resize_\" + image.split('/')[-1]\r\n #Image below is imported from PIL library\r\n imagePath = Image.open(image)\r\n imagePath.save(outputImagefile,optimize=True,quality=int(strScaleValue.get()))\r\n imagePath.close()\r\n messagebox.showinfo(\"Files Saved\",\"All the scaled files are saved at : \"+global_outputFolder )\r\n root.quit()\r\n#-------------------------------------------------------------------------------------------------\r\nLabel(root, width= \"20\", text=\"IMAGE SCALER\").grid(row=0, column=1, columnspan=4)\r\nButton(root, width=\"25\", height=\"2\",text=\"Browse and Add Image file\", command = browseImage, bg=\"lightblue\").grid(row=1,column=0,columnspan=2)\r\n\r\nlistbox = Listbox(root, width=\"30\", height=\"20\")\r\nlistbox.bind('<>')\r\nlistbox.grid(row=2, rowspan=4, column=0, columnspan=2)\r\n\r\nButton(root, width=\"20\", height=\"2\",text=\"Set Output Folder\", command = setOutDir).grid(row=1,column=3,columnspan=4)\r\nLabel(root, width=\"40\", wraplength=\"150\",text=\"Enter Value to Resize.\\n (Between 5 & 100).\\n\"\r\n \"5-> Lesser Size/Poor Quality.\\n 100-> Higher size/Good Quality.\").grid(row=2, rowspan=2,column=3, columnspan=4, sticky=\"n,s,e,w\")\r\n\r\nEntry(root, textvariable = strScaleValue, width=\"23\").grid(row=3, column = 3, columnspan=5, sticky=\"s\")\r\n\r\nButton(root, width=\"20\", height=\"2\", text=\"Resize Images\", command= resizeImage, bg=\"lightblue\").grid(row=5, column = 3, columnspan=5)\r\n#-------------------------------------------------------------------------------------------------\r\n\r\nfor child in root.winfo_children():\r\n child.grid_configure(padx=5, pady=5)\r\nmainloop()\r\n","sub_path":"ImageResizer/MultipleImageScaler.py","file_name":"MultipleImageScaler.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"593679310","text":"from array import array\nfrom random import random\n\n# write 10 million numbers to the binary file\nfloats = array('d', (random() for i in range(10 ** 7)))\nfloats[-1] # 0.07802343889111107\nfp = open('floats.bin', 'wb')\nfloats.tofile(fp)\nfp.close()\n\n# read 10 million numbers from the binary file\nfloats2 = array('d')\nfp = open('floats.bin', 'rb')\nfloats2.fromfile(fp, 10 ** 7)\nfp.close()\n\nfloats2[-1] # 0.07802343889111107 # the content is matched\nfloats2 == floats # True\n\n\"\"\"\nAs you can see, array.tofile and array.fromfile are easy to use.\nIf you try the example, you’ll notice they are also very fast. A quick experiment show that it takes about 0.1s for array.fromfile to load 10 million double-precision floats from a binary file created with array.tofile. That is nearly 60 times faster than reading the numbers from a text file, which also involves parsing each line with the float built-in.\nSaving with array.tofile is about 7 times faster than writing one float per line in a text file.\nIn addition, the size of the binary file with 10 million doubles is 80,000,000 bytes (8 bytes per double, zero overhead), while the text file has 181,515,739 bytes, for the same data.\n\"\"\"\n","sub_path":"src/library_ref/data_type/array/array_basic.py","file_name":"array_basic.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"2280816","text":"# -------------------------------------------------------------------------- #\n# Copyright 2010-2011, University of Chicago #\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, #\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\"\"\"\nContains the parsers for the two configuration files used in Globus Provision:\n\n* The instance configuration file (GPConfig): This is the configuration file\n that specifies options related to an instance's deploymenr.\n \n* The simple topology file: This is a simple format for specifying topologies\n (which internally translated to the topology JSON format). It has the\n format of a configuration file although, strictly speaking, it is *not*\n a configuration file. \n\n\"\"\"\n\nfrom globus.provision.core.topology import Domain, User, Node, Topology,\\\n DeployData, EC2DeployData, GridMapEntry, GOEndpoint\nfrom globus.provision.common.config import Config, Section, Option, OPTTYPE_INT, OPTTYPE_FLOAT, OPTTYPE_STRING, OPTTYPE_BOOLEAN, OPTTYPE_FILE\nimport os.path\nimport getpass\n\nclass GPConfig(Config):\n \"\"\"\n The instance configuration file.\n \"\"\"\n\n sections = [] \n \n # ============================= #\n # #\n # GENERAL OPTIONS #\n # #\n # ============================= # \n \n general = Section(\"general\", required=True,\n doc = \"This section is used for general options affecting Globus Provision as a whole.\")\n general.options = \\\n [\n Option(name = \"ca-cert\",\n getter = \"ca-cert\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n Location of CA certificate (PEM-encoded) used to generate user\n and host certificates. If blank, Globus Provision will generate a self-signed\n certificate from scratch. \n \"\"\"), \n Option(name = \"ca-key\",\n getter = \"ca-key\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n Location of the private key (PEM-encoded) for the certificate\n specified in ``ca-cert``.\n \"\"\"),\n Option(name = \"ca-dn\",\n getter = \"ca-dn\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n Distinguished Name of the certificates that will be signed with \n the CA certificate specified in ``ca-cert``. \n \n For example, if you set this value to ``O=Foo, OU=Bar``, the certificates\n will have subjects like ``/O=Foo/OU=Bar/CN=borja``, ``/O=Foo/OU=Bar/CN=host/foo.example.org``, etc.\n \"\"\"), \n Option(name = \"scratch-dir\",\n getter = \"scratch-dir\",\n type = OPTTYPE_STRING,\n required = False,\n default = \"/var/tmp\",\n doc = \"\"\"\n Scratch directory that Chef will use (on the provisioned machines)\n while configuring them.\n \"\"\"),\n Option(name = \"deploy\",\n getter = \"deploy\",\n type = OPTTYPE_STRING,\n required = True,\n valid = [\"ec2\", \"dummy\"],\n doc = \"\"\"\n Globus Provision can support various \"deployers\" that are used to\n deploy the hosts in a topology. Two deployers are currently supported:\n \n * ``ec2``: Hosts are deployed as Amazon EC2 instances.\n * ``dummy``: Hosts are not actually deployed and are assigned dummy\n hostnames and IP addresses.\n \n See the Globus Provision documentation for more details on the\n available deployers.\n \"\"\") \n ]\n\n sections.append(general)\n\n # ====================== #\n # #\n # EC2 OPTIONS #\n # #\n # ====================== #\n\n ec2 = Section(\"ec2\", required=False,\n required_if = [((\"general\",\"deploy\"),\"ec2\")],\n doc = \"\"\"\n When the EC2 deployer is selected, Globus Provision will need certain information about\n your EC2 account to be able to request EC2 instances on which to deploy your topology. This account\n information is specified in this section of the configuration file. If you are unclear on what values\n you need to specify here, see :ref:`chap_ec2` for more detailed instructions (including how to set up\n an Amazon EC2 account)\"\"\")\n ec2.options = \\\n [ \n Option(name = \"keypair\",\n getter = \"ec2-keypair\",\n type = OPTTYPE_STRING,\n required = True,\n doc = \"\"\"\n The *name* of the Amazon EC2 keypair you will use to log into the VMs.\n See :ref:`chap_ec2` for instructions on how to obtain this keypair.\n \"\"\"),\n Option(name = \"keyfile\",\n getter = \"ec2-keyfile\",\n type = OPTTYPE_FILE,\n required = True,\n doc = \"\"\"\n The actual location of the keypair on your local filesystem.\n See :ref:`chap_ec2` for instructions on how to obtain this keypair.\n \"\"\"),\n Option(name = \"username\",\n getter = \"ec2-username\",\n type = OPTTYPE_STRING,\n required = True,\n doc = \"\"\"\n The username that Globus Provision will use to connect to the EC2 instances,\n using the keypair specified in ``keypair``. If you are using one of the\n Globus Provision AMIs, you need to set this value to ``ubuntu``.\n \"\"\"), \n Option(name = \"server-hostname\",\n getter = \"ec2-server-hostname\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n The hostname of the EC2 server. If you are using Amazon AWS, leave this option\n unspecified. If you are using an EC2-compatible system, such as OpenNebula, Nimbus,\n Eucalyptus, etc. set this to the server running that system's EC2 interface.\n \"\"\"),\n Option(name = \"server-port\",\n getter = \"ec2-server-port\",\n type = OPTTYPE_INT,\n required = False,\n doc = \"\"\"\n The TCP port of the EC2 server. If you are using Amazon AWS, leave this option\n unspecified. If you are using an EC2-compatible system, such as OpenNebula, Nimbus,\n Eucalyptus, etc. set this to the port on which that system's EC2 interface is listening on.\n \"\"\"),\n Option(name = \"server-path\",\n getter = \"ec2-server-path\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n The path portion of the EC2 server. If you are using Amazon AWS, leave this option\n unspecified. If you are using an EC2-compatible system, such as OpenNebula, OpenStack,\n Eucalyptus, etc. set this to the path (in the host specified in ``server-hostname``)\n that the system's EC2 interface is available on.\n \"\"\") \n ] \n sections.append(ec2)\n\n # ================================ #\n # #\n # GLOBUS ONLINE OPTIONS #\n # #\n # ================================ #\n\n go = Section(\"globusonline\", required=False,\n doc = \"\"\"\n When a topology includes Globus Online transfer endpoints, Globus Provision will\n use GO's API to set up those endpoints. To do so, it will need some information\n about your GO account. If you are unclear on what values you need to specify here, \n see :ref:`chap_go` for more detailed instructions.\n \"\"\")\n go.options = \\\n [ \n Option(name = \"ssh-key\",\n getter = \"go-ssh-key\",\n type = OPTTYPE_FILE,\n default = \"~/.ssh/id_rsa\", \n required = False,\n doc = \"\"\"\n SSH key to use when connecting to the Globus Online CLI. The public key\n for this SSH key must have been previously added to your Globus Online\n profile.\n \"\"\"), \n Option(name = \"cert-file\",\n getter = \"go-cert-file\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n When this option is specified, Globus Provision will access your GO\n account using Globus Online's Transfer API (instead of sending commands\n to Globus Online's CLI via SSH). To do so, Globus Provision needs the\n location of a user certificate (PEM-encoded) that is authorized to access \n the accounts specified in your topology's endpoints.\n \n See :ref:`chap_go` for more details on the differences between using the\n Transfer API, instead of the CLI via SSH.\n \"\"\"), \n Option(name = \"key-file\",\n getter = \"go-key-file\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n Location of the private key (PEM-encoded) for the certificate\n specified in ``cert-file``.\n \"\"\"), \n Option(name = \"server-ca-file\",\n getter = \"go-server-ca-file\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n To verify the server certificate of the Globus Online Transfer API server,\n Globus Provision needs the certificate of the CA that signed that certificate.\n This file is already bundled with Globus Provision. The only reason for using\n this option to specify a different CA certificate is in the unlikely case that\n the API server decides to switch to a different CA (and the file bundled\n with Globus Provision has not been updated to that CA yet).\n \"\"\")\n ] \n sections.append(go)\n \n def __init__(self, config_file):\n Config.__init__(self, config_file, self.sections)\n\n\nclass SimpleTopologyConfig(Config):\n \"\"\"\n The simple topology file\n \"\"\" \n \n sections = [] \n \n # ============================= #\n # #\n # GENERAL OPTIONS #\n # #\n # ============================= # \n \n general = Section(\"general\", required=True,\n doc = \"This section is used for general options affecting all the topology.\")\n general.options = \\\n [ \n Option(name = \"domains\",\n getter = \"domains\",\n type = OPTTYPE_STRING,\n required = True,\n doc = \"\"\"\n The names of the domains you are defining in this topology. They must each be separated by\n a single space. \n \"\"\"), \n Option(name = \"deploy\",\n getter = \"deploy\",\n type = OPTTYPE_STRING,\n required = True,\n valid = [\"ec2\", \"dummy\"],\n doc = \"\"\"\n See the :ref:`deploy option ` in :ref:`chap_config_ref` \n \"\"\"),\n Option(name = \"ssh-pubkey\",\n getter = \"ssh-pubkey\",\n type = OPTTYPE_FILE,\n required = False,\n default = \"~/.ssh/id_rsa.pub\",\n doc = \"\"\"\n When creating users, an SSH public key must be added to their ``authorized_keys`` file\n to allow the creator of the topology to log in as those users. When using a topology file,\n each SSH key is specified separately for each user; in a simple topology, you can specify\n a single SSH public key for all the users (by default, the SSH key of the topology's creator \n will be used)\n \n Take into account that you *can* specify per-user SSH keys in a simple topology by using the\n :ref:`users-file option`.\n \"\"\") \n ] \n \n sections.append(general)\n \n domain = Section(\"domain\", required=False, multiple=(\"general\", \"domains\"),\n doc = \"\"\"\n For each domain specified in the ``domains`` option, you will need to specify a section\n titled ``[domain-DDD]`` where ``DD`` is the name of the domain. For example, if you specify the following::\n \n [general]\n domains: foo bar\n \n You will need to specify the following sections::\n \n [domain-foo]\n ...\n \n [domain-bar]\n ...\n \n Each section provides a few high-level options about each domain.\n This provides a simple, but constrained, way of specifying what services and users\n should be created in each domain. For more complex topologies, you may have\n to write a regular :ref:`topology file `. \n \"\"\")\n domain.options = \\\n [ \n Option(name = \"users\",\n getter = \"users\",\n type = OPTTYPE_STRING,\n required = False,\n default = \"0\",\n doc = \"\"\"\n This option can be either a number, or a list of usernames separated by spaces.\n \n If a number is specified, the users will be named ``D-userN``, where ``D`` is the\n domain name and ``N`` is a number between 1 and the number specified in this option.\n \n If a list of usernames is specified, users with those login names will be created.\n \n These users will be created with corresponding user certificates. To create users without user certificates\n use option ``users-no-cert``. \n \"\"\"), \n Option(name = \"users-no-cert\",\n getter = \"users-no-cert\",\n type = OPTTYPE_STRING,\n default = \"0\",\n required = False,\n doc = \"\"\"\n Same as ``users`` but creating users without certificates.\n \n Note that if you specify a number for *both* the ``users`` and ``users-no-cert`` option \n (with values N and M, respectively), the first N users will have certificates, and the \n remaining M will not. \n \"\"\"), \n Option(name = \"users-file\",\n getter = \"users-file\",\n type = OPTTYPE_FILE,\n required = False,\n doc = \"\"\"\n The path to a file with a specification of the users to create in this domain. This file will have one line\n per user, each with three fields (separated by whitespace):\n \n #. A single character, ``C`` or ``N``. If ``C`` is specified, the user will have a user certificate created\n for it. Otherwise, it will nor.\n #. The user's UNIX login name.\n #. (Optional) An SSH public key to add to the user's ``authorized_keys`` file. If not specified, the public\n key specified in :ref:`option ssh-pubkey` will be used.\n \n For example::\n \n C borja ssh-rsa FOOFOOFOO...BARBARBAR borja@example.org\n C childers ssh-rsa FOOFOOFOO...BARBARBAR childers@example.org\n N foster\n N madduri\n \n \"\"\"), \n Option(name = \"nfs-nis\",\n getter = \"nfs-nis\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether an NFS/NIS server should be setup in this domain. When ``True``, there will be a global\n filesystem and global user account space in the domain. Most notably, the users' home directories will be on an\n NFS directory, which means they will be able to access the same home directory from any host in the domain\n (as opposed to having separate home directories in each host).\n \n When ``False``, user accounts and home directories will be created on every individual host. This option can\n be useful if you are creating a single-host domain. \n \"\"\"), \n Option(name = \"login\",\n getter = \"login\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether a separate \"login node\" should be created in the topology. This option can be useful if you\n want a distinct node that users can log into but that does not host one of the topology's servers (like the NFS\n server, a GridFTP server, etc.) \n \"\"\"),\n Option(name = \"myproxy\",\n getter = \"myproxy\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether to set up a MyProxy server on this domain. \n \"\"\"), \n Option(name = \"gram\",\n getter = \"gram\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether to set up a GRAM5 server on this domain. \n \"\"\"), \n Option(name = \"gridftp\",\n getter = \"gridftp\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether to set up a GridFTP server on this domain. \n \"\"\"), \n Option(name = \"lrm\",\n getter = \"lrm\",\n type = OPTTYPE_STRING,\n valid = [\"none\", \"condor\"],\n default = \"none\",\n required = False,\n doc = \"\"\"\n Specifies whether to set up an LRM (Local Resource Manager) on this domain. Currently, only \n `Condor `_ is supported. \n \"\"\"), \n Option(name = \"cluster-nodes\",\n getter = \"cluster-nodes\",\n type = OPTTYPE_INT,\n required = False,\n doc = \"\"\"\n The number of worker nodes to create for the LRM. \n \"\"\"), \n Option(name = \"galaxy\",\n getter = \"galaxy\",\n type = OPTTYPE_BOOLEAN,\n required = False,\n default = False,\n doc = \"\"\"\n Specifies whether to set up a Galaxy server on this domain. \n \"\"\"), \n Option(name = \"go-endpoint\",\n getter = \"go-endpoint\",\n type = OPTTYPE_STRING,\n required = False,\n doc = \"\"\"\n If this domain has a GridFTP server, it can be configured as a GO endpoint.\n The format for this option is # (e.g., johnsmith#test-ep).\n Take into account that you must be authorized to use the GO account for ,\n and that you must specify the appropriate credentials in the \n :ref:`[globusonline] section` of the configuration file.\n \n See :ref:`chap_go` for more details. \n \"\"\")\n, \n Option(name = \"go-auth\",\n getter = \"go-auth\",\n type = OPTTYPE_STRING,\n required = False,\n valid = [\"myproxy\", \"go\"], \n doc = \"\"\"\n The authentication method that Globus Online will use when contacting the endpoint on\n behalf of a user. The valid options are:\n \n * ``myproxy``: Contact the MyProxy server specified in the topology. Note that \n the :ref:`myproxy option` must be set to ``true`` \n for this to work\n * ``go``: Use Globus Online authentication.\n \n See :ref:`chap_go`, and specifically :ref:`Globus Online Authentication Methods `,\n for more details on the implications of each authentication method. \n \"\"\") \n ] \n sections.append(domain)\n \n ec2 = Section(\"ec2\", required=False,\n required_if = [((\"general\",\"deploy\"),\"ec2\")],\n doc = \"\"\"\n When the EC2 deployer is selected, this section will allow you to\n specify EC2 deployment options that are specific to this topology.\"\"\") \n ec2.options = \\\n [ \n Option(name = \"ami\",\n getter = \"ec2-ami\",\n type = OPTTYPE_STRING,\n required = True,\n doc = \"\"\"\n This is the AMI (`Amazon Machine Image `_) \n that Globus Provision will use to create each host in the domani. Any recent Ubuntu or Debian\n AMI should work. Nonetheless, take into account that we provide an AMI that has most of the\n necessary software pre-installed in it, considerably speeding up the setup of the machines. \n The latest Globus Provision AMI is always listed in the Globus Provision website.\n \"\"\"),\n Option(name = \"instance-type\",\n getter = \"ec2-instance-type\",\n type = OPTTYPE_STRING,\n required = True,\n default = \"t1.micro\",\n doc = \"\"\"\n This is the `EC2 instance type `_ that will\n be used to launch the machines in this domain. The default is to use micro-instances (t1.micro),\n which tend to be enough if you are just tinkering around.\n \"\"\"), \n Option(name = \"availability-zone\",\n getter = \"ec2-availability-zone\",\n type = OPTTYPE_STRING,\n required = False,\n default = None,\n doc = \"\"\"\n The `availability zone `_ \n you want the VMs to be deployed in. \n Unless you have a good reason for choosing a specific availability zone,\n you should let Globus Provision choose a default zone for you.\n \"\"\") \n ] \n sections.append(ec2) \n \n def __init__(self, configfile):\n Config.__init__(self, configfile, self.sections)\n\n def to_topology(self):\n ssh_pubkeyf = os.path.expanduser(self.get(\"ssh-pubkey\"))\n ssh_pubkeyf = open(ssh_pubkeyf)\n ssh_pubkey = ssh_pubkeyf.read().strip()\n ssh_pubkeyf.close() \n \n topology = Topology()\n \n if self.get(\"deploy\") == \"dummy\":\n # No default deploy data\n pass\n elif self.get(\"deploy\") == \"ec2\":\n deploy_data = DeployData()\n ec2_deploy_data = EC2DeployData()\n \n ec2_deploy_data.set_property(\"ami\", self.get(\"ec2-ami\"))\n ec2_deploy_data.set_property(\"instance_type\", self.get(\"ec2-instance-type\"))\n \n deploy_data.set_property(\"ec2\", ec2_deploy_data)\n topology.set_property(\"default_deploy_data\", deploy_data)\n \n domains = self.get(\"domains\").split()\n for domain_name in domains:\n domain = Domain()\n domain.set_property(\"id\", domain_name)\n topology.add_to_array(\"domains\", domain)\n\n user = User()\n user.set_property(\"id\", getpass.getuser())\n user.set_property(\"password_hash\", \"!\")\n user.set_property(\"certificate\", \"generated\")\n user.set_property(\"admin\", True)\n user.set_property(\"ssh_pkey\", ssh_pubkey)\n domain.add_user(user) \n\n usersfile = self.get((domain_name, \"users-file\"))\n \n if usersfile != None:\n usersfile = open(usersfile, \"r\")\n \n for line in usersfile:\n fields = line.split()\n type = fields[0]\n username = fields[1]\n if len(fields) >= 3:\n user_ssh_pubkey = \" \".join(fields[2:])\n else:\n user_ssh_pubkey = ssh_pubkey\n \n user = User()\n user.set_property(\"id\", username)\n user.set_property(\"password_hash\", \"!\")\n user.set_property(\"ssh_pkey\", user_ssh_pubkey)\n if type == \"C\":\n user.set_property(\"certificate\", \"generated\")\n else:\n user.set_property(\"certificate\", \"none\")\n \n domain.add_user(user)\n \n usersfile.close()\n else:\n users = self.get((domain_name, \"users\"))\n users_nocert = self.get((domain_name, \"users-no-cert\"))\n \n if users.isdigit():\n num_users = int(users)\n usernames = [(\"%s-user%i\" % (domain_name, i), True) for i in range(1,num_users + 1)]\n else:\n num_users = 0\n usernames = [(u, True) for u in users.split() if u != getpass.getuser()]\n \n if users_nocert.isdigit():\n usernames += [(\"%s-user%i\" % (domain_name, i), False) for i in range(num_users + 1,num_users + int(users_nocert) + 1)]\n else:\n usernames += [(u, False) for u in users_nocert.split() if u != getpass.getuser()] \n\n for username, cert in usernames:\n user = User()\n user.set_property(\"id\", username)\n user.set_property(\"password_hash\", \"!\")\n user.set_property(\"ssh_pkey\", ssh_pubkey)\n if cert:\n user.set_property(\"certificate\", \"generated\")\n else:\n user.set_property(\"certificate\", \"none\")\n domain.add_user(user)\n \n for user in domain.users.values():\n gme = GridMapEntry()\n gme.set_property(\"dn\", \"/O=Grid/OU=Globus Provision (generated)/CN=%s\" % user.id)\n gme.set_property(\"login\", user.id)\n domain.add_to_array(\"gridmap\", gme) \n if self.get((domain_name,\"go-auth\")) == \"go\":\n gme = GridMapEntry()\n gme.set_property(\"dn\", \"/C=US/O=Globus Consortium/OU=Globus Connect User/CN=%s\" % user.id)\n gme.set_property(\"login\", user.id)\n domain.add_to_array(\"gridmap\", gme) \n \n \n if self.get((domain_name,\"nfs-nis\")): \n server_node = Node()\n server_name = \"%s-server\" % domain_name\n server_node.set_property(\"id\", server_name)\n server_node.add_to_array(\"run_list\", \"role[domain-nfsnis]\")\n if not self.get((domain_name,\"login\")):\n # If there is no login node, the NFS/NIS server will\n # effectively act as one. \n server_node.add_to_array(\"run_list\", \"role[globus]\")\n if self.get((domain_name,\"galaxy\")):\n # If there is a Galaxy server in the domain, the \"common\"\n # recipe has to be installed on the NFS/NIS server\n server_node.add_to_array(\"run_list\", \"recipe[galaxy::galaxy-globus-common]\")\n \n domain.add_node(server_node)\n\n if self.get((domain_name,\"login\")): \n login_node = Node()\n login_node.set_property(\"id\", \"%s-login\" % domain_name)\n if self.get((domain_name,\"nfs-nis\")): \n login_node.set_property(\"depends\", \"node:%s\" % server_name)\n login_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n login_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\")\n login_node.add_to_array(\"run_list\", \"role[globus]\")\n domain.add_node(login_node) \n\n if self.get((domain_name,\"myproxy\")):\n myproxy_node = Node()\n myproxy_node.set_property(\"id\", \"%s-myproxy\" % domain_name)\n if self.get((domain_name,\"nfs-nis\")): \n myproxy_node.set_property(\"depends\", \"node:%s\" % server_name)\n myproxy_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n myproxy_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\")\n myproxy_node.add_to_array(\"run_list\", \"role[domain-myproxy]\")\n domain.add_node(myproxy_node)\n\n if self.get((domain_name,\"gridftp\")):\n gridftp_node = Node()\n gridftp_node.set_property(\"id\", \"%s-gridftp\" % domain_name)\n if self.get((domain_name,\"nfs-nis\")): \n gridftp_node.set_property(\"depends\", \"node:%s\" % server_name)\n gridftp_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n gridftp_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\") \n if self.get((domain_name,\"go-endpoint\")) != None:\n gridftp_node.add_to_array(\"run_list\", \"recipe[globus::go_cert]\")\n gridftp_node.add_to_array(\"run_list\", \"role[domain-gridftp]\")\n domain.add_node(gridftp_node) \n \n if self.get((domain_name,\"galaxy\")):\n galaxy_node = Node()\n galaxy_node.set_property(\"id\", \"%s-galaxy\" % domain_name)\n\n if self.get((domain_name,\"nfs-nis\")): \n galaxy_node.set_property(\"depends\", \"node:%s\" % server_name)\n galaxy_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n galaxy_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\") \n galaxy_node.add_to_array(\"run_list\", \"recipe[galaxy::galaxy-globus-common]\") \n\n if self.get((domain_name,\"go-endpoint\")) != None:\n galaxy_node.add_to_array(\"run_list\", \"recipe[globus::go_cert]\")\n galaxy_node.add_to_array(\"run_list\", \"recipe[galaxy::galaxy-globus]\")\n domain.add_node(galaxy_node) \n \n \n lrm = self.get((domain_name,\"lrm\"))\n if lrm != \"none\":\n gram = self.get((domain_name,\"gram\"))\n if lrm == \"condor\":\n if gram:\n node_name = \"%s-gram-condor\" % domain_name\n role = \"role[domain-gram-condor]\"\n else:\n node_name = \"%s-condor\" % domain_name\n role = \"role[domain-condor]\"\n workernode_role = \"role[domain-clusternode-condor]\"\n\n lrm_node = Node()\n lrm_node.set_property(\"id\", node_name)\n if self.get((domain_name,\"nfs-nis\")): \n lrm_node.set_property(\"depends\", \"node:%s\" % server_name)\n lrm_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\")\n else:\n lrm_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\") \n lrm_node.add_to_array(\"run_list\", role)\n domain.add_node(lrm_node)\n\n clusternode_host = 1\n for i in range(self.get((domain_name,\"cluster-nodes\"))):\n wn_name = \"%s-condor-wn%i\" % (domain_name, i+1)\n\n wn_node = Node()\n wn_node.set_property(\"id\", wn_name)\n wn_node.set_property(\"depends\", \"node:%s\" % node_name)\n if self.get((domain_name,\"nfs-nis\")):\n wn_node.add_to_array(\"run_list\", \"role[domain-nfsnis-client]\") \n else:\n wn_node.add_to_array(\"run_list\", \"recipe[provision::domain_users]\") \n wn_node.add_to_array(\"run_list\", workernode_role)\n domain.add_node(wn_node)\n\n clusternode_host += 1\n \n if self.get((domain_name,\"go-endpoint\")) != None:\n goep = GOEndpoint()\n gouser, goname = self.get((domain_name,\"go-endpoint\")).split(\"#\")\n goep.set_property(\"user\", gouser)\n goep.set_property(\"name\", goname)\n goep.set_property(\"gridftp\", \"node:%s-gridftp\" % domain_name)\n \n if self.get((domain_name,\"go-auth\")) == \"myproxy\":\n goep.set_property(\"myproxy\", \"node:%s-myproxy\" % domain_name)\n else:\n goep.set_property(\"myproxy\", \"myproxy.globusonline.org\")\n \n domain.add_to_array(\"go_endpoints\", goep)\n \n return topology\n\n\n","sub_path":"src/globus/provision/core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":36068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"101375933","text":"import matplotlib.pyplot as plt \nfrom matplotlib.animation import FuncAnimation\n\nclass Animate():\n\n # These will hold all the required values for the simulation\n def __init__(self, marsArray, phobosArray, totalKArray):\n self.numFrames = len(marsArray)\n self.marsPos = marsArray\n self.phobosPos = phobosArray\n self.totalKArray = totalKArray\n\n # This will update both circle positions as the simulation goes on \n def animate(self, i):\n self.patchMars.center = (self.marsPos[i][0], self.marsPos[i][1])\n self.patchPhobos.center = (self.phobosPos[i][0], self.phobosPos[i][1])\n\n return self.patchMars, self.patchPhobos, \n\n def display(self):\n fig = plt.figure()\n ax = plt.axes()\n\n # Creates 2 circles to represent the moon phobos and planet mars, also size of the circles are added and\n # then added to the plot at the starting postions. \n self.patchMars = plt.Circle((self.marsPos[0][0], self.marsPos[0][1]), 0.1, color='r', animated=True)\n self.patchPhobos = plt.Circle((self.phobosPos[0][0], self.phobosPos[0][1]), 0.1, color='b', animated=True)\n self.patchMars.set_radius(1605000)\n self.patchPhobos.set_radius(850000)\n ax.add_patch(self.patchMars)\n ax.add_patch(self.patchPhobos)\n\n ax.axis('scaled')\n ax.set_ylim(-1.5e7, 1.5e7)\n ax.set_xlim(-1.5e7, 1.5e7)\n\n # Animate the plot\n anim = FuncAnimation(fig, self.animate, self.numFrames, repeat=False, interval=1, blit=True)\n # This prints the total Kinetic Energy just before the animation is shown.\n self.showTotalK()\n plt.show() \n\n \n # Displaying the total Kinetic energy at regualar intervals to the command line. \n def showTotalK(self):\n print(\"TOTAL KINETIC ENERGY: \", '{:0.4e}'.format(self.totalKArray[0]))\n for i in range(self.numFrames):\n if i % (self.numFrames/50) == 0:\n print(\"TOTAL KINETIC ENERGY: \", '{:0.4e}'.format(self.totalKArray[i]))","sub_path":"Checkpoint 5/src/Animate.py","file_name":"Animate.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"615864504","text":"class ImageProcessor:\n\tdef __init__(self, frames, k_size):\n\t\tself.frames = frames\n\t\tself.k_size = k_size\n\t\t#\n\tdef analyse_frames(self):\n\t\tif len(self.frames) == 0:\n\t\t\tboxes = []\n\t\telse:\n\t\t\tboxes = []\n\t\t\tconverted_frames = self.convert_frames(self.frames)\n\t\t\taverage = self.get_average(converted_frames)\n\t\t\timage_diffs = self.get_diffs(converted_frames, average)\n\t\t\tdiff_masks = self.diffs_to_masks(image_diffs, self.k_size)\n\t\t\tboxes, _ = self.get_bounding_boxes(diff_masks)\n\t\treturn boxes\n\t\t#\n\tdef get_frames(self, video, no_frames):\n\t\tframes = self.calculate_frames(video, no_frames)\n\t\timages = []\n\t\tfor frame in frames:\n\t\t\tvideo.set(cv2.CAP_PROP_POS_FRAMES, frame)\n\t\t\t_, image = video.read()\n\t\t\tgauss_blur = cv2.GaussianBlur(image, (7, 7), 0)\n\t\t\timages.append(gauss_blur)\n\t\tprint(f\"Extracted {len(frames)} frames\")\n\t\treturn images\n\t\t#\n\tdef convert_frames(self, frames):\n\t\tfloat_frames = []\n\t\tfor frame in frames:\n\t\t\tgauss_blur = cv2.GaussianBlur(frame, (self.k_size, self.k_size), 0)\n\t\t\tfloat_frame = gauss_blur.astype(np.float32) / 255\n\t\t\tfloat_frames.append(float_frame)\n\t\treturn float_frames\n\t\t#\n\tdef get_average(self, frames):\n\t\tframes_shape = frames[0].shape\n\t\theight = frames_shape[0]\n\t\twidth = frames_shape[1]\n\t\tif len(frames_shape) < 3:\n\t\t\taverage_image = np.full((height, width), 0, np.float32)\n\t\telse:\n\t\t\taverage_image = np.full((height, width, 3), 0, np.float32)\n\t\tno_frames = len(frames)\n\t\tfor frame in frames:\n\t\t\taverage_image += frame / no_frames\n\t\tprint(f\"Calculated mean: {average_image.shape}\")\n\t\treturn average_image\n\t\t#\n\tdef get_diffs(self, frames, average_image):\n\t\tcolour = True if len(average_image.shape) > 1 else False\n\t\tdifferences = []\n\t\tif colour:\n\t\t\tfor frame in frames:\n\t\t\t\t_, image_diff = compare_ssim(frame, average_image, multichannel=True, full=True)\n\t\t\t\tabs_diff = cv2.convertScaleAbs(image_diff)\n\t\t\t\tdifferences.append(image_diff)\n\t\telse:\n\t\t\tfor frame in frames:\n\t\t\t\timage_diff = frame - average_image\n\t\t\t\tdifferences.append(abs_diff)\n\t\tprint(f\"Calculated differences: {len(differences)} frames, {differences[0].shape}\")\n\t\treturn differences\n\t\t#\n\tdef diffs_to_masks(self, frames, k_size):\n\t\tcolour = len(frames[0].shape) > 2\n\t\tmasks = []\n\t\tkernel = cv2.getGaussianKernel(k_size, 0)\n\t\tmask_type = \"\"\n\t\tif colour:\n\t\t\tmask_type = \"colour\"\n\t\t\tfor frame in frames:\n\t\t\t\tbw_frame = cv2.cvtColor((frame * 255).astype('uint8'), cv2.COLOR_BGR2GRAY)\n\t\t\t\t_, binary = cv2.threshold(bw_frame, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\t\t\t\tmask = cv2.erode(binary, kernel, iterations = 1)\n\t\t\t\tmasks.append(mask.astype('uint8'))\n\t\tprint(f\"Calculated {len(masks)} {mask_type} masks, {masks[0].shape}, {len(masks)} frames\")\n\t\treturn masks\n\t\t#\n\tdef get_bounding_boxes(self, frames):\n\t\tboxes = []\n\t\tmax_in_one_frame = 0\n\t\tfor frame in frames:\n\t\t\tframe_boxes = self.get_bounding_boxes_for_single_frame(frame)\n\t\t\tboxes.append(frame_boxes)\n\t\t# print(f\"Extracted boxes for {len(boxes)} frames, max in one frame: {max_in_one_frame}\")\n\t\treturn boxes, max_in_one_frame\n\t\t#\n\tdef get_bounding_boxes_for_single_frame(self, frame):\n\t\tcontours, hierarchy = cv2.findContours(~frame, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\t\tbounding_boxes = []\n\t\tfor contour in contours:\n\t\t\tcontour_area = cv2.contourArea(contour)\n\t\t\tif 1750 < contour_area < 450000:\n\t\t\t\tx,y,w,h = cv2.boundingRect(contour)\n\t\t\t\tbounding_boxes.append([x, y, w, h])\n\t\tif len(bounding_boxes) > 1:\n\t\t\tbounding_boxes = self.group_boxes(bounding_boxes)\n\t\treturn bounding_boxes\n\t\t#\n\tdef group_boxes(self, bounding_boxes):\n\t\tmax_grouped = False\n\t\twhile len(bounding_boxes) > 1 and max_grouped == False:\n\t\t\tmax_grouped = True\n\t\t\ti = 0\n\t\t\twhile i < len(bounding_boxes):\n\t\t\t\tj = i + 1\n\t\t\t\tbox_1 = bounding_boxes[i]\n\t\t\t\twhile j < len(bounding_boxes):\n\t\t\t\t\tbox_2 = bounding_boxes[j]\n\t\t\t\t\tif self.boxes_overlap(box_1, box_2):\n\t\t\t\t\t\t# print(\"boxes overlap\")\n\t\t\t\t\t\tbounding_boxes[i] = self.combine_boxes(box_1, box_2)\n\t\t\t\t\t\tbounding_boxes.remove(box_2)\n\t\t\t\t\t\tmax_grouped = False\n\t\t\t\t\telse:\n\t\t\t\t\t\t# print(\"boxes do not overlap\")\n\t\t\t\t\t\tj += 1\n\t\t\t\ti += 1\n\t\treturn bounding_boxes\n\t\t#\n\tdef boxes_overlap(self, box_1, box_2):\n\t\tif box_2[0] < box_1[0] < (box_2[0] + box_2[2]) or box_2[0] < box_1[0] + box_1[2] < (box_2[0] + box_2[2]):\n\t\t\tif box_2[1] < box_1[1] < (box_2[1] + box_2[3]) or box_2[1] < box_1[1] + box_1[3] < (box_2[1] + box_2[3]):\n\t\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t\t\t#\n\tdef combine_boxes(self, box_1, box_2):\n\t\tx = min(box_1[0], box_2[0])\n\t\tmax_x = max((box_1[0] + box_1[2]), (box_2[0] + box_2[2]))\n\t\ty = min(box_1[1], box_2[1])\n\t\tmax_y = max((box_1[1] + box_1[3]), (box_2[1] + box_2[3]))\n\t\tw = max_x - x\n\t\th = max_y - y\n\t\treturn [x, y, w, h]\n\n\t# def export_all_bounding_boxes_for_frames(self, save_directory, bounding_boxes, frames):\n\t# \tglobal id\n\t# \tfor i, frame in enumerate(frames):\n\t# \t\tfor box in bounding_boxes[i]:\n\t# \t\t\tclipped_image = clip_image_by_bounding_box(frame, box)\n\t# \t\t\tsave_image(save_directory, clipped_image)\n\t# \t\t\tid += 1\n\n\t# def clip_image_by_bounding_box(image, box):\n\t# \tclip = image[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]\n\t# \treturn clip\n\n\t# def save_image(save_directory, image):\n\t# \tcv2.imwrite(f\"{save_directory}/{id}.png\", image)\n\t# \tprint(f\"image {id} saved to {save_directory}/{id}.png\")\n\n\n","sub_path":"image_processing/image_processor.py","file_name":"image_processor.py","file_ext":"py","file_size_in_byte":5210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"71975047","text":"\"\"\"\nClassifying sentiments of a tweet\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport official.nlp.bert.tokenization as tokenization\nimport official.nlp.optimization as opti\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom reading_offensive_tweet import get_offensive_data\n\ntf.get_logger().setLevel('ERROR')\n\n\ndef encode_names(tokenizer, n):\n tokens = list(tokenizer.tokenize(n))\n tokens.append('[SEP]')\n return tokenizer.convert_tokens_to_ids(tokens)\n\n\ndef bert_encode(string_list, tokenizer, max_seq_length):\n string_tokens = tf.ragged.constant([\n encode_names(tokenizer, n) for n in np.array(string_list)])\n cls = [tokenizer.convert_tokens_to_ids(['[CLS]'])] * string_tokens.shape[0]\n input_word_ids = tf.concat([cls, string_tokens], axis=-1)\n input_mask = tf.ones_like(input_word_ids).to_tensor(\n shape=(None, max_seq_length))\n type_cls = tf.zeros_like(cls)\n type_tokens = tf.ones_like(string_tokens)\n input_type_ids = tf.concat([type_cls, type_tokens], axis=-1).to_tensor(shape=(None, max_seq_length))\n inputs = {\n 'input_word_ids': input_word_ids.to_tensor(shape=(None, max_seq_length)),\n 'input_mask': input_mask,\n 'input_type_ids': input_type_ids\n }\n return inputs\n\n\nif __name__ == \"__main__\":\n train_data, test_data, val_data, mappings = get_offensive_data()\n\n # Cleaning tweets.\n train_data.tweets = train_data.tweets.transform(\n lambda x: x.lower().replace(\"@user\", \"\").strip())\n test_data.tweets = test_data.tweets.transform(\n lambda x: x.lower().replace(\"@user\", \"\").strip())\n val_data.tweets = val_data.tweets.transform(\n lambda x: x.lower().replace(\"@user\", \"\").strip())\n\n # Creating labels.\n label_encoder = LabelEncoder()\n train_data.labels = label_encoder.fit_transform(train_data.labels)\n test_data.labels = label_encoder.transform(test_data.labels)\n val_data.labels = label_encoder.transform(val_data.labels)\n\n y_train = tf.keras.utils.to_categorical(train_data.labels)\n y_test = tf.keras.utils.to_categorical(test_data.labels)\n y_val = tf.keras.utils.to_categorical(val_data.labels)\n\n print(\"Fetching BERT model\")\n bert_layer = hub.KerasLayer(\"https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/2\", trainable=True)\n print(\"Model is fetched\")\n # bert_layer = hub.KerasLayer(\"https://tfhub.dev/tensorflow/small_bert/\n # bert_en_uncased_L-8_H-512_A-8/2\", trainable=True)\n\n vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()\n do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()\n tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case)\n\n tokenizer.convert_tokens_to_ids(['[CLS]', '[SEP]'])\n tweets = tf.ragged.constant([encode_names(tokenizer, n) for n in train_data.tweets])\n\n cls = [tokenizer.convert_tokens_to_ids(['[CLS]'])] * tweets.shape[0]\n input_word_ids = tf.concat([cls, tweets], axis=1)\n\n input_mask = tf.ones_like(input_word_ids).to_tensor()\n\n type_cls = tf.zeros_like(cls)\n type_tweet = tf.ones_like(tweets)\n input_type_ids = tf.concat([type_cls, type_tweet], axis=1).to_tensor()\n\n max_seq_len = max([len(i) for i in input_word_ids])\n max_seq_len = int(1.5 * max_seq_len)\n\n X_train = bert_encode(train_data.tweets, tokenizer, max_seq_len)\n X_test = bert_encode(test_data.tweets, tokenizer, max_seq_len)\n X_val = bert_encode(val_data.tweets, tokenizer, max_seq_len)\n\n num_class = len(label_encoder.classes_)\n max_seq_length = max_seq_len\n\n input_word_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name=\"input_word_ids\")\n input_mask = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name=\"input_mask\")\n segment_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32, name=\"segment_ids\")\n\n pooled_output, sequence_output = bert_layer([input_word_ids, input_mask, segment_ids])\n output = tf.keras.layers.Dropout(rate=0.1)(pooled_output)\n output = tf.keras.layers.Dense(num_class, activation='softmax', name='output')(output)\n\n model = tf.keras.Model(\n inputs={\n 'input_word_ids': input_word_ids,\n 'input_mask': input_mask,\n 'input_type_ids': segment_ids\n },\n outputs=output)\n\n epochs = 3\n batch_size = 4\n eval_batch_size = batch_size\n\n train_data_size = len(y_train)\n steps_per_epoch = int(train_data_size / batch_size)\n num_train_steps = steps_per_epoch * epochs\n warmup_steps = int(epochs * train_data_size * 0.1 / batch_size)\n\n optimizer = opti.create_optimizer(1e-3, num_train_steps=num_train_steps, num_warmup_steps=warmup_steps)\n\n model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])\n model.summary()\n history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, validation_data=(X_val, y_val), verbose=1)\n model.save(os.path.join(\".\", \"offensive_model_final\"))\n print(model.evaluate(X_test, y_test))\n\n acc = history.history['accuracy']\n val_acc = history.history['val_accuracy']\n loss = history.history['loss']\n val_loss = history.history['val_loss']\n x = range(1, len(acc) + 1)\n\n plt.figure(figsize=(12, 5))\n plt.subplot(1, 2, 1)\n plt.plot(x, acc, 'b', label='Training acc')\n plt.plot(x, val_acc, 'r', label='Validation acc')\n plt.title('Training and validation accuracy')\n plt.legend()\n plt.subplot(1, 2, 2)\n plt.plot(x, loss, 'b', label='Training loss')\n plt.plot(x, val_loss, 'r', label='Validation loss')\n plt.title('Training and validation loss')\n plt.legend()\n plt.show()\n\n","sub_path":"offensive_analysis.py","file_name":"offensive_analysis.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"47034291","text":"#!/usr/bin/python3 -B\n\n# Copyright 2015-2020 Josh Pieper, jjp@pobox.com. 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\n'''%prog [options]\n\nInteractively display and update values from an embedded device.\n'''\n\nimport binascii\nimport io\nimport numpy\nimport optparse\nimport os\nimport re\nimport serial\nimport socket\nimport struct\nimport sys\nimport time\nimport matplotlib\nimport matplotlib.figure\n\ntry:\n import PySide2\n\n os.environ['QT_API'] = 'pyside2'\n\n from matplotlib.backends import backend_qt5agg\n from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n qt_backend = matplotlib.backends.backend_qt5agg\n\n from PySide2 import QtUiTools\n\nexcept:\n print(\"Falling back to PySide1\")\n # Fall back to pyside1\n matplotlib.use('Qt4Agg')\n matplotlib.rcParams['backend.qt4'] = 'PySide'\n\n from matplotlib.backends import backend_qt4agg\n from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas\n os.environ['QT_API'] = 'pyside'\n from PySide import QtUiTools\n qt_backend = matplotlib.backends.backend_qt4agg\n\n\nfrom qtconsole.history_console_widget import HistoryConsoleWidget\nfrom qtconsole.qt import QtCore, QtGui\n\nfrom bazel_tools.tools.python.runfiles import runfiles\nimport mjlib.telemetry.reader as reader\n\n\nLEFT_LEGEND_LOC = 3\nRIGHT_LEGEND_LOC = 2\n\nDEFAULT_RATE = 100\nMAX_HISTORY_SIZE = 100\n\ndef readline(stream):\n result = b''\n while True:\n c = stream.read(1)\n if len(c) == 0:\n return result\n result += c\n if c == b'\\n':\n return result\n\ndef dehexify(data):\n result = b''\n for i in range(0, len(data), 2):\n result += bytes([int(data[i:i+2], 16)])\n return result\n\n\ndef read_varuint(data, offset):\n '''Return (varuint, next_offset)'''\n\n result = 0\n shift = 0\n for i in range(5):\n if offset >= len(data):\n return None, offset\n this_byte, = struct.unpack('> 8) & 0xff\n\n if dest != 0x00:\n return\n\n if source != self._destination_id:\n return\n\n payload = dehexify(fields[2])\n\n sbo = 0\n subframe_id, sbo = read_varuint(payload, sbo)\n channel, sbo = read_varuint(payload, sbo)\n server_len, sbo = read_varuint(payload, sbo)\n\n if subframe_id is None or channel is None or server_len is None:\n return\n\n if subframe_id != 0x41:\n return\n\n if channel != 1:\n return\n\n payload_rest = payload[sbo:]\n to_add = payload_rest[0:server_len]\n self._read_buffer += to_add\n\n\nclass MultiplexStream(StreamBase):\n def __init__(self, *args, **kwargs):\n super(FdcanUsbStream, self).__init__(*args, **kwargs)\n\n def poll(self):\n # We only ask for a response if we're not writing immediately.\n # That way we can get multiple writes out nearly\n # simultaneously.\n wait_for_response = len(self._write_buffer) == 0\n\n header = struct.pack(' 0:\n _set_tree_widget_data(child, field)\n elif isinstance(field, list):\n _set_tree_widget_data(child, field,\n getter=lambda x, y: x[int(y)],\n required_size=len(field))\n else:\n child.setText(1, repr(field))\n\n\nclass RecordSignal(object):\n def __init__(self):\n self._index = 0\n self._callbacks = {}\n\n def connect(self, handler):\n result = self._index\n self._index += 1\n self._callbacks[result] = handler\n\n class Connection(object):\n def __init__(self, parent, index):\n self.parent = parent\n self.index = index\n\n def remove(self):\n del self.parent._callbacks[self.index]\n\n return Connection(self, result)\n\n def update(self, value):\n for handler in self._callbacks.values():\n handler(value)\n return len(self._callbacks) != 0\n\n\nclass PlotItem(object):\n def __init__(self, axis, plot_widget, name, signal):\n self.axis = axis\n self.plot_widget = plot_widget\n self.name = name\n self.line = None\n self.xdata = []\n self.ydata = []\n self.connection = signal.connect(self._handle_update)\n\n def _make_line(self):\n line = matplotlib.lines.Line2D([], [])\n line.set_label(self.name)\n line.set_color(self.plot_widget.COLORS[self.plot_widget.next_color])\n self.plot_widget.next_color = (\n self.plot_widget.next_color + 1) % len(self.plot_widget.COLORS)\n\n self.axis.add_line(line)\n self.axis.legend(loc=self.axis.legend_loc)\n\n self.line = line\n\n def remove(self):\n self.line.remove()\n self.connection.remove()\n # NOTE jpieper: matplotlib gives us no better way to remove a\n # legend.\n if len(self.axis.lines) == 0:\n self.axis.legend_ = None\n else:\n self.axis.legend(loc=self.axis.legend_loc)\n self.plot_widget.canvas.draw()\n\n def _handle_update(self, value):\n if self.plot_widget.paused:\n return\n\n if self.line is None:\n self._make_line()\n\n now = time.time()\n self.xdata.append(now)\n self.ydata.append(value)\n\n # Remove elements from the beginning until there is at most\n # one before the window.\n oldest_time = now - self.plot_widget.history_s\n oldest_index = None\n for i in range(len(self.xdata)):\n if self.xdata[i] >= oldest_time:\n oldest_index = i - 1\n break\n\n if oldest_index and oldest_index > 1:\n self.xdata = self.xdata[oldest_index:]\n self.ydata = self.ydata[oldest_index:]\n\n self.line.set_data(self.xdata, self.ydata)\n\n self.axis.relim()\n self.axis.autoscale()\n\n self.plot_widget.data_update()\n\n\nclass PlotWidget(QtGui.QWidget):\n COLORS = 'rbgcmyk'\n\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n\n self.history_s = 20.0\n self.next_color = 0\n self.paused = False\n\n self.last_draw_time = 0.0\n\n self.figure = matplotlib.figure.Figure()\n self.canvas = FigureCanvas(self.figure)\n\n self.canvas.mpl_connect('key_press_event', self.handle_key_press)\n self.canvas.mpl_connect('key_release_event', self.handle_key_release)\n\n self.left_axis = self.figure.add_subplot(111)\n self.left_axis.grid()\n self.left_axis.fmt_xdata = lambda x: '%.3f' % x\n\n self.left_axis.legend_loc = LEFT_LEGEND_LOC\n\n self.right_axis = None\n\n self.toolbar = qt_backend.NavigationToolbar2QT(self.canvas, self)\n self.pause_action = QtGui.QAction(u'Pause', self)\n self.pause_action.setCheckable(True)\n self.pause_action.toggled.connect(self._handle_pause)\n self.toolbar.addAction(self.pause_action)\n\n layout = QtGui.QVBoxLayout(self)\n layout.addWidget(self.toolbar, 0)\n layout.addWidget(self.canvas, 1)\n\n self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)\n\n def _handle_pause(self, value):\n self.paused = value\n\n def add_plot(self, name, signal, axis_number):\n axis = self.left_axis\n if axis_number == 1:\n if self.right_axis is None:\n self.right_axis = self.left_axis.twinx()\n self.right_axis.legend_loc = RIGHT_LEGEND_LOC\n axis = self.right_axis\n item = PlotItem(axis, self, name, signal)\n return item\n\n def remove_plot(self, item):\n item.remove()\n\n def data_update(self):\n now = time.time()\n elapsed = now - self.last_draw_time\n if elapsed > 0.1:\n self.last_draw_time = now\n self.canvas.draw()\n\n def _get_axes_keys(self):\n result = []\n result.append(('1', self.left_axis))\n if self.right_axis:\n result.append(('2', self.right_axis))\n return result\n\n def handle_key_press(self, event):\n if event.key not in ['1', '2']:\n return\n for key, axis in self._get_axes_keys():\n if key == event.key:\n axis.set_navigate(True)\n else:\n axis.set_navigate(False)\n\n def handle_key_release(self, event):\n if event.key not in ['1', '2']:\n return\n for key, axis in self._get_axes_keys():\n axis.set_navigate(True)\n\n\nclass SizedTreeWidget(QtGui.QTreeWidget):\n def __init__(self, parent=None):\n QtGui.QTreeWidget.__init__(self, parent)\n self.setColumnCount(2)\n self.headerItem().setText(0, 'Name')\n self.headerItem().setText(1, 'Value')\n\n def sizeHint(self):\n return QtCore.QSize(350, 500)\n\n\nclass TviewConsoleWidget(HistoryConsoleWidget):\n line_input = QtCore.Signal(str)\n\n def __init__(self, *args, **kw):\n super(TviewConsoleWidget, self).__init__(*args, **kw)\n\n self.execute_on_complete_input = False\n self._prompt = '>>> '\n self.clear()\n\n # The bionic version of ConsoleWidget seems to get the cursor\n # position screwed up after a clear. Let's just fix it up\n # here.\n self._append_before_prompt_cursor.setPosition(0)\n\n def sizeHint(self):\n return QtCore.QSize(600, 200)\n\n def add_text(self, data):\n assert data.endswith('\\n') or data.endswith('\\r')\n self._append_plain_text(data, before_prompt=True)\n self._control.moveCursor(QtGui.QTextCursor.End)\n\n def _handle_timeout(self):\n self._append_plain_text('%s\\r\\n' % time.time(),\n before_prompt=True)\n self._control.moveCursor(QtGui.QTextCursor.End)\n\n def _is_complete(self, source, interactive):\n return True, False\n\n def _execute(self, source, hidden):\n self.line_input.emit(source)\n self._show_prompt(self._prompt)\n return True\n\n\nclass Record:\n def __init__(self, archive):\n self.archive = archive\n self.tree_item = None\n self.signals = {}\n self.history = []\n\n def get_signal(self, name):\n if name not in self.signals:\n self.signals[name] = RecordSignal()\n\n return self.signals[name]\n\n def update(self, struct):\n count = 0\n self.history.append(struct)\n if len(self.history) > MAX_HISTORY_SIZE:\n self.history = self.history[1:]\n\n for key, signal in self.signals.items():\n if key.startswith('__STDDEV_'):\n remaining = key.split('__STDDEV_')[1]\n values = [_get_data(x, remaining) for x in self.history]\n value = numpy.std(values)\n elif key.startswith('__MEAN_'):\n remaining = key.split('__MEAN_')[1]\n values = [_get_data(x, remaining) for x in self.history]\n value = numpy.mean(values)\n else:\n value = _get_data(struct, key)\n if signal.update(value):\n count += 1\n return count != 0\n\n\nclass NoEditDelegate(QtGui.QStyledItemDelegate):\n def __init__(self, parent=None):\n QtGui.QStyledItemDelegate.__init__(self, parent=parent)\n\n def createEditor(self, parent, option, index):\n return None\n\n\ndef _get_item_name(item):\n name = item.text(0)\n while item.parent() and item.parent().parent():\n name = item.parent().text(0) + '.' + name\n item = item.parent()\n\n return name\n\n\ndef _get_item_root(item):\n while item.parent().parent():\n item = item.parent()\n return item.text(0)\n\n\nclass Device:\n STATE_LINE = 0\n STATE_CONFIG = 1\n STATE_TELEMETRY = 2\n STATE_SCHEMA = 3\n STATE_DATA = 4\n\n def __init__(self, number, stream, console, prefix,\n config_tree_item, data_tree_item):\n self.number = number\n self._stream = stream\n self._console = console\n self._prefix = prefix\n self._config_tree_item = config_tree_item\n self._data_tree_item = data_tree_item\n\n self._buffer = b''\n self._serial_state = self.STATE_LINE\n self._telemetry_records = {}\n self._schema_name = None\n self._config_tree_items = {}\n self._config_callback = None\n\n self._start_time = None\n\n def start(self):\n # Stop the spew.\n self._stream.write('\\r\\n'.encode('latin1'))\n self._stream.write('tel stop\\r\\n'.encode('latin1'))\n\n # We want to wait a little bit, discard everything we have\n # received, and then initialize the device.\n self._start_time = time.time()\n\n def _setup_device(self, callback):\n # When we start, get a listing of all configuration options\n # and all available telemetry channels.\n def after_config():\n self.update_telemetry(callback)\n self.update_config(after_config)\n\n def poll(self):\n self._stream.poll()\n\n if self._start_time is not None:\n now = time.time()\n if now - self._start_time < 0.2:\n return\n # Discard any junk that may be there.\n self._stream.read(8192)\n self._start_time = None\n\n self._setup_device(None)\n\n\n data = self._stream.read(8192)\n\n self._buffer += data\n\n while True:\n old_len = len(self._buffer)\n self._handle_serial_data()\n if len(self._buffer) == old_len:\n break\n\n self._stream.flush()\n\n def write(self, data):\n self._stream.write(data)\n\n def config_item_changed(self, name, value):\n if self._serial_state == self.STATE_CONFIG:\n return\n\n self.write_line('conf set %s %s\\r\\n' % (name, value))\n\n def _handle_serial_data(self):\n if self._serial_state == self.STATE_LINE:\n self._handle_serial_line()\n elif self._serial_state == self.STATE_CONFIG:\n self._handle_config()\n elif self._serial_state == self.STATE_TELEMETRY:\n self._handle_telemetry()\n elif self._serial_state == self.STATE_SCHEMA:\n self._handle_schema()\n elif self._serial_state == self.STATE_DATA:\n self._handle_data()\n else:\n assert False\n\n def _handle_serial_line(self):\n line = self._get_serial_line()\n if line is None:\n return\n\n line = line.decode('latin1')\n\n display = True\n if line == '':\n display = False\n\n if line.startswith('schema '):\n self._serial_state = self.STATE_SCHEMA\n self._schema_name = line.split(' ', 1)[1].strip()\n elif line.startswith('emit '):\n self._serial_state = self.STATE_DATA\n self._schema_name = line.split(' ', 1)[1].strip()\n display = False\n\n if display:\n self._console.add_text(self._prefix + line + '\\n')\n\n def _get_serial_line(self):\n # Consume any newlines at the start of our buffer.\n pos = 0\n while pos < len(self._buffer) and self._buffer[pos] in b'\\r\\n':\n pos += 1\n self._buffer = self._buffer[pos:]\n\n # Look for a trailing newline\n end = 0\n while end < len(self._buffer) and self._buffer[end] not in b'\\r\\n':\n end += 1\n\n if end >= len(self._buffer):\n return\n\n line, self._buffer = self._buffer[:end], self._buffer[end+1:]\n\n return line\n\n def update_config(self, callback):\n # Clear out our config tree.\n self._config_tree_item.takeChildren()\n self._config_tree_items = {}\n\n self._config_callback = callback\n self.write_line('conf enumerate\\r\\n')\n\n # TODO jpieper: In the current protocol this is racy, as there\n # is no header on the config enumeration. I should probably\n # add one.\n self._serial_state = self.STATE_CONFIG\n\n def _handle_config(self):\n line = self._get_serial_line()\n if not line:\n return\n\n line = line.decode('latin1')\n self._console.add_text(self._prefix + line + '\\n')\n\n if line.startswith('OK'):\n # We're done with config now.\n self._serial_state = self.STATE_LINE\n cbk, self._config_callback = self._config_callback, None\n if cbk:\n cbk()\n else:\n # Add it into our tree view.\n key, value = line.split(' ', 1)\n name, rest = key.split('.', 1)\n if name not in self._config_tree_items:\n item = QtGui.QTreeWidgetItem(self._config_tree_item)\n item.setText(0, name)\n self._config_tree_items[name] = item\n\n def add_config(item, key, value):\n if key == '':\n item.setText(1, value)\n item.setFlags(QtCore.Qt.ItemIsEditable |\n QtCore.Qt.ItemIsSelectable |\n QtCore.Qt.ItemIsEnabled)\n return\n\n fields = key.split('.', 1)\n this_field = fields[0]\n next_key = ''\n if len(fields) > 1:\n next_key = fields[1]\n\n child = None\n # See if we already have an appropriate child.\n for i in range(item.childCount()):\n if item.child(i).text(0) == this_field:\n child = item.child(i)\n break\n if child is None:\n child = QtGui.QTreeWidgetItem(item)\n child.setText(0, this_field)\n add_config(child, next_key, value)\n\n add_config(self._config_tree_items[name], rest, value)\n\n # TODO(jpieper)\n # self.ui.configTreeWidget.resizeColumnToContents(0)\n\n def update_telemetry(self, callback):\n self._data_tree_item.takeChildren()\n self._telemetry_records = {}\n\n self._telemetry_callback = callback\n self.write_line('tel list\\r\\n')\n\n self._serial_state = self.STATE_TELEMETRY\n\n def write_line(self, line):\n self._console.add_text(self._prefix + line)\n self._stream.write(line.encode('latin1'))\n\n def _handle_telemetry(self):\n line = self._get_serial_line()\n if not line:\n return\n\n line = line.decode('latin1')\n self._console.add_text(self._prefix + line + '\\n')\n\n if line.startswith('OK'):\n # Now we need to start getting schemas.\n self._serial_state = self.STATE_LINE\n self._update_schema()\n else:\n name = line.strip()\n self._telemetry_records[name] = None\n\n def _update_schema(self):\n # Find a channel we don't have a schema for and request it.\n for name in self._telemetry_records.keys():\n if self._telemetry_records[name] is None:\n self.write_line('tel schema %s\\r\\n' % name)\n self._serial_state = self.STATE_LINE\n return\n\n self._serial_state = self.STATE_LINE\n # Guess we are done. Update our tree view.\n\n # TODO(jpieper)\n # self.ui.telemetryTreeWidget.resizeColumnToContents(0)\n\n cbk, self._telemetry_callback = self._telemetry_callback, None\n if cbk:\n cbk()\n\n def _handle_schema(self):\n schema = self._handle_sized_block()\n if not schema:\n return\n\n name, self._schema_name = self._schema_name, None\n\n if name in self._telemetry_records:\n if self._telemetry_records[name]:\n return\n\n archive = reader.Type.from_binary(io.BytesIO(schema), name=name)\n\n record = Record(archive)\n self._telemetry_records[name] = record\n record.tree_item = self._add_schema_to_tree(name, archive, record)\n\n self._console.add_text(self._prefix + '\\n' % name)\n\n # Now look to see if there are any more we should request.\n self._update_schema()\n\n def _handle_data(self):\n data = self._handle_sized_block()\n if not data:\n return\n\n name, self._schema_name = self._schema_name, None\n\n if name not in self._telemetry_records:\n return\n\n record = self._telemetry_records[name]\n if record:\n struct = record.archive.read(reader.Stream(io.BytesIO(data)))\n record.update(struct)\n _set_tree_widget_data(record.tree_item, struct)\n\n self._serial_state = self.STATE_LINE\n\n def _handle_sized_block(self):\n # Wait until we have the complete schema in the buffer. It\n # will start with the final newline from the first line.\n if len(self._buffer) < 5:\n return\n\n size = struct.unpack(' 2 ** 24:\n # Whoops, probably bogus.\n print('Invalid schema size, skipping whatever we were doing.')\n self._serial_state = self.STATE_LINE\n return\n\n if len(self._buffer) < 5 + size:\n return\n\n block = self._buffer[5:5+size]\n self._buffer = self._buffer[5+size:]\n return block\n\n class Schema:\n def __init__(self, name, parent, record):\n self._name = name\n self._parent = parent\n self.record = record\n\n def expand(self):\n self._parent.write_line('tel fmt %s 0\\r\\n' % self._name)\n self._parent.write_line('tel rate %s %d\\r\\n' %\n (self._name, DEFAULT_RATE))\n\n def collapse(self):\n self._parent.write_line('tel rate %s 0\\r\\n' % self._name)\n\n\n def _add_schema_to_tree(self, name, schema_data, record):\n item = QtGui.QTreeWidgetItem(self._data_tree_item)\n item.setText(0, name)\n\n schema = Device.Schema(name, self, record)\n item.setData(0, QtCore.Qt.UserRole, schema)\n\n def add_item(parent, element):\n if isinstance(element, reader.ObjectType):\n for field in element.fields:\n name = field.name\n\n item = QtGui.QTreeWidgetItem(parent)\n item.setText(0, name)\n\n add_item(item, field.type_class)\n\n add_item(item, schema_data)\n return item\n\n\nclass TviewMainWindow():\n def __init__(self, options, parent=None):\n self.options = options\n self.port = None\n self.devices = []\n self.default_rate = 100\n\n self._serial_timer = QtCore.QTimer()\n self._serial_timer.timeout.connect(self._poll_serial)\n self._serial_timer.start(10)\n\n r = runfiles.Create()\n uifilename = r.Rlocation(\n \"com_github_mjbots_moteus/utils/tview_main_window.ui\")\n loader = QtUiTools.QUiLoader()\n uifile = QtCore.QFile(uifilename)\n uifile.open(QtCore.QFile.ReadOnly)\n self.ui = loader.load(uifile, parent)\n uifile.close()\n\n self.ui.configTreeWidget = SizedTreeWidget()\n self.ui.configDock.setWidget(self.ui.configTreeWidget)\n\n self.ui.telemetryTreeWidget = SizedTreeWidget()\n self.ui.telemetryDock.setWidget(self.ui.telemetryTreeWidget)\n\n self.ui.telemetryTreeWidget.itemExpanded.connect(\n self._handle_tree_expanded)\n self.ui.telemetryTreeWidget.itemCollapsed.connect(\n self._handle_tree_collapsed)\n self.ui.telemetryTreeWidget.setContextMenuPolicy(\n QtCore.Qt.CustomContextMenu)\n self.ui.telemetryTreeWidget.customContextMenuRequested.connect(\n self._handle_telemetry_context_menu)\n\n self.ui.configTreeWidget.setItemDelegateForColumn(\n 0, NoEditDelegate(self.ui))\n self.ui.configTreeWidget.itemExpanded.connect(\n self._handle_config_expanded)\n self.ui.configTreeWidget.itemChanged.connect(\n self._handle_config_item_changed)\n\n self.ui.plotItemRemoveButton.clicked.connect(\n self._handle_plot_item_remove)\n\n self.console = TviewConsoleWidget()\n self.console.ansi_codes = False\n self.console.line_input.connect(self._handle_user_input)\n self.ui.consoleDock.setWidget(self.console)\n\n self.ui.tabifyDockWidget(self.ui.configDock, self.ui.telemetryDock)\n\n layout = QtGui.QVBoxLayout(self.ui.plotHolderWidget)\n layout.setContentsMargins(0, 0, 0, 0)\n layout.setSpacing(0)\n self.ui.plotHolderWidget.setLayout(layout)\n self.ui.plotWidget = PlotWidget(self.ui.plotHolderWidget)\n layout.addWidget(self.ui.plotWidget)\n\n def update_plotwidget(value):\n self.ui.plotWidget.history_s = value\n self.ui.historySpin.valueChanged.connect(update_plotwidget)\n\n QtCore.QTimer.singleShot(0, self._handle_startup)\n\n def show(self):\n self.ui.show()\n\n def _open(self):\n if self.options.target:\n target_fields = self.options.target.split(':')\n try:\n port = NetworkPort(socket.create_connection(\n (target_fields[0], int(target_fields[1])), timeout=2.0))\n except OSError:\n print(\"could not connect to: \", self.options.target)\n exit(1)\n self.port = BufferedSerial(port)\n else:\n self.port = BufferedSerial(serial.Serial(\n port=self.options.serial,\n baudrate=self.options.baudrate,\n timeout=0.0))\n\n self.devices = []\n self.ui.configTreeWidget.clear()\n self.ui.telemetryTreeWidget.clear()\n\n for device_id in [int(x) for x in self.options.devices.split(',')]:\n if self.options.rs485:\n stream = MultiplexStream(\n self.port, device_id, self.options.max_receive_bytes)\n else:\n stream = FdcanUsbStream(\n self.port, device_id, self.options.max_receive_bytes)\n\n config_item = QtGui.QTreeWidgetItem()\n config_item.setText(0, str(device_id))\n self.ui.configTreeWidget.addTopLevelItem(config_item)\n\n data_item = QtGui.QTreeWidgetItem()\n data_item.setText(0, str(device_id))\n self.ui.telemetryTreeWidget.addTopLevelItem(data_item)\n\n device = Device(device_id, stream,\n self.console, '{}>'.format(device_id),\n config_item,\n data_item)\n\n config_item.setData(0, QtCore.Qt.UserRole, device)\n device.start()\n\n self.devices.append(device)\n\n def _handle_startup(self):\n self.console._control.setFocus()\n\n def _poll_serial(self):\n if self.port is None:\n if os.path.exists(self.options.serial) or self.options.target:\n self._open()\n else:\n return\n else:\n [x.poll() for x in self.devices]\n\n def make_writer(self, devices, line):\n def write():\n for device in devices:\n device.write((line + '\\n').encode('latin1'))\n\n return write\n\n def _handle_user_input(self, line):\n device_lines = [x.strip() for x in line.split('&&')]\n now = time.time()\n current_delay_ms = 0\n for line in device_lines:\n delay_re = re.search(r\"^:(\\d+)$\", line)\n device_re = re.search(r\"^(A|\\d+)>(.*)$\", line)\n if delay_re:\n current_delay_ms += int(delay_re.group(1))\n continue\n elif device_re:\n if device_re.group(1) == 'A':\n device_nums = [x.number for x in self.devices]\n else:\n device_nums = [int(device_re.group(1))]\n line = device_re.group(2)\n else:\n device_nums = [self.devices[0].number]\n devices = [x for x in self.devices if x.number in device_nums]\n writer = self.make_writer(devices, line)\n\n if current_delay_ms > 0:\n QtCore.QTimer.singleShot(current_delay_ms, writer)\n else:\n writer()\n\n def _handle_tree_expanded(self, item):\n self.ui.telemetryTreeWidget.resizeColumnToContents(0)\n user_data = item.data(0, QtCore.Qt.UserRole)\n if user_data:\n user_data.expand()\n\n def _handle_tree_collapsed(self, item):\n user_data = item.data(0, QtCore.Qt.UserRole)\n if user_data:\n user_data.collapse()\n\n def _handle_telemetry_context_menu(self, pos):\n item = self.ui.telemetryTreeWidget.itemAt(pos)\n if item.childCount() > 0:\n return\n\n menu = QtGui.QMenu(self.ui)\n left_action = menu.addAction('Plot Left')\n right_action = menu.addAction('Plot Right')\n left_std_action = menu.addAction('Plot StdDev Left')\n right_std_action = menu.addAction('Plot StdDev Right')\n left_mean_action = menu.addAction('Plot Mean Left')\n right_mean_action = menu.addAction('Plot Mean Right')\n\n plot_actions = [\n left_action,\n right_action,\n left_std_action,\n right_std_action,\n left_mean_action,\n right_mean_action,\n ]\n\n right_actions = [right_action, right_std_action, right_mean_action]\n std_actions = [left_std_action, right_std_action]\n mean_actions = [left_mean_action, right_mean_action]\n\n menu.addSeparator()\n copy_name = menu.addAction('Copy Name')\n copy_value = menu.addAction('Copy Value')\n\n requested = menu.exec_(self.ui.telemetryTreeWidget.mapToGlobal(pos))\n\n if requested in plot_actions:\n top = item\n while top.parent().parent():\n top = top.parent()\n\n schema = top.data(0, QtCore.Qt.UserRole)\n record = schema.record\n\n name = _get_item_name(item)\n root = _get_item_root(item)\n\n leaf = name.split('.', 1)[1]\n axis = 0\n if requested in right_actions:\n axis = 1\n\n if requested in std_actions:\n leaf = '__STDDEV_' + leaf\n name = 'stddev ' + name\n\n if requested in mean_actions:\n leaf = '__MEAN_' + leaf\n name = 'mean ' + name\n\n plot_item = self.ui.plotWidget.add_plot(\n name, record.get_signal(leaf), axis)\n self.ui.plotItemCombo.addItem(name, plot_item)\n elif requested == copy_name:\n QtGui.QApplication.clipboard().setText(item.text(0))\n elif requested == copy_value:\n QtGui.QApplication.clipboard().setText(item.text(1))\n else:\n # The user cancelled.\n pass\n\n def _handle_config_expanded(self, item):\n self.ui.configTreeWidget.resizeColumnToContents(0)\n\n def _handle_config_item_changed(self, item, column):\n if not item.parent():\n return\n\n top = item\n while top.parent():\n top = top.parent()\n\n device = top.data(0, QtCore.Qt.UserRole)\n device.config_item_changed(_get_item_name(item), item.text(1))\n\n def _handle_plot_item_remove(self):\n index = self.ui.plotItemCombo.currentIndex()\n\n if index < 0:\n return\n\n item = self.ui.plotItemCombo.itemData(index)\n self.ui.plotWidget.remove_plot(item)\n self.ui.plotItemCombo.removeItem(index)\n\n\ndef main():\n usage, description = __doc__.split('\\n\\n', 1)\n parser = optparse.OptionParser(usage=usage, description=description)\n\n parser.add_option('--serial', '-s', default='/dev/ttyACM0')\n parser.add_option('--baudrate', '-b', type='int', default=115200)\n parser.add_option('--devices', '-d', type='str', default='1')\n parser.add_option('--target', '-t', default=None)\n parser.add_option('--rs485', '-c', action='store_true')\n parser.add_option('--max-receive-bytes', default=127, type=int)\n\n options, args = parser.parse_args()\n assert len(args) == 0\n\n app = QtGui.QApplication(sys.argv)\n\n # To work around https://bugreports.qt.io/browse/PYSIDE-88\n app.aboutToQuit.connect(lambda: os._exit(0))\n\n tv = TviewMainWindow(options)\n tv.show()\n\n app.exec_()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/tview.py","file_name":"tview.py","file_ext":"py","file_size_in_byte":39735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"122517743","text":"from flask import Flask, jsonify, request\nfrom flask_cors import CORS\n\n\nTA = [\n {\n 'id': 1,\n 'name': 'Rishabh',\n 'time': 'Monday 9 am - 11 am EST'\n },\n {\n 'id': 2,\n 'name': 'Goutham',\n 'time': 'Friday 4 pm - 6 pm EST'\n },\n {\n 'id': 3,\n 'name': 'Hyun',\n 'time': 'Thursday 3 pm - 5 pm EST'\n },\n {\n 'id': 4,\n 'name': 'Reshma',\n 'time': 'Tuesday 2 pm to 4 pm EST '\n }\n]\n\n# configuration\nDEBUG = True\n\n# instantiate the app\napplication = Flask(__name__)\napplication.config.from_object(__name__)\n\n# enable CORS\nCORS(application, resources={r'/*': {'origins': '*'}})\n\n\n@application.route('/', methods=['GET'])\ndef hello_world():\n return jsonify('hello_world!')\n\n\n@application.route('/ta', methods=['GET'])\ndef all_tas():\n response_object = {'status': 'success'}\n if request.method == 'GET':\n response_object['ta'] = TA\n \n return jsonify(response_object)\n\n@application.route('/ta/', methods=['GET'])\ndef ta(ta_id):\n response_object = {'status': 'success'}\n if request.method == 'GET':\n found_ta = False\n for ta in TA:\n try:\n if int(ta['id']) == int(ta_id):\n response_object['ta'] = ta\n found_ta = True\n except:\n found_ta = False \n\n if not found_ta:\n response_message = 'No TA present with TA ID ' + str(ta_id)\n response_object = {'status': 'success', 'message': response_message}\n \n return jsonify(response_object)\n\n\n\nif __name__ == '__main__':\n application.debug = True\n application.run()","sub_path":"server/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"74632905","text":"def ease_array(nums):\n\tll = len(nums)\n\n\tfor k in range(ll-1):\n\t\tif nums[k+1]!=0 and nums[k]==nums[k+1]:\n\t\t\tnums[k]=nums[k]*2\n\t\t\tnums[k+1]=0\n\n\ti,j = 0, 0\n\tfor k in range(ll):\n\t\tif nums[k]==0:\n\t\t\tj+=1\n\t\telse:\n\t\t\tnums[i]=nums[j]\n\t\t\tj+=1 \n\t\t\ti+=1\n\t\t\n\twhile(i 0\n\n api_users = list(api_client.users)\n assert sorted(api_users) == sorted(real_users)\n\n\ndef test_get_user(api_client): # noqa: F811\n user = api_client.users.get(\"cbguder@a.co\")\n assert sorted(user.groups) == [\"group-admins\", \"permission-admins\", \"user-admins\"]\n assert user.passwords == []\n assert user.public_keys == []\n assert user.enabled\n assert user.service_account is None\n\n perms = [(p.permission, p.argument) for p in user.permissions]\n assert sorted(perms) == [(GROUP_ADMIN, \"\"), (PERMISSION_ADMIN, \"\"), (USER_ADMIN, \"\")]\n\n assert user.metadata == {}\n","sub_path":"itests/api/users_test.py","file_name":"users_test.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"564424604","text":"from __future__ import division\n\nimport uuid\nimport torch\nfrom torch.nn import Linear\nfrom torch.optim import SGD\nfrom torch.autograd import Variable\nfrom torch.nn.functional import mse_loss\nimport numpy as np\nfrom mock import call, MagicMock, Mock\nfrom pytest import raises, approx\n\nfrom ignite.trainer import Trainer, TrainingEvents, create_supervised\n\n\nclass _PicklableMagicMock(object):\n def __init__(self):\n self.uuid = str(uuid.uuid4())\n self.mock = MagicMock()\n\n def __getstate__(self):\n return {key: self.__dict__[key] for key in self.__dict__ if key != \"mock\"}\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n\n def __getattr__(self, item):\n return _PicklableMagicMock()\n\n def __call__(self, *args, **kwargs):\n return _PicklableMagicMock()\n\n def __iter__(self):\n return iter([_PicklableMagicMock()])\n\n def __eq__(self, other):\n return other.uuid == self.uuid\n\n def __repr__(self):\n return self.uuid\n\n\ndef test_adding_handler_for_non_existent_event_throws_error():\n trainer = Trainer(MagicMock(), MagicMock())\n\n event_name = uuid.uuid4()\n while event_name in TrainingEvents.__members__.values():\n event_name = uuid.uuid4()\n\n with raises(ValueError):\n trainer.add_event_handler(event_name, lambda x: x)\n\n\ndef test_exception_handler_called_on_error():\n training_update_function = MagicMock(side_effect=ValueError())\n\n trainer = Trainer(training_update_function, MagicMock())\n exception_handler = MagicMock()\n trainer.add_event_handler(TrainingEvents.EXCEPTION_RAISED, exception_handler)\n\n with raises(ValueError):\n trainer.run([1])\n\n exception_handler.assert_called_once_with(trainer)\n\n\ndef test_adding_multiple_event_handlers():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n handlers = [MagicMock(), MagicMock()]\n for handler in handlers:\n trainer.add_event_handler(TrainingEvents.TRAINING_STARTED, handler)\n\n trainer.run([1])\n for handler in handlers:\n handler.assert_called_once_with(trainer)\n\n\ndef test_args_and_kwargs_are_passed_to_event():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n kwargs = {'a': 'a', 'b': 'b'}\n args = (1, 2, 3)\n handlers = []\n for event in TrainingEvents:\n handler = MagicMock()\n trainer.add_event_handler(event, handler, *args, **kwargs)\n handlers.append(handler)\n\n trainer.run([1], max_epochs=1)\n called_handlers = [handle for handle in handlers if handle.called]\n assert len(called_handlers) > 0\n\n for handler in called_handlers:\n handler_args, handler_kwargs = handler.call_args\n assert handler_args[0] == trainer\n assert handler_args[1::] == args\n assert handler_kwargs == kwargs\n\n\ndef test_current_epoch_counter_increases_every_epoch():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n max_epochs = 5\n\n class EpochCounter(object):\n def __init__(self):\n self.current_epoch_count = 0\n\n def __call__(self, trainer):\n assert trainer.current_epoch == self.current_epoch_count\n self.current_epoch_count += 1\n\n trainer.add_event_handler(TrainingEvents.EPOCH_STARTED, EpochCounter())\n\n trainer.run([1], max_epochs=max_epochs)\n\n assert trainer.current_epoch == max_epochs\n\n\ndef test_current_iteration_counter_increases_every_iteration():\n training_batches = [1, 2, 3]\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n max_epochs = 5\n\n class IterationCounter(object):\n def __init__(self):\n self.current_iteration_count = 0\n\n def __call__(self, trainer):\n assert trainer.current_iteration == self.current_iteration_count\n self.current_iteration_count += 1\n\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_STARTED, IterationCounter())\n\n trainer.run(training_batches, max_epochs=max_epochs)\n\n assert trainer.current_iteration == max_epochs * len(training_batches)\n\n\ndef _validate(trainer, validation_data):\n trainer.validate(validation_data)\n\n\ndef test_current_validation_iteration_counter_increases_every_iteration():\n validation_batches = [1, 2, 3]\n trainer = Trainer(MagicMock(return_value=1), MagicMock(return_value=1))\n max_epochs = 5\n\n class IterationCounter(object):\n def __init__(self):\n self.current_iteration_count = 0\n self.total_count = 0\n\n def __call__(self, trainer):\n assert trainer.current_validation_iteration == self.current_iteration_count\n self.current_iteration_count += 1\n self.total_count += 1\n\n def clear(self):\n self.current_iteration_count = 0\n\n iteration_counter = IterationCounter()\n\n def clear_counter(trainer, counter):\n counter.clear()\n\n trainer.add_event_handler(TrainingEvents.TRAINING_EPOCH_COMPLETED, _validate, validation_batches)\n trainer.add_event_handler(TrainingEvents.VALIDATION_STARTING, clear_counter, iteration_counter)\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_STARTED, iteration_counter)\n\n trainer.run([1], max_epochs=max_epochs)\n assert iteration_counter.total_count == max_epochs * len(validation_batches)\n\n\ndef test_validate_is_not_called_by_default():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n trainer.validate = MagicMock()\n\n max_epochs = 5\n trainer.run([1], max_epochs=max_epochs)\n assert trainer.validate.call_count == 0\n\n\ndef test_stopping_criterion_is_max_epochs():\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n max_epochs = 5\n trainer.run([1], max_epochs=max_epochs)\n assert trainer.current_epoch == max_epochs\n\n\ndef test_terminate_at_end_of_epoch_stops_training():\n max_epochs = 5\n last_epoch_to_run = 3\n\n def end_of_epoch_handler(trainer):\n if trainer.current_epoch == last_epoch_to_run:\n trainer.terminate()\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n trainer.add_event_handler(TrainingEvents.EPOCH_COMPLETED, end_of_epoch_handler)\n\n assert not trainer.should_terminate\n\n trainer.run([1], max_epochs=max_epochs)\n\n assert trainer.current_epoch == last_epoch_to_run + 1 # counter is incremented at end of loop\n assert trainer.should_terminate\n\n\ndef test_terminate_at_start_of_epoch_stops_training_after_completing_iteration():\n max_epochs = 5\n epoch_to_terminate_on = 3\n batches_per_epoch = [1, 2, 3]\n\n def start_of_epoch_handler(trainer):\n if trainer.current_epoch == epoch_to_terminate_on:\n trainer.terminate()\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n trainer.add_event_handler(TrainingEvents.EPOCH_STARTED, start_of_epoch_handler)\n\n assert not trainer.should_terminate\n\n trainer.run(batches_per_epoch, max_epochs=max_epochs)\n\n # epoch is not completed so counter is not incremented\n assert trainer.current_epoch == epoch_to_terminate_on\n assert trainer.should_terminate\n # completes first iteration\n assert trainer.current_iteration == (epoch_to_terminate_on * len(batches_per_epoch)) + 1\n\n\ndef test_terminate_stops_training_mid_epoch():\n num_iterations_per_epoch = 10\n iteration_to_stop = num_iterations_per_epoch + 3 # i.e. part way through the 2nd epoch\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n\n def end_of_iteration_handler(trainer):\n if trainer.current_iteration == iteration_to_stop:\n trainer.terminate()\n\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_STARTED, end_of_iteration_handler)\n trainer.run(training_data=[None] * num_iterations_per_epoch, max_epochs=3)\n assert (trainer.current_iteration == iteration_to_stop +\n 1) # completes the iteration when terminate called\n assert trainer.current_epoch == np.ceil(\n iteration_to_stop / num_iterations_per_epoch) - 1 # it starts from 0\n\n\ndef test_terminate_stops_trainer_when_called_during_validation():\n num_iterations_per_epoch = 10\n iteration_to_stop = 3 # i.e. part way through the 2nd validation run\n epoch_to_stop = 2\n trainer = Trainer(MagicMock(return_value=1), MagicMock(return_value=1))\n\n def end_of_iteration_handler(trainer):\n if (trainer.current_epoch == epoch_to_stop and trainer.current_validation_iteration == iteration_to_stop):\n\n trainer.terminate()\n\n trainer.add_event_handler(TrainingEvents.TRAINING_EPOCH_COMPLETED, _validate, [None] * num_iterations_per_epoch)\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_STARTED, end_of_iteration_handler)\n trainer.run([None] * num_iterations_per_epoch, max_epochs=4)\n\n assert trainer.current_epoch == epoch_to_stop\n # should complete the iteration when terminate called\n assert trainer.current_validation_iteration == iteration_to_stop + 1\n assert trainer.current_iteration == (epoch_to_stop + 1) * num_iterations_per_epoch\n\n\ndef test_terminate_after_training_iteration_skips_validation_run():\n num_iterations_per_epoch = 10\n iteration_to_stop = num_iterations_per_epoch - 1\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n\n def end_of_iteration_handler(trainer):\n if trainer.current_iteration == iteration_to_stop:\n trainer.terminate()\n\n trainer.validate = MagicMock()\n\n trainer.add_event_handler(TrainingEvents.TRAINING_EPOCH_COMPLETED, _validate, MagicMock())\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_STARTED, end_of_iteration_handler)\n trainer.run([None] * num_iterations_per_epoch, max_epochs=3)\n assert trainer.validate.call_count == 0\n\n\ndef _create_mock_data_loader(epochs, batches_per_epoch):\n batches = [MagicMock()] * batches_per_epoch\n data_loader_manager = MagicMock()\n batch_iterators = [iter(batches) for _ in range(epochs)]\n\n data_loader_manager.__iter__.side_effect = batch_iterators\n\n return data_loader_manager\n\n\ndef test_training_iteration_events_are_fired():\n max_epochs = 5\n num_batches = 3\n training_data = _create_mock_data_loader(max_epochs, num_batches)\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n\n mock_manager = Mock()\n iteration_started = Mock()\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_STARTED, iteration_started)\n\n iteration_complete = Mock()\n trainer.add_event_handler(TrainingEvents.TRAINING_ITERATION_COMPLETED, iteration_complete)\n\n mock_manager.attach_mock(iteration_started, 'iteration_started')\n mock_manager.attach_mock(iteration_complete, 'iteration_complete')\n\n trainer.run(training_data, max_epochs=max_epochs)\n\n assert iteration_started.call_count == num_batches * max_epochs\n assert iteration_complete.call_count == num_batches * max_epochs\n\n expected_calls = []\n for i in range(max_epochs * num_batches):\n expected_calls.append(call.iteration_started(trainer))\n expected_calls.append(call.iteration_complete(trainer))\n\n assert mock_manager.mock_calls == expected_calls\n\n\ndef test_validation_iteration_events_are_fired():\n max_epochs = 5\n num_batches = 3\n validation_data = _create_mock_data_loader(max_epochs, num_batches)\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock(return_value=1))\n\n mock_manager = Mock()\n iteration_started = Mock()\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_STARTED, iteration_started)\n\n iteration_complete = Mock()\n trainer.add_event_handler(TrainingEvents.TRAINING_EPOCH_COMPLETED, _validate, validation_data)\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_COMPLETED, iteration_complete)\n\n mock_manager.attach_mock(iteration_started, 'iteration_started')\n mock_manager.attach_mock(iteration_complete, 'iteration_complete')\n\n trainer.run([None], max_epochs=max_epochs)\n\n assert iteration_started.call_count == num_batches * max_epochs\n assert iteration_complete.call_count == num_batches * max_epochs\n\n expected_calls = []\n for i in range(max_epochs * num_batches):\n expected_calls.append(call.iteration_started(trainer))\n expected_calls.append(call.iteration_complete(trainer))\n\n assert mock_manager.mock_calls == expected_calls\n\n\ndef test_validation_iteration_events_are_fired_when_validate_is_called_explicitly():\n max_epochs = 5\n num_batches = 3\n validation_data = _create_mock_data_loader(max_epochs, num_batches)\n\n trainer = Trainer(MagicMock(), MagicMock(return_value=1))\n\n mock_manager = Mock()\n iteration_started = Mock()\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_STARTED, iteration_started)\n\n iteration_complete = Mock()\n trainer.add_event_handler(TrainingEvents.VALIDATION_ITERATION_COMPLETED, iteration_complete)\n\n mock_manager.attach_mock(iteration_started, 'iteration_started')\n mock_manager.attach_mock(iteration_complete, 'iteration_complete')\n\n assert iteration_started.call_count == 0\n assert iteration_complete.call_count == 0\n\n trainer.validate(validation_data)\n\n assert iteration_started.call_count == num_batches\n assert iteration_complete.call_count == num_batches\n\n # TODO add test to assure history is written to from trainer\n\n\ndef test_create_supervised():\n model = Linear(1, 1)\n model.weight.data.zero_()\n model.bias.data.zero_()\n optimizer = SGD(model.parameters(), 0.1)\n trainer = create_supervised(model, optimizer, mse_loss)\n\n x = torch.FloatTensor([[1.0], [2.0]])\n y = torch.FloatTensor([[3.0], [5.0]])\n data = [(x, y)]\n\n trainer.validate(data)\n y_pred, y = trainer.validation_history[0]\n\n assert y_pred[0, 0] == approx(0.0)\n assert y_pred[1, 0] == approx(0.0)\n assert y[0, 0] == approx(3.0)\n assert y[1, 0] == approx(5.0)\n\n assert model.weight.data[0, 0] == approx(0.0)\n assert model.bias.data[0] == approx(0.0)\n\n trainer.run(data)\n loss = trainer.training_history[0]\n\n assert loss == approx(17.0)\n assert model.weight.data[0, 0] == approx(1.3)\n assert model.bias.data[0] == approx(0.8)\n\n\ndef test_on_decorator():\n max_epochs = 5\n num_batches = 3\n training_data = _create_mock_data_loader(max_epochs, num_batches)\n\n trainer = Trainer(MagicMock(return_value=1), MagicMock())\n\n class Counter(object):\n def __init__(self, count=0):\n self.count = count\n\n started_counter = Counter()\n\n @trainer.on(TrainingEvents.TRAINING_ITERATION_STARTED, started_counter)\n def handle_training_iteration_started(trainer, started_counter):\n started_counter.count += 1\n\n completed_counter = Counter()\n\n @trainer.on(TrainingEvents.TRAINING_ITERATION_COMPLETED, completed_counter)\n def handle_training_iteration_completed(trainer, completed_counter):\n completed_counter.count += 1\n\n trainer.run(training_data, max_epochs=max_epochs)\n\n assert started_counter.count == 15\n assert completed_counter.count == 15\n","sub_path":"tests/ignite/trainer/test_trainer.py","file_name":"test_trainer.py","file_ext":"py","file_size_in_byte":14974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"449919675","text":"import flask_restful\nfrom database import engine\nfrom flask import Response, request\nfrom api.models.m_ph import PHMeasuredValM\nfrom database import engine, db_session\nfrom api.models.m_projezd import ZakladniProjezd\nfrom flask import Response, request, make_response, jsonify\nimport pandas as pd\nfrom datetime import datetime\nimport time\n\n'''\nNáhrada tabulky vyhodnocení provoz\n'''\n\nclass PhNote(flask_restful.Resource):\n def put(self, id):\n ph = PHMeasuredValM.query.filter_by(id = id).first()\n ph.note = request.get_json()['note']\n db_session.commit()\n return make_response()\n\n# GET http://localhost:5000/api/ph/seznam//\nclass PhVyhodnoceniProvoz(flask_restful.Resource):\n def get(self, rok, kgjId = None):\n\n\n sql = \"select kmmv.id_kgj as id_kgj, \" \\\n \"nazev, \" \\\n \"year(from_unixtime(kmmv.date_record)) as year, \" \\\n \"month(from_unixtime(kmmv.date_record)) as month, \" \\\n \"mth_poc, \" \\\n \"v_tep_so, \" \\\n \"v_tep_to, \" \\\n \"v_el_celkem, \" \\\n \"ph_m_ote_el.ote_el_dodavka, \" \\\n \"ph_m_ote_el.ote_el_odber, \" \\\n \"s_el_vskjchod, \" \\\n \"ifnull(spaltep_distrib, 10.67) as spaltep_distrib, \" \\\n \"s_ply_mer_kgj_m3 \" \\\n \"from ph_m_measured_val kmmv \" \\\n \"left outer join kgj_cons as kk on kmmv.id_kgj = kk.id \" \\\n \"left outer join ph_m_ote_el on kmmv.id_kgj = ph_m_ote_el.id_kgj and kmmv.date_record = ph_m_ote_el.date_record \" \\\n \"left join ph_m_spal_tep on kk.id_distrib_obl_ply = ph_m_spal_tep.id_distrib_obl and ph_m_spal_tep.date_record = kmmv.date_record\"\n\n\n if kgjId != None and kgjId != 0:\n sql += \" where kmmv.id_kgj = %s order by year desc\" % (kgjId)\n else:\n sql += \" where year(from_unixtime(kmmv.date_record)) = %s order by nazev collate utf8_czech_ci\" % (rok)\n\n df = pd.read_sql(sql, engine)\n\n response = Response(response=df.to_json(orient='records'), status=200, mimetype=\"application/json\")\n # response = Response(status=200, mimetype=\"application/json\")\n return response\n\n\n'''\nTabulka přehled PH, zobrazování kopletní tabulky s daty exportovanými z PH do DB\n'''\n# GET http://localhost:5000/api/ph/dataview\nclass PhDataView(flask_restful.Resource):\n def get(self, year, month):\n global param\n kgj_id = str(request.args.get('id'))\n pwr_category = str(request.args.get('vykon'))\n rv_user_id = str(request.args.get('regVed'))\n\n print(year, month)\n if not kgj_id:\n kgj_id = '0'\n\n # Selecting power category\n if pwr_category != '0':\n pwr_cat_f = pwr_category_select(int(pwr_category))[0]\n pwr_cat_l = pwr_category_select(int(pwr_category))[1]\n else:\n pwr_cat_f = 0\n pwr_cat_l = 0\n\n # Main decision script for Select boxes\n \"\"\" When month = 13 (all) select data from all year\"\"\"\n if month == '13':\n month = None\n if kgj_id == '0':\n if pwr_category == '0':\n if rv_user_id == '0':\n param = 0\n else:\n param = 2\n else:\n if rv_user_id == '0':\n param = 3\n else:\n param = 4\n else:\n param = 1\n\n if (month != '13' and month!= None):\n if kgj_id == '0':\n if pwr_category == '0':\n if rv_user_id == '0':\n param = 0\n else:\n param = 2\n else:\n if rv_user_id == '0':\n param = 3\n else:\n param = 4\n else:\n param = 1\n\n # SQL Builder\n sql = build_sql_query(kgj_id, year, month, rv_user_id, pwr_cat_f, pwr_cat_l, param)\n df = pd.read_sql(sql, engine)\n\n df['v_tep_celkem'] = df['v_tep_so'] + df['v_tep_to']\n try:\n df['n_ply_fakt_kgj_kwh'] = round(df['n_ply_fakt_kgj_m3'] * df['spaltep'] * 0.9, 0)\n except:\n try:\n df['n_ply_fakt_kgj_kwh'] = round(df['n_ply_fakt_kgj_m3'] * df['spaltep_distr'] * 0.9, 0)\n except:\n df['n_ply_fakt_kgj_kwh'] = df['n_ply_fakt_kgj_m3'].astype(float).round(0) * 0.9 * 10.67\n\n df['mth_ote'] = df['v_el_celkem'] / df['lic_el']\n df['mth_ote'] = df['mth_ote'].apply(pd.np.ceil)\n try:\n df['s_ply_mer_kgj_kwh'] = round(df['s_ply_mer_kgj_m3'] * df['spaltep'] * 0.9, 0)\n except:\n try:\n df['s_ply_mer_kgj_kwh'] = round(df['s_ply_mer_kgj_m3'] * df['spaltep_distr'] * 0.9, 0)\n except:\n df['s_ply_mer_kgj_kwh'] = df['s_ply_mer_kgj_m3'].astype(float).round(0) * 0.9 * 10.67\n\n response = Response(response=df.to_json(orient='records'), status=200, mimetype=\"application/json\")\n return response\n\n\n# Build SQL query based on selected parameter.\ndef build_sql_query(kgj_id, year, month, rv_id, pwr_cat_f, pwr_cat_l, param):\n global where_param\n sql = \"\"\"select ph_m_measured_val.*, \n concat_ws('-',\n LPAD(day(FROM_UNIXTIME(ph_m_measured_val.date_record)),2,0),\n LPAD(month(FROM_UNIXTIME(ph_m_measured_val.date_record)),2,0),\n year(FROM_UNIXTIME(ph_m_measured_val.date_record))) as date_record_r,\n concat(concat_ws('-',\n LPAD(day(FROM_UNIXTIME(ph_m_measured_val.timestamp)),2,0),\n LPAD(month(FROM_UNIXTIME(ph_m_measured_val.timestamp)),2,0),\n year(FROM_UNIXTIME(ph_m_measured_val.timestamp))),' ',\n concat_ws(':',\n LPAD(hour(FROM_UNIXTIME(ph_m_measured_val.timestamp)),2,0),\n LPAD(minute(FROM_UNIXTIME(ph_m_measured_val.timestamp)),2,0))) as timestamp_r, \n kk.nazev,\n kk.lic_el,\n ph_m_fakt_gas.f_plyn as n_ply_fakt_kgj_m3,\n ph_m_fakt_gas.f_spaltep as spaltep,\n ph_m_ote_el.ote_el_dodavka as p_el_ote,\n ph_m_ote_el.ote_el_odber as n_el_ote\n FROM ph_m_measured_val\n left join kgj_cons kk on kk.id = ph_m_measured_val.id_kgj\n left join ph_m_fakt_gas on ph_m_fakt_gas.id_kgj = ph_m_measured_val.id_kgj and ph_m_fakt_gas.date_record = ph_m_measured_val.date_record \n left join ph_m_ote_el on ph_m_ote_el.id_kgj = ph_m_measured_val.id_kgj and ph_m_ote_el.date_record = ph_m_measured_val.date_record\n left join ph_m_spal_tep on ph_m_spal_tep.id_distrib_obl = kk.id_distrib_obl_ply and ph_m_spal_tep.date_record = ph_m_measured_val.date_record \"\"\"\n\n # Sorting param\n sorting = ' order by kk.nazev collate utf8_czech_ci'\n\n # Date WHERE param selector\n if month == None:\n time_param = \"where year(FROM_UNIXTIME(ph_m_measured_val.date_record)) = {} \".format(year)\n\n else:\n time_param = \"where year(FROM_UNIXTIME(ph_m_measured_val.date_record)) = {} and month(FROM_UNIXTIME(ph_m_measured_val.date_record)) = {} \".format(\n year, month)\n\n\n # Selecting where param\n if param == 0:\n where_param = \"\"\n\n if param == 1:\n where_param = \"and kk.id = {}\".format(kgj_id)\n\n if param == 2:\n where_param = \"and kk.id_regio_vedouci = {}\".format(rv_id)\n\n if param == 3:\n where_param = \"and kk.inst_vykon >{} and kk.inst_vykon <= {}\".format(pwr_cat_f, pwr_cat_l)\n\n if param == 4:\n where_param = \"and kk.id_regio_vedouci = {} and kk.inst_vykon > {} and kk.inst_vykon <= {}\".format(\n rv_id, pwr_cat_f, pwr_cat_l)\n\n return sql + time_param + where_param + sorting\n\n\ndef pwr_category_select(pwr_cat_id):\n # <100\n if pwr_cat_id == 1:\n return [0, 99]\n\n # 100-200\n if pwr_cat_id == 2:\n return [100, 200]\n\n # 400\n if pwr_cat_id == 3:\n return [201, 400]\n\n # 600\n if pwr_cat_id == 4:\n return [401, 600]\n\n # 800\n if pwr_cat_id == 5:\n return [601, 800]\n\n # 1000\n if pwr_cat_id == 6:\n return [801, 1000]\n\n # 1600\n if pwr_cat_id == 7:\n return [1001, 1600]\n\n # 2000\n if pwr_cat_id == 8:\n return [1601, 2014]\n\n","sub_path":"api/ph/c_ph.py","file_name":"c_ph.py","file_ext":"py","file_size_in_byte":8728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"226393727","text":"from tkinter import *\nfrom tkinter import ttk\n\nimport displaytable as disp\nimport SISdatabase\n\n\nclass DashboardGUI:\n def __init__(self, frame):\n self.dashboard_cont_frame = frame\n\n self.student_dshbrd_img = PhotoImage(file=r\"images\\dashboardstud.png\")\n student_count_dash = Label(self.dashboard_cont_frame, image=self.student_dshbrd_img)\n student_count_dash.photo = self.student_dshbrd_img\n student_count_dash.place(x=20, y=20, width=250, height=120)\n self.student_count = Label(self.dashboard_cont_frame, text=\"1000\", font=(\"Blinker\", 40, \"bold\"),\n fg=\"#A51d23\", bg=\"#FA9412\")\n self.student_count.place(x=20, y=20, width=140, height=77)\n\n self.course_dshbrd_img = PhotoImage(file=r\"images\\dashboardcourse.png\")\n course_count_dash = Label(self.dashboard_cont_frame, image=self.course_dshbrd_img)\n course_count_dash.photo = self.course_dshbrd_img\n course_count_dash.place(x=290, y=20, width=250, height=120)\n self.course_count = Label(self.dashboard_cont_frame, text=\"0\", font=(\"Blinker\", 40, \"bold\"),\n bg=\"#A51d23\", fg=\"#FA9412\")\n self.course_count.place(x=290, y=20, width=140, height=77)\n\n self.bg_frame = Frame(self.dashboard_cont_frame, bg=\"white\")\n\n self.stud_list_label = Label(self.dashboard_cont_frame, bg=\"#A51d23\", fg=\"white\",\n text=\" LIST OF STUDENTS\", font=(\"Blinker\", 15, \"bold\"), anchor=\"w\")\n self.stud_list_frame = Frame(self.dashboard_cont_frame, bg=\"white\", highlightbackground=\"#A51d23\",\n highlightthickness=2)\n\n self.course_label = Label(self.dashboard_cont_frame, bg=\"#A51d23\", fg=\"white\",\n text=\" LIST OF COURSES\", font=(\"Blinker\", 15, \"bold\"), anchor=\"w\")\n self.course_list_frame = Frame(self.dashboard_cont_frame, bg=\"white\", highlightbackground=\"#A51d23\",\n highlightthickness=2)\n\n scroll_x_stud_list = Scrollbar(self.stud_list_frame, orient=HORIZONTAL)\n scroll_y_stud_list = Scrollbar(self.stud_list_frame, orient=VERTICAL)\n\n scroll_x_course_list = Scrollbar(self.course_list_frame, orient=HORIZONTAL)\n scroll_y_course_list = Scrollbar(self.course_list_frame, orient=VERTICAL)\n self.student_table = ttk.Treeview(self.stud_list_frame, xscrollcommand=scroll_x_stud_list.set,\n yscrollcommand=scroll_y_stud_list.set, columns=(\"id_no\", \"name\",\n \"course_code\", \"year\",\n \"gender\"))\n scroll_x_stud_list.pack(side=BOTTOM, fill=X)\n scroll_y_stud_list.pack(side=RIGHT, fill=Y)\n scroll_x_stud_list.config(command=self.student_table.xview)\n scroll_y_stud_list.config(command=self.student_table.yview)\n self.student_table.heading(\"id_no\", text=\"ID Number\")\n self.student_table.heading(\"name\", text=\"Name\")\n self.student_table.heading(\"course_code\", text=\"Course Code\")\n self.student_table.heading(\"year\", text=\"Year\")\n self.student_table.heading(\"gender\", text=\"Gender\")\n self.student_table['show'] = 'headings'\n self.student_table.column(\"id_no\", width=70)\n self.student_table.column(\"name\", width=190)\n self.student_table.column(\"course_code\", width=100)\n self.student_table.column(\"year\", width=70)\n self.student_table.column(\"gender\", width=70)\n\n self.student_table.pack(fill=BOTH, expand=1)\n\n self.course_table = ttk.Treeview(self.course_list_frame, xscrollcommand=scroll_x_course_list.set,\n yscrollcommand=scroll_y_course_list.set, columns=(\"course_code\",\n \"course\"))\n scroll_x_course_list.pack(side=BOTTOM, fill=X)\n scroll_y_course_list.pack(side=RIGHT, fill=Y)\n scroll_x_course_list.config(command=self.course_table.xview)\n scroll_y_course_list.config(command=self.course_table.yview)\n self.course_table.heading(\"course_code\", text=\"Course Code\")\n self.course_table.heading(\"course\", text=\"Course\")\n self.course_table['show'] = 'headings'\n self.course_table.column(\"course_code\", width=50)\n self.course_table.column(\"course\", width=200)\n\n self.course_table.pack(fill=BOTH, expand=1)\n\n self.max_student_img = PhotoImage(file=r\"images\\max.png\").subsample(5, 5)\n self.max_course_img = PhotoImage(file=r\"images\\max.png\").subsample(5, 5)\n self.max_student_button = Button(self.dashboard_cont_frame, command=self.max_student_table, relief=FLAT,\n bg=\"#A51d23\", activebackground=\"#A51d23\", image=self.max_student_img)\n self.max_course_button = Button(self.dashboard_cont_frame, command=self.max_course_table, relief=FLAT,\n bg=\"#A51d23\", activebackground=\"#A51d23\", image=self.max_course_img)\n\n self.min_image = PhotoImage(file=r\"images\\min.png\").subsample(5, 5)\n self.min_button = Button(self.dashboard_cont_frame, command=self.default_layout, relief=FLAT,\n fg=\"white\", bg=\"#A51d23\", activeforeground=\"white\", activebackground=\"#A51d23\",\n image=self.min_image)\n self.min_button.photo = self.min_image\n\n self.default_layout()\n self.count_data()\n disp.display_student_table(self.student_table)\n disp.display_course_table(self.course_table)\n\n def default_layout(self):\n self.min_button.place_forget()\n self.max_student_button.place(x=530, y=190, height=30, width=30)\n self.max_course_button.place(x=840, y=190, height=30, width=30)\n self.bg_frame.place(x=10, y=190, height=350, width=880)\n self.stud_list_label.place_configure(x=20, y=190, width=550, height=30)\n self.stud_list_frame.place_configure(x=20, y=220, width=550, height=320)\n self.course_label.place_configure(x=580, y=190, width=300, height=30)\n self.course_list_frame.place_configure(x=580, y=220, width=300, height=320)\n\n def count_data(self):\n self.student_count.config(text=len(SISdatabase.view_student_rec()))\n self.course_count.config(text=len(SISdatabase.view_course_rec()))\n\n def max_student_table(self):\n self.hide_widgets()\n self.stud_list_label.place_configure(x=20, y=190, width=860, height=30)\n self.stud_list_frame.place_configure(x=20, y=220, width=860, height=320)\n self.min_button.place(x=840, y=190, height=30, width=30)\n\n def max_course_table(self):\n self.hide_widgets()\n self.course_label.place_configure(x=20, y=190, width=860, height=30)\n self.course_list_frame.place_configure(x=20, y=220, width=860, height=320)\n self.min_button.place(x=840, y=190, height=30, width=30)\n\n def hide_widgets(self):\n self.stud_list_label.place_forget()\n self.stud_list_frame.place_forget()\n self.max_student_button.place_forget()\n self.max_course_button.place_forget()\n self.course_list_frame.place_forget()\n self.course_label.place_forget()\n","sub_path":"DashboardGUI.py","file_name":"DashboardGUI.py","file_ext":"py","file_size_in_byte":7432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"367696169","text":"import configparser\nfrom src.Service.Networks.load_model import buildModels\nfrom src.Controller.DealRequest.DealRequest import dealInput1, dealInput2\n\nconfig=configparser.ConfigParser()\nconfig.read(\"ServerConfig.ini\")\nModels = buildModels()\n\n\ndef test1():\n\tdata = {}\n\tdata['sf'] = 10.6\n\tdata['hf'] = 2.32\n\tdata['hff'] = 78.98\n\tdata['gdt'] = 14.43\n\tdata['C'] = 46.5\n\tdata['H'] = 5.54\n\tdata['O'] = 41.4\n\tdata['lj'] = 2.0\n\tdata['lg'] = 800.0\n\tdata['nj'] = 500.0\n\tdata['dlb'] = 0.3\n\tprint(dealInput1(data, config, Models))\n\ndef test2():\n\tdata = {}\n\tdata['sf'] = 10.6\n\tdata['hf'] = 2.32\n\tdata['hff'] = 70.8\n\tdata['gdt'] = 16.28\n\tdata['C'] = 54.4\n\tdata['H'] = 5.78\n\tdata['O'] = 39.4\n\tdata['rlxhsl'] = 70\n\t#data['var1'] = 1\n\t#data['var1Value'] = 50.0\n\t'''\n\tdata['var0'] = 1\n\tdata['var1'] = 1\n\tdata['var2'] = 1\n\tdata['var0Value'] = 800.0\n\tdata['var1Value'] = 50.0\n\tdata['var2Value'] = 8.0\n\t'''\n\tdata['prefer0'] = 1\n\tdata['prefer0Value'] = 20\n\tdata['prefer0-level'] = 1\n\tdata['prefer1'] = 1\n\tdata['prefer1Value'] = 60\n\tdata['prefer1-level'] = 2\n\tprint(dealInput2(data, config, Models))\n\n#test1()\ntest2()","sub_path":"src/back-end/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"24904619","text":"\"\"\"core pyvger objects.\"\"\"\nfrom decimal import Decimal\nimport warnings\n\nimport arrow\n\nimport cx_Oracle as cx\n\nimport pymarc\n\nimport six.moves.configparser as configparser\n\nimport sqlalchemy as sqla\n\nfrom pyvger.constants import RELATIONS, TABLE_NAMES\nfrom pyvger.exceptions import (\n BatchCatNotAvailableError,\n NoSuchItemException,\n PyVgerException,\n)\n\ntry:\n from pyvger import batchcat\nexcept BatchCatNotAvailableError:\n batchcat = None\n\n\nclass Voy(object):\n \"\"\"\n Interface to Voyager system.\n\n :param oracle_database: database name prefix\n :param config: configuration file path\n :param oracleuser: user name for Voyager Oracle account\n :param oraclepass: password for oracleuser account\n :param oracledsn: DSN used to connect to Oracle\n :param voy_username: Voyager username to login via BatchCat\n :param voy_password: Voyager password to login via BatchCat\n :param voy_path: path to directory containing Voyager.ini for BatchCat\n :param cat_location: location name of cataloging location\n :param library_id: library ID number\n \"\"\"\n\n def __init__(self, oracle_database=\"pittdb\", config=None, **kwargs):\n self.connection = None\n self.oracle_database = oracle_database\n cfg = {}\n if config is not None:\n cf = configparser.ConfigParser()\n cf.read(config)\n config_keys = [\n \"oracleuser\",\n \"oraclepass\",\n \"oracledsn\",\n \"voy_username\",\n \"voy_password\",\n \"voy_path\",\n \"cat_location\",\n \"library_id\",\n ]\n for item in config_keys:\n val = cf.get(\"Voyager\", item, fallback=\"\", raw=True).strip('\"')\n if val:\n cfg[item] = val\n if cf.get(\"Voyager\", \"connectstring\") and \"oracledsn\" not in cfg:\n cfg[\"oracledsn\"] = cf.get(\"Voyager\", \"connectstring\", raw=True).strip(\n '\"'\n )\n\n cfg.update(kwargs)\n\n if all(arg in cfg for arg in [\"oracleuser\", \"oraclepass\", \"oracledsn\"]):\n self.connection = cx.connect(\n cfg[\"oracleuser\"], cfg[\"oraclepass\"], cfg[\"oracledsn\"]\n )\n self.engine = sqla.create_engine(\n \"oracle://\", creator=lambda: self.connection\n )\n metadata = sqla.MetaData()\n tables_to_load = TABLE_NAMES\n\n self.tables = {}\n for table_name in tables_to_load:\n self.tables[table_name] = sqla.Table(\n table_name,\n metadata,\n schema=oracle_database,\n autoload=True,\n autoload_with=self.engine,\n )\n\n for parent, foreign in RELATIONS:\n parent_column = getattr(self.tables[parent[0]].c, parent[1])\n foreign_key = getattr(self.tables[foreign[0]].c, foreign[1])\n parent_column.append_foreign_key(sqla.ForeignKey(foreign_key))\n\n self.cat_location = cfg.get(\"cat_location\")\n self.library_id = cfg.get(\"library_id\")\n\n if \"voy_path\" not in cfg:\n cfg[\"voy_path\"] = r\"C:\\Voyager\"\n\n if batchcat is not None and all(\n arg in cfg for arg in [\"voy_username\", \"voy_password\"]\n ):\n self.batchcat = batchcat.BatchCatClient(\n username=cfg[\"voy_username\"],\n password=cfg[\"voy_password\"],\n voy_interface=self,\n apppath=cfg[\"voy_path\"],\n )\n else:\n self.batchcat = None\n\n def get_raw_bib(self, bibid):\n \"\"\"Get raw MARC for a bibliographic record.\n\n :param bibid:\n :return: bytes of bib record\n \"\"\"\n if self.connection:\n curs = self.connection.cursor()\n res = curs.execute(\n \"\"\"SELECT\n utl_i18n.string_to_raw(bib_data.record_segment)\n as record_segment\n FROM %(db)s.bib_data\n WHERE bib_data.bib_id=:bib ORDER BY seqnum\"\"\"\n % {\"db\": self.oracle_database},\n {\"bib\": bibid},\n )\n marc_segments = []\n for data in res:\n marc_segments.append(data[0])\n return b\"\".join(marc_segments)\n\n def get_bib(self, bibid):\n \"\"\"Get a bibliographic record.\n\n :param bibid: Voyager bibliographic record ID\n :return: pyvger.core.BibRecord object\n \"\"\"\n if self.connection:\n curs = self.connection.cursor()\n try:\n res = curs.execute(\n \"\"\"SELECT DISTINCT utl_i18n.string_to_raw(bib_data.record_segment) as record_segment,\n bib_master.suppress_in_opac, MAX(action_date) over (partition by bib_history.bib_id) maxdate,\n bib_data.seqnum FROM %(db)s.BIB_HISTORY JOIN %(db)s.bib_master\n on bib_history.bib_id = bib_master.bib_id JOIN %(db)s.bib_data\n ON bib_master.bib_id = bib_data.bib_id WHERE bib_history.BIB_ID = :bib\n ORDER BY seqnum\"\"\"\n % {\"db\": self.oracle_database},\n {\"bib\": bibid},\n )\n marc_segments = []\n data = None\n for data in res:\n marc_segments.append(data[0])\n marc = b\"\".join(marc_segments)\n if not marc:\n raise PyVgerException(\"No MARC data for bib %s\" % bibid)\n rec = next(pymarc.MARCReader(marc))\n if data[1] == \"Y\":\n suppress = True\n elif data[1] == \"N\":\n suppress = False\n else:\n raise PyVgerException(\n \"Bad suppression value %r for bib %s\" % (data[1], bibid)\n )\n last_date = arrow.get(data[2]).datetime\n return BibRecord(rec, suppress, bibid, self, last_date)\n\n except Exception:\n print(\"error for bibid |%r|\" % bibid)\n raise\n\n def get_mfhd(self, mfhdid):\n \"\"\"Get a HoldingsRecord object for the given Voyager mfhd number.\n\n :param mfhdid: Voyager holdings ID to fetch\n :return:\n \"\"\"\n if self.connection:\n curs = self.connection.cursor()\n res = curs.execute(\n \"\"\"SELECT DISTINCT utl_i18n.string_to_raw(record_segment)\n as record_segment,\n mfhd_master.suppress_in_opac,\n location.location_code,\n location.location_display_name,\n MAX(action_date) over (partition by mfhd_history.mfhd_id) maxdate,\n mfhd_data.seqnum\n FROM %(db)s.mfhd_data, %(db)s.mfhd_master, %(db)s.location, %(db)s.mfhd_history\n WHERE mfhd_data.mfhd_id=:mfhd\n AND mfhd_data.mfhd_id = mfhd_master.mfhd_id\n AND location.location_id = mfhd_master.location_id\n AND mfhd_history.mfhd_id = mfhd_master.mfhd_id\n ORDER BY seqnum\"\"\"\n % {\"db\": self.oracle_database},\n {\"mfhd\": mfhdid},\n )\n marc_segments = []\n data = None\n for data in res:\n marc_segments.append(data[0])\n marc = b\"\".join(marc_segments)\n if not marc:\n raise PyVgerException(\"No MARC data for MFHD %s\" % mfhdid)\n try:\n rec = next(pymarc.MARCReader(marc))\n except Exception as e:\n raise PyVgerException from e\n\n if data[1] == \"Y\":\n suppress = True\n elif data[1] == \"N\":\n suppress = False\n else:\n raise PyVgerException(\n \"Bad suppression value %r for mfhd %s\" % (data[1], mfhdid)\n )\n last_date = arrow.get(data[4]).datetime\n return HoldingsRecord(\n rec, suppress, mfhdid, self, data[2], data[3], last_date\n )\n\n def iter_mfhds(self, locations=None, lib_id=None, include_suppressed=False, last=None):\n \"\"\"Iterate over all of the holdings in the given locations.\n\n You must provide exactly one of locations or lib_id\n\n :param locations: list of locations to iterate over\n :param lib_id: library ID to iterate over instead of using locations\n :param include_suppressed: whether suppressed records should be included\n :param last: last record number processed, to skip ahead\n :return: iterator of HoldingsRecord objects\n\n \"\"\"\n mm = self.tables[\"mfhd_master\"]\n if locations and lib_id is None:\n where_clause = mm.c.location_id.in_(locations)\n elif lib_id:\n where_clause = sqla.and_(\n self.tables[\"location\"].c.library_id == lib_id,\n mm.c.location_id == self.tables[\"location\"].c.location_id,\n )\n else:\n raise ValueError(\"must provide locations or lib_id, and not both\")\n if not include_suppressed:\n where_clause = sqla.and_(mm.c.suppress_in_opac == \"N\", where_clause)\n if last is not None:\n where_clause = sqla.and_(mm.c.mfhd_id > last, where_clause)\n q = sqla.select([mm.c.mfhd_id], whereclause=where_clause).order_by(mm.c.mfhd_id)\n r = self.engine.execute(q)\n for row in r:\n try:\n yield self.get_mfhd(row[0])\n except PyVgerException:\n warnings.warn(\"Skipping record %s\" % row[0])\n\n def iter_bibs(self, locations=None, lib_id=None, include_suppressed=False):\n \"\"\"Iterate over all of the bibs in the given locations.\n\n You must provide exactly one of locations or lib_id.\n\n :param locations: list of locations to iterate over\n :param lib_id: library ID to iterate over instead of using locations\n :param include_suppressed: whether suppressed records should be included\n :return: iterator of BibRecord objects\n\n \"\"\"\n bl = self.tables[\"bib_location\"]\n bm = self.tables[\"bib_master\"]\n if locations and lib_id is None:\n q = bl.select(bl.c.location_id.in_(locations))\n elif lib_id:\n q = bm.select(bm.c.library_id == lib_id)\n else:\n raise ValueError(\"must provide locations or lib_id, and not both\")\n if not include_suppressed:\n q = q.where(\n sqla.and_(bm.c.suppress_in_opac == \"N\", bm.c.bib_id == bl.c.bib_id)\n )\n r = self.engine.execute(q)\n for row in r:\n try:\n yield self.get_bib(row[0])\n except UnicodeDecodeError:\n continue\n\n def iter_items(\n self, locations, include_temporary=False, include_suppressed_mfhd=False\n ):\n \"\"\"Iterate over the item records in one or more locations.\n\n :param locations: list of locations to iterate over\n :param include_temporary: bool whether to include items with temporary locations in locations list\n :param include_suppressed_mfhd: bool, whether to include items attached to a suppressed MFHD\n \"\"\"\n item_table = self.tables[\"item\"]\n where_clause = item_table.c.perm_location.in_(locations)\n if include_temporary:\n where_clause = sqla.or_(\n where_clause, item_table.c.temp_location.in_(locations)\n )\n if not include_suppressed_mfhd:\n where_clause = sqla.and_(\n self.tables[\"mfhd_master\"].c.suppress_in_opac == \"N\", where_clause\n )\n q = sqla.select(\n [item_table.c.item_id],\n whereclause=where_clause,\n from_obj=[\n item_table.join(self.tables[\"mfhd_item\"]).join(\n self.tables[\"mfhd_master\"]\n )\n ],\n )\n r = self.engine.execute(q)\n for row in r:\n yield self.get_item(row[0])\n\n def get_item(self, item_id=None, barcode=None):\n \"\"\"\n Get an item record from Voyager.\n\n :param int item_id:\n :param str barcode:\n :return: ItemRecord -- the item\n \"\"\"\n if item_id is not None:\n return ItemRecord.from_id(item_id, self)\n else:\n return ItemRecord.from_barcode(barcode, self)\n\n def get_item_statuses(self, item_id):\n \"\"\"\n Get the statuses from a single item.\n\n :param int item_id:\n :return: list(str) -- statuses\n \"\"\"\n query = (\n sqla.sql.select([self.tables[\"item_status_type\"].c.item_status_desc])\n .select_from(\n self.tables[\"item_status\"].join(self.tables[\"item_status_type\"])\n )\n .where(self.tables[\"item_status\"].c.item_id == item_id)\n )\n r = self.engine.execute(query)\n return [row[0] for row in r]\n\n def bib_id_for_item(self, item_id):\n \"\"\"\n Get the bibliographic record ID associated with an item record.\n\n :param int item_id: the Voyager item ID\n :return: int: the bib ID\n \"\"\"\n query = (\n sqla.sql.select([self.tables[\"bib_mfhd\"].c.bib_id])\n .select_from(self.tables[\"mfhd_item\"].join(self.tables[\"bib_mfhd\"]))\n .where(self.tables[\"mfhd_item\"].c.item_id == item_id)\n )\n\n result = self.engine.execute(query)\n (row,) = result\n return row[0]\n\n def get_bib_create_datetime(self, bib_id):\n \"\"\"Get date when a record was added.\n\n :param int bib_id: the Voyager bib id\n :return: datetime.datetime: when the record was added\n \"\"\"\n bmt = self.tables[\"bib_master\"]\n query = bmt.select().where(bmt.c.bib_id == bib_id)\n result = self.engine.execute(query)\n (row,) = result\n return row.create_date\n\n def get_location_id(self, location):\n \"\"\"Get numeric ID for location.\n\n :param location: Voyager location code\n :return: int: numeric location id\n \"\"\"\n query = (\n self.tables[\"location\"]\n .select()\n .where(self.tables[\"location\"].c.location_code == location)\n )\n result = self.engine.execute(query)\n (row,) = result\n return int(row.location_id)\n\n\nclass BibRecord(object):\n \"\"\"\n A voyager bibliographic record.\n\n :param record: a valid MARC bibliographic record\n :param suppressed: boolean; whether the record is suppressed in OPAC\n :param bibid: bibliographic record ID\n :param voyager_interface: Voy object to which this record belongs\n :param last_date: datetime.datetime of last update from BIB_HISTORY table\n\n WARNING: last_date should have its tzinfo set to UTC even if the naive time in the database is \"really\"\n from another timezone. The Voyager database doesn't know what timezone is being used, and the\n win32com methods used for BatchCat will convert non-UTC datetimes to UTC, then the server\n will ignore the TZ and fail because it thinks your datetime is off by your local offset.\n \"\"\"\n\n def __init__(self, record, suppressed, bibid, voyager_interface, last_date=None):\n self.record = record\n self.suppressed = suppressed\n self.bibid = bibid\n self.last_date = last_date\n self.interface = voyager_interface\n\n def __getattr__(self, item):\n \"\"\"Pass on attributes of the pymarc record.\"\"\"\n if hasattr(self.record, item):\n return getattr(self.record, item)\n\n def __getitem__(self, item):\n \"\"\"Pass on item access for the pymarc record.\"\"\"\n return self.record[item]\n\n def holdings(self):\n \"\"\"Get the holdings for this bibliographic record.\n\n :return: a list of HoldingsRecord objects\n \"\"\"\n curs = self.interface.connection.cursor()\n result = curs.execute(\n \"\"\"SELECT mfhd_id\n FROM %(db)s.bib_mfhd\n WHERE bib_mfhd.bib_id=:bib\"\"\"\n % {\"db\": self.interface.oracle_database},\n {\"bib\": self.bibid},\n )\n\n rv = []\n for rec in result:\n rv.append(self.interface.get_mfhd(rec[0]))\n\n return rv\n\n\nclass HoldingsRecord(object):\n \"\"\"\n A single Voyager holding.\n\n :param record: a valid MARC-encoded holdings record\n :param suppressed: boolean; whether record is suppressed in OPAC\n :param mfhdid: holdings ID in database\n :param voyager_interface: the Voy instance to which this record belongs\n :param location: textual code for the holding's location\n :param location_display_name: display name for the holding's location\n :param last_date: datetime.datetime of last update from BIB_HISTORY table\n\n WARNING: last_date should have its tzinfo set to UTC even if the naive time in the database is \"really\"\n from another timezone. The Voyager database doesn't know what timezone is being used, and the\n win32com methods used for BatchCat will convert non-UTC datetimes to UTC, then the server\n will ignore the TZ and fail because it thinks your datetime is off by your local offset.\n \"\"\"\n\n def __init__(\n self,\n record,\n suppressed,\n mfhdid,\n voyager_interface,\n location,\n location_display_name,\n last_date,\n ):\n self.record = record\n self.suppressed = suppressed\n self.mfhdid = mfhdid\n self.interface = voyager_interface\n self.location = location\n self.location_display_name = location_display_name\n self.last_date = last_date\n\n def __getattr__(self, item):\n \"\"\"Pass on attributes of the pymarc record.\"\"\"\n if hasattr(self.record, item):\n return getattr(self.record, item)\n\n def __getitem__(self, item):\n \"\"\"Pass on item access for the pymarc record.\"\"\"\n return self.record[item]\n\n def get_items(self):\n \"\"\"Return a list of ItemRecords for the holding's items.\"\"\"\n mi_table = self.interface.tables[\"mfhd_item\"]\n query = sqla.select([mi_table.c.item_id]).where(\n mi_table.c.mfhd_id == self.mfhdid\n )\n res = self.interface.engine.execute(query)\n try:\n return [self.interface.get_item(i[0]) for i in res]\n except NoSuchItemException:\n print(\"failed for mfhd %s\" % self.mfhdid)\n raise\n\n def get_bib(self):\n \"\"\"Return the bib record to which this holding is attached.\"\"\"\n return self.interface.get_bib(self.record[\"004\"].data)\n\n\nclass ItemRecord(object):\n \"\"\"A Voyager item.\n\n :param int holding_id: indicates MFHD number for an item being added\n :param int item_id: indicates Voyager number of item record being updated\n :param int item_type_id: indicates valid item type ID from item_type table\n :param int perm_location_id: indicates valid Voyager location of an item\n :param bool add_item_to_top:\n :param str caption:\n :param str chron:\n :param int copy_number:\n :param str enumeration:\n :param str free_text:\n :param int media_type_id:\n :param int piece_count:\n :param str price:\n :param str spine_label:\n :param int temp_location_id:\n :param int temp_type_id:\n :param str year:\n :param Voy voyager_interface:\n :param str note:\n \"\"\"\n\n def __init__(\n self,\n holding_id=None,\n item_id=None,\n item_type_id=None,\n perm_location_id=None,\n add_item_to_top=False,\n caption=\"\",\n chron=\"\",\n copy_number=0,\n enumeration=\"\",\n free_text=\"\",\n media_type_id=None,\n piece_count=1,\n price=\"0\",\n spine_label=\"\",\n temp_location_id=None,\n temp_type_id=None,\n year=\"\",\n voyager_interface=None,\n note=\"\",\n ):\n self.holding_id = holding_id\n self.item_id = item_id\n self.item_type_id = item_type_id\n self.perm_location_id = perm_location_id\n self.add_item_to_top = add_item_to_top\n self.caption = caption\n self.chron = chron\n self.copy_number = copy_number\n self.enumeration = enumeration\n self.free_text = free_text\n self.media_type_id = media_type_id\n self.piece_count = piece_count\n self.price = price\n self.spine_label = spine_label\n self.temp_location_id = temp_location_id\n self.temp_type_id = temp_type_id\n self.year = year\n self.voyager_interface = voyager_interface\n self.note = note\n\n def get_mfhd(self):\n \"\"\"Retrieve the holdings record to which this item is attached.\"\"\"\n mi = self.voyager_interface.tables[\"mfhd_item\"]\n q = mi.select(mi.c.item_id == self.item_id)\n r = self.voyager_interface.engine.execute(q)\n rows = list(r)\n if len(rows) > 1:\n raise PyVgerException(\"Multiple MFHDs attached to item %s\", self.item_id)\n return self.voyager_interface.get_mfhd(rows[0][\"mfhd_id\"])\n\n @classmethod\n def from_id(cls, item_id, voyager_interface):\n \"\"\"Get item given ID.\"\"\"\n it = voyager_interface.tables[\"item\"]\n mit = voyager_interface.tables[\"mfhd_item\"]\n item_note_table = voyager_interface.tables[\"item_note\"]\n\n columns = [\n it.c.item_id,\n it.c.perm_location,\n mit.c.item_enum,\n item_note_table.c.item_note,\n mit.c.chron,\n mit.c.mfhd_id,\n it.c.item_type_id,\n mit.c.caption,\n it.c.copy_number,\n mit.c.freetext,\n it.c.media_type_id,\n it.c.pieces,\n it.c.price,\n it.c.spine_label,\n it.c.temp_location,\n it.c.temp_item_type_id,\n mit.c.year,\n ]\n\n q = sqla.select(\n columns,\n it.c.item_id == item_id,\n from_obj=[it.join(mit).outerjoin(item_note_table)],\n use_labels=False,\n )\n result = voyager_interface.engine.execute(q)\n rows = [x for x in result]\n if not rows:\n raise NoSuchItemException(\"item %s not found\" % item_id)\n if len(rows) != 1:\n print(\"many notes on item %s\" % item_id)\n print(rows)\n\n data = rows[0]\n\n price = f'{Decimal(data[\"price\"]) / 100:.2f}'\n\n return cls(\n item_id=data[\"item_id\"],\n perm_location_id=data[\"perm_location\"],\n enumeration=data[\"item_enum\"],\n chron=data[\"chron\"],\n note=data[\"item_note\"],\n holding_id=data[\"mfhd_id\"],\n item_type_id=data[\"item_type_id\"],\n caption=data[\"caption\"],\n copy_number=data[\"copy_number\"],\n free_text=data[\"freetext\"],\n media_type_id=data[\"media_type_id\"],\n piece_count=data[\"pieces\"],\n price=price,\n spine_label=data[\"spine_label\"],\n temp_location_id=data[\"temp_location\"],\n temp_type_id=data[\"temp_item_type_id\"],\n year=data[\"year\"],\n voyager_interface=voyager_interface,\n )\n\n @classmethod\n def from_barcode(cls, barcode, voyager_interface):\n \"\"\"Get an item record given its barcode.\"\"\"\n ib = voyager_interface.tables[\"item_barcode\"]\n q = sqla.select([ib.c.item_id], ib.c.item_barcode == barcode)\n result = voyager_interface.engine.execute(q)\n rows = [x for x in result]\n if not rows:\n raise NoSuchItemException(\"item for barcode %s not found\" % barcode)\n if len(rows) != 1:\n print(\"many items attached to barcode %s\" % barcode)\n print(rows)\n\n item_id = rows[0][0]\n return cls.from_id(item_id, voyager_interface)\n\n def get_barcode(self):\n \"\"\"Look up the active bacode for this item.\"\"\"\n ib = self.voyager_interface.tables[\"item_barcode\"]\n q = sqla.select(\n [ib.c.item_barcode],\n sqla.and_(ib.c.item_id == self.item_id, ib.c.barcode_status == \"1\"),\n )\n result = self.voyager_interface.engine.execute(q)\n rows = [x for x in result]\n if not rows:\n raise NoSuchItemException(\"barcode for item %s not found\" % self.item_id)\n if len(rows) != 1:\n print(\"many active barcodes attached to item %s\" % self.item_id)\n print(rows)\n\n return rows[0][0]\n\n def save(self):\n \"\"\"Save the item record back to the database.\"\"\"\n batchcat = self.voyager_interface.batchcat\n if batchcat is None:\n raise BatchCatNotAvailableError\n bc = batchcat.bc\n bc.cItem.HoldingId = self.holding_id\n bc.cItem.ItemID = self.item_id\n bc.cItem.ItemTypeID = self.item_type_id\n bc.cItem.PermLocationID = self.perm_location_id\n bc.cItem.Caption = self.caption or \"\"\n bc.cItem.Chron = self.chron or \"\"\n bc.cItem.CopyNumber = self.copy_number\n bc.cItem.Enumeration = self.enumeration or \"\"\n bc.cItem.FreeText = self.free_text or \"\"\n bc.cItem.MediaTypeID = self.media_type_id\n bc.cItem.PieceCount = self.piece_count\n bc.cItem.Price = self.price\n bc.cItem.SpineLabel = self.spine_label or \"\"\n bc.cItem.TempLocationID = self.temp_location_id\n bc.cItem.TempTypeID = self.temp_type_id\n bc.cItem.Year = self.year or \"\"\n result = bc.UpdateItemData(\n CatLocationID=self.voyager_interface.get_location_id(\n self.voyager_interface.cat_location\n )\n )\n if result[0]:\n raise PyVgerException(\"UpdateItemData error: {}\".format(result))\n","sub_path":"pyvger/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":25803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"139532599","text":"#!/usr/bin/env python3\n\"\"\"\nGradient Descent with L2 Regularization\n\"\"\"\n\nimport numpy as np\n\n\ndef l2_reg_gradient_descent(Y, weights, cache, alpha, lambtha, L):\n \"\"\"\n Function that updates the weights and biases of a NN using gradient descent\n with L2 regularization\n Arguments:\n - Y is a one-hot numpy.ndarray of shape (classes, m) that contains the\n correct labels for the data\n * classes is the number of classes\n * m is the number of data points\n - weights is a dictionary of the weights and biases of the NN\n - cache is a dictionary of the outputs of each layer of the NN\n - alpha is the learning rate\n - lambtha is the L2 regularization parameter\n - L is the number of layers of the network\n \"\"\"\n\n weights_copy = weights.copy()\n dz = cache[\"A\" + str(L)] - Y\n for i in range(L, 0, -1):\n A = cache[\"A\" + str(i - 1)]\n w = \"W\" + str(i)\n b = \"b\" + str(i)\n dw = (1 / len(Y[0])) * np.matmul(dz, A.T) + (\n lambtha * weights[w]) / len(Y[0])\n db = (1 / len(Y[0])) * np.sum(dz, axis=1, keepdims=True)\n weights[w] = weights[w] - alpha * dw\n weights[b] = weights[b] - alpha * db\n dz = np.matmul(weights_copy[\"W\" + str(i)].T, dz) * (1 - A * A)\n","sub_path":"supervised_learning/0x05-regularization/1-l2_reg_gradient_descent.py","file_name":"1-l2_reg_gradient_descent.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"80557900","text":"'''\nPlan:\n Split the paths on the backslashes\n Use the last item as the key, the entire path as the value\n\n Use the queries to search if the key exists\n If it does, return the corresponding value (the path) in an output array\n\n # There can be multiple different file paths that have the ending, \n # we need to return them all, append to lists at each key\n'''\n'PASSES ALL TESTS'\n\ndef finder(files, queries):\n # Dictionary to store filepath info\n file_path = {}\n\n # Iterate through each file path\n for path in files:\n # Split the file paths on the backslash\n split_path = path.split(\"/\")\n # Use the last split as the key and the whole file path as the value\n file_end = split_path[-1]\n # Store data in dictionary\n # If the key doesn't exist add it with an empty list\n if file_end not in file_path:\n file_path[file_end] = []\n # Add the ending as the key and the file path as the value\n file_path[file_end].append(path)\n \n # Create outout array\n output_array = []\n\n # Search to see if the query is in the dictionary\n for query in queries:\n # If the query is in the path dictionary, append the full file path\n if query in file_path:\n output_array.append(file_path[query])\n\n result = []\n\n # Output array is a nested list, need to return a 2-D list\n for inner_list in output_array:\n for item in inner_list:\n result.append(item)\n\n # Return result\n return result\n\n\nif __name__ == \"__main__\":\n files = [\n '/bin/foo',\n '/bin/bar',\n '/usr/bin/baz'\n ]\n queries = [\n \"foo\",\n \"qux\",\n \"baz\"\n ]\n print(finder(files, queries))\n","sub_path":"hashtables/ex5/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"375387513","text":"# %load q07_extras/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n# Your Solution\ndef extras_runs(data=data):\n\n # Write your code here\n innings1,innings2 = 0,0\n extra1 = data['innings'][0]['1st innings']['deliveries']\n for m in extra1:\n for x, y in m.items():\n if 'extras' in y:\n if 'wides' in y['extras']:\n innings1 += y['extras']['wides']\n elif 'legbyes' in y['extras']:\n innings1 += y['extras']['legbyes']\n \n extra2 = data['innings'][1]['2nd innings']['deliveries']\n for m in extra2:\n for x, y in m.items():\n if 'extras' in y:\n if 'wides' in y['extras']:\n innings2 += y['extras']['wides']\n elif 'legbyes' in y['extras']:\n innings2 += y['extras']['legbyes']\n \n print(innings2)\n print(innings1)\n difference = innings2-innings1\n\n\n return difference\nextras_runs()\n\n","sub_path":"q07_extras/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"86601981","text":"\"\"\"\nCopy and adjust data in preparation for run_cal_plotter.py\n\nThis should not be needed routinely, but is here to document\nthe provenance of the calibration data in the repository.\n\"\"\"\nfrom __future__ import print_function\nimport logging\nimport numpy as np\nimport glob\nimport os\nimport pandas as pd\nimport shutil\nfrom stompy import utils\nfrom stompy.io.local import cdec\nfrom stompy.io.local import usgs_nwis\n\ncache_dir=\"../cache\"\n\ndownload_period=[np.datetime64(\"2014-03-01\"),\n np.datetime64(\"2018-10-01\")]\n\n##\n\ncsc_stations_dir=\"/home/rusty/mirrors/Ed/Sync/UCD/Projects/CDFW_Arc/dflowfm/27-comp_bedlevtyp_2_3_4/stations\"\n\ndef any_x_in_y(x,y):\n \"\"\" true if any of the elements of list x are found in y\"\"\"\n for an_x in x:\n if an_x in y:\n return True\n return False\n\nfor fn in glob.glob(os.path.join( csc_stations_dir,\"wsel\",\"*.csv\")):\n base_fn=os.path.basename(fn)\n print(fn)\n if base_fn in ['GES_STAGE_april2014.csv']:\n print(\" Copying without modification\")\n shutil.copyfile(fn,base_fn)\n elif base_fn.startswith('HecDssExcel'):\n if any_x_in_y( ('UL1','DOP','HAAS'),base_fn): # no correction\n # unsure of status of UL1\n print(\" CWS station with no time offset\")\n shutil.copyfile(fn,base_fn)\n elif any_x_in_y( ('HS1','LN2','SG1','CCS'), base_fn):\n # Not positive about CCS, though. Will apply 1 hour shift anyway\n print(\" CWS station with assumed 1 hour offset\")\n df=pd.read_csv(fn,parse_dates=['Time'],infer_datetime_format=True)\n df.Time -= np.timedelta64(3600,'s')\n # Transition to ISO date formats\n df.to_csv(base_fn,index=False,date_format=\"%Y-%m-%d %H:%M\")\n else:\n raise Exception(\"No match for %s\"%base_fn)\n\n\n##\n\n# USGS gauges with Flow and Stage:\nfor usgs_name,usgs_station in [ (\"SRV\",\"11455420\"), # Sac River at Rio Vista\n (\"FPX\",\"11447650\"), # Sac River at Freeport\n (\"RYI\",\"11455350\"), # Cache Slough at Ryer Island\n (\"HWB\",\"11455165\"), # Miner Slough at HWY 84 Bridge\n (\"SSS\",\"11447850\"), # Steamboat Slough Btw Sac R And Sutter Sl, aka Steamboat Slough nr Walnut\n (\"SUT\",\"11447830\"), # Sutter Slough at Courtland\n (\"DWS\",\"11455335\"), # Sacramento R Deep Water Ship Channel Nr Rio Vista\n (\"GES\",\"11447905\"), # Sacramento R below Georgiana Slough\n (\"GSS\",\"11447903\"), # Georgiana Slough at Sac River\n (\"DCC\",\"11336600\"), # Delta Cross channel (used as BC, too)\n (\"SDC\",\"11447890\"), # Sac above Delta Cross Channel\n (\"CourtToe\",\"11455167\"), # Prospect Slough at Toe Drain near Courtland\n (\"LibertyToe\",\"11455140\"), # Toe Drain at Liberty Island\n (\"HNB\",\"11455143\"), # Little Holland North Breach, 2016-01 -- 2018-11\n (\"LIC\",\"382006121401601\"), # Liberty Isl at Liberty Isl. Cut\n (\"LIH\",\"11455146\"), # Liberty Cut at Little Holland\n (\"WildlandsUpMarsh\",\"381934121403201\"), # Liberty Island, Wildlands, Up Marsh\n # no physical data until 2015-07:\n (\"LIB\",\"11455315\"), # Cache Slough A S Liberty Island Nr Rio Vista CA\n (\"TSL\",\"11337080\"), # Threemile slough near Rio Vista\n (\"SDI\",\"11455478\"), # Sac River at Decker Island\n]:\n stage_fn='%s-stage.csv'%usgs_name\n flow_fn ='%s-flow.csv'%usgs_name\n if os.path.exists(stage_fn) and os.path.exists(flow_fn):\n continue # or force.\n print(\"Downloading %s\"%usgs_name)\n\n ds=usgs_nwis.nwis_dataset(usgs_station,\n download_period[0],download_period[1],\n [60,65], # Discharge and Stage\n days_per_request='M',cache_dir=cache_dir)\n # nwis_dataset() returns UTC data. Convert to PST:\n ds['time'] = ds.time - np.timedelta64(8,'h')\n\n # Match the names up with existing csv files:\n ds=ds.rename({'time':'Time'})\n if 'stream_flow_mean_daily' in ds:\n ds=ds.rename({'stream_flow_mean_daily':'Flow'})\n if 'height_gage' in ds:\n ds=ds.rename({'height_gage':'Stage'})\n df=ds.to_dataframe()\n\n if 'Stage' in df:\n df.Stage.to_csv(stage_fn,index=True,date_format=\"%Y-%m-%d %H:%M\",header=True)\n if 'Flow' in df:\n df.Flow.to_csv(flow_fn,index=True,date_format=\"%Y-%m-%d %H:%M\",header=True)\n\n##\n\nfor cdec_station in ['LIS','LIY','MIR']:\n for quant in ['flow','stage']:\n fn=\"%s-%s.csv\"%(cdec_station,quant)\n if os.path.exists(fn): continue\n if quant=='flow':\n sensor=20\n column='Flow'\n elif quant=='stage':\n sensor=1\n column='Stage'\n ds=cdec.cdec_dataset(cdec_station,\n start_date=download_period[0],\n end_date=download_period[1],\n sensor=sensor,cache_dir=cache_dir)\n if ds is None:\n print(\"No %s for %s\"%(quant,cdec_station))\n continue\n # cdec module tries to output UTC, so go back to PST here.\n ds.time.values -= np.timedelta64(8,'h')\n ds=ds.rename({'sensor%04d'%sensor:column,\n 'time':'Time'})\n \n df=ds.to_dataframe().reset_index()\n df.to_csv(fn,columns=[\"Time\",column],date_format=\"%Y-%m-%d %H:%M\",index=False)\n\n##\n\nif 0: \n # Fetch a year of stage data for Yolo Bypass near Lisbon.\n # the original file is put in cache_dir, from which\n lis_fn=\"LIS-stage-WY2014.csv\"\n lis_orig_fn=os.path.join(cache_dir,'LIS-WY2014-STAGE_15-MINUTE_DATA_DATA.CSV')\n url=\"http://wdl.water.ca.gov/waterdatalibrary/docs/Hydstra/docs/B91560/2014/STAGE_15-MINUTE_DATA_DATA.CSV\"\n\n # only fetch when necessary.\n if not os.path.exists(lis_fn):\n if not os.path.exists(lis_orig_fn):\n utils.download_url(url,lis_orig_fn,log=logging)\n df=pd.read_csv(lis_orig_fn,skiprows=3,parse_dates=['Time'],infer_datetime_format=True,\n names=[\"Time\",\"Stage\",\"Quality\",\"Comment\"])\n df.to_csv(lis_fn,columns=[\"Time\",\"Stage\"],date_format=\"%Y-%m-%d %H:%M\",index=False)\n\n\n##\n\nif 0: # Verified that these are the same vertical datum, same timezone\n # Compare datums between USGS GES, and the CSV already around\n ges_orig=pd.read_csv('GES_STAGE_april2014.csv',parse_dates=['Time'],infer_datetime_format=True)\n ges_usgs=pd.read_csv('GES-2014-04-stage.csv',parse_dates=['Time'],infer_datetime_format=True)\n\n import matplotlib.pyplot as plt\n plt.ion()\n plt.show()\n fig,ax=plt.subplots(num=1)\n ax.cla()\n ax.plot(ges_orig.Time,ges_orig.Stage,label='orig')\n ax.plot(ges_usgs.Time,ges_usgs.Stage,label='usgs')\n\n\n\n\n\n","sub_path":"dflowfm/calibration_data/collate_cal_data.py","file_name":"collate_cal_data.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"539060959","text":"#!/usr/bin/env python\n# -*- coding: iso-8859-15 -*-\n\n### This module creates the central structure of the L2A_Product and calls the L2A_Schedule module\n\nfrom numpy import *\nfrom tables import *\nimport sys, os, logging, fnmatch, warnings, platform, multiprocessing\nfrom shutil import copyfile\nfrom datetime import datetime\nfrom time import time\nfrom L2A_Logger import L2A_Logger,getLevel\nfrom L2A_Config import L2A_Config, getScriptDir\nfrom L2A_XmlParser import L2A_XmlParser\nfrom L2A_ProcessTileToolbox import SUCCESS, FAILURE, ALREADY_PROCESSED\nfrom multiprocessing import Lock\nl = Lock()\n\n\ndef readNamingConvention(input_dir, mode, logger = None):\n # step 1 test the standard naming format:\n if mode == 'generate_datastrip':\n userProduct = os.path.basename(input_dir)\n S2A_L1C_mask_safe_standard = 'S2?_OPER_MSI_L1C_DS*'\n S2A_L1C_mask_safe_compact = 'DS_MPS*'\n elif mode == 'process_tile':\n userProduct = os.path.basename(input_dir)\n S2A_L1C_mask_safe_standard = 'S2?_OPER_MSI_L1C_TL*'\n S2A_L1C_mask_safe_compact = 'L1C_T*'\n else:\n userProduct = input_dir\n S2A_L1C_mask_safe_standard = 'S2?_OPER_PRD_MSIL1C*.SAFE'\n S2A_L1C_mask_safe_compact = 'S2?_MSIL1C*.SAFE'\n\n if (fnmatch.fnmatch(userProduct, S2A_L1C_mask_safe_standard) == True):\n nc = 'SAFE_STANDARD'\n elif(fnmatch.fnmatch(userProduct, S2A_L1C_mask_safe_compact) == True):\n nc = 'SAFE_COMPACT'\n else:\n nc = 'UNKNOWN'\n if logger:\n logger.error('L1C user product directory must match the following mask: %s' % S2A_L1C_mask_safe_compact)\n logger.error('but is: %s' % userProduct)\n\n return nc\n\n\ndef parseCommandLine(args):\n\n config = L2A_Config(None)\n logger = L2A_Logger('sen2cor',operation_mode = args.mode)\n selectedTile = None\n\n try:\n test = args.input_dir\n input_dir = os.path.normpath(test)\n if not (os.path.isabs(input_dir)):\n cwd = os.getcwd()\n input_dir = os.path.join(cwd, input_dir)\n if os.path.exists(input_dir):\n # check if input_dir argument contains a tile. If yes, split the tile from path,\n # put the tile in the config object created below as selected tile,\n # create the new path for the user directory.\n if 'GRANULE' in input_dir:\n dirname, dummy = os.path.split(input_dir)\n input_dir = dirname\n userProduct = os.path.basename(input_dir)\n config = L2A_Config(None, input_dir)\n config.operationMode = 'TOOLBOX'\n config.namingConvention = readNamingConvention(userProduct, args.mode, logger = config.logger)\n if config.namingConvention == 'UNKNOWN':\n return config\n else:\n logger.error('Input user product does not exist.')\n return config\n except:\n pass\n\n if (args.mode != 'generate_datastrip' and \\\n args.mode != 'process_tile') and \\\n config.operationMode != 'TOOLBOX':\n logger.error('wrong operation mode: %s' % args.mode)\n config.operationMode = 'INVALID'\n return config\n\n if args.mode == 'generate_datastrip':\n work_dir = os.path.normpath(args.work_dir)\n if not os.path.exists(work_dir):\n os.mkdir(work_dir)\n if args.datastrip == None:\n logger.error('No argument for datastrip present.')\n return config\n elif args.processing_centre == None:\n logger.error('No argument for processing centre present.')\n return config\n elif args.archiving_centre == None:\n logger.error('No argument for archiving centre present.')\n return config\n datastrip = os.path.normpath(args.datastrip)\n if os.path.exists(datastrip):\n input_dir = os.path.dirname(datastrip)\n config = L2A_Config(None, input_dir)\n config.datastrip = os.path.basename(datastrip)\n config.datastrip_root_folder = datastrip\n config.processing_centre = args.processing_centre\n config.archiving_centre = args.archiving_centre\n config.work_dir = work_dir\n config.operationMode = 'GENERATE_DATASTRIP'\n config.namingConvention = readNamingConvention(config.datastrip, args.mode, logger = config.logger)\n else:\n logger.error('Input datastrip does not exist.')\n return config\n # end generate_datastrip\n\n elif args.mode == 'process_tile':\n work_dir = os.path.normpath(args.work_dir)\n if not os.path.exists(work_dir):\n os.mkdir(work_dir)\n if args.datastrip == None:\n logger.error('No argument for datastrip present.')\n return config \n elif args.tile == None:\n logger.error('No argument for tile present.')\n return config\n elif args.work_dir == None:\n logger.error('No argument for work directory present.')\n return config\n datastrip = os.path.normpath(args.datastrip)\n if not os.path.exists(datastrip):\n logger.error('Input datastrip does not exist.')\n return config\n tile = os.path.normpath(args.tile)\n if os.path.exists(tile):\n input_dir = os.path.dirname(tile)\n config = L2A_Config(None, input_dir)\n config.datastrip = os.path.basename(datastrip)\n config.datastrip_root_folder = datastrip\n config.L2A_DS_ID = config.datastrip\n config.L2A_DS_DIR = datastrip\n config.L2A_DS_MTD_XML = os.path.join(datastrip, 'MTD_DS.xml')\n config.tile = os.path.basename(tile)\n config.selectedTile = tile\n config.nrTiles = 1\n config.L1C_TILE_ID = os.path.basename(tile)\n config.work_dir = work_dir\n config.operationMode = 'PROCESS_TILE'\n config.namingConvention = readNamingConvention(config.tile, args.mode, logger = logger)\n else:\n logger.error('Input tile does not exist.')\n return config\n # end process_tile\n\n if config.operationMode != 'TOOLBOX':\n if args.output_dir == None:\n logger.error('No argument for output directory present.')\n config.operationMode = 'INVALID'\n return config\n output_dir = os.path.normpath(args.output_dir)\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n config.output_dir = output_dir\n # SIIMPC-1327:\n if args.img_database_dir == None:\n img_database_dir = config.work_dir\n else:\n img_database_dir = os.path.normpath(args.img_database_dir)\n if args.res_database_dir == None:\n res_database_dir = config.work_dir\n else:\n res_database_dir = os.path.normpath(args.res_database_dir)\n if img_database_dir == None:\n logger.error('No argument for image database directory present.')\n config.operationMode = 'INVALID'\n return config\n if not os.path.exists(img_database_dir):\n os.mkdir(img_database_dir)\n if not os.path.exists(res_database_dir):\n os.mkdir(res_database_dir)\n if res_database_dir == None:\n logger.error('No argument for result database directory present.')\n config.operationMode = 'INVALID'\n return config\n config.img_database_dir = img_database_dir\n config.res_database_dir = res_database_dir\n # end ! TOOLBOX\n\n else: # TOOLBOX:\n directory = os.path.normpath(args.input_dir)\n if not (os.path.isabs(directory)):\n cwd = os.getcwd()\n directory = os.path.join(cwd, directory)\n else:\n cwd = os.path.dirname(directory)\n\n config.work_dir = directory\n if args.output_dir:\n output_dir = os.path.normpath(args.output_dir)\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n config.output_dir = output_dir\n else:\n config.output_dir = cwd\n\n if args.processing_centre:\n config.processing_centre = args.processing_centre\n\n if args.processing_baseline:\n config.processingBaseline = float32(args.processing_baseline)\n\n # check if directory argument contains a tile. If yes, split the tile from path,\n # put the tile in the config object created below as selected tile,\n # create the new path for the user directory.\n if 'GRANULE' in config.work_dir:\n dirname, selectedTile = os.path.split(config.work_dir)\n directory = os.path.dirname(config.work_dir)\n\n test = os.path.basename(directory)\n # step 1 test the standard naming format:\n S2A_L1C_mask = 'S2?_OPER_PRD_MSIL1C*.SAFE'\n if (fnmatch.fnmatch(test, S2A_L1C_mask) == True):\n nc = 'SAFE_STANDARD'\n else:\n S2A_L1C_mask = 'S2?_MSIL1C*.SAFE'\n if (fnmatch.fnmatch(test, S2A_L1C_mask) == True):\n nc = 'SAFE_COMPACT'\n else:\n logger.error('L1C user product directory must match the following mask: %s, but is %s' % [S2A_L1C_mask, test])\n return FAILURE\n # end TOOLBOX\n\n # common args:\n CFG = 'cfg'\n if args.GIP_L2A:\n # is it an absolute path?\n isFile = False\n test = os.path.normpath(args.GIP_L2A)\n if os.path.isfile(test):\n config.configFn = test\n isFile = True\n else: # is it located in the config home dir?\n test = os.path.join(config.home, CFG, args.GIP_L2A)\n if os.path.isfile(test):\n config.configFn = test\n isFile = True\n if not isFile:\n logger.error('File does not exist: %s' % test)\n config.operationMode = 'INVALID'\n return config\n # same procedure for GIP_SC:\n if args.GIP_L2A_SC:\n isFile = False\n test = os.path.normpath(args.GIP_L2A_SC)\n if os.path.isfile(test):\n config.configSC = test\n isFile = True\n else:\n test = os.path.join(config.home, CFG, args.GIP_L2A_SC)\n if os.path.isfile(test):\n config.configSC = test\n isFile = True\n if not isFile:\n logger.error('File does not exist: %s' % test)\n config.operationMode = 'INVALID'\n return config\n # same procedure for GIP_AC:\n if args.GIP_L2A_AC:\n isFile = False\n test = os.path.normpath(args.GIP_L2A_AC)\n if os.path.isfile(test):\n config.configAC = test\n isFile = True\n else:\n test = os.path.join(config.home, CFG, args.GIP_L2A_AC)\n if os.path.isfile(test):\n config.configAC = test\n isFile = True\n if not isFile:\n logger.error('File does not exist: %s' % test)\n config.operationMode = 'INVALID'\n return config\n # same procedure for GIP_L2A_PB:\n if args.GIP_L2A_PB:\n isFile = False\n test = os.path.normpath(args.GIP_L2A_PB)\n if os.path.isfile(test):\n config.configPB = test\n isFile = True\n else:\n test = os.path.join(config.home, CFG, args.GIP_L2A_PB)\n if os.path.isfile(test):\n config.configPB = test\n isFile = True\n if not isFile:\n logger.error('File does not exist: %s' % test)\n config.operationMode = 'INVALID'\n return config\n\n if args.resolution == None:\n config.resolution = 0\n else:\n config.resolution = args.resolution\n\n config.scOnly = args.sc_only\n config.crOnly = args.cr_only\n config.raw = args.raw\n config.tif = args.tif\n config.logger = logger\n return config\n\n\ndef postprocess(config):\n # SIMPC-1152, third remark: report file is unwanted.\n return True\n # fix for SIIMPC-555.1, UMW\n fnLogBase = os.path.basename(config.fnLog)\n try:\n fnLogIn = config.fnLog\n f = open(fnLogIn, 'a')\n f.write('')\n f.flush()\n f.close()\n fnLogOut = os.path.join(config.L2A_UP_DIR, fnLogBase)\n copyfile(fnLogIn, fnLogOut)\n return True\n except:\n config.logger.error('cannot copy report file: %s' % fnLogIn)\n return False\n\ndef main(args=None):\n import argparse\n config = L2A_Config(None)\n processorId = config.processorName +'. Version: '+ config.processorVersion + ', created: '+ config.processorDate + \\\n ', supporting Level-1C product version 14.2 - ' + str(config.productVersion)\n \n parserPDGS = argparse.ArgumentParser(description=processorId + '.',add_help=False)\n parserPDGS.add_argument('--mode', help='Mode: generate_datastrip, process_user_product, process_tile')\n namespace,dummy = parserPDGS.parse_known_args()\n parser = argparse.ArgumentParser(description=processorId + '.',add_help=True)\n if namespace.mode == 'TOOLBOX' or namespace.mode is None:\n parser.add_argument('input_dir', help='Directory of Level-1C input')\n\n parser.add_argument('--mode', help='Mode: generate_datastrip, process_tile')\n parser.add_argument('--resolution', type=int, choices=[10, 20, 60], help='Target resolution, can be 10, 20 or 60m. If omitted, only 20 and 10m resolutions will be processed')\n parser.add_argument('--datastrip', help='Datastrip folder')\n parser.add_argument('--tile', help='Tile folder')\n parser.add_argument('--output_dir', help='Output directory')\n parser.add_argument('--work_dir', help='Work directory')\n parser.add_argument('--img_database_dir', help='Database directory for L1C input images')\n parser.add_argument('--res_database_dir', help='Database directory for results and temporary products')\n parser.add_argument('--processing_centre', help='Processing centre as regex: ^[A-Z_]{4}$, e.g \"SGS_\"')\n parser.add_argument('--archiving_centre', help='Archiving centre as regex: ^[A-Z_]{4}$, e.g. \"SGS_\"')\n parser.add_argument('--processing_baseline', help='Processing baseline in the format: \"dd.dd\", where d=[0:9]')\n parser.add_argument('--raw', action='store_true', help='Export raw images in rawl format with ENVI hdr')\n parser.add_argument('--tif', action='store_true', help='Export raw images in TIFF format instead of JPEG-2000')\n parser.add_argument('--sc_only', action='store_true', help='Performs only the scene classification at 60 or 20m resolution')\n parser.add_argument('--cr_only', action='store_true', help='Performs only the creation of the L2A product tree, no processing')\n parser.add_argument('--debug', action='store_true', help='Performs in debug mode')\n #parser.add_argument('--profile', action='store_true', help='Profiles the processor\\'s performance')\n parser.add_argument('--GIP_L2A', help='Select the user GIPP')\n parser.add_argument('--GIP_L2A_SC', help='Select the scene classification GIPP')\n parser.add_argument('--GIP_L2A_AC', help='Select the atmospheric correction GIPP')\n parser.add_argument('--GIP_L2A_PB', help='Select the processing baseline GIPP')\n args = parser.parse_args()\n config = parseCommandLine(args)\n if args.debug:\n config.logLevel = 'DEBUG'\n \n if config.operationMode == 'INVALID':\n return FAILURE\n\n dt = datetime.utcnow().strftime('%Y%m%dT%H%M%S')\n config.setSchemes()\n\n # this is to set the version info from the L1C User Product:\n if not config.setProductVersion():\n return FAILURE\n\n if config.operationMode == 'TOOLBOX':\n if not config.readPreferences():\n return FAILURE\n if config.create_L2A_UserProduct():\n config.configure_L2A_UP_metadata()\n L2A_UP_ID = os.path.join(config.logDir, config.L2A_UP_ID)\n logName = L2A_UP_ID + '_' + dt + '_report.xml'\n logDir = config.logDir\n if not os.path.exists(logDir):\n os.mkdir(logDir)\n config.fnLog = os.path.join(logDir, logName)\n\n elif config.operationMode == 'PROCESS_TILE':\n config.create_L2A_Tile()\n L2A_TILE_ID = os.path.join(config.work_dir, config.L2A_TILE_ID)\n logName = L2A_TILE_ID + '_' + dt + '_report.xml'\n config.fnLog = os.path.join(config.work_dir, logName)\n \n elif config.operationMode == 'GENERATE_DATASTRIP':\n L2A_DS_ID = os.path.join(config.work_dir, config.datastrip.replace('L1C', 'L2A'))\n logName = L2A_DS_ID + '_'+ dt + '_report.xml'\n config.fnLog = os.path.join(config.work_dir, logName)\n if not config.readPreferences():\n return FAILURE\n \n # create and initialize the base log system:\n logger = L2A_Logger('sen2cor', fnLog = config.fnLog\\\n , logLevel = config.logLevel\\\n , operation_mode = config.operationMode)\n config.logger = logger\n config.logger.stream('%s started ...' % processorId)\n if float32(config.productVersion) < 14.5:\n config.logger.stream('Old product version %2.1f detected, - will be updated to 14.5' % config.productVersion)\n config.logger.stream('Processing baseline will also be updated')\n else:\n config.logger.stream('Product version: %2.1f' % (config.productVersion))\n config.logger.stream('Operation mode: %s' % (config.operationMode))\n\n try:\n f = open(config.processingStatusFn, 'w')\n f.write('0.0\\n')\n f.close()\n except:\n config.logger.error('cannot create process status file: %s' % config.processingStatusFn)\n return FAILURE\n\n if config.processingBaseline:\n config.logger.stream('Processing baseline: %05.2f' % config.processingBaseline)\n else:\n config.logger.error('No Processing baseline found.') \n config.tStart = time()\n try:\n f = open(config.fnLog, 'w')\n f.write('\\n')\n f.write('\\n')\n f.close()\n except:\n config.logger.error('cannot update the report file: %s' % config.fnLog)\n return FAILURE\n \n if config.operationMode == 'GENERATE_DATASTRIP':\n from L2A_ProcessDataStrip import L2A_ProcessDataStrip\n ds = L2A_ProcessDataStrip(config)\n if ds.generate():\n result = SUCCESS\n else:\n result = FAILURE\n else:\n # prepare the processing:\n if args.resolution == None:\n resolution = 0\n else:\n resolution = args.resolution\n config.setTimeEstimation(resolution)\n try:\n f = open(config.processingStatusFn, 'w')\n f.write('0.0\\n')\n f.close() \n except:\n config.logger.error('cannot create process status file: %s' % config.processingStatusFn) \n return FAILURE\n \n if config.operationMode == 'PROCESS_TILE':\n from L2A_ProcessTilePdgs import L2A_ProcessTile\n config.resolution = resolution\n try:\n tile = L2A_ProcessTile(config)\n if tile.process() == True:\n result = SUCCESS\n else:\n result = FAILURE\n except Exception as e:\n if e.args[0] == 2:\n if 'pic' in e.filename:\n result = ALREADY_PROCESSED\n else:\n logger = L2A_Logger('sen2cor', operation_mode=config.operationMode)\n logger.stream(e, exc_info=True)\n sys.exit(1)\n\n elif config.operationMode == 'TOOLBOX':\n from L2A_ProcessTileToolbox import L2A_ProcessTile\n config.resolution = resolution\n config.create_L2A_Datastrip()\n L2A_TILES = config.updateTiles()\n if not L2A_TILES:\n config.logger.error('no tile in GRANULE folder found')\n result = FAILURE\n else:\n S2A_mask = '*L2A_T*'\n for tile in L2A_TILES:\n if (fnmatch.fnmatch(tile, S2A_mask) == False):\n continue\n\n config.L2A_TILE_ID = tile\n try:\n tile = L2A_ProcessTile(config)\n if tile.process() == True:\n result = SUCCESS\n else:\n result = FAILURE\n if not postprocess(config):\n result = FAILURE\n except Exception as e:\n logger = L2A_Logger('sen2cor', operation_mode=config.operationMode)\n logger.stream(e, exc_info=True)\n result = FAILURE\n\n # final cleanup in Toolbox mode:\n import glob\n try:\n files = glob.glob(os.path.join(config.L2A_UP_DIR, 'GRANULE', 'L2A_*', '*.h5'))\n for f in files:\n os.remove(f)\n except:\n pass\n try:\n os.remove(config.picFn)\n except:\n pass\n\n if not config.logger:\n logger = L2A_Logger('sen2cor',operation_mode = config.operationMode)\n config.logger = logger\n\n if result == FAILURE:\n config.logger.stream('Progress[%]: 100.00 : Application terminated with at least one error.\\n')\n elif result == ALREADY_PROCESSED:\n config.logger.stream('Progress[%]: 100.00 : Product already processed.\\n')\n result = SUCCESS\n else:\n config.logger.stream('Progress[%]: 100.00 : Application terminated successfully.\\n')\n \n return result\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"L2A_Process.py","file_name":"L2A_Process.py","file_ext":"py","file_size_in_byte":21965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"456515069","text":"import string\nimport random\nimport datetime\nimport time\n\nfrom psych_app.models import PsychDiagnosis, MedicalDiagnosis, Medication, Subject\nfrom psych_app.forms import GetTestForm\nfrom .models import Question, Response, Test \nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.core import serializers\nfrom django.db.models import Count\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.template import RequestContext, Context, loader\nfrom django.urls import reverse\nimport pdb\nimport os\nimport urllib.request\n\n# Create your views here.\ndef test_home(request):\n context = {}\n if request.method == 'POST':\n get_test_form = GetTestForm(request.POST)\n if get_test_form.is_valid():\n get_test_form = get_test_form.clean()\n potential_test_code = get_test_form['test_code'] \n test_exists = get_object_or_404(Test, test_code=potential_test_code)\n print(test_exists)\n context['test'] = test_exists\n return redirect('/test/test_page/{0}'.format(test_exists)) \n else:\n return redirect('/test')\n else:\n template = \"test_app/test_home.html\"\n get_test_form = GetTestForm()\n context['get_test_form'] = get_test_form\n return render(request, template, context)\n\ndef code_generator(size, chars):\n return ''.join(random.choice(chars) for _ in range(size))\n\ndef generate_test(subject, user):\n code = code_generator(8, string.ascii_uppercase + string.digits)\n return Test(test_code=code, subject=subject, user=user)\n \ndef test_prestart(request, test_code):\n context = {}\n template = \"test_app/test_start_page.html\"\n context['test_code'] = test_code\n return render(request, template, context)\n \ndef question(request, test_code, question):\n question_current = Question.objects.get(id=question)\n if request.method == 'POST':\n question_current = Question.objects.get(id=question)\n seq = int(question_current.seq)\n\n answer = request.POST['answer']\n\n if answer == \"-1\":\n print(\"no answer selected\")\n start_time = str(datetime.datetime.now())\n context = {'test_code':test_code, 'question':question_current, 'start_time': start_time, 'error_message': 'Make sure to select an answer before continuing'}\n template = \"test_app/question_page.html\"\n return render(request, template, context)\n else:\n test = Test.objects.get(pk=test_code)\n\n #delete old test responses if they exist\n old_responses = test.responses.filter(question=question)\n if old_responses.exists():\n old_responses.delete()\n\n #save new response\n start_time = request.POST['start_time']\n now = str(datetime.datetime.now())\n response = Response(question=question_current, response=answer, start_time=start_time, submit_time=now)\n response.save()\n test.responses.add(response)\n\n seq = int(question_current.seq)\n next_seq = seq +1\n\n #if test is complete\n if next_seq > Question.objects.all().count():\n template = 'test_app/test_completed.html'\n context = {}\n context['test'] = test\n context['score'] = test.is_finished\n return render(request, template, context)\n else:\n #get next question in seqence\n next_question = Question.objects.get(seq=next_seq) \n \n return redirect('/test/test_page/{0}/{1}'.format(test_code, next_question.id))\n else:\n start_time = str(datetime.datetime.now())\n context = {'test_code':test_code, 'question':question_current, 'start_time': start_time}\n template = \"test_app/question_page.html\"\n return render(request, template, context)\n\n# @login_required\n# def generate_test_code(request, subject):\n# test = generate_test(user=request.user, subject=Subject.objects.get(id=subject)) \n# test.save()\n\n# #blogs = Blog.objects.filter(author=author).values_list('id', flat=True)\n# path = \"http://3.16.130.76:8000/test/test_page/\"\n# context = {'test': test, 'path':path}\n# template = \"test_app/generated_code.html\"\n# return render(request, template, context)\n\n@login_required\ndef get_user_tests(request, subject):\n request.session['selected_subject_id'] = subject\n\n if request.method == 'POST':\n test = generate_test(user=request.user, subject=Subject.objects.get(id=subject)) \n test.save()\n return HttpResponseRedirect(request.path_info)\n\n tests = Test.objects.filter(subject=subject)\n context = {'tests': tests}\n\n #Get public IP\n external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')\n context['path'] = external_ip + \":8000/test/test_page/\"\n\n context['subject'] = subject\n template = \"test_app/generated_code.html\"\n\n return render(request, template, context)\n\n@login_required\ndef delete_test(request, test_code):\n test = get_object_or_404(Test, test_code=test_code)\n subject = test.subject.id\n test.delete()\n return redirect('/test/gen_test/' + subject)\n\n","sub_path":"test_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"135988232","text":"import uuid\n\nfrom django.conf import settings\nfrom django.db import models\n# from django.db.models.signals import pre_save, post_save, m2m_changed\n\nfrom products.models import Product\n\n\nUser = settings.AUTH_USER_MODEL\n\nclass Viewed_Product_Manager(models.Manager):\n def new_or_get(self, request):\n viewed_product_id = request.session.get(\"viewed_product_id\", None)\n qs = self.get_queryset().filter(id=viewed_product_id)\n if qs.count() == 1:\n new_obj = False\n viewed_product_obj = qs.first()\n if request.user.is_authenticated and viewed_product_obj.user is None:\n viewed_product_obj.user = request.user\n viewed_product_obj.save()\n else:\n viewed_product_obj = Viewed_Product.objects.new(user=request.user)\n new_obj = True\n request.session['viewed_product_id'] = viewed_product_obj.id\n return viewed_product_obj, new_obj\n\n def new(self, user=None):\n user_obj = None\n if user is not None:\n if user.is_authenticated:\n user_obj = user\n return self.model.objects.create(user=user_obj)\n\n def foo():\n \tprint('this is from the Viewed_Product model!!')\n\nclass Viewed_Product(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)\n # products = models.SlugField(Product, blank=True)\n # products = models.CharField(max_length=200)\n # products = models.SlugField(Product, blank=True)\n\n \n\n\t# slug \t\t= models.SlugField(blank=True, unique=True)\n\n # subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)\n # total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)\n # updated = models.DateTimeField(auto_now=True)\n # timestamp = models.DateTimeField(auto_now_add=True)\n\n objects = Viewed_Product_Manager()\n\n # def __str__(self):\n # return str(self.id)\n\nclass Viewed_Product_Object(models.Model):\n # id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)\n user = models.ForeignKey(Viewed_Product, on_delete=models.CASCADE)\n products = models.CharField(max_length=200)\n\n # def __str__(self):\n # return '%s %s' % (self.user, self.products)\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"viewed_products/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"506380454","text":"\"\"\"\nA function to get the action list corresponding to an indicated program.\n\n@author: Andrew Curry\n\"\"\"\nfrom elasticsearch import Elasticsearch\n\n\ndef get_action_list(program_name: str) -> str:\n \"\"\"\n A function to get the action list corresponding to an indicated program.\n Returns \"\" if there is no matching program.\n Input should be in the format 'Program:n'\n \"\"\"\n short_name = int(program_name[8:])\n es = Elasticsearch([{'host': 'localhost', 'port': 9200}])\n res = es.search(\n index='actions-index', \n params= {'size': 1}, \n body={\"query\": {\"match\": {'name' : short_name}}})\n for hit in res['hits']['hits']:\n return hit['_source']['actions']\n return \"\"","sub_path":"action_retrieval.py","file_name":"action_retrieval.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"506667352","text":"import pygame\nimport pygame.draw\nimport pygame.event\nimport pygame.font\nfrom PyQt5.QtCore import pyqtSignal,QObject\n\nfrom model.logic.gui_registration_operation.operation_gui_registrator import RegistratorGuiOperation\nfrom veiw.view_on_desctop_screen import VeiwOnDesctop\n\n\nclass Registrator_GUI(QObject):\n\n log_in_signal = pyqtSignal(str,str,str)\n next_step_signal = pyqtSignal()\n add_new_record_signal = pyqtSignal(str)\n guest_mode_signal = pyqtSignal()\n\n def __init__(self):\n super(Registrator_GUI, self).__init__()\n\n pygame.font.init()\n pygame.init()\n\n self.user_name = []\n self.password = []\n\n # списки словарей с координатами и размерами клавиш\n self.buttons_to_show = []\n RegistratorGuiOperation.creating_list_of_buttons_to_show(self.buttons_to_show)\n self.buttons_to_hide = []\n RegistratorGuiOperation.creating_list_of_buttons_to_hide(self.buttons_to_hide)\n\n # списки словарей с координатами и самими надписями\n self.captions_to_show = []\n RegistratorGuiOperation.create_list_of_captures_to_show(self.captions_to_show)\n\n self.captions_to_hide = []\n RegistratorGuiOperation.create_list_of_captures_to_hide(self.captions_to_hide)\n\n self.dinamical_captions_to_show = []\n RegistratorGuiOperation.create_list_of_dinamical_captions_to_show(self.dinamical_captions_to_show,\n [self.user_name,self.password])\n self.dinamical_captions_to_hide = []\n\n self.information_show_info_screen = []\n\n self.field_to_add = None\n self.showing_dinamicals_captions = True\n self.create_objects_and_screens()\n\n\n def check_permisions(self):\n self.registrator.gui.log_in_signal.connect(self.client.write_to_db_socket)\n self.registrator.gui.add_new_record_signal.connect(self.client.write_to_db_socket)\n\n def change_info_on_info_screen_from_db(self,info_to_scow_on_info_screen):\n self.information_show_info_screen = list(info_to_scow_on_info_screen)\n\n def create_objects_and_screens(self):\n\n self.window = pygame.display.set_mode((800, 300))\n pygame.display.set_caption('Registration')\n self.screen = pygame.Surface((800, 270))\n self.info_screen = pygame.Surface((800,30))\n self.fontobject = pygame.font.Font(None, 18)\n\n def show_buttons(self):\n color = (150,20,255)\n for i in self.buttons_to_show:\n val = list(i.values())[0]\n btn = pygame.Surface((val[0], val[1]))\n btn.fill(color)\n position = (val[2], val[3])\n VeiwOnDesctop.blitting_button_on_screen(self.screen,((30,54,128)),position,btn)\n\n def show_captions(self):\n for i in self.captions_to_show:\n position = list(i.values())[0]\n caption = list(i.keys())[0]\n VeiwOnDesctop.blitting_font_on_screen(self.screen,self.fontobject,caption,(255, 255, 255),position)\n\n def show_dinamicals_captions(self):\n cap,pos = '',(0,0)\n for i in self.dinamical_captions_to_show:\n if len(list(i.values())[0]) == 2:\n cap = ''.join(list(i.values())[0][0])\n\n elif len(list(i.values())[0]) == 3:\n cap = '*' * len(list(i.values())[0][0])\n\n pos = list(i.values())[0][1]\n VeiwOnDesctop.blitting_font_on_screen(self.screen, self.fontobject, cap, (255, 255, 255), pos)\n\n def show_info_on_info_screen(self):\n VeiwOnDesctop.blitting_font_on_screen(self.info_screen, self.fontobject, ''.join(self.information_show_info_screen),\n (255, 255, 255),(5, 5))\n\n def show_all_components(self):\n self.screen.fill((90, 60, 90))\n self.info_screen.fill((60, 90, 60))\n self.show_buttons()\n self.show_captions()\n self.show_dinamicals_captions()\n self.show_info_on_info_screen()\n VeiwOnDesctop.blitting_screen_on_window(self.window, self.screen, (0, 0))\n VeiwOnDesctop.blitting_screen_on_window(self.window, self.info_screen, (0, 270))\n\n pygame.display.flip()\n\n","sub_path":"model/entity/registrator_entity/registrator_gui.py","file_name":"registrator_gui.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"480777915","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 15 13:57:14 2016\n\n@author: austen\n\"\"\"\n#Thermodenuder Heat Tape Coverage Calculations\n#Import packages\nimport math as math\nimport pandas as pd\n\n#Import heat tape specifications file\nFilePath='/home/austen/Documents/Thermodenuder/Data/Initial Tests/12-20-16/OmegaHeatTapes.csv'\nHeatTapeSpecs=pd.read_csv(FilePath,header=0,sep=',')\n\n#Define constants for calculations\nPipeLength=1000.00\nPipeDiameter=0.5*2.54*10\nLengthPerCoil=2*math.pi*(PipeDiameter/2)\n\n#Write function to output calculations\ndef Equations(HeatTapeModel,TapeLength, TapeWidth, Gap, Voltage, Cost):\n MaxNumCoils=(TapeLength*12.0*2.54*10)/LengthPerCoil\n NumCoilsRequired=PipeLength/((TapeWidth*2.54*10)+Gap)\n MinCoilSpanwGap=PipeLength/MaxNumCoils\n CoilSpanwGap=PipeLength/NumCoilsRequired\n RequiredLessThanMax=MaxNumCoils>=NumCoilsRequired\n CalculationOutput=pd.Series(data={'Model':HeatTapeModel,'Cost (USD)':Cost,'Volts':Voltage,'Tape Length (Feet)':TapeLength,'Tape Width (Inches)':TapeWidth,'Max Coil #':MaxNumCoils,'Required Coil #':NumCoilsRequired,'Minimum Pipe Length Per Coil':MinCoilSpanwGap,'Nominal Pipe Length Per Coil (Gap Included)':CoilSpanwGap,'Nominal Less Than Maximum Coils':RequiredLessThanMax})\n CalculationOutput=pd.DataFrame(CalculationOutput).T\n return(CalculationOutput)\n \n#Perform calulations via looping over rows in the file\nResults=pd.DataFrame()\nfor i in range(len(HeatTapeSpecs.index)):\n OutputArray=Equations(HeatTapeModel=HeatTapeSpecs.loc[i,'Heat Tape Model Number'],Voltage=HeatTapeSpecs.loc[i,'Volts'],Cost=HeatTapeSpecs.loc[i,'Cost (USD)'],TapeLength=HeatTapeSpecs.loc[i,'Length (Feet)'],TapeWidth=HeatTapeSpecs.loc[i,'Width (Inches)'],Gap=5.0)\n# must be results=results.append(blah) to store the looped over data\n# ignore index is important, it basically returns the index as the row number of the particular dataframe you made\n Results=Results.append(OutputArray, ignore_index=True)\n#This is the proper way to sort through a data frame and drop rows\nfor index, row in Results.iterrows():\n if row['Nominal Less Than Maximum Coils']==False:\n Results.drop(index, inplace=True)\nfor index, row in Results.iterrows():\n if row['Volts']==240:\n Results.drop(index, inplace=True)\ncsv_filepath='/home/austen/Documents/Thermodenuder/CompatibleOmegaHeatTapes.csv'\nResults.to_csv(csv_filepath, sep=',')","sub_path":"src/HeatTapeSpecsEval.py","file_name":"HeatTapeSpecsEval.py","file_ext":"py","file_size_in_byte":2395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"602330294","text":"# Given two already-sorted lists:\n\n# Write a function that returns a new list that is the sorted merge of both of \n# them. For the above lists, our result would be:\n\n\n# It would be easy to do this by just using Python’s built-in sort method, \n# like this:\n# >>> out = a + b\n# >>> out.sort()\n\n# However, this would have the runtime of O(n log n), where n is the combined \n# length of a and b. You can get a much better runtime by exploiting the fact \n# that both of the input lists are already sorted.\n\n# Your challenge is to implement sort_ab where the runtime is O(a + b) (where a \n# and b are the lengths of those lists, respectively).\n\n\n\ndef sort_ab(a, b):\n \"\"\"Given already-sorted lists, `a` and `b`, return sorted list of both.\n\n You may not use sorted() or .sort().\n\n >>> a = [1, 3, 5, 7]\n >>> b = [2, 6, 8, 10]\n >>> sort_ab(a, b)\n [1, 2, 3, 5, 6, 7, 8, 10]\n\n \"\"\"\n\n a_ctr = 0 \n b_ctr = 0 \n sorted_ab = []\n\n # print(a, len(a))\n # print(b, len(b))\n\n while ( (a_ctr < len(a)) and (b_ctr < len(b)) ) : \n # print(a_ctr)\n # print(b_ctr)\n # print(sorted_ab)\n if a[a_ctr] < b[b_ctr] : \n # print(\"A\")\n sorted_ab.append(a[a_ctr])\n # print(sorted_ab)\n # print(a_ctr)\n a_ctr += 1 \n elif b[b_ctr] < a[a_ctr] : \n # print(\"B\")\n sorted_ab.append(b[b_ctr])\n b_ctr += 1\n elif a[a_ctr] == b[b_ctr] : \n # print(\"C\")\n sorted_ab.append(a[a_ctr])\n sorted_ab.append(b[b_ctr])\n a_ctr += 1 \n b_ctr += 1\n \n\n sorted_ab.extend(a[a_ctr:])\n sorted_ab.extend(b[b_ctr:])\n\n return sorted_ab\n\n\nif __name__ == '__main__': \n\n import doctest \n\n results = doctest.testmod()\n\n if results.failed == 0: \n print(\"ALL TESTS PASSED\")\n\n\n","sub_path":"sort_sorted_list.py","file_name":"sort_sorted_list.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"521680334","text":"import torch as tr\nimport numpy as np\nimport pickle as pk\nGame2048State = __import__('2048_game').Game2048State\nimport expectimax_ai as expect_ai\n\n# #1\n# Encode a 2048_game.Game2048State\n# Will be called by get_batch\n# return a tensor\ndef encode(state):\n return tr.from_numpy(state.board).float()\n \n# #2\n# Generate training data for NN\n# Needs to call encode function to encode state\n# return: (input, output)\n# input: stacked list of encoded states\n# output: stacked list of correspond utilities\ndef get_batch(board_size, num_games):\n inputs = []\n outputs = []\n\n # Perform 25 games\n for _ in range(0, 25):\n # Start new game\n state = Game2048State(board_size)\n state = state.initialState()\n\n # Iterate num_games times\n for i in range(0, num_games):\n # Game ended\n if state.isGameEnded()[0]: break\n\n # Record state\n inputs.append(encode(state))\n\n # Tree search next state\n state = expect_ai.getNextState(state)\n\n # Utility of tree searched state\n node = expect_ai.Node(state, None)\n outputs.append(tr.tensor([node.getUtility()]))\n\n # Add new tile to the game\n state = state.addNewTile()\n \n # Stack tensor\n inputs = tr.stack(inputs)\n outputs = tr.stack(outputs)\n\n # Result\n return (inputs, outputs)\n\n# #3\n# Generate training data file\n# Call get_batch function, save training data as a \".pkl\" file\nif __name__ == \"__main__\":\n for board_size in [2,4,6,8,10]:\n print(\"Working on data%d.pkl...\" % board_size)\n num_games = 50\n with open(\"data%d.pkl\" % board_size, \"wb\") as f: pk.dump(get_batch(board_size, num_games), f)\n print(\"data%d.pkl generated\" % board_size)","sub_path":"game-tree+NN-based-AI/expectimax_NN_data.py","file_name":"expectimax_NN_data.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"493457658","text":"\"\"\"\nModule for running ARIMA on players\n\"\"\"\nimport time\nimport streamlit as st\nimport numpy as np\nimport pandas as pd\nimport pmdarima as pm\nfrom sklearn.preprocessing import PowerTransformer\n\ndef calculate_errors(residuals):\n \"\"\" Calculates errors based on residuals \"\"\"\n num_residuals = len(residuals)\n mfe = (residuals.sum() / num_residuals).tolist()[0]\n mae = (residuals.abs().sum() / num_residuals).tolist()[0]\n rmse = (residuals.pow(2).sum().pow(0.5)).tolist()[0]\n residuals = residuals.values\n residuals = [value.item() for value in residuals]\n return mfe, mae, rmse\n\ndef calculate_test_residuals(prediction_array, test_data):\n \"\"\" Calculates test residuals based on prediction and test data \"\"\"\n prediction_array = prediction_array.reshape(len(test_data), 1)\n test_data = test_data.values\n residuals = np.subtract(test_data, prediction_array)\n residuals = residuals.tolist()\n residuals = pd.DataFrame(residuals)\n return residuals\n\ndef player_arima(data,\n player_name,\n index='date',\n feature='cumStatpoints',\n forecast_from='2018-10-03',\n transform='none',\n player_id=None,\n roster=None,\n summary=False):\n \"\"\" performs Auto-ARIMA on a single player \"\"\"\n # TODO: add logic for if the player ID is given but not a roster (use function in package)\n if player_id and roster:\n player_name = roster[roster['Unnamed: 0'] == player_id]\n player_df = data[data['name'] == player_name]\n player_df.drop_duplicates(subset='date', keep='first', inplace=True)\n player_train_df = player_df[player_df['date'] < forecast_from]\n player_test_df = player_df[player_df['date'] >= forecast_from]\n player_train_df = player_train_df.loc[:, [index, feature]]\n player_train_df = player_train_df.set_index(index, drop=True)\n if player_train_df.shape[0] == 0:\n st.write('{} is a rookie!'.format(player_name))\n return None\n if transform == 'log':\n # TODO: make this stat agnostic\n player_train_df.loc[:, 'logValues'] = np.log(player_train_df['cumStatpoints'])\n elif transform == 'yj':\n transformer = PowerTransformer()\n transformer.fit(player_train_df.values.reshape(-1, 1))\n player_train_df.loc[:, 'transformedValues'] = transformer \\\n .transform(\n player_train_df['cumStatpoints'] \\\n .values.reshape(-1, 1))\n player_train_df.drop('cumStatpoints', axis=1, inplace=True)\n player_test_df = player_test_df.loc[:, [index, feature]]\n player_test_df = player_test_df.set_index(index, drop=True)\n # player_train_df = player_train_df[:'2018-10-03']\n # player_test_df = player_test_df['2018-10-03':]\n if player_test_df.shape[0] == 0:\n st.write('{} retired!'.format(player_name))\n return None\n start_time = time.time()\n st.write('Searching ARIMA parameters for {}...'.format(player_name))\n try:\n model = pm.auto_arima(player_train_df,\n start_p=1,\n start_q=1,\n max_p=5,\n max_q=5,\n max_d=3,\n m=3,\n start_P=0,\n start_Q=0,\n seasonal=True,\n information_criterion='aicc',\n error_action='ignore',\n suppress_warnings=True,\n stepwise=True)\n st.write('Model built, fitting...')\n model.fit(player_train_df)\n except ValueError:\n st.write(\"{} doesn't have enough data!\".format(player_name))\n return None\n except IndexError:\n st.write('Index error for {}'.format(player_name))\n return None\n except:\n st.write('Unhandled error for {}'.format(player_name))\n return None\n predictions, intervals = model.predict(n_periods=player_test_df.shape[0], return_conf_int=True)\n if transform == 'log':\n predictions = np.exp(predictions)\n intervals = np.exp(intervals)\n elif transform == 'yj':\n predictions = transformer.inverse_transform(predictions.reshape(-1, 1))\n low_intervals = transformer.inverse_transform(intervals[:, 0].reshape(-1, 1))\n high_intervals = transformer.inverse_transform(intervals[:, 1].reshape(-1, 1))\n end_time = time.time()\n if transform != 'yj':\n low_intervals = []\n high_intervals = []\n for low, high in intervals:\n low_intervals.append(low)\n high_intervals.append(high)\n prediction_residuals = calculate_test_residuals(predictions, player_test_df)\n if summary:\n st.text(model.summary())\n train_residuals = pd.DataFrame(model.resid())\n train_mfe, train_mae, train_rmse = calculate_errors(train_residuals)\n test_mfe, test_mae, test_rmse = calculate_errors(prediction_residuals)\n model_params = model.get_params()\n p, d, q = model_params['order']\n try:\n P, D, Q, m = model_params['seasonal_order']\n except TypeError:\n st.write('Search failed to find valid options.')\n return None\n st.write(\"{0}'s Auto-ARIMA({1},{2},{3})({4},{5},{6},{7}) took {8:.3f} seconds.\" \\\n .format(player_name, p, d, q, P, D, Q, m, end_time-start_time))\n results_df = pd.DataFrame({'forecastStart':forecast_from,\n 'aic':model.aic(),\n 'p':p,\n 'd':d,\n 'q':q,\n 'P':P,\n 'D':D,\n 'Q':Q,\n 'm':m,\n 'trainMfe':train_mfe,\n 'trainMae':train_mae,\n 'trainRmse':train_rmse,\n 'trainResiduals':[train_residuals],\n 'testMfe':test_mfe,\n 'testMae':test_mae,\n 'testRmse':test_rmse,\n 'testResiduals':[prediction_residuals],\n 'intervalLow':[low_intervals],\n 'intervalHigh':[high_intervals]},\n index=[player_name])\n return results_df\n\ndef all_player_arima(data, roster, save_loc, transform='none', print_status=False):\n \"\"\" performs Auto_ARIMA on all players in a given roster \"\"\"\n if print_status:\n print('Running Auto-ARIMAs...')\n results = pd.DataFrame()\n for index, player in roster.iterrows():\n if print_status:\n print('Player {}'.format(index))\n player_name = player['name']\n player_results = player_arima(data, player_name=player_name, transform=transform)\n if isinstance(player_results, type(None)):\n st.write('Skipping {}'.format(player_name))\n continue\n st.dataframe(player_results)\n results = pd.concat([results, player_results])\n results.to_pickle(save_loc)\n if print_status:\n print('Done!')\n return results\n","sub_path":"AutoDraft/autodraft/arima.py","file_name":"arima.py","file_ext":"py","file_size_in_byte":7415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"425527095","text":"\n'''\nYou will receive a list of the cutomers (numbers seperated by comma and space \", \")\nand list of your taxis (numbers seperated by comma and space \", \").\n -- Each number from the customer list represents how much time it takes to drive the customer to his/her destination.\n -- Each number from the taxis list represents how much time they can drive, before they need to refill their tanks.\n -- Keep track of the total time passed to drive all the customers to their destinations (values of all customers).\n -- Each time you tend customers you should put the first customer in the last taxi until there are no customers left.\n\n - If the taxi can drive the customer to his/her destination, he does and\n - You must add the time passed to drive the customer to his/her destination to the total time.\n - Remove both the customer and the taxi.\n - If the taxi cannot drive the customer to his/her destination,\n leave the customer at the beginning of the queue and remove the taxi.\n\nAt the end if you have successfully driven all the customers to their destinations,\n print \"All customers were driven to their destinations Total time: {total_time} minutes\"\n\nOtherwise, if you ran out of taxis and there are still some customers left print \n \"Not all customers were driven to their destinations Customers left: {left_customers joined by \", \"}\"\"\n'''\n\nfrom collections import deque\n\ncustomers = deque([int(i) for i in input().split(\", \")])\ntaxis = [int(i) for i in input().split(\", \")]\n\n#print(customers)\n#print(taxis)\n\ntotal_drive = 0\ntaxis_left = True\n\nwhile customers:\n if len(taxis) > 0:\n customer = customers[0]\n taxi = taxis[-1]\n\n if taxi >= customer:\n total_drive += customer\n customers.popleft()\n taxis.pop()\n\n else:\n taxis.pop()\n else:\n taxis_left = False\n break\n\nif len(customers) == 0:\n print(\"All customers were driven to their destinations\")\n print(f'Total time: {total_drive} minutes')\nelse:\n print('Not all customers were driven to their destinations')\n print(f'Customers left: {\", \".join([str(c) for c in customers])}')\n","sub_path":"2_advanced/exam_prep/2020-08-19-01_taxi_express.py","file_name":"2020-08-19-01_taxi_express.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"233490000","text":"import itertools\nimport sys\n\nmain_grid = [[] for x in range(9)]\ncandidates_grid = [[set() for y in range(9)] for x in range(9)]\ncol_set = [set() for x in range(9)] # Access: col_set[x]\nrow_set = [set() for x in range(9)] # Access: row_set[y]\nsub_grid_set = [[set() for y in range(3)] for x in range(3)]\nfull_set = {1, 2, 3, 4, 5, 6, 7, 8, 9}\ncoordinates_set = {0, 1, 2, 3, 4, 5, 6, 7, 8}\n\ndef init():\n with open(\"../puzzles/extreme3.txt\") as puzzle:\n for y in range(9):\n next_line = puzzle.readline()\n for x in range(9):\n main_grid[x].append(int(next_line[x]))\n if next_line[x] != '0':\n col_set[x].add(int(next_line[x]))\n row_set[y].add(int(next_line[x]))\n sub_grid_set[x // 3][y // 3].add(int(next_line[x]))\n\n for y in range(9):\n for x in range(9):\n if main_grid[x][y] == 0:\n candidate_set = set.union(row_set[y], col_set[x], sub_grid_set[x // 3][y // 3])\n candidates_grid[x][y] = full_set.difference(candidate_set)\n\ndef iter_over_subgrids(func, *args):\n for sub_grid_y in range(3):\n for sub_grid_x in range(3):\n func(sub_grid_x, sub_grid_y, *args)\n\ndef iter_over_line(func, *args):\n for square in range(9):\n func(square, *args)\n\ndef print_main_grid():\n for y in range(9):\n for x in range(9):\n print(main_grid[x][y], end=\"\")\n if x % 3 == 2:\n print(\" \", end=\"\")\n print(\"\")\n\ndef is_solved():\n for y in range(9):\n if len(row_set[y]) != 9:\n return False\n return True\n\ndef pencil_in(solution, x, y, func):\n sub_grid_x = x // 3\n sub_grid_y = y // 3\n main_grid[x][y] = solution\n row_set[y].add(solution)\n col_set[x].add(solution)\n sub_grid_set[sub_grid_x][sub_grid_y].add(solution)\n candidates_grid[x][y].clear()\n for sg_y in range(sub_grid_y * 3, sub_grid_y * 3 + 3):\n for sg_x in range(sub_grid_x * 3, sub_grid_x * 3 + 3):\n candidates_grid[sg_x][sg_y].discard(solution)\n for i in range(9):\n candidates_grid[x][i].discard(solution)\n candidates_grid[i][y].discard(solution)\n\ndef single_candidate_square(y):\n for x in range(9):\n if len(candidates_grid[x][y]) == 1:\n pencil_in(candidates_grid[x][y].pop(), x, y, single_candidate_square)\n \ndef disjoint_subsets_row(y, n):\n sets = []\n for x in range(9):\n if 1 < len(candidates_grid[x][y]) <= n:\n sets.append(candidates_grid[x][y])\n for d in get_disjoint_subsets(sets, n):\n for x in range(9):\n if not candidates_grid[x][y].issubset(d):\n candidates_grid[x][y] = candidates_grid[x][y].difference(d)\n\ndef disjoint_subsets_col(x, n):\n sets = []\n for y in range(9):\n if 1 < len(candidates_grid[x][y]) <= n:\n sets.append(candidates_grid[x][y])\n for d in get_disjoint_subsets(sets, n):\n for y in range(9):\n if not candidates_grid[x][y].issubset(d):\n candidates_grid[x][y] = candidates_grid[x][y].difference(d)\n\ndef disjoint_subsets_subgrid(sub_grid_x, sub_grid_y, n):\n sets = []\n for y in range(sub_grid_y * 3, sub_grid_y * 3 + 3):\n for x in range(sub_grid_x * 3, sub_grid_x * 3 + 3):\n if 1 < len(candidates_grid[x][y]) <= n:\n sets.append(candidates_grid[x][y])\n for d in get_disjoint_subsets(sets, n):\n for y in range(sub_grid_y * 3, sub_grid_y * 3 + 3):\n for x in range(sub_grid_x * 3, sub_grid_x * 3 + 3):\n if not candidates_grid[x][y].issubset(d):\n candidates_grid[x][y] = candidates_grid[x][y].difference(d)\n\ndef get_disjoint_subsets(sets, n):\n disjoint_subsets = set()\n for combination in itertools.combinations(sets, n):\n superset = set()\n for c in combination:\n superset = superset.union(c)\n if len(superset) == n:\n disjoint_subsets.add(frozenset(superset))\n return disjoint_subsets\n\ndef solve():\n for x in range(100):\n iter_over_line(single_candidate_square)\n for n in range(2, 5):\n iter_over_line(disjoint_subsets_row, n)\n iter_over_line(disjoint_subsets_col, n)\n iter_over_subgrids(disjoint_subsets_subgrid, n)\n if is_solved() == 1:\n print_main_grid()\n break\n\ninit()\nsolve()","sub_path":"src/sudoku-minimal.py","file_name":"sudoku-minimal.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"605368879","text":"def judge(q,m):\n for i in range(m):\n for j in range(i):\n if q[i] == q[j]:\n return 0\n elif q[i] == q[j] + i - j:\n return 0\n elif q[i] == q[j] + j - i:\n return 0\n\n return 1\n\ndef backtracking(q,i):\n global m2\n k = 1\n for j in range(8):\n q[i]=j\n if i != 0: #不为第一行,则判断当前可行性,不可行则回溯到上一层\n k = judge(q,i+1)\n if k == 1:\n if (i+1 != 8): #可行,则继续往下填充皇后\n backtracking(q,i+1)\n else: #若为最后一行,则计数+1\n m2+=1\n print(q)\n\n\nm2 = 0\nq = [[]]*8\nbacktracking(q,0)\nprint(m2)\n\n","sub_path":"8queen1.py","file_name":"8queen1.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"506809106","text":"import argparse\nimport random\nimport subprocess\nimport sys\nimport xmlrpc.client\n\nfrom transformers import GPT2Tokenizer\n\nserver = xmlrpc.client.ServerProxy('http://localhost:8000')\n\ntokenizer = GPT2Tokenizer.from_pretrained('distilgpt2')\n\nPROMPT='''NOUNS: cheetah lion seal mosquito dog cat\nOUTLIERS: none\nCLASS: animal\n\nNOUNS: shirt pants computer skirt dress slacks suit tie jacket\nOUTLIERS: computer\nCLASS: clothing\n\nNOUNS: computer candle controller lighter cup paper\nOUTLIERS: none\nCLASS: object\n\nNOUNS: monitor tv display\nOUTLIERS: none\nCLASS: screen\n\nNOUNS: google dog amazon yahoo netflix\nOUTLIERS: dog\nCLASS: website\n\nNOUNS: %s\nOUTLIERS:'''\n\ndef gen_nouns(nouns):\n\tinp = PROMPT % (nouns,)\n\tinput_ids = tokenizer(inp, return_tensors='pt').input_ids\n\n\tresp = server.gen(inp, args.temp, args.rep_pen, min(2048, len(input_ids.squeeze())+args.resp_length))\n\n\treturn resp.split('\\n')[:len(inp.split('\\n'))+1][-1].split(': ')[-1]\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Complete text with GPT')\n\n\tparser.add_argument('nouns', type=str)\n\n\tparser.add_argument('--temp', type=float, default=0.2, help='Completion temperature')\n\n\tparser.add_argument('--rep_pen', type=float, default=1.1, help='Completion repetition penalty')\n\n\tparser.add_argument('--resp_length', type=int, default=128, help='Completion length, in tokens')\n\n\tparser.add_argument('--prompt_limit', type=int, default=512, help='The maximum number of tokens to use for the story generation prompt')\n\n\tparser.add_argument('--num_stories', type=int, default=5, help='The number of stories to generate')\n\n\tparser.add_argument('--num_similar', type=int, default=3, help='The number of similar stories to generate for each story, to help refine schemas')\n\n\tparser.add_argument('--similar_temp', type=float, default=0.4, help='Completion temperature for similar story generation')\n\n\tparser.add_argument('--similar_rep_pen', type=float, default=1.12, help='Completion repetition penalty for similar story generation')\n\n\tparser.add_argument('--output_dir', type=str, default='.', help='The directory to store the output story files in AFTER tokenization')\n\n\tparser.add_argument('--orig_story_dir', type=str, default='.', help='The directory to store the output story files in BEFORE tokenization')\n\n\targs = parser.parse_args()\n\n\tprint(gen_nouns(args.nouns))\n","sub_path":"pyschemas/noun_generalizer/gpt_gen.py","file_name":"gpt_gen.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"59970153","text":"import copy\nimport itertools\n\n# 데이터 구성\nn, m, k = list(map(int, input().split(\" \")))\nmat = []\nfor _ in range(n):\n row = list(map(int, input().split(\" \")))\n mat.append(row)\ncases = []\nfor _ in range(k):\n row = list(map(int, input().split(\" \")))\n cases.append(row)\ncomb_cases = itertools.permutations(cases, k) # 순서를 바꿔서도 진행해봐야 함\n\n# 시계방향으로 회전시켜주는 함수\ndef rotate(mat, case):\n # 각 인덱스가 +1 되어 있기 때문에 빼준다.\n left_top = (case[0] - case[2] - 1, case[1] - case[2] - 1)\n right_down = (case[0] + case[2] - 1, case[1] + case[2] - 1)\n tmp_mat = copy.deepcopy(mat) # 돌릴 행렬을 copy해준다\n while left_top != right_down:\n tmp_col = left_top[1] # 좌표\n tmp_row = left_top[0] # 좌표\n max_col = right_down[1] # max\n max_row = right_down[0] # max\n min_col = left_top[1] # min\n min_row = left_top[0] # min\n # 시계방향으로 돌려주기\n while True: # 오른쪽 끝으로 가는 케이스\n if tmp_col == max_col:\n break\n tmp_col += 1\n tmp_mat[tmp_row][tmp_col] = mat[tmp_row][tmp_col - 1]\n while True: # 오른쪽의 밑 끝으로 가는 케이스\n if tmp_row == max_row:\n break\n tmp_row += 1\n tmp_mat[tmp_row][tmp_col] = mat[tmp_row - 1][tmp_col]\n while True: # 왼쪽 끝으로 가는 케이스\n if tmp_col == min_col:\n break\n tmp_col -= 1\n tmp_mat[tmp_row][tmp_col] = mat[tmp_row][tmp_col + 1]\n while True: # 왼쪽 윗 끝으로 가는 케이스\n if tmp_row == min_row:\n break\n tmp_row -= 1\n tmp_mat[tmp_row][tmp_col] = mat[tmp_row + 1][tmp_col]\n # 중앙으로 둘의 간격을 좁혀준다.\n left_top = (left_top[0] + 1, left_top[1] + 1) # 얘는 하나씩 올리기\n right_down = (right_down[0] - 1, right_down[1] - 1) # 얘는 하나씩 줄이기\n return tmp_mat\n\n\nfin_min = 1000000\nfor comb_case in comb_cases: # 각 케이스별로 진행한다.\n tmp_mat = mat # matrix 복사해주기\n for case in comb_case: # 돌려주기\n tmp_mat = rotate(tmp_mat, case)\n for row in tmp_mat: # 최소 행렬값 구하기\n val = sum(row)\n if fin_min > val:\n fin_min = val\nprint(fin_min)\n","sub_path":"백준/백준_17406번.py","file_name":"백준_17406번.py","file_ext":"py","file_size_in_byte":2450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"346299639","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport math\n\n# Import scikit-learn metrics module for accuracy calculation\nfrom sklearn import metrics\n# preprossing is what we do with the data before we run the learning algorithm\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\n\n\n# In[2]:\n\n\ncol_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']\n# load dataset\npima = pd.read_csv(\"diabetes.csv\")\npima.columns = col_names\npima.head()\n\nfeature_cols = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age']\nX = pima[feature_cols] # Features\ny = pima.label # Target variable\nX = X.to_numpy()\ny = y.to_numpy()\n\nX_train, X_test, y_train, y_test = train_test_split(X, y)\nscaler = preprocessing.StandardScaler().fit(X_train)\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\n\n# Append a column of ones to x_train\n# Step 1: Create a column vector of ones (i.e. a vector of shape N',1)\nones = np.ones(X_train.shape[0]).reshape((X_train.shape[0], 1))\n# Step 2: Append a column of ones in the beginning of x_train\nX_train = np.hstack((ones, X_train))\n\n# Now do the same for the test data\n# Step 1: Create a column vector of ones (i.e. a vector of shape N\",1)\nones = np.ones(X_test.shape[0]).reshape((X_test.shape[0], 1))\n# Stemp 2: Append a column of ones in the beginning of x_test\nX_test = np.hstack((ones, X_test))\n\n\n# In[3]:\n\n\n# Logistic Regression using sklearn feature selection\nclf = LogisticRegression(random_state=0,tol=0.001).fit(X_train, y_train)\nbase_train = clf.score(X_train, y_train)\nbase_test = clf.score(X_test, y_test)\nprint(\"Logistic Regression:\")\nprint(\"train Accuracy:\",base_train)\nprint(\"test Accuracy:\",base_test,\"\\n\")\n\n# feature extraction\nfor i in range(9):\n tmp = np.delete(X_train, i, axis = 1)\n tmp1 = np.delete(X_test, i, axis = 1)\n clf = LogisticRegression(random_state=0,tol=0.001).fit(tmp, y_train)\n fs_train = clf.score(tmp, y_train)\n fs_test = clf.score(tmp1, y_test)\n if fs_train > base_train:\n if fs_test >= base_test:\n print(\"Feature Selection:\")\n print(\"remove\",i)\n print(\"train Accuracy:\",fs_train)\n print(\"test Accuracy:\",fs_test,\"\\n\")\n\n\n# In[4]:\n\n\n# logistic Regression from scratch\ndef sigmoid(z):\n return 1 / (1 + math.exp(-z))\n\nw = np.zeros((X_train.shape[1], 1))\nprint(w.shape)\n\ndef hypothesis(X, w):\n h = np.ones((X.shape[0],1))\n for i in range(0,X.shape[0]):\n z = np.matmul(X[i], w)\n h[i] = sigmoid(z)\n return h\n\n# Compute y_hat using our training examples and w (w is still set to zero).\n# This is just a preliminary test of the hypotheis function\nyhat = hypothesis(X_train, w)\n\n# print the sizes of yhat and y as a first check that the function performed correctly\nprint(yhat.shape)\nprint(y_train.shape)\n\ndef log_likelihood(X, y, w):\n log_likelihood = 0\n for i in range(0,X.shape[0]):\n z = np.matmul(X[i], w)\n log_likelihood += y[i] * np.log(sigmoid(z)) + (1 - y[i]) * np.log((1 - sigmoid(z))) \n return log_likelihood\n\ndef Logistic_Regresion_Gradient_Ascent(X, y, learning_rate, num_iters):\n # For every 100 iterations, store the log_likelihood for the current w\n # Initializing log_likelihood to be an empty list\n log_likelihood_values = []\n # Initialize w to be a zero vector of shape x_train.shape[1],1\n w = np.zeros((X.shape[1], 1))\n # Initialize N to the number of training examples\n N = X.shape[0]\n \n for i in range (num_iters):\n y_hat = hypothesis(X, w)\n temp = 0\n for j in range (0,N):\n temp += (y[j] - y_hat[j]) * X[j]\n for k in range (0,w.shape[0]):\n w[k] = w[k] + (learning_rate / N) * temp[k]\n if (i % 100) == 0:\n log_likelihood_values.append(log_likelihood(X,y,w))\n \n return w, log_likelihood_values\n\nlearning_rate = 0.1\nnum_iters = 100 # The number of iteratins to run the gradient ascent algorithm\nw, log_likelihood_values = Logistic_Regresion_Gradient_Ascent(X_train, y_train, learning_rate, num_iters)\n\n\n# In[5]:\n\n\ndef predict(X_test, w):\n pred = hypothesis(X_test, w)\n res = []\n for i in range(0,len(pred)):\n if pred[i] >= 0.5:\n res.append(1)\n else:\n res.append(0)\n return res\n\ntrain_pred = predict(X_train, w)\ntest_pred = predict(X_test, w)\nprint(\"Logistic Regression:\")\nprint(\"train Accuracy:\",metrics.accuracy_score(y_train, train_pred))\nprint(\"test Accuracy:\",metrics.accuracy_score(y_test, test_pred),\"\\n\")\n\n# feature extraction\nfor i in range(9):\n tmp = np.delete(X_train, i, axis = 1)\n tmp1 = np.delete(X_test, i, axis = 1)\n clf = LogisticRegression(random_state=0,tol=0.001).fit(tmp, y_train)\n fs_train = clf.score(tmp, y_train)\n fs_test = clf.score(tmp1, y_test)\n if fs_train > base_train:\n if fs_test >= base_test:\n print(\"Feature Selection:\")\n print(\"remove\",i)\n print(\"train Accuracy:\",fs_train)\n print(\"test Accuracy:\",fs_test,\"\\n\")\n\n\n# In[6]:\n\n\n# Random forest sklearn\ncol_names = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age', 'label']\n# load dataset\npima = pd.read_csv(\"diabetes.csv\")\npima.columns = col_names\npima.head()\n\nfeature_cols = ['pregnant', 'glucose', 'bp', 'skin', 'insulin', 'bmi', 'pedigree', 'age']\nX = pima[feature_cols] # Features\ny = pima.label # Target variable\n\n# Split dataset into training set and test set\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) # 80% training and 20% test\n\n# default (criterion=”gini”)\nclf = RandomForestClassifier(max_depth=4, random_state=2)\nclf = clf.fit(X_train,y_train)\ntrain_pred = clf.predict(X_train)\ntest_pred = clf.predict(X_test)\nprint(\"Random Forest:\")\nprint(\"train Accuracy:\",metrics.accuracy_score(y_train, train_pred))\nprint(\"test Accuracy:\",metrics.accuracy_score(y_test, test_pred),\"\\n\")\n\n\n# In[7]:\n\n\n# Random Forest Algorithm on diabetes.csv from scratch\nfrom random import randrange\nfrom csv import reader\nfrom math import sqrt\n\n# Load a CSV file\ndef load_csv(filename):\n dataset = list()\n with open(filename, 'r') as file:\n csv_reader = reader(file)\n for row in csv_reader:\n if not row:\n continue\n dataset.append(row)\n return dataset\n\n# Convert string column to integer\ndef str_column_to_int(dataset, column):\n class_values = [row[column] for row in dataset]\n unique = set(class_values)\n lookup = dict()\n for i, value in enumerate(unique):\n lookup[value] = i\n for row in dataset:\n row[column] = lookup[row[column]]\n return lookup\n\n# Split a dataset into k folds\ndef cross_validation_split(dataset, n_folds):\n dataset_split = list()\n dataset_copy = list(dataset)\n fold_size = int(len(dataset) / n_folds)\n for i in range(n_folds):\n fold = list()\n while len(fold) < fold_size:\n index = randrange(len(dataset_copy))\n fold.append(dataset_copy.pop(index))\n dataset_split.append(fold)\n return dataset_split\n\n# Calculate accuracy percentage\ndef accuracy_metric(actual, predicted):\n correct = 0\n for i in range(len(actual)):\n if actual[i] == predicted[i]:\n correct += 1\n return correct / float(len(actual)) * 100.0\n\n# Evaluate an algorithm using a cross validation split\ndef evaluate_algorithm(dataset, algorithm, n_folds, *args):\n folds = cross_validation_split(dataset, n_folds)\n scores = list()\n for fold in folds:\n train_set = list(folds)\n train_set.remove(fold)\n train_set = sum(train_set, [])\n test_set = list()\n for row in fold:\n row_copy = list(row)\n test_set.append(row_copy)\n row_copy[-1] = None\n predicted = algorithm(train_set, test_set, *args)\n actual = [row[-1] for row in fold]\n accuracy = accuracy_metric(actual, predicted)\n scores.append(accuracy)\n return scores\n\n# Split a dataset based on an attribute and an attribute value\ndef test_split(index, value, dataset):\n left, right = list(), list()\n for row in dataset:\n if row[index] < value:\n left.append(row)\n else:\n right.append(row)\n return left, right\n\n# Calculate the Gini index for a split dataset\ndef gini_index(groups, classes):\n # count all samples at split point\n n_instances = float(sum([len(group) for group in groups]))\n # sum weighted Gini index for each group\n gini = 0.0\n for group in groups:\n size = float(len(group))\n # avoid divide by zero\n if size == 0:\n continue\n score = 0.0\n # score the group based on the score for each class\n for class_val in classes:\n p = [row[-1] for row in group].count(class_val) / size\n score += p * p\n # weight the group score by its relative size\n gini += (1.0 - score) * (size / n_instances)\n return gini\n\n# Select the best split point for a dataset\ndef get_split(dataset, n_features):\n class_values = list(set(row[-1] for row in dataset))\n b_index, b_value, b_score, b_groups = 999, 999, 999, None\n features = list()\n while len(features) < n_features:\n index = randrange(len(dataset[0])-1)\n if index not in features:\n features.append(index)\n for index in features:\n for row in dataset:\n groups = test_split(index, row[index], dataset)\n gini = gini_index(groups, class_values)\n if gini < b_score:\n b_index, b_value, b_score, b_groups = index, row[index], gini, groups\n return {'index':b_index, 'value':b_value, 'groups':b_groups}\n\n# Create a terminal node value\ndef to_terminal(group):\n outcomes = [row[-1] for row in group]\n return max(set(outcomes), key=outcomes.count)\n\n# Create child splits for a node or make terminal\ndef split(node, max_depth, min_size, n_features, depth):\n left, right = node['groups']\n del(node['groups'])\n # check for a no split\n if not left or not right:\n node['left'] = node['right'] = to_terminal(left + right)\n return\n # check for max depth\n if depth >= max_depth:\n node['left'], node['right'] = to_terminal(left), to_terminal(right)\n return\n # process left child\n if len(left) <= min_size:\n node['left'] = to_terminal(left)\n else:\n node['left'] = get_split(left, n_features)\n split(node['left'], max_depth, min_size, n_features, depth+1)\n # process right child\n if len(right) <= min_size:\n node['right'] = to_terminal(right)\n else:\n node['right'] = get_split(right, n_features)\n split(node['right'], max_depth, min_size, n_features, depth+1)\n\n# Build a decision tree\ndef build_tree(train, max_depth, min_size, n_features):\n root = get_split(train, n_features)\n split(root, max_depth, min_size, n_features, 1)\n return root\n\n# Make a prediction with a decision tree\ndef predict(node, row):\n if row[node['index']] < node['value']:\n if isinstance(node['left'], dict):\n return predict(node['left'], row)\n else:\n return node['left']\n else:\n if isinstance(node['right'], dict):\n return predict(node['right'], row)\n else:\n return node['right']\n\n# Create a random subsample from the dataset with replacement\ndef subsample(dataset, ratio):\n sample = list()\n n_sample = round(len(dataset) * ratio)\n while len(sample) < n_sample:\n index = randrange(len(dataset))\n sample.append(dataset[index])\n return sample\n\n# Make a prediction with a list of bagged trees\ndef bagging_predict(trees, row):\n predictions = [predict(tree, row) for tree in trees]\n return max(set(predictions), key=predictions.count)\n\n# Random Forest Algorithm\ndef random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):\n trees = list()\n for i in range(n_trees):\n sample = subsample(train, sample_size)\n tree = build_tree(sample, max_depth, min_size, n_features)\n trees.append(tree)\n predictions = [bagging_predict(trees, row) for row in test]\n return(predictions)\n\n# load and prepare data\nfilename = 'diabetes.csv'\ndataset = load_csv(filename)\n# convert class column to integers\nstr_column_to_int(dataset, len(dataset[0])-1)\n# evaluate algorithm\nn_folds = 5\nmax_depth = 4\nmin_size = 1\nsample_size = 1.0\nn_features = int(sqrt(len(dataset[0])-1))\nprint(\"Random Forest:\")\nfor n_trees in [5, 10, 15]:\n scores = evaluate_algorithm(dataset, random_forest, n_folds, max_depth, min_size, sample_size, n_trees, n_features)\n print('Trees: %d' % n_trees)\n print('Scores: %s' % scores)\n print('Mean Accuracy: %.3f%%' % (sum(scores)/float(len(scores))))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Project/diabetes-dataset.py","file_name":"diabetes-dataset.py","file_ext":"py","file_size_in_byte":13146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"84794","text":"import logging\n\nimport requests\nfrom flask import request, jsonify\nfrom flask_restful import Resource\n\nfrom db import db\nfrom models import ReposInfo\n\n\nclass GetReposFromGithubResources(Resource):\n def get(self):\n args = request.args\n name_of_repo = args['name']\n logging.info(f\"requested to get all repos from acc '{name_of_repo}'\")\n try:\n logging.info(\"Send request to github\")\n response = requests.get(f'https://api.github.com/orgs/{name_of_repo}/repos')\n logging.info(\"Response obtained. Starting to add data to DB \")\n result = response.json()\n counter = 0\n for item in result:\n logging.info(f\"Create {counter} instance of repo\")\n db.session.add(\n ReposInfo(\n repo_id=item['id'],\n name=item['name'],\n html_url=item['html_url'],\n description=item['description'],\n private=item['private'],\n created_at=item['created_at'],\n watchers=item['watchers_count'],\n )\n )\n counter += 1\n logging.info(f\"Commit all instances to DB\")\n db.session.commit()\n return result\n except Exception as e:\n logging.error(f'Error in getting data from github. Error: {e}')\n return f'something went wrong while getting repo info from github, {e}'\n\n\nclass AllReposResources(Resource):\n def get(self):\n logging.info(\"requested to get all repos from db\")\n try:\n logging.info(\"Getting all repos from db\")\n all_repos = ReposInfo.query.all()\n return jsonify([e.serialize() for e in all_repos])\n except Exception as e:\n logging.error(f'Error in getting data from db. Error: {e}')\n return 'something went wrong while getting info from db'\n\n\nclass GetRepoResources(Resource):\n def get(self):\n logging.info(\"requested to get specific repo from db\")\n try:\n args = request.args\n repo_id = args['repo_id']\n logging.info(f\"Getting repo with id {repo_id} from db\")\n repo = ReposInfo.query.filter(ReposInfo.repo_id == repo_id).first()\n return jsonify(repo.serialize())\n except Exception as e:\n logging.error(f'Error in getting simple record from db. Error: {e}')\n return 'something went wrong while getting simple repo info from db'\n","sub_path":"api/app/worker/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"198404326","text":"'''\nCreated on Apr 13, 2011\n\n@author: christian\n'''\n\nimport logging\n\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nimport wx\n\nfrom eelbrain.psyphys import visualizers\n\nimport ID\n\n\n\n##### Events ##### ##### ##### ##### ##### ##### ####\nmyEVT_FIGURE_POS = wx.NewEventType()\nEVT_FIGURE_POS = wx.PyEventBinder(myEVT_FIGURE_POS, 1)\n\nclass FigurePosEvent(wx.PyCommandEvent):\n \"\"\"\n Event that is sent every time the user adjusts the view on a plot.\n \n \"\"\"\n def __init__(self, t0, t1, id=-1):\n wx.PyCommandEvent.__init__(self, myEVT_FIGURE_POS, id)\n self.t0 = t0\n self.t1 = t1\n\n\n\n##### Frames to test individual panels ##### ##### ##### #####\nclass OverviewFrame(wx.Frame):\n def __init__(self, parent, dataset):\n visualizer = visualizers.default(dataset)\n wx.Frame.__init__(self, parent)\n \n self.panel = OverviewPanel(self) \n self.panel.plot_overview([visualizer])\n\nclass ZoomFrame(wx.Frame):\n def __init__(self, parent, dataset):\n visualizer = visualizers.default(dataset)\n wx.Frame.__init__(self, parent)\n \n self.panel = ZoomPanel(self) \n self.panel.plot([visualizer])\n\n\n##### the Panels ##### ##### ##### #####\nclass CanvasPanel(wx.Panel):\n def __init__(self, parent, id=wx.ID_ANY):\n wx.Panel.__init__(self, parent, id=id)\n \n self.SetBackgroundColour(wx.NamedColour(\"WHITE\"))\n \n self.figure = Figure()\n self.canvas = FigureCanvas(self, -1, self.figure)\n self.canvas.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)\n \n self.sizer = wx.BoxSizer(wx.VERTICAL)\n self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)\n self.SetSizer(self.sizer)\n self.Fit()\n \n self.Bind(wx.EVT_PAINT, self.OnPaint)\n def OnEnterWindow(self, event):\n \"http://matplotlib.sourceforge.net/examples/user_interfaces/wxcursor_demo.html\"\n self.canvas.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))\n def OnPaint(self, event):\n logging.debug('%s: OnPaint!!!' % self.__class__.__name__)\n self.canvas.draw()\n def SendFigurePosEvent(self, t0, t1):\n # issue event\n logging.debug(\"EVENT sent!!\")\n evt = FigurePosEvent(t0, t1, id=self.GetId())\n self.GetEventHandler().ProcessEvent(evt)\n def OnFigurePosEvent(self, event):\n# logging.debug(\"EVENT received!!\")\n self.zoom(event.t0, event.t1, send_event=False)\n\n\n\n\nclass ZoomPanel(CanvasPanel):\n def __init__(self, parent, id=ID.CANVAS_PANEL_ZOOM):\n CanvasPanel.__init__(self, parent, id=id)\n \n # User interaction\n# self._dragging = 0\n# self._dt = 10\n self.canvas.mpl_connect('motion_notify_event', self.OnCanvasMotion)\n self.canvas.mpl_connect('button_press_event', self.OnCanvasMouseDown)\n self.canvas.mpl_connect('button_release_event', self.OnCanvasMouseUp)\n \n def plot(self, visualizers):\n self.figure.clf()\n \n ax = self.ax = self.figure.add_axes([0, .1, 1, .9], frame_on=False)\n for v in visualizers:\n v.toax(ax, None, None)\n \n self._tmin = self._t0 = t0 = v.tstart\n self._tmax = self._t1 = t1 = v.tend\n ax.set_xlim(t0, t1)\n \n def relative_zoom(self, factor):\n t0 = self._t0\n t1 = self._t1\n diff = ((t1 - t0) * (factor - 1)) / 2.\n self.zoom(t0 + diff, t1 - diff)\n def relative_move(self, factor):\n t0 = self._t0\n t1 = self._t1\n diff = (t1 - t0) * factor\n self.zoom(t0 + diff, t1 + diff)\n \n def zoom(self, t0, t1, send_event=True):\n t0 = self._t0 = max(self._tmin, t0)\n t1 = self._t1 = min(self._tmax, t1)\n self.ax.set_xlim(t0, t1)\n self.canvas.draw()\n \n if send_event:\n self.SendFigurePosEvent(t0, t1)\n \n def move(self, dt):\n t0 = self._t0 + dt\n t1 = self._t1 + dt\n if t0 < self._tmin:\n t1 += self._tmin - t0\n t0 = self._tmin\n elif t1 > self._tmax:\n t0 -= t1 - self._tmax\n t1 = self._tmax\n self.zoom(t0, t1)\n \n def move_t_to_x(self, t, x, send_event=True):\n # event.x is position within renderer\n width = self.canvas.get_renderer().width\n x_ratio = x / width\n dt = self._t1 - self._t0\n# t_rel = t - self._t0\n# t_ratio = t_rel / dt\n t0 = t - x_ratio * dt\n t1 = t0 + dt\n self.zoom(t0, t1, send_event=send_event)\n \n def OnCanvasMouseDown(self, event):\n if event.inaxes:\n self._t_grip = event.xdata\n self._xlim_grip = self._t0, self._t1\n self._grip_dt = 0\n# self._x_grip = event.x\n# self._r_width = self.canvas.get_renderer().width\n if wx.__version__ >= '2.9':\n CursorId = wx.CURSOR_CLOSED_HAND\n else:\n CursorId = wx.CURSOR_BULLSEYE\n self.canvas.SetCursor(wx.StockCursor(CursorId))\n def OnCanvasMouseUp(self, event):\n self.canvas.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))\n def OnCanvasMotion(self, event):\n# logging.debug('x=%.2f, xdata=%.2f'%(event.x, event.xdata))\n if event.button and event.inaxes:\n self.move_t_to_x(self._t_grip, event.x, send_event=True)\n\n\nclass OverviewPanel(CanvasPanel):\n def __init__(self, parent, id=ID.CANVAS_PANEL_OVERVIEW):\n CanvasPanel.__init__(self, parent, id=id)\n \n # User interaction\n# self._dragging = False\n self._dt = 10\n self.canvas.mpl_connect('motion_notify_event', self.OnCanvasMotion)\n self.canvas.mpl_connect('button_press_event', self.OnCanvasMouseDown)\n self.canvas.mpl_connect('button_release_event', self.OnCanvasMouseUp)\n \n # Mouse Events\n def OnCanvasMotion(self, event):\n if event.inaxes and hasattr(self, '_t0'):\n self.set_marker_t1(event.xdata) \n def OnCanvasMouseDown(self, event):\n# logging.debug('mouse down t=%.2f'%event.xdata)\n if event.inaxes:\n self._t0 = event.xdata\n# self._dragging = True\n def OnCanvasMouseUp(self, event):\n# logging.debug('mouse up t=%.2f'%event.xdata)\n if hasattr(self, '_t0'):\n logging.debug('has t0')\n if event.inaxes:\n if self._t0 == event.xdata:\n self.set_marker_pos(event.xdata)\n else:\n self.set_marker_t1(event.xdata)\n del self._t0\n \n def OnPaint(self, event):\n logging.debug('%s: OnPaint!!!' % self.__class__.__name__)\n if self.marker:\n self.marker.remove()\n# self.figure.remove(self.marker)\n# self.ax.remove(self.marker)\n self.canvas.draw()\n self._background = self.canvas.copy_from_bbox(self.ax.bbox)\n self._ylim = self.ax.get_ylim()\n if self.marker:\n self.ax.add_artist(self.marker)\n self.draw_marker()\n event.Skip()\n \n def plot_overview(self, visualizers):\n self.figure.clf()\n \n ax = self.ax = self.figure.add_axes([0, .1, 1, .9], frame_on=False)\n for v in visualizers:\n v.toax(ax, None, None)\n \n self.marker = None\n self._tmin = t0 = v.tstart\n self._tmax = t1 = v.tend\n ax.set_xlim(t0, t1)\n \n def set_marker_pos(self, t):\n dt = self._dt / 2\n t1 = t - dt\n t2 = t + dt\n if t1 < self._tmin:\n t2 = min(t2 + (self._tmin - t1), self._tmax)\n t1 = self._tmin\n elif t2 > self._tmax:\n t1 = max(t1 - (t2 - self._tmax), self._tmin)\n t2 = self._tmax\n self.zoom(t1, t2)\n \n def set_marker_t1(self, t1):\n \"assumes that self._t0 is set\"\n self.zoom(self._t0, t1)\n \n def zoom(self, t1, t2, send_event=True):\n if t1 == t2:\n self.set_marker_pos(t1)\n return\n t_start = min(t1, t2)\n t_end = max(t1, t2)\n \n self.canvas.restore_region(self._background)\n \n if self.marker:\n# logging.debug('marker: just updating')\n xy = self.marker.get_xy()\n xy[0,0] = t1\n xy[1,0] = t1\n xy[2,0] = t2\n xy[3,0] = t2\n xy[4,0] = t1\n# logging.debug(xy)\n else:\n self.marker = self.ax.axvspan(t_start, t_end, edgecolor='r', \n hatch='/', fill=False, aa=False,\n zorder=0) #, alpha=.1)# fill=False)\n self._dt = t_end - t_start\n self.ax.set_xlim(self._tmin, self._tmax)\n self.ax.set_ylim(*self._ylim)\n self.draw_marker()\n \n if send_event:\n self.SendFigurePosEvent(t1, t2)\n# ax.set_xlim(*self.viewer.t_lim)\n def draw_marker(self):\n try:\n self.ax.draw_artist(self.marker)\n except Exception:\n logging.debug('DRAW exception: %s'%Exception)\n else:\n pass\n self.canvas.blit(self.ax.bbox)\n def del_marker(self):\n if self.marker:\n self.figure.remove(self.marker)\n self.marker = None\n self.canvas.draw()\n \n","sub_path":"eelbrain/wxgui/psyphys/view_panels.py","file_name":"view_panels.py","file_ext":"py","file_size_in_byte":9446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"483939477","text":"# Cards\r\n# Sebastian Puerta Hincapie\r\n\r\nclass Card(object):\r\n def __init__(self,suit=1,rank=2):\r\n if suit < 1 or suit > 4:\r\n print(\"invalid suit, setting to 1\")\r\n suit = 1\r\n self.suit = suit\r\n self.rank = rank\r\n\r\n def value(self):\r\n \"\"\" we want things order primarily by rank then suit \"\"\"\r\n return self.suit + (self.rank-1)*14\r\n\r\n #if we include this to allow for comparisons with < and > between cards\r\n def __lt__(self,other):\r\n return self.value() < other.value()\r\n\r\n # Python 2 by default uses ASCII, Python 3 uses Unicode\r\n def __unicode__(self):\r\n suit = [u\"\\u2668\", #spade\r\n u\"\\u2665\", #heart\r\n u\"\\u2666\", #diamond\r\n u\"\\u2777\"] #club\r\n r = str(self.rank)\r\n if self.rank == 11: r = \"J\"\r\n elif self.rank == 12: r = \"Q\"\r\n elif self.rank == 13: r = \"K\"\r\n elif self.rank == 14: r = \"A\"\r\n\r\n return r + ':' + suit[self.suit-1]\r\n\r\n def __str__(self):\r\n return self.__unicode__() # .encode(\"utf-8\")\r\n\r\nclass Deck(object):\r\n \"\"\" the deck is a collection of cards \"\"\"\r\n def __init__(self):\r\n self.nsuits = 4\r\n self.nranks = 13\r\n self.minrank = 2\r\n self.maxrank = self.minrank + self.nranks - 1\r\n\r\n self.cards = []\r\n\r\n for rank in range(self.minrank,self.maxrank+1):\r\n for suit in range(1,self.nsuits+1):\r\n self.cards.append(Card(rank=rank,suit=suit))\r\n\r\n def shuffle(self):\r\n random.shuffle(self.cards)\r\n\r\n def get_cards(self,num=1):\r\n hand = []\r\n for n in range(num):\r\n hand.append(self.cards.pop())\r\n return hand\r\n\r\n def __str__(self):\r\n string = \"\"\r\n for c in self.cards:\r\n string += str(c) + \" \"\r\n return string\r\n \r\ndef main():\r\n # test Card class\r\n c1 = Card()\r\n print(c1)\r\n c2 = Card(3,4)\r\n print(c2)\r\n c3 = Card(17,12)\r\n print(c1 < c2)\r\n print(c2 > c1)\r\n c1.value()\r\n\r\n # test Deck class\r\n mydeck = Deck()\r\n print(\"This is my deck\")\r\n print(mydeck)\r\n print(\"The length of the deck is: \")\r\n print(len(mydeck.cards))\r\n input(\"Press a key to continue with dealing a hand...\")\r\n print(\"Shuffling the deck...\")\r\n mydeck.shuffle()\r\n print(\"this is your hand\")\r\n hand = mydeck.get_cards(5)\r\n for c in sorted(hand) : print(c)\r\n\r\nmain()\r\n","sub_path":"Cards_SPH.py","file_name":"Cards_SPH.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"493023790","text":"import pyodbc\n\nclass SQLDatabaseAPI:\n def __init__(self):\n self.start_connection()\n\n \n def start_connection(self, server = \"databases1.spartaglobal.academy\", database = \"Northwind\", username = \"**\", password = \"**\"):\n \n try:\n print(\"Establishing Connection\")\n # connect to server with pyodbc.connect()\n self.db_connection = pyodbc.connect(f\"DRIVER=ODBC Driver 17 for SQL Server;SERVER={server};DATABASE={database};UID={username};PWD={password}\")\n # init cursor to execute queries\n self.cursor = self.db_connection.cursor()\n except:\n print(\"Something went wrong\")\n \n else:\n # if no errors occurs prints following message\n print(\"Connection Successfully Made\")\n \n\n def create_table(self, table_name, **column_info):\n '''\n Creates a new table in current working Database\n table_name (str): Name of table to be created\n Specify column names and datatypes in key=value format\n E.g. name = VARCHAR(16)\n '''\n self.table_name = table_name\n self.table_column_info = column_info\n\n # creates string containing the column information, formatted correctly to be added to the query\n column_info_str = ',\\n'.join([f\"{column_name} {datatype}\" for column_name, datatype in self.table_column_info.items()])\n \n # final string formatted correctly for SQL query\n query = f\"CREATE TABLE {table_name}(\\n{column_info_str});\"\n\n # execute query\n self.cursor.execute(query) \n\n\n def insert_data(self):\n '''\n Insert Data into table, will prompt user to input data in correct format\n '''\n if not hasattr(self, 'table_name'):\n self.table_name = input(\"\\nPlease enter a table name to insert data into.\\n=> \")\n \n # Empty list of data values which will then be filled with user input\n data_values = []\n \n # Iterate through columns\n for column_name, datatype in self.table_column_info.items():\n # For each column prompt user to input data\n user_data = input(f\"\\nPlease enter Data for {column_name}\\nDATATYPE: {datatype}\\n=> \")\n\n # If datatype is VARCHAR, add extra quotes around data value before appending\n if \"VARCHAR\" in datatype:\n data_values.append(\"'\" + user_data + \"'\")\n elif \"INT\" in datatype:\n data_values.append(user_data)\n\n # create string for data values, and column names, formatted correctly\n insert_data_str = ', '.join(data_values)\n column_names = ', '.join(self.table_column_info.keys())\n \n # final SQL query string formatted correctly\n query = f\"INSERT INTO {self.table_name}\\n({column_names})\\nVALUES({insert_data_str});\"\n\n # execute query\n self.cursor.execute(query)\n \n\n def display_table(self):\n # display everything from table\n print(self.cursor.execute(f\"SELECT * FROM {self.table_name};\").fetchall())\n\n\n\nif __name__ == \"__main__\":\n python_sql_obj = SQLDatabaseAPI()\n python_sql_obj.create_table(\"ldaijiw_table\", name = \"VARCHAR(16)\" , age = \"INT\", address = \"VARCHAR(32)\")\n python_sql_obj.insert_data()\n python_sql_obj.insert_data()\n python_sql_obj.display_table()","sub_path":"03_python/python_sql/pyodbc_task/python_sql_task.py","file_name":"python_sql_task.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"363182117","text":"\"\"\"\n给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。\n\n示例 1:\n\n输入:\n[\n [ 1, 2, 3 ],\n [ 4, 5, 6 ],\n [ 7, 8, 9 ]\n]\n输出: [1,2,3,6,9,8,7,4,5]\n示例 2:\n\n输入:\n[\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9,10,11,12]\n]\n输出: [1,2,3,4,8,12,11,10,9,5,6,7]\n\n\"\"\"\n\n\nclass Solution:\n def spiralOrder(self, matrix):\n # 特判\n if not matrix:\n return []\n\n R, C = len(matrix), len(matrix[0])\n # 表示之前已经访问过的元素\n seen = [[False] * C for _ in matrix]\n # 存储答案\n ans = []\n dr = [0, 1, 0, -1]\n dc = [1, 0, -1, 0]\n # di表示前进方向\n r = c = di = 0\n for _ in range(R * C):\n ans.append(matrix[r][c])\n seen[r][c] = True\n cr, cc = r + dr[di], c + dc[di]\n if 0 <= cr < R and 0 <= cc < C and not seen[cr][cc]:\n r, c = cr, cc\n else:\n di = (di + 1) % 4\n r, c = r + dr[di], c + dc[di]\n return ans\n\n\nclass Solution2:\n \"\"\"按层模拟\"\"\"\n def spiralOrder(self, matrix):\n def spiral_coords(r1, c1, r2, c2):\n # 遍历上面\n for c in range(c1, c2 + 1):\n yield r1, c\n # 遍历右边\n for r in range(r1 + 1, r2 + 1):\n yield r, c2\n if r1 < r2 and c1 < c2:\n # 遍历下面\n for c in range(c2 - 1, c1, -1):\n yield r2, c\n # 遍历左边\n for r in range(r2, r1, -1):\n yield r, c1\n # 特判\n if not matrix:\n return []\n\n ans = []\n r1, r2 = 0, len(matrix) - 1\n c1, c2 = 0, len(matrix[0]) - 1\n while r1 <= r2 and c1 <= c2:\n for r, c in spiral_coords(r1, c1, r2, c2):\n ans.append(matrix[r][c])\n # 从最外层向里层遍历\n r1 += 1\n r2 -= 1\n c1 += 1\n c2 -= 1\n return ans\n","sub_path":"数组/54-螺旋矩阵.py","file_name":"54-螺旋矩阵.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"222270950","text":"#!/usr/bin/env python\n# coding:utf-8\nimport base64\nimport logging\nimport os\nfrom urlparse import urlparse\n\nimport fakeredis\n\nr = fakeredis.FakeStrictRedis()\ninvalid_chars = '-_.!?~/\\\\/!#$%^&**)_=Il1O0o'\n\n\ndef invalid(text):\n \"\"\"\n Checks if shortened text contains invalid characters\n :param text:\n :return:\n \"\"\"\n return any((c in invalid_chars) for c in text)\n\n\ndef generator():\n \"\"\"\n Generates random shortened char-sets until does not contain invalid characters\n :return:\n \"\"\"\n step = 0\n text = invalid_chars\n\n while invalid(text):\n text = base64.urlsafe_b64encode(os.urandom(3)).lower()\n step += 1\n if step >= 10:\n msg = '{1} in {0} step'.format(step, text)\n logging.debug(msg=msg)\n\n return text\n\n\ndef available(key):\n return not r.exists(key)\n\n\ndef shorten(url):\n step = 0\n\n while True:\n name = generator()\n if not available(key=name):\n step += 1\n continue\n if step >= 1:\n msg = '{0} shortened to in {1} in {2} step'.format(url, name, step)\n logging.info(msg=msg)\n return dict(key=name, url=url)\n\n\ndef expand(key):\n if available(key=key):\n raise KeyError(\"{0} not found\".format(key))\n return dict(name=key, value=r.get(key))\n\n\ndef save(shortened_data):\n return r.set(name=shortened_data['key'], value=shortened_data['url'])\n\n\ndef isvalid(url):\n \"\"\"\n 1. Must be only http(s)\n 2. Query parameters ? (I think it shoul be exists)\n 3. Unicode domains [ok]\n :param url:\n :return:\n \"\"\"\n parsed = urlparse(url.__str__())\n return \\\n '.' in parsed.netloc and \\\n ':' not in parsed.netloc and \\\n not parsed.netloc.endswith('.') and \\\n parsed.scheme in ['http', 'https']\n","sub_path":"bonsai/core/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"308823184","text":"def isSame(src, dst, idx):\r\n for i in range(len(dst)):\r\n if (src[idx+i] != dst[i]):\r\n return False\r\n return True\r\n\r\ndef replacePart(src, num, idx):\r\n strTmp = hex(num).split('x')[1]\r\n while (len(strTmp) < 16):\r\n strTmp = '0'+strTmp\r\n rp = bytearray.fromhex(strTmp)\r\n for i in range(8):\r\n src[idx+i] = rp[i]\r\n \r\ndef reverseByte(x):\r\n y = 0\r\n for i in range(8):\r\n y = ((y << 8) | (x & 0xFF));\r\n x = (x >> 8)\r\n return y\r\n\r\nnum = 0x8d976e1283c0f33f\r\nmmTag = memoryview(bytearray.fromhex(hex(num).split('x')[1]))\r\nprint(len(mmTag))\r\nwith open(\"src.xls\", \"rb\") as srcFile :\r\n dd = bytearray(srcFile.read())\r\n mm = memoryview(dd)\r\n\r\n i = 0\r\n while i < len(mm):\r\n if (isSame(mm, mmTag, i)):\r\n replacePart(mm, num, i)\r\n num = reverseByte(reverseByte(num) + 1);\r\n i = i + 7\r\n i = i + 1\r\n\r\n with open(\"dst.xls\", \"wb\") as dstFile:\r\n dstFile.write(dd)\r\n","sub_path":"double_15/parse_change.py","file_name":"parse_change.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"509364467","text":"from commands.base_command import BaseCommand\nfrom util.file_utils import extract_filename\nfrom util.math_utils import cosine_similarity\n\nclass PrintSimilaritiesCommand(BaseCommand):\n def __init__(self):\n self.filevectors = []\n\n def execute(self, clusters, mapped_vectors, files):\n self.init_filevectors(mapped_vectors, files)\n self.print_similiarities()\n\n def init_filevectors(self, mapped_vectors, files):\n for i in range(0, len(files)):\n vector = mapped_vectors[i][0]\n file = files[i]\n self.filevectors.append(FileVector(file, vector))\n\n def print_similiarities(self):\n filenames = []\n max_len = 0\n for file in self.filevectors:\n filename = file.file\n filename = extract_filename(filename)\n filenames.append(filename)\n if len(filename) > max_len:\n max_len = len(filename)\n print(\"Близость документов по косинусной мере:\")\n print(''.ljust(max_len), end=' ')\n for document in filenames:\n print(document.ljust(max_len), end=' ')\n print()\n for first_filevector in self.filevectors:\n print(filenames[self.filevectors.index(first_filevector)].ljust(max_len), end=' ')\n for second_filevector in self.filevectors:\n a = first_filevector.vector\n b = second_filevector.vector\n print('{0:.3f}'.format(cosine_similarity(a, b)).ljust(max_len), end=' ')\n print()\n\nclass FileVector:\n def __init__(self, file, vector):\n self.file = file\n self.vector = vector","sub_path":"commands/print_similarities_command.py","file_name":"print_similarities_command.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"290203371","text":"expression = input()\npow = expression.replace('**', ' ** ')\nmult = pow.replace('*', ' * ')\nadd = mult.replace('+', ' + ')\nsub = add.replace('-', ' - ')\ndiv = sub.replace('/', ' / ')\ns = div.split(' ')\nfor i in range(len(s)):\n s.remove('')\n print(s)\n \n\n\n\n\n\n\n\n\n","sub_path":"venv/Functions/Calc.py","file_name":"Calc.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"503772027","text":"import time\nimport subprocess\n\nfrom utils import repo\nfrom discord.ext import commands\n\n\nclass Admin:\n def __init__(self, bot):\n self.bot = bot\n self._last_result = None\n\n @commands.command()\n async def amiadmin(self, ctx):\n \"\"\" Are you admin? \"\"\"\n if ctx.author.id in repo.owners:\n return await ctx.send(f\"Yes **{ctx.author.name}** you are admin! ✅\")\n\n # Please do not remove this part :( #\n if ctx.author.id == 86477779717066752:\n return await ctx.send(f\"Well kinda **{ctx.author.name}**.. you still own the source code\")\n\n await ctx.send(f\"no, heck off {ctx.author.name}\")\n\n @commands.command()\n @commands.check(repo.is_owner)\n async def reload(self, ctx, name: str):\n \"\"\" Reloads an extension. \"\"\"\n try:\n self.bot.unload_extension(f\"cogs.{name}\")\n self.bot.load_extension(f\"cogs.{name}\")\n except Exception as e:\n await ctx.send(f\"```\\n{e}```\")\n return\n await ctx.send(f\"Reloaded extension **{name}.py**\")\n\n @commands.command()\n @commands.check(repo.is_owner)\n async def reboot(self, ctx):\n \"\"\" Reboot the bot \"\"\"\n await ctx.send('Rebooting now...')\n time.sleep(1)\n await self.bot.logout()\n\n @commands.command()\n @commands.check(repo.is_owner)\n async def load(self, ctx, name: str):\n \"\"\" Reloads an extension. \"\"\"\n try:\n self.bot.load_extension(f\"cogs.{name}\")\n except Exception as e:\n await ctx.send(f\"```diff\\n- {e}```\")\n return\n await ctx.send(f\"Loaded extension **{name}.py**\")\n\n @commands.command()\n @commands.check(repo.is_owner)\n async def unload(self, ctx, name: str):\n \"\"\" Reloads an extension. \"\"\"\n try:\n self.bot.unload_extension(f\"cogs.{name}\")\n except Exception as e:\n await ctx.send(f\"```diff\\n- {e}```\")\n return\n await ctx.send(f\"Unloaded extension **{name}.py**\")\n\n @commands.command(aliases=['exec'])\n @commands.check(repo.is_owner)\n async def execute(self, ctx, *, text: str):\n \"\"\" Do a shell command. \"\"\"\n text_parsed = list(filter(None, text.split(\" \")))\n output = subprocess.check_output(text_parsed).decode()\n await ctx.send(f\"```fix\\n{output}\\n```\")\n\n\ndef setup(bot):\n bot.add_cog(Admin(bot))\n","sub_path":"cogs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"422402219","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# =============================================================================\n# Created By : luis-eduardo@dsv.su.se\n# Created Date: 2020/06/30\n# =============================================================================\n\"\"\"\nCreation of HTML webpage with Dash and visualization with Plotly.\nThis file is called from the `dash_example_web.py`, and its main goal\nis to make the main code more readable.\n\"\"\"\n# =============================================================================\n# Imports\n# =============================================================================\n\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n\nimport plotly.express as px\n\nfrom pathlib import Path\nimport pandas as pd\n\n\n# =============================================================================\n# Functions\n# =============================================================================\n\ndef update_histogram(colname = None, sample=None):\n#def update_histogram(colname, sample=None):\n \"\"\"\n Draws a histogram plot from the original dataset and puts the value\n from the `sample` that the user has input in the website.\n \"\"\"\n fig = px.histogram(data,\n x=colname,\n color=\"Outcome\",\n labels={k:v for k,v in zip(colnames,column_labels)},\n template=\"ggplot2\")\n fig.update_layout(\n legend = dict(title=\"Class\",\n orientation=\"h\",\n y=1, yanchor=\"bottom\",\n x=0.5, xanchor=\"center\"\n )\n )\n # Show a black line with the current value of the sample\n if (sample is not None):\n fig.add_shape(type=\"line\", line_color=\"black\",\n line_width = 3, \n xref='x', yref='paper',\n x0 = float(sample[colname]), x1 = float(sample[colname]),\n y0 = 0, y1 = 1)\n return fig\n\ndef update_scatter(col1=None, col2=None, sample=None):\n#def update_scatter(col1, col2, sample=None):\n \"\"\"\n Draws a scatter plot from the original dataset and puts the value\n from the `sample` that the user has input in the website.\n \"\"\"\n fig = px.scatter(data,\n x=col1, \n y=col2, \n color=\"Outcome\",\n labels={k:v for k,v in zip(colnames,column_labels)},\n template=\"simple_white\")\n\n fig.update_layout(\n legend = dict(\n title=\"Class\",\n )\n )\n \n if (sample is not None):\n fig.add_annotation( # add a text callout with arrow\n text=\"SAMPLE!\", x=float(sample[col1]), y=float(sample[col2]),\n arrowhead=3, showarrow=True, startarrowsize=3\n )\n return fig\n\n# =============================================================================\n# Main\n# =============================================================================\n\n\n#############\n\"\"\"\nLoad and simple processing of the original dataset for visualization\npurposes in the web application.\n\"\"\"\n\n# Relative paths respect to current file\n# DO NOT MODIFY: Relative path prefix to be able to find the dataset\nTHIS_FILE_PATH = str(Path(__file__).parent.absolute())+\"/\"\nFOLDER_PATH = THIS_FILE_PATH + \"../datasets/\"\n\n# Load original dataset file\ndataset_filename = FOLDER_PATH + \"diabetes.csv\"\ndata = pd.read_csv(dataset_filename)\n\n# Structure to map df column names to meaningful labels\ncolnames = data.columns\ncolnames = colnames.drop('Outcome').values\ncolumn_labels = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']\n\n# Initialization of plots when the website is loaded the first time\n# [P,G,BP,S,I,BMI,D,A]\nfig_histogram = update_histogram(\"Pregnancies\")\nfig_scatter = update_scatter(\"Pregnancies\",\"BloodPressure\")\n\n#############\n\"\"\"\nStructure of the HTML webpage using Dash library\n\"\"\"\napp_html_layout = html.Div([\n\n html.Center(html.H1(\"DAMI HW3 - DIABETES\")),\n\n html.Div(\"This app classifies two variaties of diabetes from eight real-value attributes\"),\n\n #html.Div(['More information about dataset:', \n #html.A('https://archive.ics.uci.edu/ml/datasets/seeds')\n #]),\n\n html.H3('Classification with Trained Model'),\n\n\n #['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']\n # [P,G,BP,S,I,BMI,D,A]\n\n # Create the table to put input values\n html.Table([ html.Tbody([\n # Pregnancies\n html.Tr([\n html.Td( html.B('Pregnancies (P):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-P',\n min=0,\n max=17,\n step=1,\n value=6,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-P',children=''), style={'width':'10%'} ),\n ]),\n # Glucose\n html.Tr([\n html.Td( html.B('Glucose (G):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-G',\n min=44,\n max=199,\n step=1,\n value=88,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-G',children=''), style={'width':'20%'} ),\n ]),\n # BloodPressure\n html.Tr([\n html.Td( html.B('BloodPressure (BP):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-BP',\n min=24,\n max=122,\n step=1,\n value=67,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-BP',children=''), style={'width':'20%'} ),\n ]),\n # SkinThickness\n html.Tr([\n html.Td( html.B('SkinThickness (S):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-S',\n min=7,\n max=99,\n step=1,\n value=55,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-S',children=''), style={'width':'20%'} ),\n ]),\n # Insulin\n html.Tr([\n html.Td( html.B('Insulin (I):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-I',\n min=10,\n max=846,\n step=1,\n value=130,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-I',children=''), style={'width':'20%'} ),\n ]),\n # BMI\n html.Tr([\n html.Td( html.B('BMI (BMI):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-BMI',\n min=18,\n max=67,\n step=1,\n value=35,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-BMI',children=''), style={'width':'20%'} ),\n ]),\n # 'DiabetesPedigreeFunction'\n html.Tr([\n html.Td( html.B('DiabetesPedigreeFunction (D):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-D',\n min=0.05,\n max=2.5,\n step=0.01,\n value=1.13,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-D',children=''), style={'width':'20%'} ),\n ]), \n\n # 'Age'\n html.Tr([\n html.Td( html.B('Age (A):', style={'font-size':'9pt'}), style={'width':'25%'} ),\n html.Td( dcc.Slider(id='slider-A',\n min=1,\n max=90,\n step=1,\n value=50,\n ), style={'width':'55%'} ),\n html.Td( html.P(id='value-slider-A',children=''), style={'width':'20%'} ),\n ]),\n ]), \n ], style={'width':'100%', 'padding':'0', 'margin':'0'}),\n\n \n html.Center( \n html.Div([\n html.Br(),\n html.H4(html.B('Classification result', id='classification-result', style={'color':'#983e0f'})),\n html.Button('Execute Classification', id='submit', style={'margin':'0 auto', 'width':'30%'}),\n ])\n ),\n\n html.Br(),\n\n html.Center(html.B('Possible classes: [0:Negative], [1:Positive]', style={'color':'blue'})),\n\n html.Hr(),\n\n html.H3('Dataset Visualization'),\n\n html.Div('The next plots show some characteristics of the original dataset. Note that the values from the SAMPLE that was input above will be highlighted in the plot according to the selected variables.'),\n\n# #['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']\n \n # Layout for plots\n html.Table([\n html.Tbody([\n # Create the cell for the first plot\n html.Tr([\n html.Td([\n \n html.H5('Histogram per class of a variable'),\n\n html.Label(\"Choose a variable:\"),\n\n dcc.Dropdown(id='dropdown-histogram',\n options=[{\"label\":l, 'value':v} for l,v in zip(column_labels,colnames)],\n value='Pregnancies'\n ),\n\n dcc.Graph(\n id='graph-histogram',\n figure = fig_histogram\n ),\n ], style={'width':'40%'} ),\n\n html.Td([\n \n html.H5('Scatter plot of two variables'),\n\n html.Label(\"Choose two variables to plot:\"),\n\n dcc.Dropdown(id='dropdown-scatter-1',\n options=[{\"label\":l, 'value':v} for l,v in zip(column_labels,colnames)],\n value='Pregnancies'\n ),\n\n dcc.Dropdown(id='dropdown-scatter-2',\n options=[{\"label\":l, 'value':v} for l,v in zip(column_labels,colnames)],\n value='BloodPressure'\n ),\n\n dcc.Graph(\n id='graph-scatter',\n figure = fig_scatter\n ),\n ], style={'width':'60%'} )\n ])\n ])\n ], style={'width': '100%'}),\n \n], style={'columnCount': 1})","sub_path":"HW3/backup/backup10142225/helper_dash_example.py","file_name":"helper_dash_example.py","file_ext":"py","file_size_in_byte":10631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"586143216","text":"class Problem019:\n\n def solution(self):\n currentDay = 1 + (365 % 7)\n totalNumberOfSundays = 0\n monthsWith31Days = [0, 2, 4, 6, 7, 9, 11]\n monthsWith30Days = [3, 5, 8, 10]\n\n for year in xrange(1901, 2001):\n for month in xrange(12):\n if currentDay == 0:\n totalNumberOfSundays += 1\n if month in monthsWith31Days:\n currentDay += 31\n elif month in monthsWith30Days:\n currentDay += 30\n elif year % 4 == 0:\n currentDay += 29\n else:\n currentDay += 28\n currentDay %= 7\n\n return totalNumberOfSundays\n\n def test(self):\n return\n\nSolver = Problem019\n","sub_path":"Solutions/Problems 001-025/Problem019.py","file_name":"Problem019.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"139350416","text":"\"\"\"backend URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nfrom rest_framework import routers\n\nfrom songs import views\n\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView,\n TokenRefreshView,\n TokenVerifyView,\n)\n\nrouter = routers.DefaultRouter()\nrouter.register(r'song', views.SongView, 'song')\nrouter.register(r'book', views.BookView, 'book')\nrouter.register(r'printer', views.PrintPageView, 'printpage')\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n\n path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'),\n path('api/song//edit', views.edit_song, name=\"edit_song\"),\n path('api/book//edit', views.edit_book, name=\"edit_book\"),\n path('api/update/', views.get_status, name=\"update\"),\n path('api/', include(router.urls)),\n\n]\n","sub_path":"backend/backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"225983507","text":"#This class defines an object for reading and containing a GRAINEX sounding.\n#It reads both the ASCII and NetCDF files available on the GRAINEX NCAR page.\n#Note that it does not handle any missing data values, but retains the\n#value read from the file.\n#There are 2 broad categories of attributes:\n# Metadata\n# time - Sonde time\n# date - Date of sonde launch\n# elv - Balloon elevation\n# lat - Balloon latitude\n# lon - Balloon longitude\n# units - Wind speed units\n#\n# Atmosphere\n# pres - Level pressure\n# height - Level Height\n# temp - Level temperature\n# dewp - Level dewpoint\n# wdir - Level wind direction\n# wspd - Level wind speed\n# pblh() - Function to Estimate height of the boundary layer (returns pblh)\n# cape_cin() - Function to calculate amount of CAPE in sounding (returns [cape, cin])\n# lcl() - Function to calculate lifting condensation level\n# lfc() - Function to calculate level of free convection\n# bulk_shear() - Function to calculate bulk shear in a user-defined layer\n#\n#Additionally, there is an \"attributes\" attribute that lists the\n#object's attributes. (Say that three times fast.)\n#\n#Usage:\n# To creating a sounding object, simply run\n#\n# from grainex_sounding.py import Sounding\n# my_sounding_object = Sounding(path_to_file, ASCII) for an ASCII file\n#\n# -or-\n#\n# my_sounding_object = Sounding(path_to_file, NETCDF) for a NetCDF file\n#\n#Written by Chris Phillips, August 2019\n#University of Alabama\n#Department of Atmospheric and Earth Science\n#\n#Requirements:\n#Python 3+\n#Atmos (Available at github.com/sodoesaburningbus)\n#Metpy\n#NetCDF4 (If reading netcdf files)\n#Numpy\n\nclass Sounding():\n #Initializing sounding object with sounding information\n def __init__(self, filepath, flag):\n #Importing numpy\n import numpy\n\n #Reading an ASCII sounding file\n if (flag.lower() == \"ascii\"):\n #Creating lists to hold data\n pres = []\n elv = []\n temp = []\n dewp = []\n rh = []\n wdir = []\n wspd = []\n lat = []\n lon = []\n \n #Opening sounding file and reading\n fn = open(filepath)\n data_flag = False #Flag for whether in metadata or observations portion of sounding\n for line in fn:\n #Skipping blank lines\n if (len(line) < 2):\n continue\n \n dummy = line.split() #Splitting line on whitespace\n \n if (data_flag): #Reading observations from sounding\n if ((len(dummy) <= 4) or (dummy[4] == -999)): #Skip bad pressure levels\n continue\n pres.append(dummy[4])\n elv.append(dummy[13])\n temp.append(dummy[5])\n dewp.append(dummy[6])\n rh.append(dummy[7])\n wdir.append(dummy[11])\n wspd.append(dummy[10])\n lat.append(dummy[15])\n lon.append(dummy[14])\n \n #elif (dummy[0]+dummy[1] == \"ReleaseSite\"):\n # self.id = dummy[4]\n \n #elif (dummy[0] == \"UTC\"): #Pulling time and date from metadata\n # self.time = dummy[7]\n # self.date = dummy[4][:-1]+dummy[5][:-1]+dummy[6][:-1]\n \n elif (dummy[0] == \"sec\"): #Pulling wind speed unit\n self.units = dummy[10] \n \n elif (dummy[0][0] == \"-\"): #Detecting if starting data portion of sounding\n data_flag = True\n\n #Closing file\n fn.close()\n \n #Assigning numpy arrays to class attributes\n #Also eliminating bad pressure levels\n self.pres = numpy.array(pres, dtype=\"float\")\n self.elv = numpy.array(elv, dtype=\"float\")\n self.temp = numpy.array(temp, dtype=\"float\")\n self.dewp = numpy.array(dewp, dtype=\"float\")\n self.rh = numpy.array(rh, dtype=\"float\")\n self.wdir = numpy.array(wdir, dtype=\"float\")\n self.wspd = numpy.array(wspd, dtype=\"float\")\n self.lat = numpy.array(lat, dtype=\"float\")\n self.lon = numpy.array(lon, dtype=\"float\")\n \n #Reading a NetCDF sounding file\n elif(flag.lower() == \"netcdf\"):\n import netCDF4 as nc\n \n #Opening netcdf file and pulling in variables\n fn = nc.Dataset(filepath, \"r\")\n self.pres = fn.variables[\"pres\"][:]\n self.elv = fn.variables[\"alt\"][:]\n self.temp = fn.variables[\"tdry\"][:]\n self.dewp = fn.variables[\"dp\"][:]\n self.rh = fn.variables[\"rh\"][:]\n self.wdir = fn.variables[\"wdir\"][:]\n self.wspd = fn.variables[\"wspd\"][:]\n self.lat = fn.variables[\"lat\"][:]\n self.lon = fn.variables[\"lon\"][:]\n self.time = fn.__dict__[\"BalloonReleaseTime\"]\n self.date = fn.__dict__[\"BalloonReleaseDate\"]\n self.id = fn.__dict__[\"StationName\"]\n self.units = fn.variables[\"wspd\"].units\n \n #Handling an unrecognized flag\n else:\n print(\"ERROR - Unrecognized flag for sounding file, exiting\")\n exit()\n\n #Creating list of attributes associated with sounding object\n self.attributes = self.__dict__.keys()\n\n #Function to calculate bulk wind shear in a layer\n #Inputs:\n # low, float, lower boundary of layer in meters\n # high, float, upper boundary of layer in meters\n #Returns bulk wind shear in same units as sounding wind\n def bulk_shear(self,low,high):\n #Importing numpy\n import numpy\n \n #Correcting altitude to be AGL\n heights = self.elv-self.elv[0]\n \n #Calculating wind components\n #Not correcting for meteorological direction because only need bulk quantity at end\n u = self.wspd*numpy.cos(self.wdir*numpy.pi/180.0)\n v = self.wspd*numpy.sin(self.wdir*numpy.pi/180.0)\n \n #Calculating difference in u and v between 10m and 1km.\n du = u[numpy.where(abs(heights-high)==abs(heights-high).min())]-u[numpy.where(abs(heights-low)==abs(heights-low).min())]\n dv = v[numpy.where(abs(heights-high)==abs(heights-high).min())]-v[numpy.where(abs(heights-low)==abs(heights-low).min())]\n\n #Returning bulk shear in layer\n #Subscripting because result from above produces an array\n try:\n return numpy.sqrt(du**2+dv**2)[0]\n except: #In case above is actually a number\n return numpy.sqrt(du**2+dv**2)\n\n #Function to calculate CAPE and CIN\n #Returns [CAPE, CIN] as metpy unit aware values.\n def cape_cin(self):\n #Importing metpy\n import metpy.calc as mc\n from metpy.units import units as mu\n\n #Calculating parcel path\n parcel_path = mc.parcel_profile(self.pres*mu.hectopascal, self.temp[0]*mu.celsius, self.dewp[0]*mu.celsius)\n\n #Calculating CAPE and CIN\n return mc.cape_cin(self.pres*mu.hectopascal, self.temp*mu.celsius, self.dewp*mu.celsius, parcel_path)\n\n #Function to calculate Lifting Condensation Level (LCL)\n #Returns pressure and temperature of LCL as unit aware values\n def lcl(self):\n #Import metpy\n import metpy.calc as mc\n from metpy.units import units as mu\n \n #Calculating LCL from parcel starting point\n return mc.lcl(self.pres[0]*mu.hectopascal, self.temp[0]*mu.celsius, self.dewp[0]*mu.celsius)\n \n #Function to calculate Level of Free Convection (LFC)\n #Returns pressure and temperature of LFC as unit aware values\n def lfc(self):\n #Import metpy\n import metpy.calc as mc\n from metpy.units import units as mu\n \n #Calculating LCL from parcel starting point\n return mc.lfc(self.pres*mu.hectopascal, self.temp*mu.celsius, self.dewp*mu.celsius)\n\n #Function to calculate Planetary Boundary Layer Height (PBLH)\n #Returns PBLH as a float or NAN if not found in sounding.\n #Height is AGL\n def pblh(self):\n #Importing numpy\n import numpy\n\n #Finding PBLH by searching for minimum dewpoint gradient\n #Calculating vertical gradient of dewpoint\n ddewp = self.dewp[2:]-self.dewp[:-2]\n dheights = self.elv[2:]-self.elv[:-2]\n del_dewp = ddewp/dheights\n \n #Constructing heights at gradient levels\n heights = (self.elv[2:]+self.elv[:-2])/2-self.elv[0] #Also converting to AGL\n \n #Limiting everything to less than 4km AGL\n del_dewp = del_dewp[numpy.where(heights < 4000)]\n heights = heights[numpy.where(heights < 4000)]\n \n #Finding minimum gradient in dewpoint and calling it the boundary layer top\n pblh = heights[numpy.where(del_dewp == numpy.nanmin(del_dewp))]\n try: #making sure that only a value is returned, not an array.\n return pblh[0]\n except:\n return pblh","sub_path":"grainex_sounding.py","file_name":"grainex_sounding.py","file_ext":"py","file_size_in_byte":9158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"214167627","text":"from django.forms import Form, ModelForm, Select, DateInput, FloatField, NumberInput, Textarea, CharField, FileField\nfrom django.db import models\n\nfrom catalog.models import Vulnerability\n\nclass DateInput(DateInput):\n input_type = 'date'\n\nclass VulnerabilityForm(ModelForm):\n class Meta:\n model = Vulnerability\n fields = '__all__'\n\n cvss_value = FloatField(min_value=0, max_value=10)\n report_page = FloatField(min_value=0)\n\n widgets = {\n 'perimeter': Select(),\n 'synopsis': Textarea(attrs={'cols':30,'rows':5,'wrap':\"hard\"}),\n 'identification_date': DateInput(),\n 'remediation_deadline': DateInput(),\n 'remediation': Textarea(attrs={'cols':30,'rows':5,'wrap':\"hard\"}),\n 'observation': Textarea(attrs={'cols':30,'rows':5,'wrap':\"hard\"}),\n 'cvss_value': NumberInput(attrs={'min':0, 'max':10}),\n 'report_page': NumberInput(attrs={'min':0})\n }\n\nclass FastUpdateForm(ModelForm):\n class Meta:\n model = Vulnerability\n fields =['status', 'risk', 'remediation_deadline']\n\n widgets = {\n 'remediation_deadline': DateInput()\n }\n\nclass UploadFileForm(Form):\n title = CharField(max_length=50)\n file = FileField()","sub_path":"metadata/forms/catalog/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"489668432","text":"import numpy as np\n\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense, Dropout\nfrom keras.utils.visualize_util import plot\n\ndata_dim = 4\ntimesteps = 1\nnb_classes = 4\n\n\n\ndef Jarvis():\n\n\n model = Sequential()\n model.add(LSTM(128,return_sequences=True ,input_shape=(timesteps, data_dim)))\n model.add(Dropout(0.2))\n model.add(LSTM(32, init='uniform',activation = 'tanh'))\n model.add(Dropout(0.2))\n model.add(Dense(nb_classes, init='normal', activation='sigmoid'))\n\n model.compile(loss = 'mse', optimizer='rmsprop', metrics=['accuracy'])\n\n return model\n\ndef test():\n x_train = np.random.random((1000, timesteps, data_dim))\n y_train = np.random.random((1000, nb_classes))\n\n # generate dummy validation data\n x_val = np.random.random((100, timesteps, data_dim))\n y_val = np.random.random((100, nb_classes))\n\n model = Jarvis()\n\n model.fit(x_train, y_train,\n batch_size=16, nb_epoch=5,\n validation_data=(x_val, y_val))\n\n plot(model, \"jarvis.png\", show_shapes=True, show_layer_names=True)\n\n print(\"FINISHED!!\")\n\n\n","sub_path":"neural_nets/jarvis.py","file_name":"jarvis.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"512132632","text":"def quickSort(S, low, high):\n if (high > low):\n mid = partition(S, low, high)\n quickSort(S, low, mid)\n quickSort(S, mid + 1, high)\n\n\ndef partition(S, low, high):\n pivotitem = S[low]\n j = low\n for i in range(low + 1, high + 1):\n print(i, j, S)\n if (S[i] < pivotitem):\n j += 1\n S[i], S[j] = S[j], S[i]\n pivotpoint = j\n S[low], S[pivotpoint] = S[pivotpoint], S[low]\n return pivotpoint\n\n\nS = [15, 22, 13, 27, 12, 10, 20, 25]\nprint('Before=', S)\nquickSort(S, 0, len(S) - 1)\nprint('After=', S)\n","sub_path":"AlgorithmList/DivideConquer/QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"328156457","text":"# -*- coding: utf-8 -*-\nfrom typing import Tuple, Union\n\nimport numpy as np\nimport torch\nfrom torch import Tensor\n\n\"\"\"\nHint: To use on packed sequences:\n\n # Unpacking\n inputs_tensor = inputs.data\n\n result = embedding(inputs_tensor)\n\n # Packing back\n # Not using pack_sequence because we want to keep the same info as\n # the inputs (nb of feature has changed, but not the number of inputs\n # -- i.e. streamlines)\n result = PackedSequence(result, inputs.batch_sizes,\n inputs.sorted_indices,\n inputs.unsorted_indices)\n\"\"\"\n\n\nclass EmbeddingAbstract(torch.nn.Module):\n def __init__(self, nb_features_in: int, nb_features_out: int,\n key: str = ''):\n \"\"\"\n Params\n -------\n input_size: int\n Size of each data point.\n Ex: MRI features * nb neighbors for flattened MRI data.\n Ex: 3D coordinates [x,y,z] for streamlines.\n output_size: int\n Size of each output data point.\n \"\"\"\n super().__init__()\n self.nb_features_in = nb_features_in\n self.nb_features_out = nb_features_out\n self.key = key\n\n @property\n def params_for_checkpoint(self):\n \"\"\"All parameters necessary to create again the same model. Will be\n used in the trainer, when saving the checkpoint state. Params here\n will be used to re-create the model when starting an experiment from\n checkpoint. You should be able to re-create an instance of your\n model with those params.\"\"\"\n # We need real int types, not numpy.int64, not recognized by json\n # dumps.\n params = {\n 'nb_features_in': int(self.nb_features_in),\n 'nb_features_out': int(self.nb_features_out),\n 'key': self.key\n }\n return params\n\n def forward(self, inputs):\n raise NotImplementedError\n\n\nclass NNEmbedding(EmbeddingAbstract):\n def __init__(self, nb_features_in, nb_features_out: int):\n super().__init__(nb_features_in, nb_features_out, key='nn_embedding')\n self.linear = torch.nn.Linear(self.nb_features_in, self.nb_features_out)\n self.relu = torch.nn.ReLU()\n\n def forward(self, inputs: Tensor):\n # Calling forward.\n result = self.linear(inputs)\n result = self.relu(result)\n return result\n\n\nclass NoEmbedding(EmbeddingAbstract):\n def __init__(self, nb_features_in, nb_features_out: int = None):\n if nb_features_out is None:\n nb_features_out = nb_features_in\n if nb_features_in != nb_features_out:\n raise ValueError(\"Identity embedding should have input_size == \"\n \"output_size but you gave {} and {}\"\n .format(nb_features_in, nb_features_out))\n\n super().__init__(nb_features_in, nb_features_out, key='no_embedding')\n self.identity = torch.nn.Identity()\n\n def forward(self, inputs: Tensor = None):\n # Should check that input size = self.input_size but we don't\n # know how the data is organized. Letting user be responsible.\n result = self.identity(inputs)\n return result\n\n\nclass CNNEmbedding(EmbeddingAbstract):\n def __init__(self, nb_features_in: int, nb_features_out: int,\n kernel_size: Union[int, Tuple[int, int, int]],\n image_shape: Tuple[int, int, int]):\n \"\"\"\n Applies a 3D convolution. For now: a single layer.\n\n Parameters\n ----------\n nb_features_in: int\n Size should refer to the number of features per voxel. (Contrary to\n other embeddings, where data in each neighborhood is flattened and\n input_size is thus nb_features * nb_neighboors).\n nb_features_out: int\n Size of the output = number of out_channels = number of filters.\n kernel_size: int, or a tuple of 3 ints\n Size of the kernel (will be a 3D [k, k, k] kernel).\n image_shape: (int, int, int)\n Size of the image.\n \"\"\"\n super().__init__(nb_features_in, nb_features_out, key='cnn_embedding')\n\n if not isinstance(kernel_size, int):\n raise NotImplementedError(\"Need to verify order of the 3D kernel \"\n \"size.\")\n self.in_image_shape = np.asarray(image_shape)\n self.cnn_layer = torch.nn.Conv3d(\n nb_features_in, nb_features_out, kernel_size=kernel_size)\n\n # Computing values, just to help user.\n padding = 0\n stride = 1\n dilation = 1\n # Using default stride=1, padding=0, dilation=1, etc.\n # Output size formula is given here:\n # https://pytorch.org/docs/stable/generated/torch.nn.Conv3d.html\n numerator = \\\n self.in_image_shape + 2 * padding - dilation * (kernel_size - 1) - 1\n self.out_image_shape = np.floor(numerator / stride + 1)\n self.out_flattened_size = int(np.prod(self.out_image_shape) * nb_features_out)\n\n def forward(self, inputs: Tensor):\n \"\"\"\n Expected inputs shape: (batch size, x, y, z, channels)\n (We will reorder to torch's input shape.)\n Outputs shape: (batch size, x2, y2, x2, c2)\n \"\"\"\n # Torch:\n # Note that depth is first, but we can pretend it is (N, C, X, Y, Z).\n # 3D operation is the same.\n # Input size = (N, C1, D1, H1, W1) --> (B, C1, X1, Y1, Z1)\n # Output size = (N, C2, D2, H2, W2) --> (B, C2, X2, Y2, Z2)\n # N = Batch size.\n # C = Number of channels\n # D = Depth of image\n # H = Height of image\n # W = Width of image\n assert inputs.shape[-1] == self.nb_features_in\n assert np.array_equal(inputs.shape[1:4], self.in_image_shape), \\\n \"Expecting inputs of shape {} ({} channels per voxel), but \"\\\n \"received {}.\".format(self.in_image_shape, self.nb_features_in,\n inputs.shape[2:])\n\n inputs = torch.permute(inputs, (0, 4, 1, 2, 3))\n outputs = self.cnn_layer(inputs)\n outputs = torch.permute(outputs, (0, 2, 3, 4, 1))\n # Current shape = (B, X2, Y2, Z2, C2)\n outputs = torch.flatten(outputs, start_dim=1, end_dim=4)\n\n # Final shape: (B, X2*Y2*Z2*C2)\n return outputs\n\n\nkeys_to_embeddings = {'no_embedding': NoEmbedding,\n 'nn_embedding': NNEmbedding,\n 'cnn_embedding': CNNEmbedding}\n","sub_path":"dwi_ml/models/embeddings.py","file_name":"embeddings.py","file_ext":"py","file_size_in_byte":6536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"264864021","text":"#!/usr/bin/env python3\n# coding: utf8\n__author__ = \"Juan Manuel Fernández Nácher\"\n\n# Clase que maneja la api de telegram\nfrom TelegramBot import TelegramBot\n\ndef main():\n\tTOKEN = open('token', 'r').read().strip()\n\ttelegramBot = TelegramBot(TOKEN)\n\ttelegramBot.startBot()\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"223639765","text":"from Token import Token\n\n\nclass Gem(Token):\n \n def __init__ (self, color, name):\n super().__init__(color, name)\n \n \n#test\nif __name__ == '__main__':\n gem = Gem(\"red\", \"Ruby\")\n print(\"Name: {}\".format(gem.get_name()));\n print(\"Color: {}\".format(gem.get_color()));","sub_path":"Gem.py","file_name":"Gem.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"551886198","text":"from flask_wtf import FlaskForm\nfrom wtforms import SubmitField, StringField, SelectField, TextAreaField\nfrom wtforms.fields.html5 import DateField\nfrom wtforms.validators import DataRequired\n\n\nclass addDailyAttendanceForm(FlaskForm):\n studentID = StringField(\"Student ID\")\n chattStateANumber = StringField(\"Chatt State A Number\")\n attendanceCode = SelectField(\n \"Attendance Code\",\n choices=[\n (\"Missed Swipe\", \"Missed Swipe\"),\n (\"W/D Use Only\", \"W/D Use Only\"),\n (\"P (Present)\", \"P (Present)\"),\n (\"UNX (Unexcused)\", \"UNX (Unexcused)\"),\n (\"EXC (Excused)\", \"EXC (Excused)\"),\n (\"UTY (Unexcused Tardy)\", \"UTY (Unexcused Tardy)\"),\n (\"TDY (Tardy)\", \"TDY (Tardy)\"),\n (\"ACT (Activity)\", \"ACT (Activity)\"),\n (\"ALT (Alt_Remanded)\", \"ALT (Alt_Remanded)\"),\n (\"DTH (Death in Family)\", \"DTH (Death in Family)\"),\n (\"CRT (Court)\", \"CRT (Court)\"),\n (\"EVS (Evening School)\", \"EVS (Evening School)\"),\n (\"FLU (Flu)\", \"FLU (Flu)\"),\n (\"HBD (Homebound)\", \"HBD (Homebound)\"),\n (\"ISS (In-School Suspension)\", \"ISS (In-School Suspension)\"),\n (\"MED (Medical)\", \"MED (Medical)\"),\n (\"PEX (Parent Excuse)\", \"PEX (Parent Excuse)\"),\n (\"REL (Religious)\", \"REL (Religious)\"),\n (\"SUS (Suspended)\", \"SUS (Suspended)\"),\n (\"TNT (Unexcused Trans)\", \"TNT (Unexcused Trans)\"),\n (\"TXT (Excused Trans)\", \"TXT (Excused Trans)\"),\n (\"Z (Expelled)\", \"Z (Expelled)\"),\n ],\n validators=[DataRequired()],\n )\n absenceDate = DateField(\"Absence Date\", validators=[DataRequired()])\n comment = TextAreaField(\"Comment\")\n submitDailyAttendance = SubmitField(\"Submit New Daily Attendance\")\n","sub_path":"P2MT_App/dailyAttendance/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"371042054","text":"# coding=utf-8\n\npirate = {}\npirate['sir'] = 'matey'\npirate['hotel'] = 'fleabag inn'\npirate['student'] = 'swabbie'\npirate['boy'] = 'matey'\npirate['madam'] = 'proud beauty'\npirate['professor']='foul blaggart'\npirate['restaurant'] = 'galley'\npirate['your']='yer'\npirate['excuse']='arr'\npirate['students']='swabbies'\npirate['are']='be'\npirate['lawyer']='foul blaggart'\npirate['the']='th’'\npirate['restroom']='head'\npirate['my']='me'\npirate['hello']='avast'\npirate['is']='be'\npirate['man']='matey'\n\n\nsentence = input(\"Please enter a sentence in English\")\n\npsentence = []\nwords = sentence.split()\nfor aword in words:\n if aword in pirate:\n psentence.append(pirate[aword])\n else:\n psentence.append(aword)\n\nprint(\" \".join(psentence))\n","sub_path":"19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"425899150","text":"A, B, K = map(int, input().split())\n\ndef main():\n cnt = 0\n for x in range(min(A, B), 0, -1):\n if A%x==0 and B%x==0:\n cnt += 1\n if cnt == K:\n print(x)\n \n\nif __name__ == '__main__':\n main()\n","sub_path":"atcoder_problems/atcoder_begginer_contest/120/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"627452394","text":"# from transform import ReLabel, ToLabel, ToSP, Scale\nfrom gan_model_time import ConvGenTime\nfrom gan_model import ConvDis\nfrom gan_model_time import PatchDis\nfrom utils import *\nimport gan_model_time\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom torch.utils import data\nimport torch.nn.init as init\nimport torch.nn.functional as F\nimport torchvision\nfrom torchvision import datasets, models, transforms\nfrom skimage import color\nfrom movie_time_data_loader import *\n\nimport time\nimport os\nimport sys\nfrom PIL import Image\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\n\nimport matplotlib\n\n\nparser = argparse.ArgumentParser(description='Colorization using GAN')\nparser.add_argument('--path', type=str,\n help='Root path for dataset')\nparser.add_argument('--large', action=\"store_true\",\n help='Use larger images?')\nparser.add_argument('--batch_size', default=4, type=int,\n help='Batch size: default 4')\nparser.add_argument('--lr', default=1e-4, type=float,\n help='Learning rate for optimizer')\nparser.add_argument('--weight_decay', default=0, type=float,\n help='Weight decay for optimizer')\nparser.add_argument('--num_epoch', default=20, type=int,\n help='Number of epochs')\nparser.add_argument('--lamb', default=100, type=int,\n help='Lambda for L1 Loss')\nparser.add_argument('--test', default='', type=str,\n help='Path to the model, for testing')\nparser.add_argument('--model_G', default='', type=str,\n help='Path to resume for Generator model')\nparser.add_argument('--model_D', default='', type=str,\n help='Path to resume for Discriminator model')\nparser.add_argument('--ngf', default=32, type=int,\n help='# of gen filters in first conv layer')\nparser.add_argument('--ndf', default=32, type=int,\n help='# of discrim filters in first conv layer')\n\nparser.add_argument('--numG', default=1, type=int, help='G trains numG times when D trains per time')\nparser.add_argument('--numD', default=1, type=int, help='D trains numD times when G trains per time')\nparser.add_argument('--patchGAN', action='store_true', help='Use patchGAN in Discriminator')\nparser.add_argument('--use_lsgan', action='store_true', help='Use LSGAN in loss criterion')\nparser.add_argument('--use_self_attn', action='store_true', help='Use self attention in both G and D')\n\n# parser.add_argument('-p', '--plot', action=\"store_true\",\n# help='Plot accuracy and loss diagram?')\nparser.add_argument('-s','--save', action=\"store_true\",\n help='Save model?')\nparser.add_argument('--gpu', default=0, type=int,\n help='Which GPU to use?')\n\n\ndef main():\n global args, date\n args = parser.parse_args()\n date = str(datetime.datetime.now()).replace(':', '_').replace(' ', '_').replace('.', '_')\n\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.gpu)\n\n model_G = ConvGenTime(args.ngf, args.use_self_attn)\n if args.patchGAN:\n model_D = PatchDis(large=args.large, ndf=args.ndf, use_self_attn=args.use_self_attn)\n else:\n model_D = ConvDis(large=args.large, ndf=args.ndf, use_self_attn=args.use_self_attn)\n\n start_epoch_G = start_epoch_D = 0\n if args.model_G:\n print('Resume model G: %s' % args.model_G)\n checkpoint_G = torch.load(resume)\n model_G.load_state_dict(checkpoint_G['state_dict'])\n start_epoch_G = checkpoint_G['epoch']\n if args.model_D:\n print('Resume model D: %s' % args.model_D)\n checkpoint_D = torch.load(resume)\n model_D.load_state_dict(checkpoint_D['state_dict'])\n start_epoch_D = checkpoint_D['epoch']\n assert start_epoch_G == start_epoch_D\n if args.model_G == '' and args.model_D == '':\n print('No Resume')\n start_epoch = 0\n\n model_G.cuda()\n model_D.cuda()\n\n # optimizer\n optimizer_G = optim.Adam(model_G.parameters(),\n lr=args.lr, betas=(0.5, 0.999),\n eps=1e-8, weight_decay=args.weight_decay)\n optimizer_D = optim.Adam(model_D.parameters(),\n lr=args.lr, betas=(0.5, 0.999),\n eps=1e-8, weight_decay=args.weight_decay)\n if args.model_G:\n optimizer_G.load_state_dict(checkpoint_G['optimizer'])\n if args.model_D:\n optimizer_D.load_state_dict(checkpoint_D['optimizer'])\n\n # loss function\n global criterionGAN\n #criterion = nn.BCELoss()\n criterionGAN = gan_model_time.GANLoss(use_lsgan=args.use_lsgan, tensor =torch.cuda.FloatTensor)\n\n global L1\n L1 = nn.L1Loss()\n\n # dataset\n data_root = args.path\n\n train_loader = get_movie_time_loader(os.path.join(data_root, 'train/'),\n batch_size=args.batch_size,\n large=args.large,\n mode='train',\n start_index = 1,\n num_workers=4,\n shuffle=True\n )\n\n val_loader = get_movie_time_loader(os.path.join(data_root, 'val/'),\n batch_size=args.batch_size,\n large=args.large,\n mode='val',\n start_index = 10000,\n num_workers=4,\n shuffle=True\n )\n\n global val_bs\n val_bs = val_loader.batch_size\n\n # set up plotter, path, etc.\n global iteration, print_interval, plotter, plotter_basic\n iteration = 0\n print_interval = args.numG * 5\n plotter = Plotter_GAN_TV()\n plotter_basic = Plotter_GAN()\n\n global img_path\n size = ''\n if args.large: size = 'Large'\n img_path = 'img/model_time/%s/GAN_%s_L1%d_bs%d_%s_lr%s_ngf%d_ndf%d_numG%d_numD%d/' \\\n % (date, size, args.lamb, args.batch_size, 'Adam', str(args.lr), args.ngf, args.ndf, args.numG, args.numD)\n model_path = 'model/model_time/%s/GAN_%s_L1%d_bs%d_%s_lr%s_ngf%d_ndf%d_numG%d_numD%d/' \\\n % (date, size, args.lamb, args.batch_size, 'Adam', str(args.lr), args.ngf, args.ndf, args.numG, args.numD)\n if not os.path.exists(img_path):\n os.makedirs(img_path)\n if not os.path.exists(model_path):\n os.makedirs(model_path)\n\n # start loop\n start_epoch = 0\n\n for epoch in range(start_epoch, args.num_epoch):\n print('Epoch {}/{}'.format(epoch, args.num_epoch - 1))\n print('-' * 20)\n\n if epoch == 0:\n val_lerrG, val_errD = validate(val_loader, model_G, model_D, optimizer_G, optimizer_D, epoch=-1)\n # train\n train_errG, train_errD = train(train_loader, model_G, model_D, optimizer_G, optimizer_D, epoch, iteration)\n # validate\n val_lerrG, val_errD = validate(val_loader, model_G, model_D, optimizer_G, optimizer_D, epoch)\n\n plotter.train_update(train_errG, train_errD)\n plotter.val_update(val_lerrG, val_errD)\n plotter.draw(img_path + 'train_val.png')\n\n if args.save and (epoch % 10 == 1):\n print('Saving check point')\n save_checkpoint({'epoch': epoch + 1,\n 'state_dict': model_G.state_dict(),\n 'optimizer': optimizer_G.state_dict(),\n 'Large': args.large,\n 'ngf': args.ngf,\n 'batch_size': args.batch_size,\n 'ndf': args.ndf,\n 'numG': args.numG,\n 'numD': args.numD,\n 'use_self_attn': args.use_self_attn,\n },\n filename=model_path+'G_epoch%d.pth.tar' \\\n % epoch)\n\n # Save the latest model\n print('Save the lastest model')\n save_checkpoint({'epoch': epoch + 1,\n 'state_dict': model_G.state_dict(),\n 'optimizer': optimizer_G.state_dict(),\n 'Large': args.large,\n 'ngf': args.ngf,\n 'batch_size': args.batch_size,\n 'ndf': args.ndf,\n 'numG': args.numG,\n 'numD': args.numD,\n 'use_self_attn': args.use_self_attn,\n },\n filename=model_path+'Last_G_epoch%d.pth.tar' \\\n % epoch)\n\n\n save_checkpoint({'epoch': epoch + 1,\n 'state_dict': model_D.state_dict(),\n 'optimizer': optimizer_D.state_dict(),\n 'Large': args.large,\n 'ngf': args.ngf,\n 'batch_size': args.batch_size,\n 'ndf': args.ndf,\n 'numG': args.numG,\n 'numD': args.numD,\n 'use_self_attn': args.use_self_attn,\n },\n filename=model_path+'Last_D_epoch%d.pth.tar' \\\n % epoch)\n\n\n\ndef train(train_loader, model_G, model_D, optimizer_G, optimizer_D, epoch, iteration):\n errorG = AverageMeter() # will be reset after each epoch\n errorD = AverageMeter() # will be reset after each epoch\n errorG_basic = AverageMeter() # basic will be reset after each print\n errorD_basic = AverageMeter() # basic will be reset after each print\n errorD_real = AverageMeter()\n errorD_fake = AverageMeter()\n errorG_GAN = AverageMeter()\n #errorG_L1_lab = AverageMeter()\n errorG_R = AverageMeter()\n\n model_G.train()\n model_D.train()\n\n real_label = 1\n fake_label = 0\n\n #for i, (_now, _prev, _next, target, target_lab) in enumerate(train_loader):\n for i, (_now, _prev, _next, target) in enumerate(train_loader):\n\n #_now, _prev, _next, target, target_lab = Variable(_now.cuda()), Variable(_prev.cuda()), Variable(_next.cuda()), Variable(target.cuda()), Variable(target_lab.cuda())\n _now, _prev, _next, target = Variable(_now.cuda()), Variable(_prev.cuda()), Variable(_next.cuda()), Variable(target.cuda())\n\n ########################\n # update D network\n ########################\n # train with real\n if (i % args.numG) == 0:\n # dr1, dr2, df1, df2, gf1, gf2 are attention scores\n model_D.zero_grad()\n output = model_D(target)\n #label = torch.FloatTensor(target.size(0)).fill_(real_label).cuda()\n #labelv = Variable(label)\n #errD_real = criterion(torch.squeeze(output), labelv)\n errD_real = criterionGAN(output, True)\n errD_real.backward()\n D_x = output.data.mean()\n\n # train with fake\n #fake, _ = model_G(_now, _prev, _next)\n fake = model_G(_now, _prev, _next)\n #labelv = Variable(label.fill_(fake_label))\n output = model_D(fake.detach())\n #errD_fake = criterion(torch.squeeze(output), labelv)\n errD_fake = criterionGAN(output, False)\n errD_fake.backward()\n D_G_x1 = output.data.mean()\n\n errD = errD_real + errD_fake\n optimizer_D.step()\n\n ########################\n # update G network\n ########################\n\n if (i % args.numD) == 0:\n #labelv = Variable(label.fill_(real_label))\n #fake, fake_lab = model_G(_now, _prev, _next)\n fake = model_G(_now, _prev, _next)\n model_G.zero_grad()\n output = model_D(fake)\n #errG_GAN = criterion(torch.squeeze(output), labelv)\n errG_GAN = criterionGAN(output, True)\n errG_L1 = L1(fake.view(fake.size(0),-1), target.view(target.size(0),-1))\n #errG_L1_lab = L1(fake_lab.view(fake_lab.size(0),-1), target_lab.view(target_lab.size(0),-1))\n\n #errG = errG_GAN + args.lamb * (0.7 * errG_L1 + 0.3 * errG_L1_lab)\n errG = errG_GAN + args.lamb * errG_L1\n errG.backward()\n D_G_x2 = output.data.mean()\n optimizer_G.step()\n\n # store error values\n if (i % max(args.numG, args.numD)) == 0:\n errorG.update(errG, target.size(0), history=1)\n errorD.update(errD, target.size(0), history=1)\n errorG_basic.update(errG, target.size(0), history=1)\n errorD_basic.update(errD, target.size(0), history=1)\n errorD_real.update(errD_real, target.size(0), history=1)\n errorD_fake.update(errD_fake, target.size(0), history=1)\n #errorG_L1_lab.update(errG_L1_lab, target.size(0), history=1)\n\n errorD_real.update(errD_real, target.size(0), history=1)\n errorD_fake.update(errD_fake, target.size(0), history=1)\n errorG_GAN.update(errG_GAN, target.size(0), history=1)\n errorG_R.update(errG_L1, target.size(0), history=1)\n\n if i == 0:\n vis_result(_now.data, target.data, fake.data, epoch, mode = 'train')\n\n if iteration % print_interval == 0:\n print('Epoch%d[%d/%d]: Loss_D: %.4f(R%0.4f+F%0.4f) Loss_G: %0.4f(GAN%.4f+RGB%0.4f) D(x): %.3f D(G(z)): %.3f / %.3f' \\\n % (epoch, i, len(train_loader),\n errorD_basic.avg, errorD_real.avg, errorD_fake.avg,\n errorG_basic.avg, errorG_GAN.avg, errorG_R.avg * args.lamb,\n D_x, D_G_x1, D_G_x2\n ))\n # plot image\n plotter_basic.g_update(errorG_basic.avg)\n plotter_basic.d_update(errorD_basic.avg)\n plotter_basic.draw(img_path + 'train_basic.png')\n # reset AverageMeter\n errorG_basic.reset()\n errorD_basic.reset()\n errorD_real.reset()\n errorD_fake.reset()\n errorG_GAN.reset()\n errorG_R.reset()\n #errorG_L1_lab.reset()\n\n iteration += 1\n\n return errorG.avg, errorD.avg\n\n\ndef validate(val_loader, model_G, model_D, optimizer_G, optimizer_D, epoch):\n errorG = AverageMeter()\n errorD = AverageMeter()\n\n model_G.eval()\n model_D.eval()\n\n real_label = 1\n fake_label = 0\n\n with torch.no_grad(): # Fuck torch.no_grad!! Gradient will accumalte if you don't set torch.no_grad()!!\n #for i, (_now, _prev, _next, target, target_lab) in enumerate(val_loader):\n for i, (_now, _prev, _next, target) in enumerate(val_loader):\n #_now, _prev, _next, target, target_lab = Variable(_now.cuda()), Variable(_prev.cuda()), Variable(_next.cuda()), Variable(target.cuda()), Variable(target_lab.cuda())\n _now, _prev, _next, target = Variable(_now.cuda()), Variable(_prev.cuda()), Variable(_next.cuda()), Variable(target.cuda())\n ########################\n # D network\n ########################\n # validate with real\n output = model_D(target)\n #label = torch.FloatTensor(target.size(0)).fill_(real_label).cuda()\n #labelv = Variable(label)\n \n errD_real = criterionGAN(output, True)\n\n # validate with fake\n #fake, fake_lab = model_G(_now, _prev, _next)\n fake = model_G(_now, _prev, _next)\n #labelv = Variable(label.fill_(fake_label))\n output = model_D(fake.detach())\n errD_fake = criterionGAN(output, False)\n\n errD = errD_real + errD_fake\n\n ########################\n # G network\n ########################\n #labelv = Variable(label.fill_(real_label))\n output = model_D(fake)\n errG_GAN = criterionGAN(output, True)\n errG_L1 = L1(fake.view(fake.size(0),-1), target.view(target.size(0),-1))\n #errG_L1_lab = L1(fake_lab.view(fake_lab.size(0),-1), target_lab.view(target_lab.size(0),-1))\n\n #errG = errG_GAN + args.lamb * (0.8 * errG_L1 + 0.2 * errG_L1_lab)\n errG = errG_GAN + args.lamb * errG_L1 \n\n errorG.update(errG, target.size(0), history=1)\n errorD.update(errD, target.size(0), history=1)\n\n if i == 0:\n vis_result(_now.data, target.data, fake.data, epoch, mode = 'val')\n\n if i % 50 == 0:\n print('Validating Epoch %d: [%d/%d]' \\\n % (epoch, i, len(val_loader)))\n\n print('Validation: Loss_D: %.4f Loss_G: %.4f '\\\n % (errorD.avg, errorG.avg))\n\n return errorG.avg, errorD.avg\n\ndef vis_result(data, target, output, epoch, mode='val'):\n '''visualize images for GAN'''\n img_list = []\n for i in range(min(32, val_bs)):\n l = torch.unsqueeze(torch.squeeze(data[i]), 0).cpu().numpy()\n # from IPython import embed; embed()\n raw = target[i].cpu().numpy()\n pred = output[i].cpu().numpy()\n\n raw_rgb = (np.transpose(raw, (1,2,0)).astype(np.float64) + 1) / 2.\n pred_rgb = (np.transpose(pred, (1,2,0)).astype(np.float64) + 1) / 2.\n\n # denormalize the grey image for visualization \n grey = l * 0.5 + 0.5 \n grey = np.transpose(grey, (1,2,0))\n grey = np.repeat(grey, 3, axis=2).astype(np.float64)\n img_list.append(np.concatenate((grey, raw_rgb, pred_rgb), 1))\n display_len = 4 if len(img_list) >= 4 else 2\n img_list = [np.concatenate(img_list[display_len*i:display_len*(i+1)], axis=1) for i in range(len(img_list) // display_len)]\n img_list = np.concatenate(img_list, axis=0)\n\n if mode=='val':\n matplotlib.image.imsave(img_path + 'epoch%d_val.png' % epoch, img_list)\n else:\n matplotlib.image.imsave(img_path + 'epoch%d_train.png' % epoch, img_list)\n\nif __name__ == '__main__':\n main()\n","sub_path":"gan_main_time.py","file_name":"gan_main_time.py","file_ext":"py","file_size_in_byte":17838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"445889183","text":"import numbers\nimport warnings\n\nimport numpy as np\n\n\"\"\"\nPixel coordinate conversion\n\nThe phantom_base.py module creates raster volumes from vector\nrepresentations using CELL_BASED coordinates. That is, each pixel is referred to\nby the coordinate of the pixel center.\n+---+---\n| x |\n+---+-\n| |\n\nwhere the center `x` is numerically represented as (0, 0), and\nthe top left `+` is (-0.5, -0.5). This cell-based coordinate system is useful\nwhen the volume is numerically represented between [-1, 1] across all cube dimensions.\n\nArrays are typically numerically represented in EDGE-BASED coordinates, where\nthe top left `+` is numerically represented as (0, 0) and the center\n`x` is (0.5, 0.5).\n\nIf a volume's raster shape is (32, 32, 32), we will want to refer to a point in\nthat shape via pixel coordinate. The coordinate system used is undefined, i.e.\ndoes the pixel (31, 31, 31) map to (1, 1, 1), or 1-eps (where eps is the raster\nconversion factor)?\n\"\"\"\nCAP_TYPES = [\"flat\", \"sphere\", \"none\"]\n\n\ndef to_basecoord(x: int, shape: int):\n \"\"\"\n Scale a single coordinate from pixel-based edge coordinate to numerical\n cell-based coordinate for vector-to-raster.\n\n Inputs:\n x -- integer coordinate, must be < shape\n shape -- the size of the dimension we are scaling from\n\n Output:\n the coordinate in base [-1, 1] coordinate space, to be used directly with\n phantom_base methods\n\n Raises:\n AssertionError when x is not within range [0, shape)\n\n Eg:\n >>> s = 32 # the shape of the raster dimension we are scaling to\n >>> x = 0 # the coordinate of the pixel we are scaling\n >>> to_basecoord(x, s)\n -1.0\n >>> to_basecoord(31, s)\n 1.0\n \"\"\"\n assert shape > 0, \"Shape must be positive integer, found {}\".format(shape)\n assert 0 <= x < shape, \"point `{}` is not within shape `{}`\".format(x, shape)\n if shape == 1:\n shape = 2 # make sure that we can still have a single dimension and dont divide by zero\n return -1 + (x * 2) / (shape - 1)\n\n\ndef scale_point_to_basecoord(point: (int, int, int), shape: (int, int, int)):\n \"\"\"\n Take an n-tuple `point` within a volume's `shape`, and scale to coordinate in a -1:1 unit volume\n \"\"\"\n return tuple(to_basecoord(p, s) for p, s in zip(point, shape))\n\n\ndef scale_radius_to_basecoord(radius: int, shape: tuple):\n \"\"\"\n Scale a radius from pixel space to base space [-1, 1]\n\n We divide by the minimum of the XY dimension. Since we may want to have a single z\n face, we scale by the minimum of the XY coordinates, which are also likely to be\n the same shape.\n\n Inputs:\n radius -- integer radius\n shape -- the size of the dimension we are scaling from\n\n Returns:\n radius scaled to base coordinate space, between [-1, 1],\n scaled by the minimum of the XY shape\n\n Raises an AssertionError if radius is a negative value\n \"\"\"\n assert radius > 0, \"Radius must be a positive integer, given {}\".format(radius)\n return (radius * 2) / min(shape[:2])\n\n\ndef to_pixelcoord(base: float, shape: int):\n \"\"\"\n Scale the coordinate from base coordinate (in -1:1 unit volume) to pixel coordinate (0:shape)\n \"\"\"\n assert -1.0 <= base <= 1.0, \"point base dimension coordinate is not within [-1, 1]\"\n return int(np.round((base + 1) * (shape - 1) / 2))\n\n\ndef scale_point_to_pixelcoord(point: (float, float, float), shape: (int, int, int)):\n \"\"\"\n Scale a 3-tuple point to its coordinate in pixel space defined by `shape`\n \"\"\"\n return tuple(to_pixelcoord(p, s) for p, s in zip(point, shape))\n\n\ndef scale_radius_to_pixelcoord(radius: float, shape: tuple):\n \"\"\"\n Scale the cylinder radius from base space [-1, 1] to pixel space\n We scale by the minimum of the XY dimension, as in `scale_radius_to_basecoord`\n \"\"\"\n assert radius > 0.0, \"Radius must be positive, given {}\".format(radius)\n return int(np.round((radius * min(shape[:2])) / 2))\n\n\ndef create_coordinate_block(shape: (int, int, int)):\n \"\"\"\n Create three blocks where the indices key to the\n normalized (-1 to 1) coordinate in three space.\n\n This can be used to construct more complex objects\n in three dimensions.\n\n Keyword Arguments:\n shape {tuple} -- Shape of the coordinate grid\n \"\"\"\n return np.mgrid[-1.0:1.0:1.0j * shape[0],\n -1.0:1.0:1.0j * shape[1],\n -1.0:1.0:1.0j * shape[2]]\n\n\ndef trace_function(xyzr_callable,\n shape: (int, int, int)=(256, 256, 256),\n isotropy: tuple=(1, 1, 1),\n step_count: int=100):\n '''\n This is a tool to turn a parameterized function into a\n 3d raster feature. It outputs an array with shape specified\n where points \"inside\" the feature are masked to 255. All other\n values will be 0.\n\n xyzr_callable is a function which must take a single floating\n point argument, and produce a tuple with 4 floating point elements\n the elements are representative of a ball (x, y, z, r) which will\n be considered as 'within' the raster.\n\n xyzr_callable will be called \"step_count\" times with values ranging\n from 0 to 1. This allows the user to select their perferred parametric\n mapping for output.\n\n This way complex rasters can be constructed from simple parametric\n functions. This is used as a workhorse in several simple phantoms\n generated below.\n\n Input parameters:\n xyzr_callable: a method object that takes in a value t between [0, 1],\n and returns (x, y, z, r)\n\n shape: a 3-tuple defining the shape of the returned raster (voxel) volume\n\n isotropy: a 3-tuple that indicates the scaling per dimension\n Since the parameterization is created in a normalized space [-1, 1],\n any non-cubic volumes will need to be scaled appropriately to have\n the correct sphere radius in that direction. That is, if isotropy\n isn't adjusted correctly for a non-cubic volume, a sphere would become\n a squashed ellipsoid.\n\n To appropriately scale isotropy, the target axis isotropy value\n should be scaled by the size of the target axis shape and\n the unary axis shape\n shape = (64, 64, 128)\n isotropy = (1, 1, 0.5) == (1, 1, shape[0] / shape[2]))\n\n step_count: how many steps to iterate across the parameterization\n\n Returns:\n ndarray, dtype uint8, of input shape. Values are 0 and 255.\n\n '''\n output = np.zeros(shape, dtype=np.uint8)\n xi, yi, zi = create_coordinate_block(shape)\n\n # Accrue the steps first, and unique them\n for t in np.linspace(0.0, 1.0, step_count):\n xc, yc, zc, r = xyzr_callable(t)\n mask = np.sqrt((xc - xi) ** 2 / isotropy[0] ** 2 +\n (yc - yi) ** 2 / isotropy[1] ** 2 +\n (zc - zi) ** 2 / isotropy[2] ** 2) < r\n\n nd_spacing = 1.0 / min(shape)\n if r < nd_spacing:\n warnings.warn(\"Radius of phantom is approaching grid rez. {} v. {}\".format(r, nd_spacing))\n output[mask] = 255\n\n return output\n\n\ndef cylinder_in_x(r, shape: (int, int, int)=(256, 256, 256), step_count=512):\n def cylinder(t):\n return -1 + (t * 2), 0, 0, r\n\n return trace_function(cylinder, shape=shape, step_count=step_count)\n\n\ndef cylinder_in_xy(r, shape: (int, int, int)=(256, 256, 256), step_count=512):\n def cylinder(t):\n return -1 + (t * 2), -1 + (t * 2), 0, r\n\n return trace_function(cylinder, shape=shape, step_count=step_count)\n\n\ndef cylinder_in_xyz(r, shape: (int, int, int)=(256, 256, 256), step_count=512):\n def cylinder(t):\n return -1 + (t * 2), -1 + (t * 2), -1 + (t * 2), r\n\n return trace_function(cylinder, shape=shape, step_count=step_count)\n\n\ndef torus_xy(r1, r2, shape: (int, int, int)=(256, 256, 256), step_count=101):\n \"\"\"\n Create a raster of a torus with radii r1, r2.\n - r1 is the small radius (donut cross section)\n - r2 is the large radius.\n\n (r2 - r1) is the center hole size\n \"\"\"\n # NOTE(meawoppl) - This is technically valid,\n # but unlikey to be what is intended.\n assert r2 > r1, \"Degenerate torus\"\n\n # NOTE(meawoppl) even step count might fail to\n # come out with full D4 symmetry\n def torus(t):\n theta = 2 * np.pi * t\n return r2 * np.cos(theta), r2 * np.sin(theta), 0, r1\n\n return trace_function(torus, shape=shape, step_count=step_count)\n\n\ndef contiguous_elements(arr: np.array):\n \"\"\"\n Finds contiguous True regions of the boolean array \"arr\".\n\n :param array: 1D boolean ndarray\n :returns array: 2d with first column as the (inclusive) start index of the matching\n regions, and second column is the (exclusive) end index.\n\n :Example:\n\n >>> kmath.contiguous_elements(np.array([0, 1, 1, 1, 2]) == 1)\n ... array([[1, 4]])\n\n \"\"\"\n d = np.diff(arr) # Find the indices of changes in \"array\"\n idx, = d.nonzero()\n # the start index is the next element after the change, so shift by 1\n idx += 1\n\n # deal with edges of diff\n if arr[0]: # If the start of arr is True prepend a 0\n idx = np.r_[0, idx]\n if arr[-1]: # If the end of arr is True, append the length\n idx = np.r_[idx, arr.size]\n\n idx.shape = (-1, 2) # Reshape the result into two columns\n return idx\n\n\ndef nonzero_bounds(arr: np.array):\n \"\"\"\n Return a tuple of the indices (inclusive, exclusive) that bracket nonzero values of `arr`.\n\n Useful for identifying the max and min bins of a histogram,\n or rising and falling edges of an object\n\n :param arr: 1D ndarray\n :returns tuple: first and last index of non-zero values.\n The last index is one greater than the last nonzero value (exclusive)\n\n :raises ValueError: if no nonzero elements found\n :raises AssertionError: if not a 1D array\n \"\"\"\n np.testing.assert_array_equal(arr.ndim, 1)\n nonzeros = np.nonzero(arr)[0]\n if nonzeros.size == 0:\n raise ValueError(\"No nonzero elements found in array\")\n return min(nonzeros), max(nonzeros) + 1\n\n\ndef normalized(arr: np.array, axis: int=-1, order: int=2):\n \"\"\"\n Normalize vector using 2-norm, across arbitrary axes,\n\n Deals with length 0 vectors well; avoids dividing by zero\n\n :param arr: ndarray, will be normalized along given `axis`\n :param axis: axis to normalize against (default=-1), same guidelines as np.linalg.norm\n :param order: the order of the normalization factor, default L2 (default=2)\n follows same guidelines as np.linalg.norm\n\n :returns: ndarray of same dimensions as `arr`\n \"\"\"\n norm_length = np.atleast_1d(np.linalg.norm(arr, order, axis))\n # set any zero elements to be 1, avoiding divide by zero errors\n norm_length[norm_length == 0] = 1\n if arr.ndim == 1:\n # single dimensions are speyshul\n return arr / norm_length\n return arr / np.expand_dims(norm_length, axis) # use array broadcasting\n\n\ndef cylinder(shape,\n p1: (numbers.Number, numbers.Number, numbers.Number),\n p2: (numbers.Number, numbers.Number, numbers.Number),\n r: numbers.Number,\n cap=\"flat\",\n dtype=np.uint8):\n \"\"\"\n Create a boolean right circular cylinder between two points, p1 and p2, with radius r\n\n Inputs:\n shape: shape of the volume to allocate\n p1: 3-tuple with coordinates of endpoint of cylinder, in base coordinates [-1, 1]\n p2: 3-tuple with coordinates of endpoint of cylinder, in base coordinates [-1, 1]\n r: uniform radius of the cylinder, in base coordinates\n Anything larger than 2 will be outside of the shape of the volume\n cap: str, or None.\n Use one of the types available in base.CAP_TYPES (Default=\"flat\")\n \"flat\" -- cuts the cylinder at each cylinder point (p1 & p2), leaving\n a circular plane cut normal to the line\n between (p2 - p1), at points p1 and p2. The resulting plane\n should have radius `r`.\n \"sphere\" -- adds a spherical end at each of the points given.\n The sphere will have the same radius as the cylinder at that point.\n \"none\" -- Leaves a cylinder along the given line between the two points, but\n does not terminate at the point; it is fully expanded to fill\n the line across the full volume\n\n foreground: the value to use in voxels inside the cylinder, default=1\n dtype: data type of the returned array, default=np.uint8\n\n Returns:\n ndarray, boolean, shape=`shape`\n\n Displays warnings.warn if radius is close to grid resolution\n Displays warnings.warn if radius is larger than the volume grid (>2)\n Raises AssertionError if cap is not in base.CAP_TYPES\n \"\"\"\n assert cap in CAP_TYPES\n nd_spacing = 1.0 / min(shape)\n if r < nd_spacing:\n warnings.warn(\n \"Radius of phantom is approaching grid rez. {} v. {}\".format(r, nd_spacing))\n if r >= 2:\n warnings.warn(\n \"Radius of cylinder is larger than the base volume: {} >= 2\".format(r))\n # allocate the output array\n output = np.zeros(shape, dtype=bool)\n\n # get the volume's coordinates in R^3 [-1, 1] inclusive\n xi, yi, zi = create_coordinate_block(shape)\n x1, y1, z1 = p1\n x2, y2, z2 = p2\n # wrap input tuples as arrays\n p1 = np.array(p1)\n p2 = np.array(p2)\n\n # first create the infinite cylinder\n cyl_length = np.linalg.norm(p2 - p1) # length of cylinder\n\n # This is essentially the cross product of the difference between a given point\n # p and the two points that define our line, squared and normalized\n # distances_vec ?= np.cross((points - p1), (points - p2)) ** 2 / (cyl_length ** 2)\n # This gives us the distance from all points to our cylinder center line\n # We aren't using the full vectorized form yet because we may need to have\n # a space to put in the isotropy vector for each component, and I wanted\n # to confirm this method works first.\n # We will somehow need to add isotropy to this equation\n distances = (((yi - y1) * (zi - z2) - (zi - z1) * (yi - y2)) ** 2 +\n ((zi - z1) * (xi - x2) - (xi - x1) * (zi - z2)) ** 2 +\n ((xi - x1) * (yi - y2) - (yi - y1) * (xi - x2)) ** 2) / (cyl_length ** 2)\n output[distances <= r ** 2] = 1\n # we have an infinite cylinder in our volume now\n\n # create set of vectorized points\n points = np.vstack((xi, yi, zi)).reshape(3, -1).T\n # Set the plane equation as the normalized vector, defined by the line between p2 and p1,\n # with p1 as the reference point\n normal = normalized(p2 - p1)\n\n # Find the correct sign by seeing which side the other point is on\n # sign will be zero if the two points are the same\n # We use p1 as reference, since thats what we did with the `normal` above\n sign = np.sign((p2 - p1).dot(normal))\n\n if cap != \"none\":\n # always trim the infinite cylinder here\n # any use of points could be masked to only the vectors that are already on\n # this would make the math a lot faster.\n # would need to figure out how to reallocate back into output array\n\n # first point\n plane_distance = distance_point_from_plane(points, normal, p1, -sign).reshape(shape)\n output[plane_distance > 0] = 0\n # second point\n plane_distance = distance_point_from_plane(points, normal, p2, sign).reshape(shape)\n output[plane_distance > 0] = 0\n\n if cap == \"sphere\":\n # requires that we have already cropped to \"flat\"\n # add a sphere on the cap after we chop the infinite cylinder\n sphere_distance = distance_point_from_point(points, p1).reshape(shape)\n output[sphere_distance < r] = 1\n sphere_distance = distance_point_from_point(points, p2).reshape(shape)\n output[sphere_distance < r] = 1\n\n return output\n\n\ndef distance_point_from_plane(points: np.array,\n plane_normal: np.array,\n ref_point: np.array,\n sign=1):\n \"\"\"\n Returns distance of all input points from a given plane\n\n Inputs:\n points: NxM ndarray, with N points of dimension M\n eg: a (200, 3) array of 200 3D point coordinates\n plane_normal: A length M 1D ndarray that defines the normal of a plane\n (a, b, c) would define the plane at ax + by + cz = 0\n ref_point: A length M ndarray, the point we use to offset the plane from the origin\n sign: integer, decides the negative or positive value of the returned distance\n One way to get the target sign is to Find a point that is on the side\n of the plane that you want, and use the sign of that point to decide\n the correct distance sign for the volume you want to mask.\n Default=1, or\n A positive `sign` will give positive distances on the associated target side\n You can get the correct target sign via:\n >>> target_sign = np.sign((selection_point - ref_point).dot(plane_normal))\n\n Returns:\n Nx1 ndarray of the distance from the input vectors to the plane\n\n Raises AssertionError if sign is anything other than -1 or 1\n\n TODO: sanity check that these are actual vector distances\n This doesnt matter when we are just using the sign, but it does if we actually want distance\n \"\"\"\n assert sign == 1 or sign == -1, \\\n \"'sign' must be positive or negative 1, got {}\".format(sign)\n return sign * (points - ref_point).dot(plane_normal)\n\n\ndef distance_point_from_point(points: np.array,\n ref_point: np.array):\n \"\"\"\n Distance of all input points from a given point\n Can be used to create a spherical mask around a point\n\n Inputs:\n points: NxM ndarray, with N points of dimension M\n eg: a (200, 3) array of 200 3D point coordinates\n ref_point: A length M ndarray, the relative origin\n\n Returns:\n Nx1 ndarray of the distance from the input vectors to the point\n \"\"\"\n return np.linalg.norm(points - ref_point, axis=-1)\n","sub_path":"skeletonization/skeleton/phantom_base.py","file_name":"phantom_base.py","file_ext":"py","file_size_in_byte":18238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"549732299","text":"from pydantic import BaseModel\n\n\nclass DefaultDarwin(BaseModel):\n \"\"\"Default Darwin-Py pydantic settings for meta information.\n Default settings include:\n - auto validating variables on setting/assignment\n - underscore attributes are private\n - objects are passed by reference to prevent unnecesary data copying\n \"\"\"\n\n class Config:\n validate_assignment = True\n underscore_attrs_are_private = True\n copy_on_model_validation = \"none\"\n","sub_path":"darwin/future/pydantic_base.py","file_name":"pydantic_base.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"473233122","text":"import numpy as np\n# ============================================================\n# Defining my own functions here\n# ============================================================\n\ndef dist_conv(amt,inp_unit,out_unit):\n meter=1.0\n feet=3.28084\n inches=39.3701\n miles=0.000621371\n if inp_unit==\"feet\":\n amt=amt/feet\n if inp_unit==\"inches\":\n amt=amt/inches\n if inp_unit==\"miles\":\n amt=amt/miles\n if out_unit==\"feet\":\n amt=amt*feet\n if out_unit==\"inches\":\n amt=amt*inches\n if out_unit==\"miles\":\n amt=amt*miles\n return amt\n\n\ndef weight_conv(amt,inp_unit,out_unit):\n kilogram=1.0\n ounces=35.274\n pounds=2.20462\n if inp_unit==\"ounces\":\n amt=amt/ounces\n if inp_unit==\"pounds\":\n amt=amt/pounds\n if out_unit==\"ounces\":\n amt=amt*ounces\n if out_unit==\"pounds\":\n amt=amt*pounds\n return amt\n\ndef temp_conv(amt,inp_unit,out_unit):\n fahrenheit=(9/5)*amt+32\n celcius=(amt-32)/1.8\n if out_unit==\"fahrenheit\":\n return fahrenheit\n if out_unit==\"celcius\":\n return celcius\n\ndef find_units(request):\n unit1=\"\"\n unit2=\"\"\n unit_type=\"\"\n flag=0\n signal=0\n hold=9223372036854775807\n hold2=0\n distance=[[\"eter\",\" m \"],[\"eet\",\"ft\",\"oot\"],[\"nch\",\"in\"],[\"mi\",\"ile\"]]\n dist=[\"meters\",\"feet\",\"inches\",\"miles\"]\n weight=[[\"ilogram\",\"Kg\",\"kg\"],[\"unce\",\"oz\"],[\"lb\",\"pound\"]]\n wght=[\"kilograms\",\"ounces\",\"pounds\"]\n temperature=[[\"elcius\",\" C \"],[\"ahrenheit\",\" F \"]]\n temp=[\"celcius\",\"fahrenheit\"]\n unit_type=\"\"\n for b in range(len(distance)):\n u=distance[b]\n\n for x in u:\n if -1hold2:\n hold2=request.find(y)\n unit_type=\"distance\"\n unit2=dist[b]\n\n for b in range(len(weight)):\n u=weight[b]\n\n for x in u:\n for x in u:\n if -1hold2:\n hold2=request.find(y)\n unit_type=\"weight\"\n unit2=wght[b]\n\n for b in range(len(temperature)):\n u=temperature[b]\n\n for x in u:\n for x in u:\n if -1hold2:\n hold2=request.find(y)\n unit_type=\"temperature\"\n unit2=temp[b]\n\n return [unit1,unit2,unit_type]\n\ndef myParser(txt):\n\n units=find_units(txt)\n input_u=units[0]\n output_u=units[1]\n un_type=units[2]\n myflag=0\n num1=0\n num2=0\n for i in range(len(txt)):\n if txt[i].isdigit() and myflag==0:\n num1=i\n myflag=1\n if txt[i].isdigit() and myflag==1:\n num2=i\n final_num=float(txt[num1:num2+1])\n des_out=0\n if un_type == \"distance\":\n des_out=dist_conv(final_num,input_u,output_u)\n if un_type == \"weight\":\n des_out=weight_conv(final_num,input_u,output_u)\n if un_type == \"temperature\":\n des_out=temp_conv(final_num,input_u,output_u)\n if (input_u is output_u):\n return \"ERROR: You have entered incorrect units\"\n else:\n return (str(round(des_out,1))+\" \"+output_u)\n","sub_path":"UnitConverter.py","file_name":"UnitConverter.py","file_ext":"py","file_size_in_byte":3548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"379674674","text":"# Copyright 2019 Atalaya Tech, 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\nimport click\n\nfrom bentoml.utils.lazy_loader import LazyLoader\nfrom bentoml.cli.utils import Spinner\nfrom bentoml.utils import get_default_yatai_client\nfrom bentoml.cli.click_utils import (\n BentoMLCommandGroup,\n parse_bento_tag_callback,\n _echo,\n CLI_COLOR_SUCCESS,\n parse_labels_callback,\n)\nfrom bentoml.cli.deployment import (\n _print_deployment_info,\n _print_deployments_info,\n)\nfrom bentoml.yatai.deployment import ALL_NAMESPACE_TAG\nfrom bentoml.exceptions import CLIException\nfrom bentoml.utils import status_pb_to_error_code_and_message\n\nyatai_proto = LazyLoader('yatai_proto', globals(), 'bentoml.yatai.proto')\n\n\nDEFAULT_SAGEMAKER_INSTANCE_TYPE = 'ml.m4.xlarge'\nDEFAULT_SAGEMAKER_INSTANCE_COUNT = 1\n\n\ndef get_aws_sagemaker_sub_command():\n # pylint: disable=unused-variable\n\n @click.group(\n name='sagemaker',\n help='Commands for AWS Sagemaker BentoService deployments',\n cls=BentoMLCommandGroup,\n )\n def aws_sagemaker():\n pass\n\n @aws_sagemaker.command(help='Deploy BentoService to AWS Sagemaker')\n @click.argument('name', type=click.STRING)\n @click.option(\n '-b',\n '--bento',\n '--bento-service-bundle',\n type=click.STRING,\n required=True,\n callback=parse_bento_tag_callback,\n help='Target BentoService to be deployed, referenced by its name and version '\n 'in format of name:version. For example: \"iris_classifier:v1.2.0\"',\n )\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration yatai_service/default_namespace',\n )\n @click.option(\n '-l',\n '--labels',\n type=click.STRING,\n callback=parse_labels_callback,\n help='Key:value pairs that are attached to deployments and intended to be used '\n 'to specify identifying attributes of the deployments that are meaningful to '\n 'users. Multiple labels are separated with `,`',\n )\n @click.option('--region', help='AWS region name for deployment')\n @click.option(\n '--api-name',\n help='User defined API function will be used for inference.',\n required=True,\n )\n @click.option(\n '--instance-type',\n help='Type of instance will be used for inference. Default to \"m1.m4.xlarge\"',\n type=click.STRING,\n default=DEFAULT_SAGEMAKER_INSTANCE_TYPE,\n )\n @click.option(\n '--instance-count',\n help='Number of instance will be used. Default value is 1',\n type=click.INT,\n default=DEFAULT_SAGEMAKER_INSTANCE_COUNT,\n )\n @click.option(\n '--num-of-gunicorn-workers-per-instance',\n help='Number of gunicorn worker will be used per instance. Default value for '\n 'gunicorn worker is based on the instance\\' cpu core counts. '\n 'The formula is num_of_cpu/2 + 1',\n type=click.INT,\n )\n @click.option(\n '--timeout',\n help=\"The amount of time Sagemaker will wait before return response\",\n type=click.INT,\n default=60,\n )\n @click.option('-o', '--output', type=click.Choice(['json', 'yaml']), default='json')\n @click.option(\n '--wait/--no-wait',\n default=True,\n help='Wait for apply action to complete or encounter an error.'\n 'If set to no-wait, CLI will return immediately. The default value is wait',\n )\n @click.option(\n '--data-capture-s3-prefix',\n help=\"To enable data capture (input and output), \"\n \"provide a destination s3 prefix \"\n \"(of the format `s3://bucket-name/optional/prefix`)\"\n \" for the captured data. To disable data capture, leave this blank.\",\n type=click.STRING,\n default=None,\n )\n @click.option(\n '--data-capture-sample-percent',\n help=\"When data capture is enabled, the sampling percentage. Default 100%. \"\n \"No effect without data-capture-s3-prefix.\",\n type=click.IntRange(1, 100),\n default=100,\n )\n def deploy(\n name,\n bento,\n namespace,\n labels,\n region,\n instance_type,\n instance_count,\n num_of_gunicorn_workers_per_instance,\n api_name,\n timeout,\n output,\n wait,\n data_capture_s3_prefix,\n data_capture_sample_percent,\n ):\n # use the DeploymentOperator name in proto to be consistent with amplitude\n bento_name, bento_version = bento.split(':')\n yatai_client = get_default_yatai_client()\n with Spinner('Deploying Sagemaker deployment '):\n result = yatai_client.deployment.create_sagemaker_deployment(\n name=name,\n namespace=namespace,\n labels=labels,\n bento_name=bento_name,\n bento_version=bento_version,\n instance_count=instance_count,\n instance_type=instance_type,\n num_of_gunicorn_workers_per_instance=num_of_gunicorn_workers_per_instance, # noqa E501\n api_name=api_name,\n timeout=timeout,\n region=region,\n wait=wait,\n data_capture_s3_prefix=data_capture_s3_prefix,\n data_capture_sample_percent=data_capture_sample_percent,\n )\n if result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n _echo(\n f'Successfully created AWS Sagemaker deployment {name}', CLI_COLOR_SUCCESS,\n )\n _print_deployment_info(result.deployment, output)\n\n @aws_sagemaker.command(help='Update existing AWS Sagemaker deployment')\n @click.argument('name', type=click.STRING)\n @click.option(\n '-b',\n '--bento',\n '--bento-service-bundle',\n type=click.STRING,\n callback=parse_bento_tag_callback,\n help='Target BentoService to be deployed, referenced by its name and version '\n 'in format of name:version. For example: \"iris_classifier:v1.2.0\"',\n )\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration file',\n )\n @click.option(\n '--instance-type',\n help='Type of instance will be used for inference. Default to \"m1.m4.xlarge\"',\n type=click.STRING,\n )\n @click.option(\n '--instance-count',\n help='Number of instance will be used. Default value is 1',\n type=click.INT,\n )\n @click.option(\n '--num-of-gunicorn-workers-per-instance',\n help='Number of gunicorn worker will be used per instance. Default value for '\n 'gunicorn worker is based on the instance\\' cpu core counts. '\n 'The formula is num_of_cpu/2 + 1',\n type=click.INT,\n )\n @click.option(\n '--api-name', help='User defined API function will be used for inference.',\n )\n @click.option(\n '--timeout',\n help=\"The amount of time Sagemaker will wait before return response\",\n type=click.INT,\n default=60,\n )\n @click.option('-o', '--output', type=click.Choice(['json', 'yaml']), default='json')\n @click.option(\n '--wait/--no-wait',\n default=True,\n help='Wait for apply action to complete or encounter an error.'\n 'If set to no-wait, CLI will return immediately. The default value is wait',\n )\n @click.option(\n '--data-capture-s3-prefix',\n help=\"To enable data capture (input and output), \"\n \"provide a destination s3 prefix \"\n \"(of the format `s3://bucket-name/optional/prefix`)\"\n \" for the captured data. To disable data capture, leave this blank.\",\n type=click.STRING,\n default=None,\n )\n @click.option(\n '--data-capture-sample-percent',\n help=\"When data capture is enabled, the sampling percentage. Default 100%. \"\n \"No effect without data-capture-s3-prefix.\",\n type=click.IntRange(1, 100),\n default=100,\n )\n def update(\n name,\n namespace,\n bento,\n api_name,\n instance_type,\n instance_count,\n num_of_gunicorn_workers_per_instance,\n timeout,\n output,\n wait,\n data_capture_s3_prefix,\n data_capture_sample_percent,\n ):\n yatai_client = get_default_yatai_client()\n if bento:\n bento_name, bento_version = bento.split(':')\n else:\n bento_name = None\n bento_version = None\n with Spinner('Updating Sagemaker deployment '):\n result = yatai_client.deployment.update_sagemaker_deployment(\n namespace=namespace,\n deployment_name=name,\n bento_name=bento_name,\n bento_version=bento_version,\n instance_count=instance_count,\n instance_type=instance_type,\n num_of_gunicorn_workers_per_instance=num_of_gunicorn_workers_per_instance, # noqa E501\n timeout=timeout,\n api_name=api_name,\n wait=wait,\n data_capture_s3_prefix=data_capture_s3_prefix,\n data_capture_sample_percent=data_capture_sample_percent,\n )\n if result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n _echo(\n f'Successfully updated AWS Sagemaker deployment {name}', CLI_COLOR_SUCCESS,\n )\n _print_deployment_info(result.deployment, output)\n\n @aws_sagemaker.command(help='Delete AWS Sagemaker deployment')\n @click.argument('name', type=click.STRING)\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration yatai_service/default_namespace',\n )\n @click.option(\n '--force',\n is_flag=True,\n help='force delete the deployment record in database and '\n 'ignore errors when deleting cloud resources',\n )\n def delete(name, namespace, force):\n yatai_client = get_default_yatai_client()\n get_deployment_result = yatai_client.deployment.get(namespace, name)\n if get_deployment_result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n get_deployment_result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n result = yatai_client.deployment.delete(name, namespace, force)\n if result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n _echo(\n f'Successfully deleted AWS Sagemaker deployment \"{name}\"',\n CLI_COLOR_SUCCESS,\n )\n\n @aws_sagemaker.command(help='Get AWS Sagemaker deployment information')\n @click.argument('name', type=click.STRING)\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration yatai_service/default_namespace',\n )\n @click.option(\n '-o', '--output', type=click.Choice(['json', 'yaml', 'table']), default='json'\n )\n def get(name, namespace, output):\n yatai_client = get_default_yatai_client()\n get_result = yatai_client.deployment.get(namespace, name)\n if get_result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n get_result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n describe_result = yatai_client.deployment.describe(namespace, name)\n if describe_result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n describe_result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n get_result.deployment.state.CopyFrom(describe_result.state)\n _print_deployment_info(get_result.deployment, output)\n\n @aws_sagemaker.command(\n name='list', help='List AWS Sagemaker deployment information'\n )\n @click.option(\n '-n',\n '--namespace',\n type=click.STRING,\n help='Deployment namespace managed by BentoML, default value is \"dev\" which '\n 'can be changed in BentoML configuration yatai_service/default_namespace',\n default=ALL_NAMESPACE_TAG,\n )\n @click.option(\n '--limit',\n type=click.INT,\n help='The maximum amount of AWS Sagemaker deployments to be listed at once',\n )\n @click.option(\n '-l',\n '--labels',\n type=click.STRING,\n help=\"Label query to filter Sagemaker deployments, supports '=', '!=', 'IN', \"\n \"'NotIn', 'Exists', and 'DoesNotExist'. (e.g. key1=value1, \"\n \"key2!=value2, key3 In (value3, value3a), key4 DoesNotExist)\",\n )\n @click.option(\n '--order-by', type=click.Choice(['created_at', 'name']), default='created_at',\n )\n @click.option(\n '--asc/--desc',\n default=False,\n help='Ascending or descending order for list deployments',\n )\n @click.option(\n '-o',\n '--output',\n type=click.Choice(['json', 'yaml', 'table', 'wide']),\n default='table',\n )\n def list_deployment(namespace, limit, labels, order_by, asc, output):\n yatai_client = get_default_yatai_client()\n list_result = yatai_client.deployment.list_sagemaker_deployments(\n limit=limit,\n labels=labels,\n namespace=namespace,\n order_by=order_by,\n ascending_order=asc,\n )\n if list_result.status.status_code != yatai_proto.status_pb2.Status.OK:\n error_code, error_message = status_pb_to_error_code_and_message(\n list_result.status\n )\n raise CLIException(f'{error_code}:{error_message}')\n _print_deployments_info(list_result.deployments, output)\n\n return aws_sagemaker\n","sub_path":"bentoml/cli/aws_sagemaker.py","file_name":"aws_sagemaker.py","file_ext":"py","file_size_in_byte":15420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"312712268","text":"from urllib import request\n\n\nAPI_ENDPOINT = 'http://www.nbp.pl/kursy/xml/'\nTABLE_LIST_ENDPOINT = API_ENDPOINT + 'dir.txt'\nDATE_FORMAT = '%y%m%d'\nTABLE_NAME_PREFIX = 'a'\n\n\ndef get_tables():\n stream = request.urlopen(TABLE_LIST_ENDPOINT)\n bytes = stream.read()\n text = bytes.decode('utf-8-sig')\n tables = text.splitlines()\n return tables\n\n\ndef get_table_name(date):\n tables = get_tables()\n for table_name in tables:\n if is_right_table(table_name, date):\n return table_name\n return None\n\n\ndef is_right_table(table_name, date):\n right_prefix = table_name.startswith(TABLE_NAME_PREFIX)\n date_as_str = date.strftime(DATE_FORMAT)\n right_date = table_name.endswith(date_as_str)\n return right_prefix and right_date\n","sub_path":"nbpapi-mocking/nbpapi.py","file_name":"nbpapi.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"626914777","text":"import asyncio\nimport aiohttp\nfrom .db import RedisClient\nimport time\nimport sys\nfrom .settings import *\nfrom .logger_proxy import mylogger\nlogger=mylogger.get_logger('test')\ntry:\n from aiohttp import ClientError\nexcept:\n from aiohttp import ClientProxyConnectionError as ProxyConnectionError\n\nclass tester(object):\n def __init__(self):\n self.redis=RedisClient()\n async def test_single_proxy(self,proxy):\n conn = aiohttp.TCPConnector(verify_ssl=False) #下一句with as session:前后文管理器,with结束,session会话结束\n async with aiohttp.ClientSession(connector=conn) as session:#aiohttp则是基于asyncio实现的HTTP框架;这里要引入一个类,aiohttp.ClientSession.\n # 首先要建立一个session对象,然后用该session对象去打开网页\n try:\n if isinstance(proxy,bytes):\n proxy=proxy.decode('utf-8')#将bytes对象解码成字符串,默认使用utf-8进行解码。防止数据库提取的proxy是bytes格式。\n real_proxy = 'http://' + proxy\n logger.info('正在测试代理')\n async with session.get(Test_url,proxy=real_proxy,timeout=15,allow_redirects=False) as response:\n if response.status in VALID_STATUS_CODES:\n self.redis.max(proxy)# 将可用代理分值设为100\n logger.info('proxy is enable %s' %proxy)\n else:\n self.redis.decrease(proxy)\n logger.info('请求响应码不合适 %s %s'%(response.status,proxy))\n except (ConnectionError,ClientError,TimeoutError,ArithmeticError):\n self.redis.decrease(proxy)\n logger.info('代理请求失败 %s'%proxy)\n def run(self):\n \"\"\"\n 测试主函数\n :return:\n \"\"\"\n logger.info('测试器开始运行')\n try:\n count=self.redis.count()\n logger.info('当前剩余 %d 个代理'%count)\n for i in range(0,count,Batch_test_size):#所有代理,按照批次检测的个数,分段\n start = i\n stop=min(i+Batch_test_size,count)\n logger.info('正在检测第 %s 到%s之间的代理'%(start + 1,stop))\n test_proxies = self.redis.batch(start=start,stop=stop)\n loop = asyncio.get_event_loop()#asyncio实现并发,就需要多个协程组成列表来完成任务【创建多个协程的列表,然后将这些协程注册到事件循环中】,\n # 每当有任务阻塞的时候就await,然后其他协程继续工作,所以下面是协程列表;\n # 所谓的并发:多个任务需要同时进行;\n tasks=[self.test_single_proxy(proxy) for proxy in test_proxies]\n loop.run_until_complete(asyncio.wait(tasks))#asyncio.wait(tasks)接受一个列表\n sys.stdout.flush()\n time.sleep(5)\n except Exception as e:\n logger.exception('测试发生错误 %s'%e)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"proxy_pool_new/proxy_pool_new/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":3287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"247660952","text":"# 종이의 개수\n\n# def solve(y, x):\n# global paper, visited, N\n# number = paper[y][x]\n# checkList = ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1))\n# for check in checkList:\n# if 0 <= check[0] < N and 0 <= check[1] < N:\n# if number == paper[check[0]][check[1]] and not visited[check[0]][check[1]]:\n# visited[check[0]][check[1]] = True\n# solve(check[0], check[1])\n\n# for x in range(N):\n# for y in range(N):\n# if not visited[y][x]:\n# solve(y, x)\n# countList[paper[y][x] + 1] += 1\n\nimport sys\n\npaper = []\nN = int(sys.stdin.readline())\nfor _ in range(N):\n paper.append(list(map(int, sys.stdin.readline().split())))\n\ncountList = [0, 0, 0]\n\n\ndef nine_range(part_paper):\n n = len(part_paper[0])\n three = n // 3\n three_list = [range(three), range(three, n - three), range(n - three, n)]\n nine_paper = []\n for x in three_list:\n for y in three_list:\n nine_paper.append([[part_paper[i][j] for i in y] for j in x])\n return nine_paper\n\n\ndef solve(part_paper):\n flat_paper = [item for sub in part_paper for item in sub]\n if len(set(flat_paper)) <= 1:\n countList[flat_paper[0] + 1] += 1\n else:\n for part_part_paper in nine_range(part_paper):\n solve(part_part_paper)\n\n\nsolve(paper)\nfor count in countList:\n print(count)\n","sub_path":"SsangWoo/python/baekjoon/1780.py","file_name":"1780.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"14696431","text":"\"\"\"Convert zim wiki syntax to markdown\n\nStripped and modified from markdown2.py\n\nSyntax converted:\n\n type Markdown <- Zim\n ----------------------------------------------------\n Heading1 # heading ===== heading =====\n Heading2 ## heading ==== heading ====\n Heading3 ### heading === heading ===\n Heading4 #### heading == heading ==\n Heading5 ##### heading = heading =\n Heading6 ###### heading = heading =\n ----------------------------------------------------\n unordered list -/+/* *\n ordered list 1. 2. 3. 1. 2. 3.\n ----------------------------------------------------\n bold **bold** **bold**\n __bold__ __bold__\n italic *italic* //italic//\n _italic_ //italic//\n strike ~~strike~~ ~~strike~~\n ----------------------------------------------------\n quote > '''\n texts... texts...\n '''\n code ``` ```\n texts... texts...\n ``` ```\n ----------------------------------------------------\n inline link [text](url) [[url|text]]\n ----------------------------------------------------\n ref link [text](url)\n [[url|text]]\n ----------------------------------------------------\n image  {{url}}\n ----------------------------------------------------\n\n\n\nSyntax not supported:\n - footnote\n - tables\n\n\nUpdate time: 2019-09-27 19:59:00.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\n\nfrom builtins import bytes\nfrom builtins import str\nfrom builtins import range\nfrom past.builtins import basestring\nfrom builtins import object\nimport re\nimport sys,os\nimport argparse\nfrom lib import tools\ntry:\n from hashlib import md5\nexcept ImportError:\n from md5 import md5\nfrom random import random, randint\n\n# Use `bytes` for byte strings and `unicode` for unicode strings (str in Py3).\nif sys.version_info[0] <= 2:\n py3 = False\n try:\n bytes\n except NameError:\n bytes = str\n base_string_type = basestring\nelif sys.version_info[0] >= 3:\n py3 = True\n base_string_type = str\n\n\n\n#---- globals\nDEBUG = False\n\nDEFAULT_TAB_WIDTH = 4\n\n\nSECRET_SALT = bytes(randint(0, 1000000))\ndef _hash_text(s):\n return 'md5-' + md5(SECRET_SALT + s.encode(\"utf-8\")).hexdigest()\n\n\n\ng_escape_table = dict([(ch, _hash_text(ch))\n for ch in '\\\\`*_{}[]()>#+-.!'])\n\n\n_home_re=re.compile('^(~)(.+)$')\n\ndef _home_re_sub(match):\n return os.path.expanduser(match.group(1))+match.group(2)\n\ndef findBaseDir(curdir):\n target_file='notebook.zim'\n\n if os.path.exists(os.path.join(curdir,target_file)):\n return curdir\n else:\n return findBaseDir(os.path.split(curdir)[0])\n\ndef parseLink(link_text, dec, file_path):\n\n if file_path is None:\n if dec in [':', '+', '']:\n return '%s%s' %(dec, link_text)\n else:\n return dec\n\n file_path=_home_re.sub(_home_re_sub,file_path)\n curdir, curfile=os.path.split(file_path)\n link_file='%s.txt' %link_text\n\n if dec=='':\n result=os.path.join(curdir,link_file)\n if os.path.exists(result):\n return result\n else:\n parentdir=os.path.split(curdir)[0]\n result=os.path.join(parentdir,link_file)\n if os.path.exists(result):\n return result\n else:\n return link_text\n\n elif dec==':':\n try:\n basedir=findBaseDir(curdir)\n except:\n return '%s%s' %(dec,link_text)\n\n result=os.path.join(basedir,link_file)\n if os.path.exists(result):\n return result\n else:\n return '%s%s' %(dec,link_text)\n\n elif dec=='+':\n subdir=os.path.join(curdir,os.path.splitext(curfile)[0])\n result=os.path.join(subdir,link_file)\n if os.path.isdir(subdir) and os.path.exists(result):\n return result\n else:\n return '%s%s' %(dec,link_text)\n\n else:\n return dec\n\n\n\nclass Zim2Markdown(object):\n urls = None\n titles = None\n\n # Used to track when we're inside an ordered or unordered list\n # (see _ProcessListItems() for details):\n list_level = 0\n\n _ws_only_line_re = re.compile(r\"^[ \\t]+$\", re.M)\n\n def __init__(self, html4tags=False, tab_width=4, file=None):\n\n self.tab_width = tab_width\n self.file=file\n self._outdent_re = re.compile(r'^(\\t|[ ]{1,%d})' % tab_width, re.M)\n self._escape_table = g_escape_table.copy()\n\n def reset(self):\n self.urls = {}\n self.titles = {}\n self.list_level = 0\n self.footnotes = {}\n self.footnote_ids = []\n\n\n def convert(self, text):\n \"\"\"Convert the given text.\"\"\"\n # Main function. The order in which other subs are called here is\n # essential. Link and image substitutions need to happen before\n # _EscapeSpecialChars(), so that any *'s or _'s in the \n # and tags get encoded.\n\n # Clear the global hashes. If we don't clear these, you get conflicts\n # from other articles when generating a page which contains more than\n # one article (e.g. an index page that shows the N most recent\n # articles):\n self.reset()\n\n # Standardize line endings:\n text = re.sub(\"\\r\\n|\\r\", \"\\n\", text)\n\n # Make sure $text ends with a couple of newlines:\n text += \"\\n\\n\"\n\n # Convert all tabs to spaces.\n #text = self._detab(text)\n\n # Strip any lines consisting only of spaces and tabs.\n # This makes subsequent regexen easier to write, because we can\n # match consecutive blank lines with /\\n+/ instead of something\n # contorted like /[ \\t]*\\n+/ .\n text = self._ws_only_line_re.sub(\"\", text)\n\n text = self._do_fenced_code_blocks(text)\n\n # Strip link definitions, store in hashes.\n # Must do footnotes first because an unlucky footnote defn\n # looks like a link defn:\n # [^4]: this \"looks like a link defn\"\n text = self._strip_footnote_definitions(text)\n\n text = self._strip_link_definitions(text)\n\n text = self._run_block_gamut(text)\n\n #text = self._add_footnotes(text)\n\n text += \"\\n\"\n\n return text\n\n\n\n _detab_re = re.compile(r'(.*?)\\t', re.M)\n def _detab_sub(self, match):\n g1 = match.group(1)\n return g1 + (' ' * (self.tab_width - len(g1) % self.tab_width))\n\n def _detab(self, text):\n r\"\"\"Remove (leading?) tabs from a file.\n\n >>> m = Markdown()\n >>> m._detab(\"\\tfoo\")\n ' foo'\n >>> m._detab(\" \\tfoo\")\n ' foo'\n >>> m._detab(\"\\t foo\")\n ' foo'\n >>> m._detab(\" foo\")\n ' foo'\n >>> m._detab(\" foo\\n\\tbar\\tblam\")\n ' foo\\n bar blam'\n \"\"\"\n if '\\t' not in text:\n return text\n return self._detab_re.subn(self._detab_sub, text)[0]\n\n\n\n def _strip_link_definitions(self, text):\n # Strips link definitions from text, stores the URLs and titles in\n # hash references.\n less_than_tab = self.tab_width - 1\n\n # Link defs are in the form:\n # [id]: url \"optional title\"\n _link_def_re = re.compile(r\"\"\"\n ^[ ]{0,%d}\\[(.+)\\]: # id = \\1\n [ \\t]*\n \\n? # maybe *one* newline\n [ \\t]*\n (.+?)>? # url = \\2\n [ \\t]*\n (?:\n \\n? # maybe one newline\n [ \\t]*\n (?<=\\s) # lookbehind for whitespace\n ['\"(]\n ([^\\n]*) # title = \\3\n ['\")]\n [ \\t]*\n )? # title is optional\n (?:\\n+|\\Z)\n \"\"\" % less_than_tab, re.X | re.M | re.U)\n return _link_def_re.sub(self._extract_link_def_sub, text)\n\n # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:\n # http://bumppo.net/projects/amputator/\n _ampersand_re = re.compile(r'&(?!#?[xX]?(?:[0-9a-fA-F]+|\\w+);)')\n _naked_lt_re = re.compile(r'<(?![a-z/?\\$!])', re.I)\n _naked_gt_re = re.compile(r'''(?''', re.I)\n\n def _encode_amps_and_angles(self, text):\n # Smart processing for ampersands and angle brackets that need\n # to be encoded.\n text = self._ampersand_re.sub('&', text)\n\n # Encode naked <'s\n text = self._naked_lt_re.sub('<', text)\n\n # Encode naked >'s\n # Note: Other markdown implementations (e.g. Markdown.pl, PHP\n # Markdown) don't do this.\n text = self._naked_gt_re.sub('>', text)\n return text\n\n\n\n\n def _extract_link_def_sub(self, match):\n id, url, title = match.groups()\n key = id.lower() # Link IDs are case-insensitive\n self.urls[key] = self._encode_amps_and_angles(url)\n if title:\n self.titles[key] = title\n return \"\"\n\n\n def _extract_footnote_def_sub(self, match):\n id, text = match.groups()\n text = _dedent(text, skip_first_line=not text.startswith('\\n')).strip()\n normed_id = re.sub(r'\\W', '-', id)\n # Ensure footnote text ends with a couple newlines (for some\n # block gamut matches).\n self.footnotes[normed_id] = text + \"\\n\\n\"\n return \"\"\n\n def _strip_footnote_definitions(self, text):\n \"\"\"A footnote definition looks like this:\n\n [^note-id]: Text of the note.\n\n May include one or more indented paragraphs.\n\n Where,\n - The 'note-id' can be pretty much anything, though typically it\n is the number of the footnote.\n - The first paragraph may start on the next line, like so:\n\n [^note-id]:\n Text of the note.\n \"\"\"\n less_than_tab = self.tab_width - 1\n footnote_def_re = re.compile(r'''\n ^[ ]{0,%d}\\[\\^(.+)\\]: # id = \\1\n [ \\t]*\n ( # footnote text = \\2\n # First line need not start with the spaces.\n (?:\\s*.*\\n+)\n (?:\n (?:[ ]{%d} | \\t) # Subsequent lines must be indented.\n .*\\n+\n )*\n )\n # Lookahead for non-space at line-start, or end of doc.\n (?:(?=^[ ]{0,%d}\\S)|\\Z)\n ''' % (less_than_tab, self.tab_width, self.tab_width),\n re.X | re.M)\n return footnote_def_re.sub(self._extract_footnote_def_sub, text)\n\n\n def _run_block_gamut(self, text):\n # These are all the transformations that form block-level\n # tags like paragraphs, headers, and list items.\n\n text = self._do_fenced_code_blocks(text)\n\n text = self._do_headers(text)\n\n # Do Horizontal Rules:\n # On the number of spaces in horizontal rules: The spec is fuzzy: \"If\n # you wish, you may use spaces between the hyphens or asterisks.\"\n # Markdown.pl 1.0.1's hr regexes limit the number of spaces between the\n # hr chars to one or two. We'll reproduce that limit here.\n\n text = self._do_lists(text)\n\n text = self._do_code_blocks(text)\n\n text = self._do_block_quotes(text)\n\n # We already ran _HashHTMLBlocks() before, in Markdown(), but that\n # was to escape raw HTML in the original Markdown source. This time,\n # we're escaping the markup we've just created, so that we don't wrap\n # tags around block-level tags.\n #text = self._hash_html_blocks(text)\n\n text = self._form_paragraphs(text)\n\n return text\n\n\n\n\n\n\n def _run_span_gamut(self, text):\n # These are all the transformations that occur *within* block-level\n # tags like paragraphs, headers, and list items.\n\n text = self._do_code_spans(text)\n\n text = self._do_links(text)\n\n text = self._do_strike(text)\n\n text = self._do_italics_and_bold(text)\n\n return text\n\n\n\n _inline_link_title = re.compile(r'''\n ( # \\1\n [ \\t]+\n (['\"]) # quote char = \\2\n (?P
.*?)\n \\2\n )? # title is optional\n \\)$\n ''', re.X | re.S)\n _tail_of_reference_link_re = re.compile(r'''\n # Match tail of: [text][id]\n [ ]? # one optional space\n (?:\\n[ ]*)? # one optional newline followed by spaces\n \\[\n (?P.*?)\n \\]\n ''', re.X | re.S)\n\n _whitespace = re.compile(r'\\s*')\n\n _strip_anglebrackets = re.compile(r'<(.*)>.*')\n\n def _find_non_whitespace(self, text, start):\n \"\"\"Returns the index of the first non-whitespace character in text\n after (and including) start\n \"\"\"\n match = self._whitespace.match(text, start)\n return match.end()\n\n def _find_balanced(self, text, start, open_c, close_c):\n \"\"\"Returns the index where the open_c and close_c characters balance\n out - the same number of open_c and close_c are encountered - or the\n end of string if it's reached before the balance point is found.\n \"\"\"\n i = start\n l = len(text)\n count = 1\n while count > 0 and i < l:\n if text[i] == open_c:\n count += 1\n elif text[i] == close_c:\n count -= 1\n i += 1\n return i\n\n def _extract_url_and_title(self, text, start):\n \"\"\"Extracts the url and (optional) title from the tail of a link\"\"\"\n # text[start] equals the opening parenthesis\n idx = self._find_non_whitespace(text, start+1)\n if idx == len(text):\n return None, None, None\n end_idx = idx\n has_anglebrackets = text[idx] == \"<\"\n if has_anglebrackets:\n end_idx = self._find_balanced(text, end_idx+1, \"<\", \">\")\n end_idx = self._find_balanced(text, end_idx, \"(\", \")\")\n match = self._inline_link_title.search(text, idx, end_idx)\n if not match:\n return None, None, None\n url, title = text[idx:match.start()], match.group(\"title\")\n if has_anglebrackets:\n url = self._strip_anglebrackets.sub(r'\\1', url)\n return url, title, end_idx\n\n\n\n\n def _do_links(self, text):\n \"\"\"Turn Markdown link shortcuts into XHTML and tags.\n\n This is a combination of Markdown.pl's _DoAnchors() and\n _DoImages(). They are done together because that simplified the\n approach. It was necessary to use a different approach than\n Markdown.pl because of the lack of atomic matching support in\n Python's regex engine used in $g_nested_brackets.\n \"\"\"\n MAX_LINK_TEXT_SENTINEL = 3000 # markdown2 issue 24\n\n # `anchor_allowed_pos` is used to support img links inside\n # anchors, but not anchors inside anchors. An anchor's start\n # pos must be `>= anchor_allowed_pos`.\n anchor_allowed_pos = 0\n\n curr_pos = 0\n while True: # Handle the next link.\n # The next '[' is the start of:\n # - an inline anchor: [text](url \"title\")\n # - a reference anchor: [text][id]\n # - an inline img: \n # - a reference img: ![text][id]\n # - a footnote ref: [^id]\n # (Only if 'footnotes' extra enabled)\n # - a footnote defn: [^id]: ...\n # (Only if 'footnotes' extra enabled) These have already\n # been stripped in _strip_footnote_definitions() so no\n # need to watch for them.\n # - a link definition: [id]: url \"title\"\n # These have already been stripped in\n # _strip_link_definitions() so no need to watch for them.\n # - not markup: [...anything else...\n try:\n try:\n start_idx = text.index('[[', curr_pos)\n is_img=False\n except:\n start_idx = text.index('{{', curr_pos)\n is_img=True\n except ValueError:\n break\n\n text_length = len(text)\n\n # Find the matching closing ']]' or '}}'.\n bracket_depth = 0\n for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL,\n text_length)):\n ch = text[p:p+2]\n if ch in [']]', '}}']:\n bracket_depth -= 1\n if bracket_depth < 0:\n break\n elif ch in ['[[', '{{']:\n bracket_depth += 1\n else:\n # Closing bracket not found within sentinel length.\n # This isn't markup.\n curr_pos = start_idx + 1\n continue\n link_text = text[start_idx+2:p]\n\n # Now determine what this is by the remainder.\n p += 1\n if p == text_length:\n return text\n\n if is_img:\n\n ########## syntax: link ##############\n result_head = '![%s]' % link_text\n result = '%s(%s)' % (result_head, link_text)\n text = text[:start_idx] + result + text[p+1:]\n ########## syntax: link END ##############\n\n elif start_idx >= anchor_allowed_pos:\n\n if '|' in link_text:\n link_re=re.compile('(.+)\\\\|(.+)',re.X | re.M)\n else:\n link_re=re.compile('(:|\\\\+|\\\\b)(.+)',re.X | re.M)\n\n m1=link_re.match(link_text)\n if m1 == None:\n url = \"\"\n link = link_text\n else:\n url,link=m1.groups()\n\n ########## syntax: link ##############\n result_head = '[%s]' % link\n url=parseLink(link, url, self.file)\n result = '%s(%s)' % (result_head, url)\n text = text[:start_idx] + result + text[p+1:]\n ########## syntax: link END ##############\n else:\n # Anchor not allowed here.\n curr_pos = start_idx + 1\n continue\n\n\n return text\n\n\n _h_re_base = r'''\n ^(\\={1,6}) # \\1 = string of ='s\n [ \\t]%s\n (.+?) # \\2 = Header text\n [ \\t]*\n \\1\n \\n+\n '''\n _h_re = re.compile(_h_re_base % '*', re.X | re.M)\n\n def _h_sub(self, match):\n n = len(match.group(1))\n n = max(1,6-n)\n text=match.group(2)\n return \"%s %s\\n\\n\" % (n*'#', text)\n\n\n def _do_headers(self, text):\n # Setext-style headers:\n # Header 1\n # ========\n #\n # Header 2\n # --------\n\n # atx-style headers:\n # # Header 1\n # ## Header 2\n # ## Header 2 with closing hashes ##\n # ...\n # ###### Header 6\n\n return self._h_re.sub(self._h_sub, text)\n\n _marker_ul_chars = '*+-'\n _marker_any = r'(?:[%s]|\\d+\\.)' % _marker_ul_chars\n _marker_ul = '(?:[%s])' % _marker_ul_chars\n _marker_ol = r'(?:\\d+\\.)'\n\n def _list_sub(self, match):\n lst = match.group(1)\n #lst_type = match.group(3) in self._marker_ul_chars and \"ul\" or \"ol\"\n result = self._process_list_items(lst)\n if self.list_level:\n\n ########## syntax: list item (ordered) ##############\n return \"\\n%s\\n\" % result\n else:\n return \"\\n%s\\n\\n\" % result\n ########## syntax: list item (ordered) END ##############\n\n def _do_lists(self, text):\n # Form HTML ordered (numbered) and unordered (bulleted) lists.\n\n # Iterate over each *non-overlapping* list match.\n pos = 0\n while True:\n # Find the *first* hit for either list style (ul or ol). We\n # match ul and ol separately to avoid adjacent lists of different\n # types running into each other (see issue #16).\n hits = []\n for marker_pat in (self._marker_ul, self._marker_ol):\n less_than_tab = self.tab_width - 1\n whole_list = r'''\n ( # \\1 = whole list\n ( # \\2\n [ ]{0,%d}\n (%s) # \\3 = first list item marker\n [ \\t]+\n (?!\\ *\\3\\ ) # '- - - ...' isn't a list. See 'not_quite_a_list' test case.\n )\n (?:.+?)\n ( # \\4\n \\Z\n |\n \\n{2,}\n (?=\\S)\n (?! # Negative lookahead for another list item marker\n [ \\t]*\n %s[ \\t]+\n )\n )\n )\n ''' % (less_than_tab, marker_pat, marker_pat)\n if self.list_level: # sub-list\n list_re = re.compile(\"^\"+whole_list, re.X | re.M | re.S)\n else:\n list_re = re.compile(r\"(?:(?<=\\n\\n)|\\A\\n?)\"+whole_list,\n re.X | re.M | re.S)\n match = list_re.search(text, pos)\n if match:\n hits.append((match.start(), match))\n if not hits:\n break\n hits.sort()\n match = hits[0][1]\n start, end = match.span()\n middle = self._list_sub(match)\n text = text[:start] + middle + text[end:]\n pos = start + len(middle) # start pos for next attempted match\n\n return text\n\n _list_item_re = re.compile(r'''\n (\\n)? # leading line = \\1\n (^[ \\t]*) # leading whitespace = \\2\n (?P%s) [ \\t]+ # list marker = \\3\n ((?:.+?) # list item text = \\4\n (\\n{1,2})) # eols = \\5\n (?= \\n* (\\Z | \\2 (?P%s) [ \\t]+))\n ''' % (_marker_any, _marker_any),\n re.M | re.X | re.S)\n\n _last_li_endswith_two_eols = False\n\n def _list_item_sub(self, match):\n item = match.group(4)\n leading_line = match.group(1)\n if leading_line or \"\\n\\n\" in item or self._last_li_endswith_two_eols:\n item = self._run_block_gamut(self._outdent(item))\n else:\n # Recursion for sub-lists:\n item = self._do_lists(self._outdent(item))\n if item.endswith('\\n'):\n item = item[:-1]\n item = self._run_span_gamut(item)\n self._last_li_endswith_two_eols = (len(match.group(5)) == 2)\n\n ########## syntax: list item (unordered) ##############\n bul=match.group(3)\n if bul in self._marker_ul_chars:\n bul=u'*'\n return \"%s %s\\n\" % (bul,item)\n ########## syntax: list item (unordered) END ##############\n\n\n\n def _process_list_items(self, list_str):\n # Process the contents of a single ordered or unordered list,\n # splitting it into individual list items.\n\n # The $g_list_level global keeps track of when we're inside a list.\n # Each time we enter a list, we increment it; when we leave a list,\n # we decrement. If it's zero, we're not in a list anymore.\n #\n # We do this because when we're not inside a list, we want to treat\n # something like this:\n #\n # I recommend upgrading to version\n # 8. Oops, now this line is treated\n # as a sub-list.\n #\n # As a single paragraph, despite the fact that the second line starts\n # with a digit-period-space sequence.\n #\n # Whereas when we're inside a list (or sub-list), that line will be\n # treated as the start of a sub-list. What a kludge, huh? This is\n # an aspect of Markdown's syntax that's hard to parse perfectly\n # without resorting to mind-reading. Perhaps the solution is to\n # change the syntax rules such that sub-lists must start with a\n # starting cardinal number; e.g. \"1.\" or \"a.\".\n self.list_level += 1\n self._last_li_endswith_two_eols = False\n list_str = list_str.rstrip('\\n') + '\\n'\n list_str = self._list_item_re.sub(self._list_item_sub, list_str)\n self.list_level -= 1\n return list_str\n\n\n\n def _code_block_sub(self, match, is_fenced_code_block=False):\n if is_fenced_code_block:\n codeblock = match.group(2)\n codeblock = codeblock[:-1] # drop one trailing newline\n else:\n codeblock = match.group(1)\n codeblock = self._outdent(codeblock)\n codeblock = self._detab(codeblock)\n codeblock = codeblock.lstrip('\\n') # trim leading newlines\n codeblock = codeblock.rstrip() # trim trailing whitespace\n\n return \"\\n\\n```%s\\n```\\n\\n\" % codeblock\n\n\n\n\n def _do_code_blocks(self, text):\n return text\n\n _fenced_code_block_re = re.compile(r'''\n (?:\\n\\n|\\A\\n?)\n ^```([\\w+-]+)?[ \\t]*\\n # opening fence, $1 = optional lang\n (.*?) # $2 = code block content\n ^```[ \\t]*\\n # closing fence\n ''', re.M | re.X | re.S)\n\n def _fenced_code_block_sub(self, match):\n return self._code_block_sub(match, is_fenced_code_block=True);\n\n def _do_fenced_code_blocks(self, text):\n \"\"\"Process ```-fenced unindented code blocks ('fenced-code-blocks' extra).\"\"\"\n return self._fenced_code_block_re.sub(self._fenced_code_block_sub, text)\n\n # Rules for a code span:\n # - backslash escapes are not interpreted in a code span\n # - to include one or or a run of more backticks the delimiters must\n # be a longer run of backticks\n # - cannot start or end a code span with a backtick; pad with a\n # space and that space will be removed in the emitted HTML\n # See `test/tm-cases/escapes.text` for a number of edge-case\n # examples.\n _code_span_re = re.compile(r'''\n (?%s\" % c\n '''\n\n def _code_span_sub(self, match):\n c = match.group(2).strip(\" \\t\")\n #c = self._encode_code(c)\n\n ########## syntax: code block ##############\n #return \"%s\" % c\n codesym=match.group(1)\n if codesym=='```':\n return \"%s\\n%s\\n%s\" % (codesym,c,codesym)\n elif codesym=='`':\n return \"%s%s%s\" % (codesym,c,codesym)\n ########## syntax: code block END ##############\n\n def _do_code_spans(self, text):\n # * Backtick quotes are used for spans.\n #\n # * You can use multiple backticks as the delimiters if you want to\n # include literal backticks in the code span. So, this input:\n #\n # Just type ``foo `bar` baz`` at the prompt.\n #\n # Will translate to:\n #\n # Just type foo `bar` baz at the prompt.
\n #\n # There's no arbitrary limit to the number of backticks you\n # can use as delimters. If you need three consecutive backticks\n # in your code, use four for delimiters, etc.\n #\n # * You can use spaces to get literal backticks at the edges:\n #\n # ... type `` `bar` `` ...\n #\n # Turns to:\n #\n # ... type `bar` ...\n return self._code_span_re.sub(self._code_span_sub, text)\n\n def _encode_code(self, text):\n \"\"\"Encode/escape certain characters inside Markdown code runs.\n The point is that in code, these characters are literals,\n and lose their special Markdown meanings.\n \"\"\"\n replacements = [\n # Encode all ampersands; HTML entities are not\n # entities within a Markdown code span.\n ('&', '&'),\n # Do the angle bracket song and dance:\n ('<', '<'),\n ('>', '>'),\n ]\n for before, after in replacements:\n text = text.replace(before, after)\n hashed = _hash_text(text)\n self._escape_table[text] = hashed\n return hashed\n\n _strike_re = re.compile(r\"~~(?=\\S)(.+?)(?<=\\S)~~\", re.S)\n def _do_strike(self, text):\n text = self._strike_re.sub(r\"~~\\1~~\", text)\n return text\n\n _strong_re = re.compile(r\"(\\*\\*|__)(?=\\S)(.+?[*_]*)(?<=\\S)\\1\", re.S)\n _em_re = re.compile(r\"(//)(?=\\S)(.+?)(?<=\\S)\\1\", re.S)\n\n\n def _do_italics_and_bold(self, text):\n # must go first:\n ########## syntax: italic and bold ##############\n text = self._strong_re.sub(r\"**\\2**\", text)\n text = self._em_re.sub(r\"*\\2*\", text)\n ########## syntax: italic and bold END ##############\n return text\n\n\n\n _block_quote_base = r\"\"\"\n ( # Wrap whole match in \\1\n ^'''[ \\t]*\\n # ''' at the start of a line\n (\n (.+\\n)* # subsequent consecutive lines\n \\n* # blanks\n )\n ^'''[ \\t]*\\n\n )\n \"\"\"\n\n _block_quote_re = re.compile(_block_quote_base, re.M | re.X)\n _bq_one_level_re = re.compile('^[ \\t]*>[ \\t]?', re.M);\n _bq_one_level_re_spoiler = re.compile('^[ \\t]*>[ \\t]*?![ \\t]?', re.M);\n _bq_all_lines_spoilers = re.compile(r'\\A(?:^[ \\t]*>[ \\t]*?!.*[\\n\\r]*)+\\Z', re.M)\n _html_pre_block_re = re.compile(r'(\\s*.+?)', re.S)\n def _dedent_two_spaces_sub(self, match):\n return re.sub(r'(?m)^ ', '', match.group(1))\n\n\n\n def _block_quote_sub(self, match):\n bq = match.group(2)\n\n bq = self._bq_one_level_re.sub('', bq)\n # trim whitespace-only lines\n bq = self._ws_only_line_re.sub('', bq)\n bq = self._run_block_gamut(bq) # recurse\n\n bq = re.sub('(?m)^', ' ', bq)\n # These leading spaces screw with content, so we need to fix that:\n bq = self._html_pre_block_re.sub(self._dedent_two_spaces_sub, bq)\n\n return '> %s\\n\\n' % bq\n\n\n\n\n\n def _do_block_quotes(self, text):\n if \"'''\" not in text:\n return text\n return self._block_quote_re.sub(self._block_quote_sub, text)\n\n def _form_paragraphs(self, text):\n # Strip leading and trailing lines:\n text = text.strip('\\n')\n\n # Wrap tags.\n grafs = []\n for i, graf in enumerate(re.split(r\"\\n{2,}\", text)):\n graf = self._run_span_gamut(graf)\n grafs.append(graf.lstrip(\" \\t\"))\n\n return \"\\n\\n\".join(grafs)\n\n\n\n\n def _add_footnotes(self, text):\n if self.footnotes:\n footer = [\n '
')\n return text + '\\n\\n' + '\\n'.join(footer)\n else:\n return text\n\n\n\n def _outdent(self, text):\n # Remove one level of line-leading tabs or spaces\n return text\n #return self._outdent_re.sub('', text)\n\n\n\n\ndef _dedent(text, tabsize=8, skip_first_line=False):\n \"\"\"_dedent(text, tabsize=8, skip_first_line=False) -> dedented text\n\n \"text\" is the text to dedent.\n \"tabsize\" is the tab width to use for indent width calculations.\n \"skip_first_line\" is a boolean indicating if the first line should\n be skipped for calculating the indent width and for dedenting.\n This is sometimes useful for docstrings and similar.\n\n textwrap.dedent(s), but don't expand tabs to spaces\n \"\"\"\n lines = text.splitlines(1)\n _dedentlines(lines, tabsize=tabsize, skip_first_line=skip_first_line)\n return ''.join(lines)\n\ndef _xml_escape_attr(attr, skip_single_quote=True):\n \"\"\"Escape the given string for use in an HTML/XML tag attribute.\n\n By default this doesn't bother with escaping `'` to `'`, presuming that\n the tag attribute is surrounded by double quotes.\n \"\"\"\n escaped = (attr\n .replace('&', '&')\n .replace('\"', '"')\n .replace('<', '<')\n .replace('>', '>'))\n if not skip_single_quote:\n escaped = escaped.replace(\"'\", \"'\")\n return escaped\n\n\ndef _dedentlines(lines, tabsize=8, skip_first_line=False):\n \"\"\"_dedentlines(lines, tabsize=8, skip_first_line=False) -> dedented lines\n\n \"lines\" is a list of lines to dedent.\n \"tabsize\" is the tab width to use for indent width calculations.\n \"skip_first_line\" is a boolean indicating if the first line should\n be skipped for calculating the indent width and for dedenting.\n This is sometimes useful for docstrings and similar.\n\n Same as dedent() except operates on a sequence of lines. Note: the\n lines list is modified **in-place**.\n \"\"\"\n DEBUG = False\n if DEBUG:\n print(\"dedent: dedent(..., tabsize=%d, skip_first_line=%r)\"\\\n % (tabsize, skip_first_line))\n margin = None\n for i, line in enumerate(lines):\n if i == 0 and skip_first_line: continue\n indent = 0\n for ch in line:\n if ch == ' ':\n indent += 1\n elif ch == '\\t':\n indent += tabsize - (indent % tabsize)\n elif ch in '\\r\\n':\n continue # skip all-whitespace lines\n else:\n break\n else:\n continue # skip all-whitespace lines\n if DEBUG: print(\"dedent: indent=%d: %r\" % (indent, line))\n if margin is None:\n margin = indent\n else:\n margin = min(margin, indent)\n if DEBUG: print(\"dedent: margin=%r\" % margin)\n\n if margin is not None and margin > 0:\n for i, line in enumerate(lines):\n if i == 0 and skip_first_line: continue\n removed = 0\n for j, ch in enumerate(line):\n if ch == ' ':\n removed += 1\n elif ch == '\\t':\n removed += tabsize - (removed % tabsize)\n elif ch in '\\r\\n':\n if DEBUG: print(\"dedent: %r: EOL -> strip up to EOL\" % line)\n lines[i] = lines[i][j:]\n break\n else:\n raise ValueError(\"unexpected non-whitespace char %r in \"\n \"line %r while removing %d-space margin\"\n % (ch, line, margin))\n if DEBUG:\n print(\"dedent: %r: %r -> removed %d/%d\"\\\n % (line, ch, removed, margin))\n if removed == margin:\n lines[i] = lines[i][j+1:]\n break\n elif removed > margin:\n lines[i] = ' '*(removed-margin) + lines[i][j+1:]\n break\n else:\n if removed:\n lines[i] = lines[i][removed:]\n return lines\n\n\n\n\n\n\n\n\ndef main(filein,fileout,verbose=True):\n\n text=tools.readFile(filein,verbose)\n if verbose:\n print('# : Converting to zim...')\n newtext=Zim2Markdown(file=filein).convert(text)\n tools.saveFile(fileout,newtext,verbose)\n\n return\n\n\n\n#-----------------------Main-----------------------\nif __name__=='__main__':\n\n\n parser=argparse.ArgumentParser(description=\\\n 'Convert zim wiki note files to markdown syntax.')\n\n parser.add_argument('file',type=str,\\\n help='Input zim note text file.')\n parser.add_argument('-o','--out',type=str,\\\n help='Output file name.')\n parser.add_argument('-v','--verbose',action='store_true',\\\n default=True)\n\n try:\n args=parser.parse_args()\n except:\n sys.exit(1)\n\n FILEIN=os.path.abspath(args.file)\n if not args.out:\n FILEOUT='%s_%s.md' %(os.path.splitext(args.file)[0], 'zim2md')\n else:\n FILEOUT=args.out\n FILEOUT=os.path.abspath(FILEOUT)\n\n main(FILEIN,FILEOUT,args.verbose)\n\n\n","sub_path":"zim2markdown.py","file_name":"zim2markdown.py","file_ext":"py","file_size_in_byte":37891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"82233053","text":"# Copyright 2014 - Rackspace\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\n\"\"\"\nMistral DSL and Heat Template parsing and representation routines.\n\nThis code does not import the original YAML representations of the Mistral DSL\nand Heat Templates as the data may be in memory instead of file. PyYAML is a\ngood library to load the YAML and translate into a Python dictionary with code\nlike:\n\nimport yaml\n\nwith open(\"mistral_dsl.yaml\", \"r\") as fptr\n data = yaml.safe_load(fptr)\n\nImportant note:\nThis code expects that the loading code performs some basic YAML validation\n* Mistral DSLs must include a \"Workflow\" section with a \"tasks\" subsection\n* Mistral DSLs must have one task with no on-success (last task)\n* Heat Templates must include a \"requirements\" section\n\"\"\"\n\n\ndef get_mistral_tasks(data, start_task_name=None):\n \"\"\"Returns an ordered Mistral task list from a DSL.\"\"\"\n task_list = []\n task_dict = data[\"Workflow\"][\"tasks\"]\n for key, task in task_dict.items():\n on_success = task.get(\"on-finish\", task.get(\"on-success\"))\n on_error = task.get(\"on-finish\", task.get(\"on-error\"))\n task_list.append([key, on_success, on_error])\n curr_task_name = None\n sorted_task_list = []\n no_suc_list = ([[name, on_suc, on_err] for (name, on_suc, on_err) in\n task_list if on_suc is None])\n sorted_task_list.insert(0, no_suc_list[0])\n curr_task_name = no_suc_list[0][0]\n for count in range(len(task_list) - 1):\n for task in task_list:\n task_name, on_success, on_error = task\n if on_success == curr_task_name:\n curr_task_name = task_name\n sorted_task_list.insert(0, task)\n break\n if start_task_name:\n if start_task_name == task_name:\n break\n return sorted_task_list\n\n\ndef create_svg_mistral_tasks(task_list, radius=45):\n \"\"\"Create an SVG UI diagram of Mistral task flow.\n\n This takes the output of get_mistral_tasks() and generates an SVG-based\n graphical diagram of the ordered Mistral tasks. The code automatically\n scales the SVG based on the circle radius value. Note that SVG circles\n don't scale radius by percentages very well which is why this is still\n pixel math. The circle radius is the diagonal length of the viewport\n which is not very useful in this case.\n \"\"\"\n indent = radius * 1.1\n diameter = radius * 2\n num_tasks = len(task_list)\n if num_tasks < 1:\n return \"[No Tasks Found]\"\n svg_output = (\"\\n\" %\n ((diameter * 1.10), ((num_tasks-1) * diameter * 1.3) +\n indent * 2))\n svg_output += (\" \\n\" %\n (indent, ((num_tasks-1) * diameter * 1.2) + indent))\n svg_output += (\" \\n\")\n for counter in range(num_tasks):\n svg_output += (\" \\n\" %\n ((counter * diameter * 1.2 + indent), radius))\n svg_output += \" \\n\"\n svg_output += \" \\n\"\n for counter in range(num_tasks):\n svg_output += (\" %s \\n\" %\n ((counter * diameter * 1.2 + indent),\n task_list[counter][0]))\n svg_output += \" \\n\"\n svg_output += \" \\n\"\n return svg_output\n\n\ndef get_mistral_required_input(data, start_task_name=None):\n \"\"\"Returns required Mistral DSL user input field information.\n\n Note that this code ignores Mistral DSL values that are enumerated in the\n ignore_list list below which are under the \"parameters:\" label. The\n recommendation is to not nest sections under a \"parameters:\" label and\n just list name/value pairs in the parameters section.\n \"\"\"\n input_dict = {}\n task_list = get_mistral_tasks(data, start_task_name)\n task_key_list = [item[0] for item in task_list]\n task_dict = data[\"Workflow\"][\"tasks\"]\n ignore_list = [\"params\", \"settings\", \"arguments\"]\n publish_list = []\n for task in task_key_list:\n param_list = task_dict[task].get(\"parameters\", [])\n publish_list.extend(task_dict[task].get(\"publish\", []))\n for param in param_list:\n if param not in ignore_list and param not in publish_list:\n if param not in input_dict:\n input_dict[param] = [task]\n else:\n input_dict[param].append(task)\n return input_dict\n\n\ndef get_heat_required_input(data):\n \"\"\"Returns Heat required user input fields.\"\"\"\n heat_params = []\n heat_param_dict = data[\"parameters\"]\n for key, heat_param in heat_param_dict.items():\n heat_params.append([key,\n heat_param.get(\"type\"),\n heat_param.get(\"default\"),\n heat_param.get(\"description\")])\n return sorted(heat_params)\n\n\nif __name__ == \"__main__\":\n # This code is left for example and basic testing purposes; it is not\n # intended for production use.\n\n import yaml\n\n with open(\"dsl.yaml\", \"r\") as FPTR:\n DATA = yaml.safe_load(FPTR)\n print(\"\\nMistral Task workflow:\")\n RET_DICT = get_mistral_tasks(DATA)\n for VAL in RET_DICT:\n print(\"%s - success: %s, error: %s\" % (VAL[0], VAL[1], VAL[2]))\n\n SVG_TEXT = create_svg_mistral_tasks(RET_DICT, 45)\n print(\"\\nSVG task output:\\n\" + SVG_TEXT)\n\n # Mistral required input\n print(\"\\nMistral required inputs:\")\n RET_DICT = get_mistral_required_input(DATA)\n for KEY, VAL in RET_DICT.items():\n print(KEY, \"\", VAL)\n\n # Heat required input\n print(\"\\nHeat required inputs:\")\n with open(\"hot.yaml\", \"r\") as FPTR:\n DATA = yaml.safe_load(FPTR)\n RET_DICT = get_heat_required_input(DATA)\n for VAL in RET_DICT:\n print(\"%s - %s, %s, %s\" % (VAL[0], VAL[1], VAL[2], VAL[3]))\n","sub_path":"solumdashboard/common/workflow_parsers.py","file_name":"workflow_parsers.py","file_ext":"py","file_size_in_byte":6587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"512832040","text":"#!/usr/bin/env python\n\nwith open('input/day_1') as infile:\n data = infile.read()\n\nfloor = 0\nfor c in data:\n if c == '(':\n floor += 1\n elif c == ')':\n floor -= 1\n\nprint(floor)\n","sub_path":"2015/dec1a.py","file_name":"dec1a.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"600224439","text":"#!/usr/bin/python3\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy import linspace, polyval, polyfit, sqrt, stats, randn\nsns.set_palette(\"deep\", desat=.6)\nsns.set_context(rc={\"figure.figsize\": (8, 7)})\ndef head(data,num):\n i = 0 \n for each in data:\n print( each)\n if i == num:\n return()\n i += 1\ndef get_plot(data,ax,c,l):\n\tml=data[:,0]\n\tbin_num = (max(ml)-min(ml)) / 0.01\n\tax.hist(ml, bins=bin_num, color=c, alpha=0.3, label=l)\n\t#ax.plot(ml,xr)\n\tax.legend()\nf, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True)\nfile_CG = 'S_total.CG.dict.genemethylv.txt'\nfile_CHG = 'S_total.CHG.dict.genemethylv.txt'\nfile_CHH = 'S_total.CHH.dict.genemethylv.txt'\ndata_CG = np.loadtxt(file_CG,skiprows=1,usecols = (3,4))\ndata_CHG = np.loadtxt(file_CHG,skiprows=1,usecols = (3,4))\ndata_CHH = np.loadtxt(file_CHH,skiprows=1,usecols = (3,4))\nplt.ylim(0,1000)\nplt.xlim(0,1)\nget_plot(data_CG,ax1,'r','CG')\nget_plot(data_CHG,ax2,'b','CHG')\nget_plot(data_CHH,ax3,'g','CHH')\n\n#f.set_size_inches(18.5,10.5)\nplt.savefig('mungbean_methyl_sup_fig_7.png',dpi=300)\nplt.show()\n","sub_path":"py/sunhwa/4_gene_met_plot_hist.py","file_name":"4_gene_met_plot_hist.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"623050739","text":"#\n# Explicit model for potential drop across a lithium metal electrode\n#\nfrom .base_ohm import BaseModel\n\n\nclass LithiumMetalExplicit(BaseModel):\n \"\"\"Explicit model for potential drop across a lithium metal electrode.\n\n Parameters\n ----------\n param : parameter class\n The parameters to use for this submodel\n options : dict, optional\n A dictionary of options to be passed to the model.\n\n **Extends:** :class:`pybamm.electrode.ohm.BaseModel`\n \"\"\"\n\n def __init__(self, param, options=None):\n super().__init__(param, \"Negative\", options=options)\n\n def get_coupled_variables(self, variables):\n param = self.param\n\n i_boundary_cc = variables[\"Current collector current density\"]\n T_n = variables[\"Negative current collector temperature\"]\n l_n = param.l_n\n delta_phi_s = i_boundary_cc * l_n / param.sigma_n(T_n)\n delta_phi_s_dim = param.potential_scale * delta_phi_s\n\n variables.update(\n {\n \"Negative electrode potential drop\": delta_phi_s,\n \"Negative electrode potential drop [V]\": delta_phi_s_dim,\n \"X-averaged negative electrode ohmic losses\": delta_phi_s / 2,\n \"X-averaged negative electrode ohmic losses [V]\": delta_phi_s_dim / 2,\n }\n )\n\n return variables\n\n def set_boundary_conditions(self, variables):\n pass\n","sub_path":"pybamm/models/submodels/electrode/ohm/li_metal_explicit.py","file_name":"li_metal_explicit.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"63306706","text":"from player import *\nfrom game import *\n\n\nGAME_COUNT = 1000\n\n\nhistorian = HistoricalPlayer(1)\nrandom_player = RandomPlayer()\nsequential_player = SequentialPlayer()\nfrequency_player = FrequencyPlayer()\ntournament = SeveralGames(historian, frequency_player, GAME_COUNT)\n\ntournament.play_tournament()","sub_path":"rock_paper_scissors/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"132636008","text":"\nimport selenium, pandas\nimport pandas as pd\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport time\nimport matplotlib.pyplot as plt\nimport os\nfrom tkinter import *\nfrom PIL import ImageTk, Image\nfrom AnimatedGif import *\nimport datetime\n\n\n\n\n\ndef scrapNmatch(name):\n\n driver = webdriver.Chrome('script/chromedriver')\n df=[]\n driver.get(\"https://ecdms.energy.ca.gov/elecbycounty.aspx\")\n\n country=driver.find_elements_by_tag_name(\"option\")\n for k in country:\n if k.text==name:\n k.click()\n\n\n #country=driver.find_element_by_xpath(\"//option[@value=k]\")\n #country.click()\n sector=driver.find_element_by_xpath(\"//img[@alt='Select All Sectors']\")\n sector.click()\n\n year=driver.find_element_by_xpath(\"//img[@alt='Select All Years']\")\n year.click()\n\n report=driver.find_element_by_xpath(\"//input[@value='Create Report']\")\n report.click()\n\n csv=driver.find_element_by_xpath(\"//input[@value='Export to CSV']\")\n csv.click()\n\n time.sleep(2)\n\n df = pd.read_csv(r\"C:\\Users\\RAMD\\Downloads\\ElectricityByCounty.csv\")\n del df['County']\n del df['Total Usage']\n df2 = df.T\n export_csv = df2.to_csv(r'C:\\Users\\export_dataframedf2.csv', index=True, header=None)\n df4 = pd.read_csv(r'C:\\Users\\export_dataframedf2.csv')\n df4 = df4.rename(columns={'Sector': 'Year'})\n fig = plt.figure()\n plt.plot(df4['Year'], df4['Non-Residential'], label='Non-Residential')\n plt.plot(df4['Year'], df4['Residential'], label='Residential')\n plt.plot(df4['Year'], df4['Total'], label='Total')\n plt.legend()\n plt.xlabel('Year', fontsize=16)\n plt.ylabel(' Millions of kWh (GWh)', fontsize=16)\n plt.show()\n\n time.sleep(2)\n\n if os.path.exists(r\"C:\\Users\\ElectricityByCounty.csv\"):\n os.remove(r\"C:\\Users\\ElectricityByCounty.csv\")\n","sub_path":"usfile.py","file_name":"usfile.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"45172567","text":"import os\nimport shutil\nimport json\n\nimport paraFilehandle\n\n\ndef get_project_name(project_dir):\n project_name = os.path.basename(project_dir)\n return project_name\n\n\ndef get_para_dir(project_dir):\n project_name = get_project_name(project_dir)\n para_dir = project_dir + \"/\" + project_name + \".para\"\n return para_dir\n\n\ndef get_vehicle_PlateNumber(project_dir):\n vehicle_plate_number = get_project_name(project_dir).split(\"_\")[3]\n return vehicle_plate_number\n\n\n# pointcloudDir\n# /media/yanzhe/SHCJ01/1205/20201205115519_WYT_SHANGHAI_AFA1119/03_LiDAR_RAW/01_POINTCLOUD/LiDAR_2\ndef get_pointcloudDir(project_dir, lidar_name):\n pointcloudDir = project_dir + \"/03_LiDAR_RAW/01_POINTCLOUD/LiDAR_1\"\n return pointcloudDir\n\n\n# trajectoryFile\n# /media/yanzhe/SHCJ01/1205/20201205115519_WYT_SHANGHAI_AFA1119/06_INS_PROC/20201205115519_WYT_SHANGHAI_AFA1119_Proc.nav\ndef get_trajectoryFile(project_dir):\n trajectoryFile = project_dir + \\\n \"/06_INS_PROC/\" + get_project_name(project_dir) + \".nav\"\n return trajectoryFile\n # print(\"trajectoryFile:\" + trajectoryFile)\n\n\ndef get_all_scanfolder_name(project_dir):\n # todo.............\n scan_paths = os.listdir(project_dir + \"/03_LiDAR_RAW/01_POINTCLOUD\")\n\n return scan_paths\n\n\ndef get_sigle_scanfolder_path(project_dir, lidar_name):\n # todo.............\n\n # scan_paths = {}\n for scan_folder in os.listdir(project_dir + \"/03_LiDAR_RAW/01_POINTCLOUD\"):\n if scan_folder == lidar_name:\n return project_dir + \"/03_LiDAR_RAW/01_POINTCLOUD/\" + scan_folder\n\n\ndef create_11_pointcloud_dir(project_dir, lidar_name):\n\n POINTCLOUD_dir = project_dir + \"/11_POINTCLOUD/\"\n if os.path.exists(POINTCLOUD_dir) is False:\n os.mkdir(POINTCLOUD_dir)\n\n outputDir = project_dir + \"/11_POINTCLOUD/\" + lidar_name + \"_POINTCLOUD\"\n if os.path.exists(outputDir):\n os.removedirs(outputDir)\n\n # os.mkdir(project_dir + \"/11_POINTCLOUD/\" + lidar_name)\n os.mkdir(outputDir)\n\n return outputDir\n\n\ndef get_lidar_type(project_dir, lidar_name):\n # 1#CAR and LiDAR_1\n if str(project_dir).find(\"DSX116\") != -1 and str(lidar_name).find(\n \"1\") != -1:\n return str(128)\n # 1#CAR and not LiDAR_1\n elif str(project_dir).find(\"DSX116\") != -1 and str(lidar_name).find(\n \"1\") == -1:\n return 32\n\n # not 1#CAR and LiDAR_1\n elif str(project_dir).find(\n \"DSX116\") == -1 and str(lidar_name).find(\"1\") != -1:\n return 64\n\n # not 1# car and not LiDAR_1\n elif str(project_dir).find(\"DSX116\") == -1 and str(lidar_name).find(\n \"1\") == -1:\n return 32\n\n # def get_outputDir(project_dir, lidar_name):\n # return project_dir + \"/11_POINTCLOUD/\"+lidar_name\n\n\ndef createProcNavFile(project_dir):\n ProcNavFile = project_dir + \"/06_INS_PROC/\" + get_project_name(\n project_dir) + \"_Proc.nav\"\n\n if os.path.exists(ProcNavFile):\n os.remove(ProcNavFile)\n\n # cloudParaFile = open(ProcNavFile, \"w+\")\n # cloudParaFile.writelines(\"1tesdfsdst....test\")\n # cloudParaFile.close\n\n shutil.copy(get_trajectoryFile(project_dir), ProcNavFile)\n\n return ProcNavFile\n\n\ndef createCloudParaFile(project_dir):\n cloudParaPath = project_dir + \"/\" + get_project_name(\n project_dir) + \"_cloud.para\"\n\n if os.path.exists(cloudParaPath):\n os.remove(cloudParaPath)\n\n vehiclePara = paraFilehandle.getVehiclePara(project_dir)\n\n cloudParaDictionary = json.dumps(vehiclePara)\n\n cloudParaFile = open(cloudParaPath, \"w+\")\n cloudParaFile.writelines(cloudParaDictionary)\n cloudParaFile.close\n\n return cloudParaPath\n\n\n# TEST...........\n# project_dir = \"/home/slam/WM-20201006/learn_python_202012/point_cloud_join/2020120511551119_WYT_SHANGHAI_AFA1119\"\n# # create_11_pointcloud_dir(project_dir, \"LiDAR_1\")\n\n# print(get_sigle_scanfolder_path(project_dir, \"LiDAR_2\"))\n# print(get_lidar_type(project_dir, \"LiDAR_3\"))\n# print(createProcNavFile(project_dir))\n","sub_path":"learn_python_202012/datamapping_pointcloud/projectPathHandle.py","file_name":"projectPathHandle.py","file_ext":"py","file_size_in_byte":3964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"351150686","text":"from django.http import *\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.shortcuts import render_to_response\nfrom django.newforms import *\nfrom django import oldforms\nfrom django.conf import settings\nfrom django.template import RequestContext\n\nfrom datetime import date, timedelta\nimport datetime\n\nfrom tic_tac_toe.board.models import *\nfrom tic_tac_toe.settings import *\nfrom tic_tac_toe.board.forms import *\n\ndef index(request):\n \n if request.POST:\n g=GameForm(request.POST)\n g.is_bound\n\n #validate the blog, save, and redirect to the blog entry\n if g.is_valid():\n new_game = Game()\n \n if 'block1' in request.POST:\n new_game.block1 = request.POST['block1']\n if new_game.block1 == \"X\":\n new_game.block3 = \"O\"\n \n if 'block2' in request.POST:\n new_game.block2 = request.POST['block2']\n if new_game.block2 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block3' in request.POST:\n new_game.block3 = request.POST['block3']\n if new_game.block3 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block4' in request.POST:\n new_game.block4 = request.POST['block4']\n if new_game.block4 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block5' in request.POST:\n new_game.block5 = request.POST['block5']\n if new_game.block5 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block6' in request.POST:\n new_game.block6 = request.POST['block6']\n if new_game.block6 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block7' in request.POST:\n new_game.block7 = request.POST['block7']\n if new_game.block7 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block8' in request.POST:\n new_game.block8 = request.POST['block8']\n if new_game.block8 == \"X\":\n new_game.block1 = \"O\"\n \n if 'block9' in request.POST:\n new_game.block9 = request.POST['block9']\n if new_game.block9 == \"X\":\n new_game.block1 = \"O\" \n \n new_game.save() \n \n return HttpResponseRedirect(\"/game/\")\n else:\n errors = g.errors\n return render_to_response('errors.html',\n {\n \n })\n else:\n g=GameForm()\n \n \n return render_to_response('index.html',\n {\n \n }) \n \ndef game(request):\n \n try:\n curr_game = Game.objects.filter().order_by('-id')[:1].get()\n except ObjectDoesNotExist:\n curr_game = {}\n \n GameInstanceForm = form_for_instance(curr_game, fields=GAME_FIELDS)\n \n if request.POST: \n g=GameInstanceForm(request.POST)\n \n if g.is_valid(): \n \n if 'block2' in request.POST:\n curr_game.block2 = request.POST['block2']\n if curr_game.block9 == None:\n curr_game.block9 = \"O\"\n \n if 'block4' in request.POST:\n curr_game.block4 = request.POST['block4']\n \n if curr_game.block5:\n curr_game.block6 = \"O\"\n \n if curr_game.block1:\n if curr_game.block9:\n curr_game.block6 = \"O\"\n else: \n curr_game.block7 = \"O\"\n \n if 'block5' in request.POST:\n curr_game.block5 = request.POST['block5']\n \n if curr_game.block9:\n curr_game.block8 = \"O\"\n elif curr_game.block4:\n curr_game.block6 = \"O\" \n \n if curr_game.block1 == \"X\":\n curr_game.block9 = \"O\"\n \n if curr_game.block3 == \"X\":\n curr_game.block7 = \"O\"\n \n \n if 'block6' in request.POST:\n curr_game.block6 = request.POST['block6']\n if curr_game.block7 == None:\n curr_game.block7 = \"O\"\n \n if 'block7' in request.POST:\n curr_game.block7 = request.POST['block7']\n \n if curr_game.block1 == \"X\":\n curr_game.block4 = \"O\" \n \n if curr_game.block3:\n curr_game.block5 = \"O\" \n \n if 'block8' in request.POST:\n curr_game.block8 = request.POST['block8']\n \n if curr_game.block9:\n if curr_game.block7:\n curr_game.block8 = \"O\" \n else: \n curr_game.block5 = \"O\"\n \n if curr_game.block7 == \"X\":\n if curr_game.block9 == \"X\":\n curr_game.block8 = \"X\"\n \n \n if 'block9' in request.POST:\n curr_game.block9 = request.POST['block9']\n \n if curr_game.block3:\n if curr_game.block7:\n curr_game.block8 = \"O\"\n \n if curr_game.block1:\n curr_game.block5 = \"O\"\n \n \n curr_game.save()\n return HttpResponseRedirect(\"/game/\") \n \n else:\n g = GameInstanceForm()\n \n \n return render_to_response('game.html',\n {\n 'curr_game':curr_game,\n }) ","sub_path":"tic_tac_toe/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"192720158","text":"# -*- coding: utf-8 -*-\r\nimport os\r\nfrom datetime import datetime, timedelta\r\n\r\nfrom airflow import DAG\r\nfrom airflow.models import Variable\r\nfrom airflow.operators.bash_operator import BashOperator\r\nfrom airflow.operators.dummy_operator import DummyOperator\r\n\r\nu\"\"\"\r\nAirflow script for calc_08\r\n\"\"\"\r\n\r\nALERT_MAILS = Variable.get(\"gv_ic_admin_lst\")\r\nDAG_NAME = str(os.path.basename(__file__).split('.')[0])\r\nOWNER = 'User Airflow'\r\nDEPENDS_ON_PAST = True\r\nEMAIL_ON_FAILURE = True\r\nEMAIL_ON_RETRY = False\r\nRETRIES = int(Variable.get('gv_dag_retries'))\r\nPOOL = 'data_pool'\r\nMAIN_VAR_NAME = 'gv_' + DAG_NAME\r\n\r\nSRV_LIST = Variable.get('gv_psg_kafka_srv_list')\r\nQUEUE_NAME = Variable.get('gv_psg_kafka_queue_name')\r\nPARTITIONS = Variable.get('gv_psg_kafka_partitions')\r\nLOADDTTM=str(datetime.now()).replace(\" \",\"_\")\r\nWAIT_HRS = 1\r\n\r\nstart_dt = datetime(2018, 11, 15)\r\n\r\n# setting default arguments of dag\r\ndefault_args = {\r\n 'owner': OWNER,\r\n 'depends_on_past': DEPENDS_ON_PAST,\r\n 'start_date': start_dt,\r\n 'email': ALERT_MAILS,\r\n 'email_on_failure': EMAIL_ON_FAILURE,\r\n 'email_on_retry': EMAIL_ON_RETRY,\r\n 'retries': RETRIES,\r\n 'pool': POOL\r\n}\r\n\r\n# Creating DAG with parameters\r\ndag = DAG(DAG_NAME, default_args=default_args, schedule_interval=\"0 */4 * * *\")\r\ndag.doc_md = __doc__\r\n\r\ndag_start = DummyOperator(\r\n task_id='dag_start',\r\n dag=dag\r\n)\r\n\r\ndag_end = DummyOperator(\r\n task_id='dag_end',\r\n dag=dag\r\n)\r\n\r\nalgo_bash_cmd = \"\"\"\r\nkinit airflow/airflow@HOME.LOCAL -kt /opt/airflow/airflow_home/kt/airflow.keytab\r\nspark-submit --master yarn \\\r\n--num-executors {{ params.partitions }} \\\r\n--executor-cores 3 \\\r\n--executor-memory 6G \\\r\n--driver-cores 5 \\\r\n--driver-memory 10G \\\r\n--conf 'spark.driver.extraJavaOptions=-Djava.security.auth.login.config={{ params.home }}/kt/kafka_client.conf' \\\r\n--conf 'spark.executor.extraJavaOptions=-Djava.security.auth.login.config={{ params.home }}/kt/kafka_client.conf' \\\r\n--packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.1.1 \\\r\n--jars \"\"\"+\"/opt/airflow/airflow-home/utils/HiveHomeUDF-0.0.1.jar\"+\"\"\" \\\r\n{{ params.home }}/dags/pyspark/prod_data/calc_08.py {{ params.srv_list }} {{ params.queue_name }} {{ params.partitions }} {{ params.loaddttm }}\r\n\"\"\"\r\n\r\nalgo_bash_load = BashOperator(\r\n task_id='prod_data_algo_calc_08',\r\n bash_command=algo_bash_cmd,\r\n execution_timeout=timedelta(hours=WAIT_HRS),\r\n params={\r\n 'home': '/opt/airflow/airflow_home',\r\n 'srv_list': SRV_LIST,\r\n 'queue_name': QUEUE_NAME,\r\n 'partitions': PARTITIONS,\r\n 'loaddttm': LOADDTTM\r\n },\r\n wait_for_downstream=True,\r\n dag=dag\r\n)\r\n\r\ndag_start.set_downstream(algo_bash_load)\r\nalgo_bash_load.set_downstream(dag_end)\r\n","sub_path":"Raif/pyspark/run_calc_08.py","file_name":"run_calc_08.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
+{"seq_id":"277158789","text":"from Post import Post\nfrom Photo import Photo\nfrom config import telegram_token\nimport requests\nimport urllib\nimport json\nimport time\nimport os\nimport logging\n\nLOGGER = logging.getLogger(__name__)\nLOGGER.setLevel(\"DEBUG\")\n\n\nclass TelegramPost(Post):\n def __init__(self, photo: Photo, chatIdFilePath):\n super().__init__(photo)\n self.chatIdFilePath = chatIdFilePath\n self.chatIds = self.updateAndGetRecipientList(self.chatIdFilePath)\n self.closureText = \"TelegramBot (GitHub: http://bit.ly/PotDGithub)\"\n self.locationName = None\n self.telegramPostText = self.composeTelegramPostText()\n\n def composeTelegramPostText(self):\n if self.locationName is not None:\n locationSection = f\"Shot in {self.locationName} \"\n else:\n locationSection = \"\"\n\n return (\n f\"{self.introText} \"\n f\"{self.exifSection} {self.closureText} \"\n f\"{self.photo.tensorFlowHashtags} \"\n f\"{locationSection}\"\n f\"| Sent with ❤️\"\n )\n\n def updateAndGetRecipientList(self, chatIdFilePath):\n # Download updated from the Telegram's bot API\n # See: https://core.telegram.org/bots/api\n\n updatesUrl = f\"https://api.telegram.org/bot{telegram_token}/getUpdates\"\n response = urllib.request.urlopen(updatesUrl)\n data = json.loads(response.read().decode())\n\n # get chatIds from the getUpdates endpoint, extract chatIds of private\n # conversations only ~ a private message sent from users asking bot\n # to be subscribed to the daily delivery\n chatIds = set(\n [\n message[\"message\"][\"chat\"][\"id\"]\n for message in data[\"result\"]\n if message[\"message\"][\"chat\"][\"type\"] == \"private\"\n ]\n )\n\n # Retrieve preserved chatIds from the existing json file\n if os.path.isfile(chatIdFilePath):\n with open(chatIdFilePath) as jsonData:\n jsonContent = json.load(jsonData)\n # Put chatIds into the existing chatIds set\n list(map(lambda x: chatIds.add(x), jsonContent[\"chatIds\"]))\n\n # Save all chatIds to the JSON file\n with open(chatIdFilePath, \"w\") as jsonData:\n jsonData.write(json.dumps({\"chatIds\": list(chatIds)}))\n\n return chatIds\n\n def setLocation(self, locationName):\n self.locationName = locationName\n\n def postTelegramPost(self):\n # refresh telegram's message\n self.telegramPostText = self.composeTelegramPostText()\n result = 0\n try:\n #\n # https://core.telegram.org/bots/faq#how-can-i-message-all-of-my-bot-39s-subscribers-at-once\n # How can I message all of my bot's subscribers at once?\n # Unfortunately, at this moment we don't have methods for sending bulk\n # messages, e.g. notifications. We may add something along these lines in the future.\n\n # In order to avoid hitting our limits when sending out mass notifications, consider\n # spreading them over longer intervals, e.g. 8-12 hours. The API will not allow more than ~30 messages\n # to different users per second, if you go over that, you'll start getting 429 errors.\n\n # push the message to every chatId\n for chatId in self.chatIds:\n url = f\"https://api.telegram.org/bot{telegram_token}/sendPhoto\"\n files = {\"photo\": open(self.photo.photoPath, \"rb\")}\n data = {\"chat_id\": chatId, \"caption\": self.telegramPostText}\n response = requests.post(url, files=files, data=data)\n if response.status_code != 200:\n raise Exception(f\"{response.status_code} {response.reason}\")\n # being nice to the Telegram's api\n time.sleep(0.05)\n except Exception as e:\n LOGGER.error(e)\n result = -1\n\n return result\n","sub_path":"app/src/TelegramPost.py","file_name":"TelegramPost.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"54"}
diff --git a/749.jsonl b/749.jsonl
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/752.jsonl b/752.jsonl
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/766.jsonl b/766.jsonl
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391