diff --git "a/2412.jsonl" "b/2412.jsonl" new file mode 100644--- /dev/null +++ "b/2412.jsonl" @@ -0,0 +1,720 @@ +{"seq_id":"194570612","text":"from collections import defaultdict\nimport time\n\ndef crosswordFormation(words):\n possible_crosswords = 0\n\n #check case where all the words are the same or have one letter repeated\n\n #setup a map charting the word to each letter to a list of the indices of the letters\n word_map = defaultdict(lambda: defaultdict(list))\n for word in words:\n for i in range(len(word)):\n word_map[word][word[i]].append(i)\n\n seen = set()\n\n #first, use nested loops to get all combinations of the words (4! = 24)\n for word in words:\n print(words)\n curr_set = set(words[::])\n curr_set.discard(word)\n print(curr_set)\n for left_down in curr_set:\n two_words_set = set(curr_set.copy())\n two_words_set.discard(left_down)\n for bottom_word in two_words_set:\n right_down = set(two_words_set.copy())\n right_down.discard(bottom_word)\n right_down = right_down.pop()\n\n #check that the word combination has not already been seen\n #as a rotation\n if(not any([isRotated(a, (word, left_down, bottom_word, right_down)) for a in seen])):\n seen.add((word, left_down, bottom_word, right_down))\n else:\n continue\n #now need to look letter by letter\n #and match the letters in the words in each position\n for i in range(len(word)):\n top_letter = word[i]\n down_match_inds = word_map[left_down][top_letter]\n for j in down_match_inds:\n #special case where the middle rectangle area is zero\n if(j+2 >= len(left_down)):\n continue\n for k in range(j+2, len(left_down)):\n second_intersection_letter = left_down[k]\n left_bottom_match_inds = word_map[bottom_word][second_intersection_letter]\n for l in left_bottom_match_inds:\n #special case where middle rectangle area would be zero\n if(i + 2 >= len(word)):\n continue\n for m in range(i+2, len(word)):\n second_top_letter = word[m]\n second_top_match_inds = [a for a in word_map[right_down][second_top_letter] if a+2<=len(right_down)]\n for n in second_top_match_inds:\n for o in range(n+2, len(right_down)):\n bottom_right_letter = right_down[o]\n second_bottom_letter_match_inds = [a for a in word_map[bottom_word][bottom_right_letter]\n if a >= l+2]\n for item in second_bottom_letter_match_inds:\n if(o - n == k - j and m - i == item - l):\n possible_crosswords += 1\n\n return possible_crosswords*2\n\n\n\ndef isRotated(a, b):\n a = list(a)\n b = list(b)\n if(a[0] == b[1] and a[1] == b[0] and a[2] == b[3] and a[3] == b[2]):\n return True\n\n return False\n\n\nwords = ['aaaaaaaaaaaaaa', 'aaaaaaaaaaaaab', 'aaaaaaaaaaaaca', 'aaaaaaaaaaadaa']\nstart = time.clock()\nprint(crosswordFormation(words))\nprint(time.clock() - start)\n","sub_path":"Arcade/crossword_creator.py","file_name":"crossword_creator.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"163441722","text":"import nltk\nfrom nltk.corpus import gutenberg\nimport numpy as np\n\ndef get_prob(frequency,length): \n for key in frequency:\n frequency[key] = frequency[key]/length\n return frequency\n\n''' ______________________________________________________________________________________ '''\ndef laplace_smoothing(ngrams,oder,dim):\n if oder == 2:\n freq_gram = np.ones((dim,dim)) \n freq_Dist = nltk.FreqDist(ngrams)\n for gram in set(ngrams):\n freq_gram[gram] = freq_Dist[gram]\n div = np.sum(freq_gram)\n smoothed_gram = freq_gram/ div \n \n if oder == 3: # because of memory error no smoothing with enough memory same as oder == 2\n freq_Dist = nltk.FreqDist(ngrams)\n smoothed_gram = get_prob(freq_Dist,len(ngrams)) \n \n if oder == 4: # because of memory error no smoothing\n freq_Dist = nltk.FreqDist(ngrams)\n smoothed_gram = get_prob(freq_Dist,len(ngrams))\n \n return smoothed_gram\n\n\n\n\ndef sent_to_sequence(sentence):\n #return [word_2_id['']] + [word_2_id.get(word, word_2_id['']) for word in sentence] + [word_2_id['']]\n sentence = [''] + sentence + ['']\n return [word_2_id.get(word, word_2_id['']) for word in sentence] #wenn word in dict nicht gefunden wird, wird returned \n\ndef sequence_to_ngram(corpus, oder): # oder >= 2\n ngrams = []\n for sequence in corpus:\n ngrams += list(nltk.ngrams(sequence, oder))\n return ngrams\n\n\n\ndef prepare_dataset(shakespeare, Vocab, oder):\n dataset = [sent_to_sequence(s) for s in shakespeare]\n print(dataset)\n dataset_ngram = sequence_to_ngram(dataset, oder)\n dataset_ngram = laplace_smoothing(dataset_ngram,oder,len(Vocab))\n return dataset_ngram\n\ndef get_next_word(seed_ids,oder,model):\n \n if oder == 2:\n seed = seed_ids[-1]\n row = LM_2gram[seed,:]\n word = np.where(row == np.amax(row))\n word = np.max(word[0])\n prob = np.amax(row)\n \n if oder == 3:\n seed = seed_ids[-2]+ seed_ids[-1]\n prob= 0\n word = 0\n for i in range(0,len(Vocab)):\n if (seed_ids[-2],seed_ids[-1],i) in model:\n if model[(seed_ids[-2],seed_ids[-1],i)] > prob:\n prob= model[(seed_ids[-2],seed_ids[-1],i)]\n word = i\n \n if oder == 4:\n seed = seed_ids[-3] + seed_ids[-2]+ seed_ids[-1]\n prob= 0\n word = 0\n for i in range(0,len(Vocab)):\n if (seed_ids[-3],seed_ids[-2],seed_ids[-1],i) in model:\n if model[(seed_ids[-3],seed_ids[-2],seed_ids[-1],i)] > prob:\n prob = model[(seed_ids[-3],seed_ids[-2],seed_ids[-1],i)]\n word = i\n return prob,word\n''' ______________________________________________________________________________________ \nDefine Model \n'''\n\ndef shakespeare_LM(shakespeare, Vocab, oder):\n dataset_ngram = prepare_dataset(shakespeare, Vocab, oder)\n #model = define_model(oder, len(Vocab))\n #train(model, input_data, output_data, 100)\n return dataset_ngram\n\n\n\n\n\n'''\nGenerate Text\n'''\ndef generate(seed_text, num_words, oder, model):\n seed_words = seed_text.split()\n seed_words = [w for w in seed_words] # dataset is unicode instead of string.\n \n for i in range(num_words):\n seed_ids = [word_2_id.get(w, word_2_id['']) for w in seed_words]\n #print(seed_ids)\n prob,predict_word = get_next_word(seed_ids,oder,model)\n #print (seed_ids)\n \n #print (prob)\n #print(predict_word )\n word = id_2_word[predict_word]\n #print (word)\n seed_words.append(word)\n \n print (' '.join(seed_words))\n\n\n''' ____________________________________________________________________________________________________________ '''\n'''\nGet Data and Preprocess Data\n'''\n#nltk.download('gutenberg')\nguten = gutenberg.fileids()\nids = guten[-4: -1] # nur die letzten texte auswählen bis auf den allerletzten\n#print (guten)\n#print (ids)\n'''\n# only use Hamlet here for simiplicity.\n#nltk.download('punkt')\n'''\nshakespeare = list(gutenberg.sents(fileids=ids[1])) # nur hamlet wir ausgewählt\nshakespeare = [ [w.lower() for w in s if w.isalpha()] for s in shakespeare ] # words to lowercase\n#print (shakespeare[:5])\n\n'''\nbuild vocabulary\n'''\nwords = list(gutenberg.words(fileids=ids[1])) #worte aus hamlet in liste\nwords = [w.lower() for w in words] #worte aus hamlet klein\nwords = nltk.FreqDist(words).most_common(5000) #FreqDist ist die Frequency Distribution einzelner Worte in der Liste words\nwords = [w[0] for w in list(set(words)) if w[0].isalpha()] #Set hat jedes Element nur1mla und ist effizienter für suche da es auf hash basiert\n\n'''\nadd functional tokens\n'''\nVocab = ['','']\nVocab += list(words) \n\n'''\n# vocab index\n'''\nword_2_id = {}\nid_2_word = {}\nfor i, w in enumerate(Vocab):\n word_2_id[w] = i\n id_2_word[i] = w\n\n#print (word_2_id['prayers'])\n#print (id_2_word[3589])\n\n#print(word_2_id.get('lord',word_2_id['']))\n \n'''\nbuild statistical model\n''' \n \nLM_2gram = shakespeare_LM(shakespeare, Vocab, 2) \nLM_3gram = shakespeare_LM(shakespeare, Vocab, 3)\nLM_4gram = shakespeare_LM(shakespeare, Vocab, 4)\n\n'''\nGenerate Text from model\n'''\n\ngenerate('To be', 10, 2, LM_2gram)\ngenerate('To be or', 10, 3, LM_3gram)\ngenerate('To be or not', 10, 4, LM_4gram)\n \n \n\n ","sub_path":"Exercise_02/exercise2.2.py","file_name":"exercise2.2.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"251226957","text":"# Problem 7-8\n\nsandwich_orders = ['tuna', 'pepperoni', 'beef', 'cheese', 'vegetarian']\nfinished_sandwiches = []\n\nwhile sandwich_orders:\n\tsandwich = sandwich_orders.pop()\n\tprint(\"I made your \" + sandwich + \" sandwich.\")\n\tfinished_sandwiches.append(sandwich)\n\nprint(\"Sandwiches that have been made: \")\nprint(finished_sandwiches)\n","sub_path":"python/python_crash_course/chapter_7/deli.py","file_name":"deli.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"410423999","text":"import numpy as np\n\n\ndef sort_asc(array):\n \"\"\"Sort input array by ascending.\"\"\"\n sortedarray = list(array)\n for j in range(1, len(sortedarray)):\n key = sortedarray[j]\n i = j - 1\n while i >= 0 and key < sortedarray[i]:\n sortedarray[i + 1] = sortedarray[i]\n i = i - 1\n sortedarray[i + 1] = key\n return sortedarray\n\n\ndef sort_desc(array):\n \"\"\"Sort input array by descending.\"\"\"\n sortedarray = list(array)\n for j in range(1, len(sortedarray)):\n key = sortedarray[j]\n i = j - 1\n while i >= 0 and key > sortedarray[i]:\n sortedarray[i + 1] = sortedarray[i]\n i = i - 1\n sortedarray[i + 1] = key\n return sortedarray\n\n\n# start test here\nn = 20\nmaxvalue = n * 100\nminvalue = 0\n\n#create random array\ntestarray = np.random.randint(low=minvalue, high=maxvalue, size=n).tolist()\n\n#sort by ascending\narrayasc = sort_asc(testarray)\ntestarrayasc = np.sort(testarray).tolist()\nassert arrayasc == testarrayasc, 'Error in sort_asc function'\n\n#sort by descending\narraydesc = sort_desc(testarray)\ntestarraydesc = testarrayasc[::-1]\nassert arraydesc == testarraydesc, 'Error in sort_desc function'\n","sub_path":"Cormen/sorting/insertion.py","file_name":"insertion.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"386614042","text":"a=[1, 4, 5, 7, 8, -2, 0, -1]\nprint(a[2],a[4])\na_sorted=sorted(a)\nprint(a_sorted[:3])\nprint(a_sorted[1:6])\na_sorted.pop(2)\na_sorted.pop(2)\nprint(a_sorted)\nb=['grapes', 'Potatoes','tomatoes', 'Orange', 'Lemon', 'Broccoli', 'Carrot', 'Sausages']\nb_copy=b.copy()\nb_copy.sort(reverse=True)\nb_sorted=b_copy\nc=list()\nc.extend(a[:3])\nc.extend(b[3:6])\nprint(c)\n\n","sub_path":"Lecture3/L3_Homework/L3_Homework1/L3_Homework1.py","file_name":"L3_Homework1.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"204549873","text":"import datetime\nimport time\nimport smtplib\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nimport pymysql\nimport re\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.select import Select\n\n\ndef sendMail(location,addr,data,logFile):\n\n #收发配置\n sender = '@stu.xmu.edu.cn'\n receiver = addr\n smtpserver = 'smtp.stu.xmu.edu.cn'\n username = '@stu.xmu.edu.cn'\n password = ''\n #邮件信息\n subject = '[%s-%s-%s] %.2f元,%.2f度。'%(location[0],location[1],location[2],data[0],data[1])\n notice=\"

%s同学,你好:

\"%addr\n notice=notice+\"

你查询的宿舍电费信息为:

\"\n url2=\"http://elec.xmu.edu.cn/PdmlWebSetup/Pages/SMSMain.aspx\" #电费查询地址\n url1=\"http://ecardservice.xmu.edu.cn/\" #电费充值地址\n url3=\"https://shimo.im/doc/wYcxGoVhdM0TwgtE?r=XPRDMG/「电费查询信息代码」\"#代码展示地址\n url4=\"https://www.wjx.top/jq/17948119.aspx\"#问卷地址\n notice=notice+'''\n

【%s-%s-%s】电费余额:

\n '''%(location[0],location[1],location[2])\n notice=notice+\"

%.2f 元 ;%.2f 度。

\"%(data[0],data[1])\n notice=notice+'

'\n notice=notice+\"

==========

\"\n notice=notice+'''\n

【在线交电费】厦门大学校园卡电子服务平台

\n

【电费查询】厦门大学学生宿舍智能控电电费查询

\n

【程序源代码】

\n

【更改通知】填写问卷即可订阅/取消电费通知或者修改通知类型

\n

任何意见/建议/反馈/问题,直接回复:)

\n '''%(url1,url2,url3,url4)\n msg = MIMEMultipart()\n msg.attach(MIMEText(notice, 'html', 'utf-8'))\n # msg = MIMEText(notice,'html','utf-8')#中文需参数‘utf-8',单字节字符不需要\n msg['Subject'] = Header(subject, 'utf-8')\n # 添加附件就是加上一个MIMEBase,从本地读取一个图片:\n with open('./180101.png', 'rb') as f:\n # 设置附件的MIME和文件名,这里是png类型:\n mime = MIMEBase('image', 'png', filename='elecH2X.png')\n # 加上必要的头信息:\n mime.add_header('Content-Disposition', 'attachment', filename='elecH2X.png')\n mime.add_header('Content-ID', '<0>')\n mime.add_header('X-Attachment-Id', '0')\n # 把附件的内容读进来:\n mime.set_payload(f.read())\n # 用Base64编码:\n encoders.encode_base64(mime)\n # 添加到MIMEMultipart:\n msg.attach(mime)\n\n #发送邮件\n try:\n smtp = smtplib.SMTP()\n smtp.connect('smtp.stu.xmu.edu.cn')\n smtp.login(username, password)\n smtp.sendmail(sender, receiver, msg.as_string())\n logFile.write (\"SUC:[%s-%s-%s]\\n\"%(location[0],location[1],location[2]))\n except smtplib.SMTPException as e:\n logFile.write (\"ERR:[%s-%s-%s]: %s\\n\"%(location[0],location[1],location[2],str(e)))\n smtp.quit()\n\nif __name__ == '__main__':\n\n logFile = open(\"./test.log\",'w')\n\n #测试代码段\n location=[\"52\",\"映雪6\",\"0205\"]\n addr=\"@163.com\"\n addr=\"@qq.com\"\n data=[20.9,80.9]\n\n sendMail(location,addr,data,logFile)\n","sub_path":"H2X/elecH2X/sn_oop/testMailImg.py","file_name":"testMailImg.py","file_ext":"py","file_size_in_byte":3523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"98540695","text":"\nfrom math import prod\ndef boxed_cell(s, idx):\n s2 = ''\n tree = False\n for i, ch in zip(range(len(s)), s):\n if idx == i:\n s2 += f\"[{ch}]\"\n if ch == '#':\n tree = True\n\n else:\n s2 += f\" {ch} \"\n return s2, tree\n\ndef count_trees( ski_slope, coords, slope):\n tree_count = 0\n while coords[1] < len(ski_slope):\n parsed_row, tree = boxed_cell(ski_slope[coords[1]], coords[0])\n print(parsed_row, tree)\n tree_count += tree\n #print(''.join(arr[coords[0]]), arr[coords[0], coords[1] ], coords)\n coords[0] += slope[0]\n coords[1] += slope[1]\n if coords[0] >= len(ski_slope[0]):\n coords[0] -= len(ski_slope[0])\n return(tree_count)\n\nslopes =[(1,1),\n (3,1),\n (5,1),\n (7,1),\n (1,2)]\n\nwith open(\"toboggan_map_d3\") as f:\n ski_slope = [line.strip() for line in f.readlines()] \n n_trees = []\n for slope in slopes:\n coords = [0,0]\n n_trees.append(count_trees(ski_slope,coords, slope))\n\nprint(n_trees)\nprint(prod(n_trees) )\n\n \n\n\n\n \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"476905138","text":"def dibTrianguloE(num):\r\n for i in range(num + 1):\r\n k = num - 1\r\n print(' '*(2*num-i)+\"*\"*(2*i-1)+' '*k,end=' ')\r\n k -= 1\r\n print()\r\ndef main():\r\n dibTrianguloE(6)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"Examenes/L-2.py","file_name":"L-2.py","file_ext":"py","file_size_in_byte":240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"104679501","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCopied from:\nhttps://github.com/Tagar/stuff/blob/master/spinner.py\n\nFound from:\nhttps://stackoverflow.com/a/58174909/8792159\n\nNote: For even more fancier spinners, one could also use the halo package\n(https://github.com/manrajgrover/halo) but this would require an installation\nof halo and I want demetrius to be as plain as possible\n\n@author: Johannes.Wiesner\n\"\"\"\n\nimport sys\nimport threading\nimport itertools\nimport time\n\nclass Spinner:\n\n def __init__(self, message, delay=0.1):\n self.spinner = itertools.cycle(['-', '/', '|', '\\\\'])\n self.delay = delay\n self.busy = False\n self.spinner_visible = False\n sys.stdout.write(message)\n\n def write_next(self):\n with self._screen_lock:\n if not self.spinner_visible:\n sys.stdout.write(next(self.spinner))\n self.spinner_visible = True\n sys.stdout.flush()\n\n def remove_spinner(self, cleanup=False):\n with self._screen_lock:\n if self.spinner_visible:\n sys.stdout.write('\\b')\n self.spinner_visible = False\n if cleanup:\n sys.stdout.write(' ') # overwrite spinner with blank\n sys.stdout.write('\\r') # move to next line\n sys.stdout.flush()\n\n def spinner_task(self):\n while self.busy:\n self.write_next()\n time.sleep(self.delay)\n self.remove_spinner()\n\n def __enter__(self):\n if sys.stdout.isatty():\n self._screen_lock = threading.Lock()\n self.busy = True\n self.thread = threading.Thread(target=self.spinner_task)\n self.thread.start()\n\n def __exit__(self, exc_type, exc_val, exc_traceback):\n if sys.stdout.isatty():\n self.busy = False\n self.remove_spinner(cleanup=True)\n else:\n sys.stdout.write('\\r')","sub_path":"spinner.py","file_name":"spinner.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"174630177","text":"#!/home/carl/Projects/algotrader/algotrader/bin/python2.7\n\nimport talib\nimport numpy\nimport itertools\n\nfrom pyalgotrade import strategy\nfrom pyalgotrade.technical import cross, macd\n\nfrom pyalgotrade.talibext.indicator import CDLDRAGONFLYDOJI\n\n\ndef parameters_generator(paramnames=False):\n if paramnames:\n return (\"exitdays\",\"penetration\") # to retreive these names, making caller agnostic !! always an array !! ORDER MATTER\n exitDays = (2,5,7,10)\n #belowzero = (True, False)\n penetration = range(0,101,20)\n return itertools.product(exitDays,penetration)\n\nclass TestStrat(strategy.BacktestingStrategy):\n def __init__(self, feed, instrument, exitDays,penetration):\n super(TestStrat, self).__init__(feed,cash_or_brk=100000)\n\n self.TestShort = False # Test only short or long, not both.\n\n self.STRATNAME = \"Dragonfly_Doji\"\n self.STRATDESC = '''Tests what the edge is when macd line crosses below macd-ema both when the macd is below and above the zero line'''\n\n self.exitDays = exitDays\n self.penetration = penetration\n\n self.__instrument = instrument\n\n # We'll use adjusted close values, if available, instead of regular close values.\n if feed.barsHaveAdjClose():\n self.setUseAdjustedValues(True)\n\n #self.BarDs = self.getFeed().getDataSeries(self.__instrument)\n self.__priceDS = self.getFeed().getDataSeries(self.__instrument).getPriceDataSeries()\n\n self.__longPos = None\n self.__shortPos = None\n self.getBroker().getFillStrategy().setVolumeLimit(None) # hack / CARL\n\n def onEnterCanceled(self, position):\n if self.__longPos == position:\n self.__longPos = None\n elif self.__shortPos == position:\n self.__shortPos = None\n else:\n assert(False)\n\n def onExitOk(self, position):\n if self.__longPos == position:\n self.__longPos = None\n elif self.__shortPos == position:\n self.__shortPos = None\n else:\n assert(False)\n\n def onExitCanceled(self, position):\n position.exitMarket()\n\n def onBars(self, bars):\n # Wait for enough bars to be available to calculate SMA and RSI.\n # We want to have at least N values \n barDs = self.getFeed().getDataSeries(self.__instrument)\n\n bar = bars[self.__instrument]\n\n self.candleform = CDLDRAGONFLYDOJI(barDs, self.penetration)\n\n if self.__longPos is not None: # We have a long position\n if self.exitLongSignal():\n self.__longPos.exitMarket()\n elif self.__shortPos is not None: # We have a short position\n if self.exitShortSignal():\n self.__shortPos.exitMarket()\n else:\n if not self.TestShort:\n if self.enterLongSignal(bar):\n #shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())\n shares = 10\n self.__longPos = self.enterLong(self.__instrument, shares, True)\n #self.__longPos = self.enterLongStop(instrument, stopPrice, quantity, goodTillCanceled=False, allOrNone=False)\n #self.__longPos = self.enterLongStopLimit(instrument, stopPrice, limitPrice, quantity, goodTillCanceled=False, allOrNone=False)\n if self.TestShort:\n if self.enterShortSignal(bar): # Exit short\n shares = 10\n self.__shortPos = self.enterShort(self.__instrument, shares, True)\n\n# elif self.enterShortSignal(bar): # Exit short\n# shares = int(self.getBroker().getCash() * 0.9 / bars[self.__instrument].getPrice())\n# self.__shortPos = self.enterShort(self.__instrument, shares, True)\n\n def enterLongSignal(self, bar): # Conditiond for long\n return self.candleform[-1] == 100\n\n def exitLongSignal(self):\n # Ma cross\n # return cross.cross_above(self.__priceDS, self.__exitSMA) and not self.__longPos.exitActive()\n #return cross.cross_above(self.__priceDS, self.__exitSMA) and not self.__longPos.exitActive()\n\n # N periods exit\n return self.__longPos.getAge().days > self.exitDays and not self.__longPos.exitActive()\n\n\n def enterShortSignal(self, bar):\n thismacd = self.macd[-1]\n macdsig = self.macd.getSignal()[-1]\n if self.belowzero:\n if cross.cross_above(self.macd, self.macd.getSignal()) and macdsig < 0:\n #print \"Entering short trade below zero macd\", thismacd, macdsig\n return True\n else:\n if cross.cross_above(self.macd, self.macd.getSignal()) and macdsig > 0:\n #print \"Entering short trade above zero macd\", thismacd, macdsig\n return True\n\n def exitShortSignal(self):\n return self.__shortPos.getAge().days > self.exitDays and not self.__shortPos.exitActive()\n","sub_path":"strategy_candleform.py","file_name":"strategy_candleform.py","file_ext":"py","file_size_in_byte":4949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"54431374","text":"\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport time\nimport datetime\nimport functools\nimport collections\nimport math\nfrom scipy.stats import entropy\n\nnba = pd.read_csv(\"Data//mc1-reports-data.csv\", parse_dates=['time'])\n\nnba = nba.set_index('time')\nnba['time'] = nba.index\n\n\ndef get_damage_mean_by_category(category):\n nba[\"time\"] = pd.to_datetime(nba[\"time\"])\n nba['hour'] = nba.time.dt.hour\n nba['date'] = nba.time.dt.date\n nba_location = nba.groupby(nba.location, as_index=False)\n locations = 0*[19]\n locations_timelyAverage = 0*[19]\n locations_timeAnalysis = 0*[19]\n for group_name, location in nba_location:\n locations_daysData = 0*[5]\n temp = nba_location.get_group(group_name).dropna(subset=[category])\n temp = temp.set_index('time')\n temp['time'] = temp.index\n locations_daysData.append(temp.loc['2020-04-06'])\n locations_daysData.append(temp.loc['2020-04-07'])\n locations_daysData.append(temp.loc['2020-04-08'])\n locations_daysData.append(temp.loc['2020-04-09'])\n locations_daysData.append(temp.loc['2020-04-10'])\n locations.append(locations_daysData)\n locations_timelyAverage.append(locations[group_name-1][2].groupby(\n locations[group_name-1][2].hour, as_index=False)[category].mean())\n locations_timeAnalysis.append(locations[group_name-1][2].groupby(\n locations[group_name-1][2].time, as_index=False)[category].mean())\n maxList = max(locations_timelyAverage, key=lambda i: len(i))\n maxLength = len(maxList)\n df = functools.reduce(lambda left, right: pd.merge(\n left, right, on='time', how='outer'), locations_timeAnalysis)\n damage = pd.DataFrame(df)\n locations = [\"time\", \"palace_hills\", \"northwest\", \"old_town\", \"safe_town\", \"southwest\", \"downtown\", \"wilson_forest\", \"scenic_vista\", \"broadview\",\n \"chapparal\", \"terrapin_springs\", \"pepper_mill\", \"cheddarford\", \"easton\", \"weston\", \"southton\", \"oak_willow\", \"east_parton\", \"west_parton\"]\n damage.columns = locations\n return damage\n\n\ndef get_mean_by_category(category, t1, t2):\n mask = (nba['time'] >= t1) & (nba['time'] <= t2)\n temp = nba.loc[mask]\n nba_location = temp.groupby(temp.location, as_index=False)\n locations = 0*[19]\n locations_timelyAverage = 0*[19]\n for group_name, location in nba_location:\n temp_category = nba_location.get_group(\n group_name).dropna(subset=[category])\n locations_timelyAverage.append(\n [group_name, temp_category[category].mean()])\n df = pd.DataFrame(locations_timelyAverage)\n return df\n\n\ndef get_entropy_by_category(category, t1, t2):\n mask = (nba['time'] >= t1) & (nba['time'] <= t2)\n temp = nba.loc[mask]\n nba_location = temp.groupby(temp.location, as_index=False)\n locations = 0*[19]\n locations_timelyAverage = 0*[19]\n for group_name, location in nba_location:\n temp_category = nba_location.get_group(\n group_name).dropna(subset=[category])\n if temp_category.empty:\n entropy_value=None \n else: \n bases = collections.Counter([tmp_base for tmp_base in temp_category[category]])\n dist = [x/sum(bases.values()) for x in bases.values()]\n entropy_value = entropy(dist, base=11)\n locations_timelyAverage.append([group_name, entropy_value])\n df = pd.DataFrame(locations_timelyAverage)\n return df\n\n\ndef get_damage(t1, t2):\n mask = (nba['time'] >= t1) & (nba['time'] <= t2)\n temp = nba.loc[mask]\n categories = ['sewer_and_water', 'power', 'roads_and_bridges',\n 'medical', 'buildings', 'shake_intensity']\n nba_location = temp.groupby(temp.location, as_index=False)\n all_categories = 0*[6]\n locations = 0*[19]\n locations_timelyAverage = 0*[19]\n for group_name, location in nba_location:\n for category in categories:\n temp_category=nba_location.get_group(group_name).dropna(subset=[category])\n locations_timelyAverage.append([group_name,category,temp_category[category].mean()])\n df=pd.DataFrame(locations_timelyAverage)\n return df\n\n\ndef get_report_count():\n nba_time = nba.groupby(nba.time, as_index=False)['time'].agg(['count'])\n nba_time['log_value'] = np.log(nba_time['count'])/np.log(11)\n nba_time.reset_index(level=0, inplace=True)\n return nba_time\n\n\ndef get_reports_n_damage_by_location(loc):\n nba_time = nba.groupby(nba.location, as_index=False)\n location = nba_time.get_group(loc)\n temp = location.groupby(pd.Grouper(level='time', freq='3h')).agg(power=('power', 'mean'), medical=('medical', 'mean'), sewer_and_water=('sewer_and_water', 'mean'), roads_and_bridges=('roads_and_bridges', 'mean'), buildings=('buildings', 'mean'), shake_intensity=('shake_intensity', 'mean'), count=('time', 'count'))\n temp.reset_index(level=0, inplace=True)\n return temp\n","sub_path":"Backend/preprocessData.py","file_name":"preprocessData.py","file_ext":"py","file_size_in_byte":4942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"530977918","text":"from params_and_consts import save_path, vocab_size, embedding_dim, rnn_units, start_event, generation_length\nfrom model import build_model\n\nimport muspy\nimport tensorflow as tf\nimport numpy as np\nimport os\n\ndef get_gen_model():\n gen_model = build_model(vocab_size, embedding_dim, rnn_units, batch_size=1)\n\n trained_model = tf.keras.models.load_model(save_path)\n old_weights = trained_model.get_weights()\n gen_model.set_weights(old_weights)\n\n return gen_model\n\ndef generate_notes(model, start, generation_length=100):\n input_seq = start\n input_seq = tf.expand_dims(input_seq, 0)\n\n notes_generated = []\n\n model.reset_states()\n\n for _ in range(generation_length):\n predictions = model(input_seq)\n predictions = tf.squeeze(predictions, 0)\n \n predicted_id = tf.random.categorical(predictions, num_samples=1)[-1,0].numpy()\n notes_generated.append(predicted_id)\n predicted_id_exp = tf.constant([predicted_id], dtype=np.int32)\n\n input_seq = tf.concat([input_seq[0], predicted_id_exp], 0)\n input_seq = tf.expand_dims(input_seq, axis=0)\n\n return (start + notes_generated)\n\n\ndef arr_to_event_repr(arr):\n return np.array([[el] for el in arr])\n\ndef main():\n gen_model = get_gen_model()\n generated_notes = generate_notes(gen_model, start=[start_event], generation_length=generation_length)\n generated_events = arr_to_event_repr(generated_notes)\n generated_muspy = muspy.inputs.from_event_representation(generated_events)\n midi_program = 0\n generated_muspy[0].program = midi_program\n #midi_program = songs_muspy[0][0].program\n # generated_muspy[0].is_drum = True\n\n gen_midi_path = os.path.join(\"..\", \"gen.mid\")\n muspy.write_midi(gen_midi_path, generated_muspy)\n # muspy.visualization.show_pianoroll(generated_muspy)\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"406071139","text":"import sys\n\ndx = [0, 0, -1, 1]\ndy = [1, -1, 0, 0]\n\nsys.setrecursionlimit(10**8)\n\n\ndef dfs(x, y, cnt, part_sum):\n global ans, flag\n # 부분 합이 답보다 크다면 종료\n if part_sum > ans:\n return\n # 3에 도착한다면 답 계산\n if (x, y) == end:\n flag = True\n ans = min(part_sum, ans)\n return\n\n for mode in range(4):\n nx, ny = x + dx[mode], y + dy[mode]\n if 0 <= nx < N and 0 <= ny < M:\n if miro[nx][ny] == '1' and cnt == 0 and not visited[nx][ny]:\n dfs(nx, ny, cnt + 1, part_sum + 1)\n\n elif miro[nx][ny] != '1' and not visited[nx][ny]:\n visited[nx][ny] = 1\n dfs(nx, ny, cnt, part_sum+1)\n visited[nx][ny] = 0\n\n\nN, M = map(int, sys.stdin.readline().split())\nmiro = [list(sys.stdin.readline()) for _ in range(N)]\nvisited = [[0]*M for _ in range(N)]\nans = N*M\nflag = False\n\nstart = (0, 0)\nend = (N-1, M-1)\n\nvisited[start[0]][start[1]] = 1\ndfs(start[0], start[1], 0, 1)\n\nif flag:\n print('{}'.format(ans))\nelse:\n print(-1)","sub_path":"AHYEON/08.DFSBFS/boj_2206_벽 부수고 이동하기.py","file_name":"boj_2206_벽 부수고 이동하기.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"535259246","text":"\"\"\"dmenu-bluetooth\n\nUsage:\n dmenu-bluetooth [--status]\n\"\"\"\n\nimport os\nimport subprocess\nimport sys\nfrom time import sleep\nfrom typing import List\n\nfrom docopt import docopt\n\n__author__ = 'Riccardo Mazzarini (noib3)'\n__email__ = 'riccardo.mazzarini@pm.me'\n\n\n# TODO\n# 1. What's the difference between 'discovering', 'pairing' and 'scanning' in\n# the main menu?\n# 2. remove as much overhead as possible\n# 3. refactor\n# 4. send notifications\n# 5. use emojis\n\nclass Device:\n FORMAT_MENU = \"\"\"\\\n{connected}\n{paired}\n{trusted}\n\"\"\"\n\n def __init__(self, line: str):\n fields = line.split(' ')\n self.address = fields[1]\n self.name = ' '.join(fields[2:])\n\n def __get_info(self) -> str:\n return subprocess.run(\n ['bluetoothctl', 'info', self.address],\n capture_output=True,\n text=True,\n ).stdout\n\n def __is_connected(self) -> bool:\n return 'Connected: yes' in self.__get_info()\n\n def __is_paired(self) -> bool:\n return 'Paired: yes' in self.__get_info()\n\n def __is_trusted(self) -> bool:\n return 'Trusted: yes' in self.__get_info()\n\n def __toggle_connected(self):\n toggle = self.__is_connected() and 'disconnect' or 'connect'\n proc = subprocess.run(['bluetoothctl', toggle, self.address])\n return toggle, proc.returncode\n\n def __toggle_paired(self):\n toggle = self.__is_paired() and 'remove' or 'pair'\n subprocess.run(['bluetoothctl', toggle, self.address])\n\n def __toggle_trusted(self):\n toggle = self.__is_trusted() and 'untrust' or 'trust'\n subprocess.run(['bluetoothctl', toggle, self.address])\n\n def is_connected(self):\n return self.__is_connected()\n\n def show_menu(self):\n \"\"\"A submenu for a specific device that allows connecting, pairing, and\n trusting.\"\"\"\n preselect_index = 0\n while True:\n connected = self.__is_connected() and 'Disconnect' or 'Connect'\n paired = self.__is_paired() and 'Unpair' or 'Pair'\n trusted = self.__is_trusted() and 'Untrust' or 'Trust'\n\n options = self.FORMAT_MENU.format(\n connected=connected,\n paired=paired,\n trusted=trusted,\n )\n\n selection = subprocess.run(\n ['dmenu', '-p', '{}> '.format(self.name),\n '-n', str(preselect_index)],\n capture_output=True,\n text=True,\n input=options,\n ).stdout.rstrip()\n\n if not selection:\n break\n\n elif selection == connected:\n preselect_index = 0\n toggle, ret_code = self.__toggle_connected()\n if toggle == 'connect' and ret_code == 0:\n sys.exit()\n\n elif selection == paired:\n preselect_index = 1\n self.__toggle_paired()\n\n elif selection == trusted:\n preselect_index = 2\n self.__toggle_trusted()\n\n\nclass Bluetooth:\n ICON_POWER_ON = ''\n ICON_POWER_OFF = ''\n ICON_DEVICE_CONNECTED = ''\n\n FORMAT_STATUS = '{icon}{info}'\n FORMAT_MAIN_MENU = \"\"\"\\\n{list_devices}\n{discovering}\n{pairing}\n{scanning}\n{power}\n\"\"\"\n\n def __get_status(self) -> str:\n return subprocess.run(\n ['bluetoothctl', 'show'],\n capture_output=True,\n text=True,\n ).stdout.rstrip()\n\n def __get_paired_devices(self) -> List[Device]:\n devices = subprocess.run(\n ['bluetoothctl', 'paired-devices'],\n capture_output=True,\n text=True,\n ).stdout.rstrip()\n return [Device(line) for line in devices.split('\\n') if line]\n\n def __get_connected_devices(self) -> List[Device]:\n return [d for d in self.__get_paired_devices() if d.is_connected()]\n\n def __is_on(self) -> bool:\n return 'Powered: yes' in self.__get_status()\n\n def __is_discoverable(self) -> bool:\n return 'Discoverable: yes' in self.__get_status()\n\n def __is_pairable(self) -> bool:\n return 'Pairable: yes' in self.__get_status()\n\n def __is_scanning(self) -> bool:\n return 'Discovering: yes' in self.__get_status()\n\n def __toggle_power(self):\n toggle = self.__is_on() and 'off' or 'on'\n proc = subprocess.run(['bluetoothctl', 'power', toggle])\n return toggle, proc.returncode\n\n def __toggle_discovering(self):\n toggle = self.__is_discoverable() and 'off' or 'on'\n subprocess.run(['bluetoothctl', 'discoverable', toggle])\n\n def __toggle_pairing(self):\n toggle = self.__is_pairable() and 'off' or 'on'\n subprocess.run(['bluetoothctl', 'pairable', toggle])\n\n def __toggle_scanning(self):\n if self.__is_scanning():\n scan_pid = int(subprocess.run(\n ['pgrep', '-f', 'bluetoothctl scan on'],\n capture_output=True,\n text=True,\n ).stdout.rstrip())\n os.kill(scan_pid, 9)\n subprocess.run(['bluetoothctl', 'scan', 'off'])\n else:\n subprocess.Popen(['bluetoothctl', 'scan', 'on'])\n sleep(3)\n\n def __show_devices_menu(self):\n preselect_index = 0\n while True:\n paired_devices = self.__get_paired_devices()\n device_names = [\n '{}{}'.format(d.name, d.is_connected() and ' (c)' or '')\n for d in paired_devices\n ]\n\n selection = subprocess.run(\n ['dmenu', '-p', 'Devices> ', '-n', str(preselect_index)],\n capture_output=True,\n text=True,\n input='\\n'.join(device_names),\n ).stdout.rstrip()\n\n if not selection:\n break\n\n elif selection in device_names:\n for i, d in enumerate(paired_devices):\n if d.name in selection:\n preselect_index = i\n d.show_menu()\n break\n\n def print_status(self):\n \"\"\"Prints a short string with the current Bluetooth status.\"\"\"\n if self.__is_on():\n connected_devices = self.__get_connected_devices()\n if len(connected_devices) == 0:\n icon = self.ICON_POWER_ON\n info = ''\n elif len(connected_devices) == 1:\n icon = self.ICON_DEVICE_CONNECTED\n info = ' {}'.format(connected_devices[0].name)\n else:\n icon = self.ICON_DEVICE_CONNECTED\n info = ' {}'.format(len(connected_devices))\n else:\n icon = self.ICON_POWER_OFF\n info = ''\n\n print(self.FORMAT_STATUS.format(icon=icon, info=info))\n\n def show_main_menu(self):\n \"\"\"Launches dmenu with the current Bluetooth status and options to\n connect.\"\"\"\n preselect_index = 0\n while True:\n if self.__is_on():\n icon = (\n len(self.__get_connected_devices()) == 0\n and self.ICON_POWER_ON\n or self.ICON_DEVICE_CONNECTED\n )\n list_devices = 'List devices'\n discovering = '{} discovering'.format(\n self.__is_discoverable() and 'Stop' or 'Start')\n pairing = '{} pairing'.format(\n self.__is_pairable() and 'Stop' or 'Start')\n scanning = '{} scanning'.format(\n self.__is_scanning() and 'Stop' or 'Start')\n power = 'Turn off'\n else:\n icon = self.ICON_POWER_OFF\n list_devices = ''\n discovering = ''\n pairing = ''\n scanning = ''\n power = 'Turn on'\n\n options = '\\n'.join([line for line in self.FORMAT_MAIN_MENU.format(\n list_devices=list_devices,\n discovering=discovering,\n pairing=pairing,\n scanning=scanning,\n power=power,\n ).split('\\n') if line])\n\n selection = subprocess.run(\n ['dmenu', '-p', '{} Bluetooth> '.format(icon),\n '-n', str(preselect_index)],\n capture_output=True,\n text=True,\n input=options,\n ).stdout.rstrip()\n\n if not selection:\n sys.exit()\n\n elif selection == list_devices:\n preselect_index = 0\n self.__show_devices_menu()\n\n elif selection == discovering:\n preselect_index = 1\n self.__toggle_discovering()\n\n elif selection == pairing:\n preselect_index = 2\n self.__toggle_pairing()\n\n elif selection == scanning:\n preselect_index = 3\n self.__toggle_scanning()\n\n elif selection == power:\n preselect_index = 0\n toggle, ret_code = self.__toggle_power()\n if toggle == 'off' and ret_code == 0:\n sys.exit()\n\n\nif __name__ == '__main__':\n args = docopt(__doc__, version='dmenu-bluetooth 0.0.1')\n bluetooth = Bluetooth()\n if args['--status']:\n bluetooth.print_status()\n else:\n bluetooth.show_main_menu()\n","sub_path":"defaults/dmenu/scripts/dmenu-bluetooth.py","file_name":"dmenu-bluetooth.py","file_ext":"py","file_size_in_byte":9393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"93948524","text":"import re\nimport math\n\n\nclass classifier:\n def incf(self, f, cat):\n self.fc.setdefault(f, {})\n self.fc[f].setdefault(cat, 0)\n self.fc[f][cat] += 1\n\n def __init__(self, getfeatures, filename=None):\n # Counts of feature/category combinations\n self.fc = {}\n # Counts of documents in each category\n self.cc = {}\n self.getfeatures = getfeatures\n self.thresholds = {}\n\n def setthreshold(self, cat, threshold):\n self.thresholds[cat] = threshold\n\n def getthreshold(self, cat):\n if cat not in self.thresholds:\n return 1.0\n return self.thresholds[cat]\n\n # Increase the count of a feature/category pair\n def incc(self, cat):\n self.cc.setdefault(cat, 0)\n self.cc[cat] += 1\n # Increase the count of a category\n\n # The number of times a feature has appeared in a category\n def fcount(self, f, cat):\n if f in self.fc and cat in self.fc[f]:\n return float(self.fc[f][cat])\n return 0.0\n\n # The number of times in a category\n def catcount(self, cat):\n if cat in self.cc:\n return float(self.cc[cat])\n return 0\n\n # The total number of items\n def totalcount(self):\n return sum(self.cc.values())\n\n # The list of all categories\n def categories(self):\n return self.cc.keys()\n\n def train(self, item, cat):\n # In our example, features are words\n features = self.getfeatures(item)\n # Increment the count of every feature in this category\n for f in features:\n self.incf(f, cat)\n # Increment the count of this category\n self.incc(cat)\n\n # Calculate probability of feature being in a given category\n def fprob(self, feature, cat):\n if self.catcount(cat) == 0:\n return 0\n # The total number of times this feature appeared in this category divided\n # by the total number of items in this category\n return self.fcount(feature, cat) / self.catcount(cat)\n\n # ap - assumed probablity for when we have very little data\n def weightedprob(self, feature, category, prf, weight=1.0, ap=0.5):\n # Calculate current probability\n basicprob = prf(feature, category)\n # Count the number of times this feature has appeared in all categories\n totals = sum([self.fcount(feature, c) for c in self.categories()])\n # Calculate the weighted average. Here we simply combine real probablity\n # with assumed occurances of this feature (weight) with probablity ap\n return ((weight*ap)+(totals*basicprob))/(weight+totals)\n\n def classify(self, item, default = None):\n probs = {}\n # Find the category with the highest probablity\n max = 0.0\n for cat in self.categories():\n probs[cat] = self.prob(item, cat)\n if probs[cat] > max:\n max = probs[cat]\n best_prob_cat = cat\n # Make sure that found best category probablity is higher then any\n # other category probablity * threshold, return default if its not\n for cat in probs:\n if cat == best_prob_cat:\n continue\n if probs[cat] * self.getthreshold(best_prob_cat) > probs[best_prob_cat]:\n return default\n return best_prob_cat\n\n\nclass naivebayes(classifier):\n # Calculate probability of entire document belonging to a category\n def docprob(self, item, cat):\n features = self.getfeatures(item)\n # Multiply the probablitiesi of all the feautures together\n p = 1\n for f in features:\n p *= self.weightedprob(f, cat, self.fprob)\n return p\n\n def prob(self, item, cat):\n # Probability of given catetory\n catprob = self.catcount(cat)/self.totalcount()\n docprob = self.docprob(item, cat)\n return docprob*catprob\n\n\nclass fisherclassifier(classifier):\n\n def __init__(self, getfeatures):\n classifier.__init__(self, getfeatures)\n self.minimums = {}\n\n def setminimum(self, cat, min):\n self.minimums[cat] = min\n\n def getminimum(self, cat):\n if cat not in self.minimums:\n return 0\n return self.minimums[cat]\n\n def classify(self, item, default = None):\n # Loop through looking for the best result\n best = default\n max = 0.0\n for c in self.categories():\n p = self.fisherprob(item, c)\n # Make sure it exceeds its minimum\n if p > self.getminimum(c) and p > max:\n best = c\n max = p\n return best\n\n def fisherprob(self, item, cat):\n # Multiply all probablities together\n p = 1\n features = self.getfeatures(item)\n for f in features:\n p *= (self.weightedprob(f, cat, self.cprob))\n # Take the natural log and multiply by -2\n fscore = -2*math.log(p)\n # Use the inverse chi2 function to get a probability\n return self.invchi2(fscore, len(features)*2)\n\n def invchi2(self, chi, df):\n m = chi / 2.0\n sum = term = math.exp(-m)\n for i in range(1, df//2):\n term *= m / i\n sum += term\n return min(sum, 1.0)\n\n def cprob(self, f, cat):\n \"\"\"# Calculate probability that specified feature belongs to spciefied category\"\"\"\n # The frequency of this feature in this category\n clf = self.fprob(f, cat)\n if clf == 0:\n return 0\n # The frequency of this feature in all categories\n freqsum = sum([self.fprob(f, c) for c in self.categories()])\n # The probability is the frequency in this category divided by the\n # overall frequency\n return clf/freqsum\n\n\ndef sampletrain(cl):\n cl.train('Nobody owns the water.', 'good')\n cl.train('the quick rabbit jumps fences', 'good')\n cl.train('buy pharmaceuticals now', 'bad')\n cl.train('make quick money at the online casino', 'bad')\n cl.train('the quick brown fox jumps', 'good')\n\ndef getwords(doc):\n splitter = re.compile('\\\\W*')\n # Slit the words by non-alpha characters\n words = [s.lower() for s in splitter.split(doc)\n if 2 < len(s) < 20]\n # Return the unique set of words only\n return dict([(w, 1) for w in words])\n\n\n\n\n","sub_path":"colint/chapter6/docclass.py","file_name":"docclass.py","file_ext":"py","file_size_in_byte":6331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"646216562","text":"from graph import Vertex\nfrom simplestack import SimpleStack\n\nclass Trie:\n '''\n Alphabet trie\n '''\n def __init__(self):\n self.root = TrieNode(\".\") # to signify root node\n\n def add(self, item):\n '''\n Adds a prefix to the trie\n '''\n item = item.lower()\n tokens = list(item)\n current_node = self.root\n\n for token in tokens:\n if token not in current_node.children:\n new_node = TrieNode(token)\n current_node.children[token] = new_node\n current_node = new_node\n else:\n current_node = current_node.children[token]\n current_node.is_leaf = True # set the last item to be a leaf\n\n def is_member(self, item):\n '''\n Checks the trie for a certain prefix\n '''\n item = item.lower()\n tokens = list(item)\n current_node = self.root\n\n for token in tokens:\n if token not in current_node.children:\n return False\n else:\n current_node = current_node.children[token]\n\n return True if current_node.is_leaf_node() else False\n\n def remove(self, item):\n '''\n Case 1: Item is not in trie, do nothing\n Case 2: Item is not a part of any other prefix -> remove all\n Case 3: Item is in trie and has a smaller prefix within it, delete up until that prefix\n Case 4: Item is a prefix of another key in trie, unmark item's leaf\n '''\n if self.is_member(item) is False: # case 1\n return\n\n keys = SimpleStack()\n item = item.lower()\n tokens = list(item)\n current_node = self.root\n\n # get all the nodes\n for token in tokens:\n keys.push(current_node)\n current_node = current_node.children[token]\n\n # unmark the last node\n current_node.is_leaf = False\n last_key = current_node\n if not self._deletable(last_key): # case 4\n return\n\n # remove nodes marked for deletion\n while not keys.is_empty(): # case 2\n current_key = keys.pop()\n del current_key.children[last_key.key]\n if self._deletable(current_key):\n last_key = current_key\n else: # reached case 3\n return\n return\n\n def _deletable(self, node):\n return True if not node.is_leaf_node() and not node.has_children() \\\n else False\n\n def remove_recursive(self, item):\n return\n\n def _remove_recursive_helper(self, node, item, level):\n return\n\n def __str__(self):\n '''\n Lists of lists trie string representation\n '''\n return str(self.__str_helper__(self.root))\n\n def __str_helper__(self, node):\n '''\n Recursive helper\n '''\n if node is None:\n return []\n\n node_list = [node.key]\n\n if len(node.children) == 0:\n return node_list\n else:\n node_list = [node.key]\n for child in node.children.values():\n node_list.append(self.__str_helper__(child))\n return node_list\n\nclass TrieNode:\n def __init__(self, key):\n self.key = key\n self.children = {}\n self.is_leaf = False\n\n def is_leaf_node(self):\n return self.is_leaf\n\n def has_children(self):\n return True if len(self.children) > 0 else False\n\n def __str__(self):\n return \"TrieNode with key: \" + self.key\n\nt = Trie()\nt.add(\"a\")\nt.add(\"answer\")\nt.add(\"any\")\nt.add(\"bye\")\nt.add(\"by\")\nt.add(\"their\")\nt.add(\"there\")\nt.add(\"the\")\n","sub_path":"algorithms/Graphs and Trees/trie.py","file_name":"trie.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"257929240","text":"import copy\nimport random\nimport os\nfrom TSP import TSP\nimport math\nfrom time import process_time\n\n\nclass RallyNode():\n def __init__(self,symbol,connections):\n self.symbol = symbol\n self.connections = connections\n\n\n def search_in_dict(self,key):\n return self.connections.get(key,-1)\n\n def print_node(self):\n return \"Symbol: \" + str(self.symbol) + \"\\n\" + \"Connections: \"+ str(self.connections)\n\nclass Tarefa2():\n\n def geradorMapas(self,n_cidades,symbols):\n cities = symbols[:n_cidades]\n rally_list = []\n temp_dict = {}\n for k in range(len(cities)):\n s = cities[k]\n for i in range(len(cities)):\n if cities[i] != s:\n temp_dict[cities[i]] = random.randint(50,1000)\n new = RallyNode(s,copy.deepcopy(temp_dict))\n rally_list.append(new)\n temp_dict.clear()\n\n return rally_list\n\n def print_map(self,dakar_map):\n print(\"Starts in \" + str(dakar_map[0].symbol)+\"\\n\")\n for i in range(len(dakar_map)):\n for key,value in dakar_map[i].connections.items():\n print(dakar_map[i].symbol + \" ----> \" + key + \"\\t\" + str(value))\n\n def read_symbols(self):\n symbol_list = []\n with open('./symbols.txt') as f:\n for line in f:\n line = line.strip()\n symbol_list.append(line)\n return symbol_list\n\n def search_file(self,path):\n if os.path.isfile(path) and os.access(path, os.R_OK):\n print(\"Ficheiro já existe e é legível\")\n return True\n return False\n\n def save_repeated_file(self,filename,cidades):\n i = 1\n new_name = filename[:-5] + str(cidades) + '(' + str(i) +')'+ \".txt\"\n new_path = \"./\" + new_name\n while self.search_file(new_path):\n i += 1\n new_name = filename[:-5] + str(cidades) + '(' + str(i) + ')'+\".txt\"\n new_path = \"./\" + new_name\n\n return new_name\n\n def write_file(self,rally_list,filename):\n f = open(filename, \"w\")\n for i in range(len(rally_list)):\n for key, value in rally_list[i].connections.items():\n to_file = str(rally_list[i].symbol) + \" \" + key + \" \" + str(value) + \"\\n\"\n f.write(to_file)\n f.close()\n print(\"Dados guardados no ficheiro \"+filename)\n\n def to_file(self,rally_list,n_cidades):\n filename = \"tarefa_2_\"\n filename += str(n_cidades) + \".txt\"\n path = \"./\" + filename\n if self.search_file(path):\n option = input(\"Quer reescrever os dados no mesmo ficheiro?(y/n): \")\n if option == 'n':\n final_name = self.save_repeated_file(filename,n_cidades)\n self.write_file(rally_list,final_name)\n elif option == 'y':\n self.write_file(rally_list,filename)\n else:\n self.write_file(rally_list, filename)\n\n def input_map(self,cidades):\n symbols = self.read_symbols()\n cities = symbols[:cidades]\n rally_list = []\n temp_dict = {}\n print(\"Símbolos escolhidos: \")\n for i in range(cidades):\n print(cities[i])\n for i in range(len(cities)):\n for j in range(len(cities)):\n if cities[j] != cities[i]:\n temp_dict[cities[j]] = eval(input(cities[i] + \"---->\" + cities[j] + \" : \"))\n new = RallyNode(cities[i], copy.deepcopy(temp_dict))\n rally_list.append(new)\n temp_dict.clear()\n return rally_list\n\n def quadratic_equation(self,a,b,c):\n delta = ((-b)**2) - (4*a*c)\n if delta < 0:\n delta = -delta\n s1 = int((-b-math.sqrt(delta)) / (2*a))\n s2 = int((-b+math.sqrt(delta)) / (2*a))\n if s1 < 0:\n return s2\n elif s2 < 0:\n return s1\n\n def get_cidades(self,filename):\n with open(filename) as f:\n for i, l in enumerate(f):\n pass\n return i+1\n\n def get_line_number(self,filename,number):\n with open(filename) as fp:\n for i, line in enumerate(fp):\n if i == number:\n return line.rstrip('\\n')\n\n def load_map(self,filename):\n rally_list = []\n temp_dict = {}\n file_length = self.get_cidades(filename)\n temp = -file_length\n cidades = self.quadratic_equation(1,-1,temp)\n n = cidades\n inicio = 0\n fim = n - 1\n for i in range(n):\n for j in range(inicio,fim):\n new_line = self.get_line_number(filename,j)\n number = new_line[4] + new_line[5]\n try:\n number += new_line[6]\n number += new_line[7]\n temp_dict[new_line[2]] = int(number)\n except IndexError:\n temp_dict[new_line[2]] = int(number)\n simbolo = new_line[0]\n new = RallyNode(simbolo, copy.deepcopy(temp_dict))\n rally_list.append(new)\n temp_dict.clear()\n inicio = fim\n fim = inicio + n - 1\n t = TSP()\n m = t.create_adjancency_maxtrix(rally_list)\n t.solve_tsp(m,rally_list)\n\n\n\n\n\n def main_tarefa2_2(self):\n s = self.read_symbols()\n n_cidades = eval(input(\"Número de cidades: \"))\n new = self.geradorMapas(n_cidades,s)\n self.print_map(new)\n option = input(\"Quer gravar o mapa num ficheiro?(y/n): \")\n if option == 'y':\n self.to_file(new,len(new))\n\n def main_tarefa2_3(self):\n option = input(\"Quer carregar um ficheiro?(y/n): \")\n if option == 'y':\n filename = input(\"Nome do ficheiro: \")\n while not self.search_file(\"./\"+filename):\n filename = input(\"Nome do ficheiro não existe por favor introduza um nome válido: \")\n inicio = process_time()\n self.load_map(filename)\n fim = process_time()\n print(\"Operação concluida em \" + str(fim - inicio) + \" segundos\")\n elif option == 'n':\n n_cidades = eval(input(\"Número de cidades: \"))\n rally_list = self.input_map(n_cidades)\n self.print_map(rally_list)\n print(\"Mapa criado\\n\\n\")\n t = TSP()\n m = t.create_adjancency_maxtrix(rally_list)\n t.solve_tsp(m, rally_list)\n\n\n\n\ndef main():\n s = Tarefa2().read_symbols()\n new = Tarefa2().geradorMapas(4,s)\n Tarefa2().print_map(new)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Tarefa2.py","file_name":"Tarefa2.py","file_ext":"py","file_size_in_byte":6610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"78005165","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2015, Selco and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nfrom frappe.utils import now,now_datetime\nimport operator\nfrom erpnext.accounts.party import get_party_account, get_due_date\nfrom datetime import datetime\nfrom datetime import timedelta\n\n\nclass SelcoCustomizations(Document):\n pass\n\n@frappe.whitelist()\ndef service_call_info():\n #triggerS aT 12 O'clocK\n\n if str(frappe.utils.data.nowtime().split(\":\")[0]) == '13':\n info=frappe.db.sql(\"\"\"SELECT B.day1,B.day2,B.day3,B.day4,B.day5,B.day6,B.day7,B.day8,B.day9,B.day10,B.day11,B.day12,B.day13,B.day14,B.day15,B.day16,B.day17,B.day18,B.day19,B.day20,B.day21,B.day22,B.day23,B.day24,B.day25,B.day26,B.day27,B.day28,B.day29,B.day30,B.day31,B.day1+B.day2+B.day3+B.day4+B.day5+B.day6+B.day7+B.day8+B.day9+B.day10+B.day11+B.day12+B.day13+B.day14+B.day15+B.day16+B.day17+B.day18+B.day19+B.day20+B.day21+B.day22+B.day23+B.day24+B.day25+B.day26+B.day27+B.day28+B.day29+B.day30+B.day31,B.service_person FROM `tabService Call` AS A INNER JOIN `tabService Call Details` AS B ON A.name=B.parent WHERE A.month=MONTHNAME(MONTH(ADDDATE(CURDATE(), -1))*100) \"\"\",as_list=1)\n #0-30 indeX oF numbeR oF callS\n #31 totaL callS\n #32 servicE persoN\n\n todate=int(str((datetime.now()+timedelta(days=-1)).date()).split(\"-\")[2])\n #yesterday'S datE\n i=0\n while i Warranty Claim Number : \" + var5 + \"
Customer Name : \" + var6 + \"
You cannot link same complaint for tow warranty claims.
Please create another complaint.\")\n if doc.workflow_state ==\"Dispatched From Godown\":\n doc.status = \"Closed\"\n \"\"\"if doc.complaint_number and doc.workflow_state == \"Warranty Claim Format Raised - WC\":\n complaint = frappe.get_doc(\"Issue\",doc.complaint_number)\n complaint.warranty_claim_number = doc.name\n complaint.save()\"\"\"\n\n@frappe.whitelist()\ndef get_address_display(address_dict):\n if not address_dict:\n return\n\n if not isinstance(address_dict, dict):\n address_dict = frappe.db.get_value(\"Address\", address_dict, \"*\", as_dict=True) or {}\n\n name, template = get_address_templates(address_dict)\n\n try:\n return frappe.render_template(template, address_dict)\n except TemplateSyntaxError:\n frappe.throw(_(\"There is an error in your Address Template {0}\").format(name))\n\n@frappe.whitelist()\ndef selco_delivery_note_validates(doc,method):\n selco_warehouse = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_warehouse\")\n selco_cost_center = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_cost_center\")\n frappe.msgprint(selco_warehouse)\n frappe.msgprint(selco_cost_center)\n for d in doc.get('items'):\n d.warehouse = selco_warehouse\n d.cost_center = selco_cost_center\n if not d.rate:\n d.rate = frappe.db.get_value(\"Item Price\",{\"price_list\": \"Branch Sales\",\"item_code\":d.item_code}, \"price_list_rate\")\n@frappe.whitelist()\ndef selco_delivery_note_before_insert(doc,method):\n if doc.is_return:\n doc.naming_series = \"DC-RET/\"\n else:\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_delivery_note_naming_series\")\n selco_warehouse = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_warehouse\")\n selco_cost_center = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_cost_center\")\n for d in doc.get('items'):\n d.warehouse = selco_warehouse\n d.cost_center = selco_cost_center\n if not d.rate:\n d.rate = frappe.db.get_value(\"Item Price\",{\"price_list\": \"Branch Sales\",\"item_code\":d.item_code}, \"price_list_rate\")\n\n@frappe.whitelist()\ndef selco_material_request_before_insert(doc,method):\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_material_request_naming_series\")\n local_warehouse = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_git_warehouse\")\n for d in doc.get('items'):\n if not d.warehouse:\n d.warehouse = local_warehouse\n\n@frappe.whitelist()\ndef selco_material_request_validate(doc,method):\n #frappe.msgprint(\"selco_material_request_updates\")\n doc.items.sort(key=operator.attrgetter(\"item_code\"), reverse=False)\n\n selco_material_approved_and_dispatched(doc,method)\n\n if doc.workflow_state == \"Partially Dispatched From Godown - IBM\":\n flag = \"N\"\n for d in doc.get('items'):\n if d.selco_dispatched_quantity != 0:\n flag = \"Y\"\n for d in doc.get('items'):\n if flag != \"Y\":\n d.dispatched_quantity = d.qty\n if doc.workflow_state == \"Dispatched From Godown - IBM\":\n for d in doc.get('items'):\n d.selco_dispatched_quantity = d.qty\n doc.selco_branch_credit_limit = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_branch_credit_limit\")\n doc.selco_senior_sales_manager_email_id = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_senior_sales_manager_email_id\")\n doc.selco_godown_email_id = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_godown_email_id\")\n doc.selco_agms_email_id = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_agm_email_id\")\n #End of Insert By Poorvi on 08-02-2017\n\n@frappe.whitelist()\ndef selco_material_approved_and_dispatched(doc,method):\n #frappe.msgprint(\"selco_material_approved_and_dispatched\")\n\n if doc.workflow_state == \"Approved - IBM\":\n doc.selco_approved_time = now()\n\n elif doc.workflow_state == \"Dispatched From Godown - IBM\":\n doc.selco_dispatched_time = now()\n\n@frappe.whitelist()\ndef selco_purchase_receipt_before_insert(doc,method):\n local_branch = frappe.db.get_value(\"Warehouse\",doc.selco_godown,\"selco_branch\")\n doc.naming_series = frappe.db.get_value(\"Branch\",local_branch,\"selco_mrn_naming_series\")\n\n@frappe.whitelist()\ndef selco_purchase_order_before_insert(doc,method):\n local_branch = frappe.db.get_value(\"Warehouse\",doc.selco_godown,\"selco_branch\")\n doc.naming_series = frappe.db.get_value(\"Branch\",local_branch,\"selco_po_naming_series\")\n\n\n\n@frappe.whitelist()\ndef selco_purchase_order_validate(doc,method):\n from frappe.contacts.doctype.address.address import get_address_display\n local_branch = frappe.db.get_value(\"Warehouse\",doc.selco_godown,\"selco_branch\")\n doc.selco_godown_email = frappe.db.get_value(\"Branch\",local_branch,\"selco_branch_email_id\")\n doc.selco_godown_address = frappe.db.get_value(\"Branch\",local_branch,\"selco_address\")\n doc.selco_godown_address_details = get_address_display(doc.selco_godown_address)\n doc.base_rounded_total= round(doc.base_grand_total)\n advance_local = doc.base_rounded_total * (float(doc.selco_advance_percentage_1) / 100)\n advance_local = round(advance_local)\n balance_local = doc.base_rounded_total - advance_local\n doc.selco_advance_details_currency=advance_local\n doc.selco_balance_details_currency=balance_local\n\n for d in doc.get('items'):\n d.warehouse = doc.selco_godown\n\n\n\n@frappe.whitelist()\ndef selco_purchase_receipt_validate(doc,method):\n local_branch = frappe.db.get_value(\"Warehouse\",doc.selco_godown,\"selco_branch\")\n selco_cost_center = frappe.db.get_value(\"Branch\",local_branch,\"selco_cost_center\")\n\n for d in doc.get('items'):\n d.cost_center = selco_cost_center\n d.warehouse = doc.selco_godown\n for d in doc.get('taxes'):\n d.cost_center = selco_cost_center\n\n\n doc.set('selco_purchase_receipt_item_print', [])\n\n flag=0\n row = doc.append('selco_purchase_receipt_item_print', {})\n row.selco_item_code = doc.items[0].item_code\n row.selco_item_name = doc.items[0].item_name\n row.selco_received_quantity = doc.items[0].received_qty\n row.selco_accepted_quantity = doc.items[0].qty\n row.selco_rejected_quantity = doc.items[0].rejected_qty\n row.selco_rate = doc.items[0].rate\n\n for i,rowi in enumerate(doc.get('items')):\n if (i != 0):\n for j,rowj in enumerate(doc.get('selco_purchase_receipt_item_print')):\n if (doc.items[i].item_code == doc.selco_purchase_receipt_item_print[j].selco_item_code and doc.items[i].item_name == doc.selco_purchase_receipt_item_print[j].selco_item_name):\n flag=1\n doc.selco_purchase_receipt_item_print[j].selco_received_quantity = doc.selco_purchase_receipt_item_print[j].selco_received_quantity+doc.items[i].received_qty\n doc.selco_purchase_receipt_item_print[j].selco_accepted_quantity = doc.selco_purchase_receipt_item_print[j].selco_accepted_quantity+doc.items[i].qty\n doc.selco_purchase_receipt_item_print[j].selco_rejected_quantity = doc.selco_purchase_receipt_item_print[j].selco_rejected_quantity+doc.items[i].rejected_qty\n\n if(flag!= 1):\n r = doc.append('selco_purchase_receipt_item_print', {})\n r.selco_item_code = doc.items[i].item_code\n r.selco_item_name = doc.items[i].item_name\n r.selco_received_quantity = doc.items[i].received_qty\n r.selco_accepted_quantity = doc.items[i].qty\n r.selco_rejected_quantity = doc.items[i].rejected_qty\n r.selco_rate = doc.items[i].rate\n #frappe.msgprint(str(flag))\n flag=0\n po_list = []\n po_list_date = []\n for item_selco in doc.items:\n if item_selco.purchase_order not in po_list:\n po_list.append(item_selco.purchase_order)\n po_list_date.append(frappe.utils.formatdate(frappe.db.get_value('Purchase Order', item_selco.purchase_order, 'transaction_date'),\"dd-MM-yyyy\"))\n doc.selco_list_of_po= ','.join([str(i) for i in po_list])\n doc.selco_list_of_po_date= ','.join([str(i) for i in po_list_date])\n #End of Insert By basawaraj On 7th september for printing the list of PO when PR is done by importing items from multiple PO\n if doc.selco_type_of_purchase == \"Normal\":\n for d in doc.get('items'):\n if not d.purchase_order :\n frappe.throw(\"Purchase Order Is Mandatory\")\n\n\n\n\n\n@frappe.whitelist()\ndef selco_stock_entry_updates(doc,method):\n\n selco_cost_center = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_cost_center\")\n selco_selco_warehouse = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_warehouse\")\n selco_repair_warehouse = frappe.db.get_value(\"Branch\",doc.selco_branch,\"repair_warehouse\")\n\n\n if doc.purpose==\"Material Transfer\":\n if doc.selco_inward_or_outward==\"Inward\" and doc.selco_type_of_stock_entry == \"GRN\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_receipt_note_naming_series\")\n\n if doc.selco_type_of_material==\"Good Stock\":\n doc.from_warehouse = \"SELCO GIT - SELCO\"\n doc.to_warehouse = selco_selco_warehouse\n for d in doc.get('items'):\n d.cost_center = selco_cost_center\n d.from_warehouse = \"SELCO GIT - SELCO\"\n d.to_warehouse = selco_selco_warehouse\n\n else:\n for d in doc.get('items'):\n d.s_warehouse = \"SELCO GIT Repair - SELCO\"\n d.t_warehouse = selco_repair_warehouse\n d.cost_center = selco_cost_center\n d.is_sample_item = 1\n elif doc.selco_inward_or_outward==\"Inward\" and doc.selco_type_of_stock_entry == \"Demo - Material Return\":\n for d in doc.get('items'):\n d.cost_center = selco_cost_center\n d.s_warehouse = \"Demo Warehouse - SELCO\"\n d.t_warehouse = selco_selco_warehouse\n elif doc.selco_inward_or_outward==\"Outward\" and doc.selco_type_of_stock_entry== \"Outward DC\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_delivery_note_naming_series\")\n if doc.selco_type_of_material==\"Good Stock\":\n doc.from_warehouse = selco_selco_warehouse\n frappe.msgprint(selco_selco_warehouse)\n doc.to_warehouse = \"SELCO GIT - SELCO\"\n for d in doc.get('items'):\n d.s_warehouse = selco_selco_warehouse\n d.t_warehouse = \"SELCO GIT - SELCO\"\n d.cost_center = selco_cost_center\n else:\n doc.from_warehouse = selco_repair_warehouse\n doc.to_warehouse = \"SELCO GIT Repair - SELCO\"\n for d in doc.get('items'):\n d.s_warehouse = selco_repair_warehouse\n d.t_warehouse = \"SELCO GIT Repair - SELCO\"\n d.cost_center = selco_cost_center\n d.is_sample_item = 1\n elif doc.selco_inward_or_outward==\"Outward\" and doc.selco_type_of_stock_entry== \"Demo - Material Issue\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_delivery_note_naming_series\")\n for d in doc.get('items'):\n d.s_warehouse = selco_selco_warehouse\n d.t_warehouse = \"Demo Warehouse - SELCO\"\n d.cost_center = selco_cost_center\n elif doc.purpose==\"Material Receipt\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_rejection_in_naming_series\")\n doc.to_warehouse = selco_repair_warehouse\n for d in doc.get('items'):\n d.t_warehouse = selco_repair_warehouse\n d.cost_center = selco_cost_center\n d.is_sample_item = 1\n elif doc.purpose==\"Material Issue\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_rejection_out__naming_series\")\n doc.from_warehouse = selco_repair_warehouse\n for d in doc.get('items'):\n d.f_warehouse = selco_repair_warehouse\n d.cost_center = selco_cost_center\n d.is_sample_item = 1\n elif doc.purpose==\"Repack\":\n if doc.stock_journal == 0:\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_bill_of_material_naming_series\")\n else:\n doc.naming_series = \"SJ/HO/17-18/\"\n for d in doc.get('items'):\n d.cost_center = selco_cost_center\n d.s_warehouse = selco_selco_warehouse\n d.t_warehouse = selco_selco_warehouse\n if d.t_warehouse:\n d.basic_rate = 0\n if doc.selco_type_of_stock_entry == \"Outward DC\":\n doc.selco_recipient_email_id = frappe.db.get_value(\"Branch\",doc.selco_being_dispatched_to,\"selco_branch_email_id\")\n\n@frappe.whitelist()\ndef selco_stock_entry_validate(doc,method):\n from frappe.contacts.doctype.address.address import get_address_display\n if doc.selco_type_of_stock_entry == \"Outward DC\":\n local_warehouse = frappe.db.get_value(\"Branch\",doc.selco_being_dispatched_to,\"selco_warehouse\")\n doc.selco_recipient_address_link = frappe.db.get_value(\"Warehouse\",local_warehouse,\"address\")\n doc.selco_recipient_address = \"\" + doc.selco_being_dispatched_to.upper() + \" BRANCH
\"\n doc.selco_recipient_address+= \"SELCO SOLAR LIGHT PVT. LTD.
\"\n doc.selco_recipient_address+= str(get_address_display(doc.selco_recipient_address_link))\n elif doc.selco_type_of_stock_entry == \"GRN\":\n sender = frappe.db.get_value(\"Stock Entry\",doc.selco_suppliers_ref,\"selco_branch\")\n frappe.msgprint(doc.selco_suppliers_ref)\n sender_warehouse = frappe.db.get_value(\"Branch\",sender,\"selco_warehouse\")\n doc.sender_address_link = frappe.db.get_value(\"Warehouse\",sender_warehouse,\"address\")\n doc.sender_address = \"\" + str(sender) + \" SELCO BRANCH
\"\n doc.sender_address += \"SELCO SOLAR LIGHT PVT. LTD.
\"\n doc.sender_address += str(get_address_display(doc.sender_address_link))\n\n@frappe.whitelist()\ndef get_items_from_outward_stock_entry(selco_doc_num,selco_branch):\n selco_var_dc = frappe.get_doc(\"Stock Entry\",selco_doc_num)\n if selco_var_dc.selco_type_of_stock_entry != \"Demo - Material Issue\" and selco_var_dc.selco_being_dispatched_to != selco_branch:\n frappe.throw(\"Incorrect DC Number\");\n from_warehouse = selco_var_dc.to_warehouse\n if selco_var_dc.selco_type_of_material==\"Good Stock\":\n to_warehouse = frappe.db.get_value(\"Branch\",selco_var_dc.selco_being_dispatched_to,\"selco_warehouse\")\n else:\n to_warehouse = frappe.db.get_value(\"Branch\",selco_var_dc.selco_being_dispatched_to,\"repair_warehouse\")\n return { 'dc' : selco_var_dc,'from_warehouse' : from_warehouse, 'to_warehouse' :to_warehouse }\n\n@frappe.whitelist()\ndef get_items_from_rejection_in(selco_rej_in,selco_branch):\n selco_var_dc = frappe.get_doc(\"Stock Entry\",selco_rej_in)\n return { 'dc' : selco_var_dc }\n\n \"\"\"frappe.msgprint(\"Button Clicked\");\n selco_cost_center = frappe.db.get_value(\"Branch\",selco_branch,\"cost_center\")\n selco_selco_warehouse = frappe.db.get_value(\"Branch\",selco_branch,\"selco_warehouse\")\n selco_repair_warehouse = frappe.db.get_value(\"Branch\",selco_branch,\"repair_warehouse\")\n outward_dc = frappe.get_doc(\"Stock Entry\",selco_doc_num)\n if outward_dc.selco_type_of_material==\"Good Stock\":\n for d in outward_dc.get('items'):\n d.s_warehouse = \"SELCO GIT - SELCO\"\n d.t_warehouse = selco_selco_warehouse\n d.cost_center = selco_cost_center\n else:\n for d in outward_dc.get('items'):\n d.s_warehouse = \"SELCO GIT Repair - SELCO\"\n d.t_warehouse = selco_selco_warehouse\n d.cost_center = selco_cost_center\"\"\"\n\n@frappe.whitelist()\ndef selco_customer_before_insert(doc,method):\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_customer_naming_series\")\n\n@frappe.whitelist()\ndef selco_customer_validate(doc,method):\n if not ( doc.selco_customer_contact_number or doc.selco_landline_mobile_2 ):\n frappe.throw(\"Enter either Customer Contact Number ( Mobile 1 ) or Mobile 2 / Landline\")\n if doc.selco_customer_contact_number:\n if len(doc.selco_customer_contact_number) != 10:\n frappe.throw(\"Invalid Customer Contact Number ( Mobile 1 ) - Please enter exact 10 digits of mobile no ex : 9900038803\")\n selco_validate_if_customer_contact_number_exists(doc.selco_customer_contact_number,doc.name)\n if doc.selco_landline_mobile_2:\n selco_validate_if_customer_contact_number_exists(doc.selco_landline_mobile_2,doc.name)\n\ndef selco_validate_if_customer_contact_number_exists(contact_number,customer_id):\n #frappe.msgprint(frappe.session.user)\n var4 = frappe.db.get_value(\"Customer\", {\"selco_customer_contact_number\": (contact_number)})\n var5 = unicode(var4) or u''\n var6 = frappe.db.get_value(\"Customer\", {\"selco_customer_contact_number\": (contact_number)}, \"customer_name\")\n if var5 != \"None\" and customer_id != var5:\n frappe.throw(\"Customer with contact no \" + contact_number + \" already exists \\n Customer ID : \" + var5 + \"\\n Lead Name : \" + var6)\n\n var14 = frappe.db.get_value(\"Customer\", {\"selco_landline_mobile_2\": (contact_number)})\n var15 = unicode(var14) or u''\n var16 = frappe.db.get_value(\"Customer\", {\"selco_landline_mobile_2\": (contact_number)}, \"customer_name\")\n if var15 != \"None\" and customer_id != var15:\n frappe.throw(\"Customer with contact no \" + contact_number + \" already exists \\n Customer ID : \" + var15 + \"\\n Lead Name : \" + var16)\n\n\n@frappe.whitelist()\ndef selco_sales_invoice_before_insert(doc,method):\n\n doc.selco_customer_contact_number = frappe.db.get_value(\"Customer\",doc.customer,\"selco_customer_contact_number\")\n doc.selco_customer_tin_number = frappe.db.get_value(\"Customer\",doc.customer,\"selco_customer_tin_number\")\n if doc.is_return == 1:\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_credit_note_naming_series\")\n else:\n if doc.selco_type_of_invoice == \"System Sales Invoice\" or doc.selco_type_of_invoice == \"Spare Sales Invoice\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_sales_invoice_naming_series\")\n elif doc.selco_type_of_invoice == \"Service Bill\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_service_bill_naming_series\")\n elif doc.selco_type_of_invoice == \"Bill of Sale\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_bill_of_sales_naming_series\")\n\n@frappe.whitelist()\ndef selco_sales_invoice_validate(doc,method):\n #selco_warehouse = frappe.db.get_value(\"Branch\",doc.branch,\"selco_warehouse\")\n selco_cost_center = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_cost_center\")\n for d in doc.get('items'):\n d.cost_center = selco_cost_center\n d.income_account = doc.selco_sales_account\n for d in doc.get('taxes'):\n d.cost_center = selco_cost_center\n for i,c in enumerate(doc.get('taxes')):\n if doc.taxes[i].account_head == \"Discount Karnataka 14.5% - SELCO\":\n if doc.taxes[i].tax_amount>0:\n doc.taxes[i].tax_amount = doc.taxes[i].tax_amount * -1\ndef selco_payment_entry_before_insert(doc,method):\n if doc.payment_type == \"Receive\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_receipt_naming_series\")\n if doc.mode_of_payment == \"Bank\":\n if doc.amount_credited_to_platinum_account == 1:\n doc.paid_to = frappe.db.get_value(\"Branch\",\"Head Office\",\"selco_collection_account\")\n else:\n doc.paid_to = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_collection_account\")\n elif doc.mode_of_payment == \"Cash\":\n doc.paid_to = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_collection_account_cash\")\n elif doc.payment_type == \"Pay\":\n if doc.mode_of_payment == \"Bank\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_bank_payment_naming_series\")\n doc.paid_from = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_expenditure_account\")\n\ndef selco_payment_entry_validate(doc,method):\n if doc.payment_type == \"Receive\":\n if doc.mode_of_payment == \"Bank\":\n doc.paid_to = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_collection_account\")\n elif doc.mode_of_payment == \"Cash\":\n doc.paid_to = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_collection_account_cash\")\n frappe.msgprint(\"Cash Account is\" + doc.paid_to)\n local_sum = 0\n local_sum = doc.paid_amount\n for deduction in doc.deductions:\n local_sum = local_sum + deduction.amount\n doc.received_amount_with_deduction = local_sum\n\ndef selco_payment_entry_before_delete(doc,method):\n if \"System Manager\" not in frappe.get_roles():\n frappe.throw(\"You cannot delete Payment Entries\")\n\ndef selco_journal_entry_before_insert(doc,method):\n frappe.msgprint(doc.name)\n local_cost_center = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_cost_center\")\n for account in doc.accounts:\n account.cost_center = local_cost_center\n\n if doc.voucher_type == \"Contra Entry\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_contra_naming_series\")\n if doc.voucher_type == \"Cash Payment\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_cash_payment_naming_series\")\n if doc.voucher_type == \"Debit Note\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_debit_note_naming_series\")\n if doc.voucher_type == \"Credit Note\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_credit_note_naming_series\")\n if doc.voucher_type == \"Journal Entry\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_journal_entry_naming_series\")\n if doc.voucher_type == \"Write Off Entry\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_write_off_naming_series\")\n if doc.voucher_type == \"Bank Payment\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_bank_payment_naming_series\")\n if doc.voucher_type == \"Receipt\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_receipt_naming_series\")\n if doc.voucher_type == \"Commission Journal\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_commission_journal_naming_series\")\n \"\"\"if doc.branch == \"Head Office\" and doc.transfer_type == \"Branch Collectiion To Platinum\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.branch,\"bank_payment_collection\")\n elif doc.branch == \"Head Office\" and doc.transfer_type == \"Platinum To Branch Expenditure\":\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.branch,\"bank_payment_expenditure\")\"\"\"\n\n@frappe.whitelist()\ndef selco_journal_entry_validate(doc,method):\n local_cost_center = frappe.db.get_value(\"Branch\",doc.selco_branch,\"selco_cost_center\")\n if doc.selco_use_different_cost_center == 1:\n local_cost_center = doc.selco_alternative_cost_center\n for account in doc.accounts:\n account.cost_center = local_cost_center\n\n@frappe.whitelist()\ndef selco_purchase_invoice_before_insert(doc,method):\n if doc.is_return == 1:\n doc.naming_series = \"DN/HO/16-17/\"\n local_branch = frappe.db.get_value(\"Warehouse\",doc.selco_godown,\"selco_branch\")\n doc.naming_series = frappe.db.get_value(\"Branch\",local_branch,\"selco_purchase_invoice_naming_series\")\n\n\n\n@frappe.whitelist()\ndef selco_purchase_invoice_validate(doc,method):\n from erpnext.accounts.party import get_due_date\n doc.due_date = get_due_date(doc.selco_supplier_invoice_date,\"Supplier\",doc.supplier)\n #doc\n #doc.bill_no = doc.selco_supplier_invoice_number\n #doc.due_date = get_due_date(doc.selco_supplier_invoice_date, \"Supplier\", doc.supplier, doc.company)\"\n\n@frappe.whitelist()\ndef clean_up(doc,method):\n var1 = 1\n #var1 = frappe.get_doc(\"Purchase Receipt\", \"MRN/S/17/004\")\n #var1.cancel()\n #frappe.delete_doc(\"Purchase Receipt\", var1.name)\n #frappe.msgprint(\"Triggered\")\n\n@frappe.whitelist()\ndef selco_lead_before_insert(doc,method):\n doc.naming_series = frappe.db.get_value(\"Branch\",doc.selco_branch,\"lead_naming_series\")\n if doc.selco_project_enquiry == 1:\n doc.naming_series = \"ENQ/17-18/\"\n\n@frappe.whitelist()\ndef selco_lead_validate(doc,method):\n if not ( doc.selco_customer_contact_number__mobile_1 or doc.selco_customer_contact_number__mobile_2_landline ):\n frappe.throw(\"Enter either Customer Contact Number ( Mobile 1 ) or Mobile 2 / Landline\")\n if doc.selco_customer_contact_number__mobile_1 :\n if len(doc.selco_customer_contact_number__mobile_1 ) != 10:\n frappe.throw(\"Invalid Customer Contact Number ( Mobile 1 ) - Please enter exact 10 digits of mobile no ex : 9900038803\")\n selco_validate_if_lead_contact_number_exists(doc.selco_customer_contact_number__mobile_1 ,doc.name)\n if doc.selco_customer_contact_number__mobile_2_landline:\n selco_validate_if_lead_contact_number_exists(doc.selco_customer_contact_number__mobile_2_landline,doc.name)\n\n\ndef selco_validate_if_lead_contact_number_exists(contact_number,lead_id):\n var4 = frappe.db.get_value(\"Lead\", {\"selco_customer_contact_number__mobile_2_landline\": (contact_number)})\n var5 = unicode(var4) or u''\n var6 = frappe.db.get_value(\"Lead\", {\"selco_customer_contact_number__mobile_2_landline\": (contact_number)}, \"lead_name\")\n if var5 != \"None\" and lead_id != var5:\n frappe.throw(\"Lead with contact no \" + contact_number + \" already exists \\n Lead ID : \" + var5 + \"\\n Lead Name : \" + var6)\n\n var14 = frappe.db.get_value(\"Lead\", {\"selco_customer_contact_number__mobile_1\": (contact_number)})\n var15 = unicode(var14) or u''\n var16 = frappe.db.get_value(\"Lead\", {\"selco_customer_contact_number__mobile_1\": (contact_number)}, \"lead_name\")\n if var15 != \"None\" and lead_id != var15:\n frappe.throw(\"Lead with contact no \" + contact_number + \" already exists \\n Lead ID : \" + var15 + \"\\n Lead Name : \" + var16)\n\n@frappe.whitelist()\ndef selco_address_before_insert(doc,method):\n if doc.selco_customer_link:\n temp_name = frappe.get_value(\"Customer\",doc.selco_customer_link,\"customer_name\")\n doc.address_title = doc.selco_customer_link + \" - \" + temp_name\n doc.name = doc.selco_customer_link + \" - \" + temp_name + \" - \"\n if doc.selco_customer_link:\n doc.append(\"links\",{\"link_doctype\":\"Customer\",\"link_name\":doc.selco_customer_link})\n #doc.links[0].link_name=doc.selco_customer_link\n\n\n@frappe.whitelist()\ndef send_birthday_wishes():\n list_of_bday = frappe.db.sql('SELECT salutation,employee_name,designation,branch FROM `tabEmployee` where DAY(date_of_birth) = DAY(CURDATE()) AND MONTH(date_of_birth) = MONTH(CURDATE()) AND status=\"Active\" ',as_list=True)\n bday_wish = \"\"\n if list_of_bday:\n for employee in list_of_bday:\n bday_wish += \" Dear \" + employee[0] + \".\" + employee[1].upper() + \" (\" + employee[2] + \",\" + employee[3] + \") \" + \"\" + \"
\"\n bday_wish += \"
\" + \"सुदिनम् सुदिना जन्मदिनम् तव | भवतु मंगलं जन्मदिनम् || चिरंजीव कुरु कीर्तिवर्धनम् | चिरंजीव कुरुपुण्यावर्धनम् || विजयी भवतु सर्वत्र सर्वदा | जगति भवतु तव सुयशगानम् ||

\"\n bday_wish +=\"​ಸೂರ್ಯನಿಂದ ನಿಮ್ಮೆಡೆಗೆ ಬರುವ ಪ್ರತಿಯೊಂದು ರಶ್ಮಿಯೂ ನಿಮ್ಮ ಬಾಳಿನ ಸಂತಸದ ಕ್ಷಣವಾಗಲಿ ಎಂದು ಹಾರೈಸುತ್ತಾ ಜನುಮ ದಿನದ ಹಾರ್ದಿಕ ​ಶುಭಾಶಯಗಳು​.​

\"\n bday_wish +=\"Wishing you a wonderful day on your birthday. Let this be sacred and auspicious day for you. Wish you long live with a good fame and wish you long live with your good deeds. Wish you always make ever great achievements and let the world praise you for your success. Happy Birthday to our most beloved​. ​ ​SELCO Family wishes you Happy birthday.........!!!!!​​​

\"\n bday_wish +=\"Best Regards
\"\n bday_wish +=\"SELCO Family​​
\"\n local_recipient = []\n local_recipient.append(\"venugopal@selco-india.com\")\n local_recipient.append(\"hr@selco-india.com\")\n frappe.sendmail(\n recipients = local_recipient,\n subject=\"ಹುಟ್ಟುಹಬ್ಬದ ಶುಭಾಶಯಗಳು...............!!! - ERP\",\n message=bday_wish)\n\n@frappe.whitelist()\ndef send_po_reminder():\n list_of_po = frappe.db.sql('SELECT name FROM `tabPurchase Order` where workflow_state = \"AGM Approval Pending - PO\" ',as_list=True)\n po_reminder = \"Please note below mentioned POs are in AGM Approval Pending Status, Please approve the same.
\"\n if list_of_po:\n for name in list_of_po:\n po_reminder += name[0]\n po_reminder += '
'\n local_recipient = []\n local_recipient.append(\"jpai@selco-india.com\")\n frappe.sendmail(\n recipients = local_recipient,\n subject=\"Purchase Order Approval Pending\",\n message=po_reminder)\n\n@frappe.whitelist()\ndef selco_stock_entry_on_submit_updates(doc,method):\n if((doc.selco_type_of_stock_entry == \"Rejection Out\") and (doc.selco_supplier_or_customer == \"Customer\")):\n for item in doc.items:\n ref_doc = frappe.get_doc(\"Stock Entry\",item.reference_rej_in_or_rej_ot)\n #frappe.msgprint(ref_doc)\n for ref_item in ref_doc.items:\n if ref_item.item_code == item.item_code:\n ref_item.reference_rej_in_or_rej_quantity = ref_item.reference_rej_in_or_rej_quantity + item.qty\n if ref_item.reference_rej_in_or_rej_quantity > ref_item.qty:\n frappe.throw(\"Please enter correct Quantity\")\n ref_doc.save()\n if((doc.selco_type_of_stock_entry == \"Rejection In\") and (doc.selco_supplier_or_customer == \"Supplier\")):\n for item in doc.items:\n ref_doc = frappe.get_doc(\"Stock Entry\",item.reference_rej_in_or_rej_ot)\n #frappe.msgprint(ref_doc)\n for ref_item in ref_doc.items:\n if ref_item.item_code == item.item_code:\n ref_item.reference_rej_in_or_rej_quantity = ref_item.reference_rej_in_or_rej_quantity + item.qty\n if ref_item.reference_rej_in_or_rej_quantity > ref_item.qty:\n frappe.throw(\"Please enter correct Quantity\")\n ref_doc.save(ignore_permissions=True)\n if(doc.selco_type_of_stock_entry == \"GRN\"):\n for item in doc.items:\n item.reference_rej_in_or_rej_ot = doc.suppliers_ref\n ref_doc = frappe.get_doc(\"Stock Entry\",doc.selco_suppliers_ref)\n #frappe.msgprint(ref_doc)\n for ref_item in ref_doc.items:\n if (ref_item.item_code == item.item_code and ref_item.item_code == item.item_code):\n ref_item.reference_rej_in_or_rej_quantity = ref_item.reference_rej_in_or_rej_quantity + item.qty\n if ref_item.reference_rej_in_or_rej_quantity > ref_item.qty:\n frappe.throw(\"Please enter correct Quantity\")\n ref_doc.save(ignore_permissions=True)\n if(doc.selco_type_of_stock_entry == \"Outward DC\"):\n pass\n \"\"\"recipient_email_id = frappe.db.get_value(\"Branch\",doc.selco_being_dispatched_to,\"selco_branch_email_id\")\n dc_submitted = \"Please note new outwrad DC \" + doc.name + \" has been submitted
\"\n frappe.sendmail(\n recipients = recipient_email_id,\n subject=\"Materials Dispatched To Your Branch\",\n message=dc_submitted)\"\"\"\n\n@frappe.whitelist()\ndef selco_stock_entry_on_cancel_updates(doc,method):\n if(doc.selco_type_of_stock_entry == \"Rejection Out\"):\n for item in doc.items:\n ref_doc = frappe.get_doc(\"Stock Entry\",item.reference_rej_in_or_rej_ot)\n for ref_item in ref_doc.items:\n if ref_item.item_code == item.item_code:\n ref_item.reference_rej_in_or_rej_quantity = ref_item.reference_rej_in_or_rej_quantity - item.qty\n ref_doc.save()\n \"\"\"if(doc.type_of_stock_entry == \"Rejection In\"):\n for item in doc.items:\n ref_doc = frappe.get_doc(\"Stock Entry\",item.reference_rej_in_or_rej_ot)\n for ref_item in ref_doc.items:\n if ref_item.item_code == item.item_code:\n ref_item.reference_rej_in_or_rej_quantity = ref_item.reference_rej_in_or_rej_quantity - item.qty\n ref_doc.save()\"\"\"\n if(doc.selco_type_of_stock_entry == \"GRN\"):\n for item in doc.items:\n ref_doc = frappe.get_doc(\"Stock Entry\",item.reference_rej_in_or_rej_ot)\n for ref_item in ref_doc.items:\n if ref_item.item_code == item.item_code:\n ref_item.reference_rej_in_or_rej_quantity = ref_item.reference_rej_in_or_rej_quantity - item.qty\n ref_doc.save()\n\n\"\"\"@frappe.whitelist()\ndef cleanup_si():\n for d in frappe.db.get_all(\"Sales Invoice\",filters={\"type_of_invoice\": \"Spare Sales Invoice\"}):\n si = frappe.get_doc(\"Sales Invoice\",d.name)\n si.cancel()\n si.delete()\n for d in frappe.db.get_all(\"Sales Invoice\",filters={\"type_of_invoice\": \"System Sales Invoice\"}):\n si = frappe.get_doc(\"Sales Invoice\",d.name)\n si.cancel()\n si.delete()\n for d in frappe.db.get_all(\"Sales Invoice\",filters={\"type_of_invoice\": \"Service Bill\"}):\n si = frappe.get_doc(\"Sales Invoice\",d.name)\n si.cancel()\n si.delete()\ndef cleanup_dc():\n for d in frappe.db.get_all(\"Delivery Note\",filters={\"docstatus\": 2 }):\n dc = frappe.get_doc(\"Delivery Note\",d.name)\n dc.delete()\n for d in frappe.db.get_all(\"Delivery Note\",filters={\"docstatus\": 0 }):\n dc = frappe.get_doc(\"Delivery Note\",d.name)\n dc.delete()\n for d in frappe.db.get_all(\"Delivery Note\"):\n dc = frappe.get_doc(\"Delivery Note\",d.name)\n dc.cancel()\n dc.delete()\ndef cleanup_se():\n for d in frappe.db.get_all(\"Stock Entry\",filters={\"docstatus\": 0 }):\n dc = frappe.get_doc(\"Stock Entry\",d.name)\n dc.delete()\n se_list = frappe.db.sql(\"select name from `tabStock Entry` where NULLIF(amended_from, '') IS NOT NULL AND docstatus AND purpose = 'Material Transfer' \",as_list = True)\n for d in se_list:\n dc = frappe.get_doc(\"Stock Entry\",d[0])\n dc.cancel()\n dc.delete()\"\"\"\n@frappe.whitelist()\ndef selco_create_customer(selco_branch,customer_group,customer_name,selco_customer_contact_number,selco_landline_mobile_2,selco_gender,selco_electrification_status):\n local_cust = frappe.new_doc(\"Customer\")\n local_cust.selco_branch = selco_branch\n local_cust.customer_group = customer_group\n local_cust.customer_name = customer_name\n local_cust.selco_customer_contact_number = selco_customer_contact_number\n local_cust.selco_landline_mobile_2 = selco_landline_mobile_2\n local_cust.selco_gender = selco_gender\n local_cust.selco_electrification_status = selco_electrification_status\n local_cust.insert()\n return local_cust.name,local_cust.customer_name\n@frappe.whitelist()\ndef selco_add_new_address(selco_branch,address_type,address_line1,address_line2,city,selco_district,country,customer,address_title):\n from frappe.contacts.doctype.address.address import get_address_display\n local_address = frappe.new_doc(\"Address\")\n local_address.selco_branch = selco_branch\n local_address.address_type = address_type\n local_address.address_line1 = address_line1\n local_address_line2 = address_line2\n local_address.city = city\n local_address.selco_district = selco_district\n local_address.country = country\n local_address.customer = customer\n\n local_address.address_title= address_title\n local_address.insert()\n return local_address.name,str(get_address_display(local_address.name))\n\n@frappe.whitelist()\ndef selco_purchase_receipt_cancel_updates():\n from erpnext.buying.doctype.purchase_order.purchase_order import update_status\n mrn_list = frappe.db.sql(\"\"\"SELECT name FROM `tabPurchase Receipt` where posting_date < '2016-06-11' \"\"\",as_list=True)\n for mrn in mrn_list:\n local_mrn = frappe.get_doc(\"Purchase Receipt\",mrn[0])\n closed_po = []\n if local_mrn.status == \"To Bill\":\n for item in local_mrn.items:\n local_po1 = frappe.get_doc(\"Purchase Order\",item.purchase_order)\n if local_po1.status == \"Closed\":\n closed_po.append(local_po1.name)\n update_status('To Receive and Bill',local_po1.name)\n #local_po1.status = \"To Receive and Bill\"\n #local_po1.save()\n local_mrn.cancel()\n for po in closed_po:\n update_status('Closed',po)\n@frappe.whitelist()\ndef selco_stock_entry_cancel_updates():\n dc_list = frappe.db.sql(\"\"\"SELECT name FROM `tabStock Entry` where posting_date BETWEEN '2017-10-01' AND '2017-10-02' ORDER BY posting_date DESC \"\"\",as_list=True)\n for dc in dc_list:\n local_dc = frappe.get_doc(\"Stock Entry\",dc[0])\n if local_dc.docstatus == 1:\n local_dc.cancel()\n\n@frappe.whitelist()\ndef selco_test_print():\n #my_attachments = [frappe.attach_print(\"Purchase Order\", \"PO/MPL/16-17/00468\", file_name=\"po_file\",print_format=\"SELCO PO\")]\n my_attachments = []\n local_var = []\n receipt_list = frappe.db.sql(\"\"\"SELECT name from `tabPayment Entry` where posting_date BETWEEN \"20170901\" AND \"20170930\" \"\"\",as_dict=True)\n for receipt in receipt_list:\n local_var += frappe.attach_print(\"Payment Entry\", receipt, file_name=\"Receipts\",print_format=\"SELCO_Receipt_4_Copies\")\n my_attachments = local_var\n frappe.sendmail(\n recipients = [\"basawaraj@selco-india.com\"],\n subject=\"Your PO\",\n message=\"PO\",\n attachments=my_attachments,\n now=True)\n","sub_path":"selco/selco/selco_customizations.py","file_name":"selco_customizations.py","file_ext":"py","file_size_in_byte":42952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"570148092","text":"def InputBoard():\n board = []\n for row in range(0, 3):\n board.append([])\n string = input(\"What is the next row? \")\n for piece in string:\n board[row].append(piece)\n return board\n\ndef CalculateScore(board, values):\n black = 0\n white = 0\n for row in board:\n for piece in row:\n if piece!=\"k\" and piece!=\"K\" and piece!=\"-\":\n if piece.isupper():\n black += values[piece]\n elif piece.islower():\n white += values[piece]\n print(\"black:\", end = \"\")\n print(black)\n print(\"white:\", end = \"\")\n print(white)\n if black>white:\n print(\"Black is winning\")\n elif white>black:\n print(\"White is winning\")\n else:\n print(\"They are tied\")\ndef Main():\n values = {\"p\": 1, \"P\": 1, \"r\": 5, \"R\": 5, \"n\": 3, \"N\": 3, \"b\": 3, \"B\": 3, \"q\": 10, \"Q\": 10}\n board = InputBoard()\n CalculateScore(board, values)\n\nMain()","sub_path":"Comp 1405B/assigments/assignment 5/Larose_101013798_A5/Larose_101013798_Q2/Larose_101013798_Q2.py","file_name":"Larose_101013798_Q2.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"82090731","text":"import pytest\nfrom django.contrib.auth import get_user_model\nfrom allauth.account.models import EmailAddress\n\nUser = get_user_model()\n\n\n@pytest.fixture\ndef user(transactional_db):\n \"\"\"Fixture creating a user with a verified email.\"\"\"\n user = User.objects.create_user(\n \"testuser\", \"testuser@oc.com\", \"asdnFSdh7sd8Fa8f\"\n )\n EmailAddress.objects.create(\n user=user, email=\"testuser@oc.com\", verified=True, primary=True\n )\n yield user","sub_path":"tests/functional/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"439896530","text":"from collections import namedtuple\n\nfrom madison_wcb import wcb\n\n\n### Watercolor helper functions\n\ndef draw_box(color_index, x, y, width, height):\n wcb.get_color(color_index)\n wcb.move_to(x, y)\n wcb.brush_down()\n\n wcb.point_in_direction(0)\n wcb.move_forward(width)\n wcb.turn_right(90)\n wcb.move_forward(height)\n wcb.turn_right(90)\n wcb.move_forward(width)\n wcb.turn_right(90)\n wcb.move_forward(height)\n wcb.brush_up()\n wcb.wash_brush()\n\n### Game code\n\nRoom = namedtuple(\"Room\", [\"id\", \"x\", \"y\", \"width\", \"height\", \"color_index\", \"description_fn\"])\n\ndef describe_kitchen():\n description = \"A kitchen. It's very tidy.\"\n\n if state['jar_opened']:\n if state['frank_fed']:\n description += \"\\nThere's a huge jar of cat treats on the counter.\"\n else:\n description += \"\\nThere's a huge jar of cat treats on the counter. It's open.\"\n else:\n description += \"\\nThere's a huge jar of cat treats on the counter. It's tightly closed so that Frank can't get into it.\"\n\n return description\n\ndef describe_hallway():\n description = \"A hallway.\"\n\n if state['frank_fed']:\n description += \"\\nA giant picture of your family used to hang on the wall, but it's been knocked down somehow.\\nThere's a weird door behind where the picture used to be.\"\n else:\n description += \"\\nA giant picture of your family hangs on the wall. It's incredibly big, stretching from the floor to the ceiling.\"\n\n return description\n\ndef describe_your_room():\n if state['lights_on']:\n description = \"Your room. Your bed is unmade.\"\n if not state['key_taken']:\n description += \"\\nYour favorite book is on the nightstand. There's a weird key next to it.\"\n\n else:\n description = \"It's too dark to see anything. You should probably turn on the lights.\"\n\n return description\n\nworld = {\n 'rooms': [\n Room(0, -130, 50, 50, 50, 4, lambda: \"A living room. There is a comfy couch here, but you don't want to sit in it right now.\"),\n Room(1, -130, 0, 50, 50, 1, lambda: \"A dining room. Not much going on in here.\"),\n Room(2, -170, 50, 40, 50, 2, lambda: \"A bathroom. It's not very interesting.\"),\n Room(3, -180, 0, 50, 50, 3, describe_kitchen),\n Room(4, -230, 0, 50, 50, 0, lambda: \"A garage. It's empty - you're all alone for the weekend.\"),\n Room(5, -80, 50, 150, 50, 5, describe_hallway),\n Room(6, -50, 100, 100, 50, 6, describe_your_room),\n Room(7, 70, 50, 100, 100, 7, lambda: \"Your parents' room. You're not supposed to be in here.\"),\n Room(8, -30, 0, 50, 50, 4, lambda: \"You walk through the weird door and into a strange closet.\"),\n ],\n # A map of {room_id -> {direction_string: room_id}},\n # indicating which rooms are connected to which.\n 'connections': {\n 0: {'west': 2, 'south': 1, 'east': 5},\n 1: {'north': 0, 'west': 3},\n 2: {'east': 0, 'south': 3},\n 3: {'north': 2, 'east': 1, 'west': 4},\n 4: {'east': 3},\n 5: {'west': 0, 'north': 6, 'east': 7},\n 6: {'south': 5},\n 7: {'west': 5},\n }\n}\n\nstate = {\n 'current_room': world['rooms'][0],\n 'drawn_rooms': set(),\n 'jar_opened': False,\n 'frank_fed': False,\n 'key_taken': False,\n 'lights_on': False,\n}\n\ndef travel_in_direction(direction):\n connections = world['connections'][state['current_room'].id]\n\n if direction in connections:\n state['current_room'] = world['rooms'][connections[direction]]\n render_room(state['current_room'])\n else:\n print(\"There isn't an exit in that direction.\")\n\n\ndef process_command(command):\n command = command.lower()\n words = command.split(\" \")\n in_kitchen = state['current_room'].id == 3\n in_hallway = state['current_room'].id == 5\n in_your_room = state['current_room'].id == 6\n\n if words[0] == \"go\":\n travel_in_direction(words[1])\n\n elif command == \"help\":\n print(\"\"\"Here are some example commands to try:\nlook\ngo east\npet frank\ntake key\nopen jar\n\nThere are other commands, too, but you've got to figure them out on your own!\"\"\")\n\n elif command == \"look\":\n render_room(state['current_room'])\n\n elif command == \"pet frank\":\n print(\"You pet Frank. He purrs contentedly.\")\n\n elif in_kitchen and command in (\"open jar\", \"take lid off jar\", \"open the jar\", \"take the lid off the jar\"):\n if state['jar_opened']:\n print(\"The jar's already open.\")\n else:\n state['jar_opened'] = True\n print(\"You take the lid off the jar. Frank is frantic with excitement.\")\n\n elif in_kitchen and command in (\"feed frank\", \"give frank a treat\", \"give treat to frank\", \"give a treat to frank\", \"feed frank a treat\"):\n if state['frank_fed']:\n print(\"Frank's full and doesn't want any more treats.\")\n else:\n state['frank_fed'] = True\n print(\"\"\"Frank gobbles down the treat.\nHe's suddenly filled with energy. He bolts out of the room and runs a lap around the house.\n\nYou hear a loud crash off in the distance.\n\nFrank returns and sits by your feet. He purrs happily.\"\"\")\n\n elif in_your_room and command in (\"flip switch\", \"turn lights on\", \"turn on lights\", \"turn light on\", \"turn on light\", \"turn on the lights\", \"turn on lights\", \"turn on the light\"):\n if state['lights_on']:\n print(\"The lights are already on.\")\n else:\n state['lights_on'] = True\n print(\"You flip the light switch. The lights turn on - you can see well enough to look around now.\")\n\n elif in_your_room and command in (\"take key\", \"take the key\", \"pick up the key\", \"get the key\", \"get key\", \"pick up key\", \"take weird key\") and not state['key_taken']:\n state['key_taken'] = True\n print(\"You take the weird key.\")\n\n elif in_hallway and command in (\"open door\", \"open the door\") and not state['key_taken']:\n print(\"It's locked.\")\n\n elif in_hallway and command in (\"open door\", \"open the door\", \"unlock door\", \"unlock the door\") and state['key_taken']:\n print(\"You use the weird key to unlock the weird door. The door swings open.\\n\")\n\n # Add connection from hallway to end room.\n world['connections'][5]['south'] = 8\n\n render_room(state['current_room'])\n\n else:\n print(\"I don't know how to do that. Try something like 'go east' or 'help'.\")\n\ndef render_room(room):\n if room.id not in state['drawn_rooms']:\n state['drawn_rooms'].add(room.id)\n draw_box(room.color_index, room.x, room.y, room.width, room.height)\n\n wcb.move_to(room.x + room.width / 2, room.y - room.height / 2)\n\n print(room.description_fn() + \"\\n\")\n if room.id in world['connections']:\n exits = world['connections'][room.id]\n print(\"There are exits in these directions: {0}\".format(', '.join(exits.keys())))\n\n\ndef play():\n wcb.initialize()\n\n print(\"\"\"You're sitting on the couch in your living room, absentmindedly petting your cat Frank,\nwhen a local news report on the TV catches your attention:\n\n\"...that's right, Bob, this year's winter is going to be just truly, unbelievably dark.\nIt's barely October, and Portland residents are already preparing for the worst;\nmarshmallows and blankets are flying off store shelves, and there isn't a single\nSAD lamp left for sale in the entire city.\"\n\nOh no, it's almost winter! Your mom gave you a SAD lamp last year when you were feeling\nsuper depressed, and it sounds like you're really going to need it this year.\nNow where did you put it?\n\nSuddenly nothing in the world is more important to you than finding your special lamp.\nYou jump off the couch and begin your search. Frank follows you, meowing hungrily.\n\n[This game is a text adventure. Type commands after the >>> and press \"enter\". Type \"help\"\nto see a list of some example commands.]\n\"\"\")\n\n render_room(state['current_room'])\n\n while True:\n if state['current_room'] == world['rooms'][-1]:\n print(\"\"\"You've found your SAD lamp! You can't remember why you put it here in the first place, but that doesn't matter now.\nExhausted, you turn the lamp on and flop down next to it.\nFrank meows happily and curls up next to you, basking in the lamp's glorious blue glow.\n\"\"\")\n wcb.park()\n input(\"Congratulations, you've beaten the game! Press Enter to quit.\")\n break\n\n print('')\n process_command(input(\">>> \"))\n\n\nif __name__ == '__main__':\n play()\n","sub_path":"waterventure.py","file_name":"waterventure.py","file_ext":"py","file_size_in_byte":8512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"33821667","text":"from conans.client.store.sqlite import SQLiteDB\nfrom conans.errors import ConanException\n\nUSER_TABLE = \"users\"\n\n\nclass LocalDB(SQLiteDB):\n\n def __init__(self, dbfile):\n self.dbfile = dbfile\n super(LocalDB, self).__init__(dbfile)\n self.connect()\n self.init()\n\n def init(self):\n SQLiteDB.init(self)\n cursor = None\n try:\n cursor = self.connection.cursor()\n\n # To avoid multiple usernames in the login table, use always \"login\" as id\n cursor.execute(\"create table if not exists %s (id TEXT UNIQUE, \"\n \"username TEXT UNIQUE, token TEXT)\" % USER_TABLE)\n\n except Exception as e:\n message = \"Could not initalize local cache\"\n raise ConanException(message, e)\n finally:\n if cursor:\n cursor.close()\n\n def get_login(self):\n '''Returns login credentials.\n This method is also in charge of expiring them.\n '''\n try:\n statement = self.connection.cursor()\n statement.execute('select * from %s where id=\"login\"' % USER_TABLE)\n rs = statement.fetchone()\n if not rs:\n return None, None\n name = rs[1]\n token = rs[2]\n return name, token\n except Exception:\n raise ConanException(\"Could read login\\n Try removing '%s' file\" % self.dbfile)\n\n def get_username(self):\n return self.get_login()[0]\n\n def set_login(self, login):\n \"\"\"Login is a tuple of (login, token)\"\"\"\n try:\n statement = self.connection.cursor()\n statement.execute(\"INSERT OR REPLACE INTO %s (id, username, token) \"\n \"VALUES (?, ?, ?)\" % USER_TABLE,\n (\"login\", login[0], login[1]))\n self.connection.commit()\n except Exception as e:\n raise ConanException(\"Could not store credentials\", e)\n","sub_path":"conans/client/store/localdb.py","file_name":"localdb.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"490640454","text":"from collections.abc import Sequence as AbstractSequence\nfrom functools import reduce\nfrom typing import Any, Dict, List, Optional, Sequence, Set, cast\n\nfrom ..error import GraphQLError\nfrom ..language import ast\nfrom ..pyutils import inspect, FrozenList\nfrom .definition import (\n GraphQLAbstractType,\n GraphQLInterfaceType,\n GraphQLNamedType,\n GraphQLObjectType,\n GraphQLUnionType,\n GraphQLInputObjectType,\n GraphQLWrappingType,\n is_abstract_type,\n is_input_object_type,\n is_interface_type,\n is_named_type,\n is_object_type,\n is_union_type,\n is_wrapping_type,\n)\nfrom .directives import GraphQLDirective, specified_directives, is_directive\nfrom .introspection import introspection_types\n\n__all__ = [\"GraphQLSchema\", \"is_schema\", \"assert_schema\"]\n\n\nTypeMap = Dict[str, GraphQLNamedType]\n\n\nclass GraphQLSchema:\n \"\"\"Schema Definition\n\n A Schema is created by supplying the root types of each type of operation, query\n and mutation (optional). A schema definition is then supplied to the validator\n and executor.\n\n Example::\n\n MyAppSchema = GraphQLSchema(\n query=MyAppQueryRootType,\n mutation=MyAppMutationRootType)\n\n Note: When the schema is constructed, by default only the types that are\n reachable by traversing the root types are included, other types must be\n explicitly referenced.\n\n Example::\n\n character_interface = GraphQLInterfaceType('Character', ...)\n\n human_type = GraphQLObjectType(\n 'Human', interfaces=[character_interface], ...)\n\n droid_type = GraphQLObjectType(\n 'Droid', interfaces: [character_interface], ...)\n\n schema = GraphQLSchema(\n query=GraphQLObjectType('Query',\n fields={'hero': GraphQLField(character_interface, ....)}),\n ...\n # Since this schema references only the `Character` interface it's\n # necessary to explicitly list the types that implement it if\n # you want them to be included in the final schema.\n types=[human_type, droid_type])\n\n Note: If a list of `directives` are provided to GraphQLSchema, that will be the\n exact list of directives represented and allowed. If `directives` is not provided,\n then a default set of the specified directives (e.g. @include and @skip) will be\n used. If you wish to provide *additional* directives to these specified directives,\n you must explicitly declare them. Example::\n\n MyAppSchema = GraphQLSchema(\n ...\n directives=specified_directives + [my_custom_directive])\n \"\"\"\n\n query_type: Optional[GraphQLObjectType]\n mutation_type: Optional[GraphQLObjectType]\n subscription_type: Optional[GraphQLObjectType]\n type_map: TypeMap\n directives: FrozenList[GraphQLDirective]\n ast_node: Optional[ast.SchemaDefinitionNode]\n extension_ast_nodes: Optional[FrozenList[ast.SchemaExtensionNode]]\n\n def __init__(\n self,\n query: GraphQLObjectType = None,\n mutation: GraphQLObjectType = None,\n subscription: GraphQLObjectType = None,\n types: Sequence[GraphQLNamedType] = None,\n directives: Sequence[GraphQLDirective] = None,\n ast_node: ast.SchemaDefinitionNode = None,\n extension_ast_nodes: Sequence[ast.SchemaExtensionNode] = None,\n assume_valid: bool = False,\n ) -> None:\n \"\"\"Initialize GraphQL schema.\n\n If this schema was built from a source known to be valid, then it may be marked\n with `assume_valid` to avoid an additional type system validation. Otherwise\n check for common mistakes during construction to produce clear and early error\n messages.\n \"\"\"\n if assume_valid:\n # If this schema was built from a source known to be valid, then it may be\n # marked with assume_valid to avoid an additional type system validation.\n self._validation_errors: Optional[List[GraphQLError]] = []\n else:\n # Otherwise check for common mistakes during construction to produce clear\n # and early error messages.\n if types is None:\n types = []\n else:\n if not isinstance(types, AbstractSequence) or (\n # if reducer has been overridden, don't check types\n getattr(self.type_map_reducer, \"__func__\", None)\n is GraphQLSchema.type_map_reducer\n and not all(is_named_type(type_) for type_ in types)\n ):\n raise TypeError(\n \"Schema types must be specified as a sequence\"\n \" of GraphQLNamedType instances.\"\n )\n if directives is not None:\n # noinspection PyUnresolvedReferences\n if not isinstance(directives, AbstractSequence) or (\n # if reducer has been overridden, don't check directive types\n getattr(self.type_map_directive_reducer, \"__func__\", None)\n is GraphQLSchema.type_map_directive_reducer\n and not all(is_directive(directive) for directive in directives)\n ):\n raise TypeError(\n \"Schema directives must be specified as a sequence\"\n \" of GraphQLDirective instances.\"\n )\n if not isinstance(directives, FrozenList):\n directives = FrozenList(directives)\n if ast_node and not isinstance(ast_node, ast.SchemaDefinitionNode):\n raise TypeError(\"Schema AST node must be a SchemaDefinitionNode.\")\n if extension_ast_nodes:\n if not isinstance(extension_ast_nodes, AbstractSequence) or not all(\n isinstance(node, ast.SchemaExtensionNode)\n for node in extension_ast_nodes\n ):\n raise TypeError(\n \"Schema extension AST nodes must be specified\"\n \" as a sequence of SchemaExtensionNode instances.\"\n )\n if not isinstance(extension_ast_nodes, FrozenList):\n extension_ast_nodes = FrozenList(extension_ast_nodes)\n\n self._validation_errors = None\n\n self.query_type = query\n self.mutation_type = mutation\n self.subscription_type = subscription\n # Provide specified directives (e.g. @include and @skip) by default\n self.directives = (\n specified_directives\n if directives is None\n else cast(FrozenList[GraphQLDirective], directives)\n )\n self.ast_node = ast_node\n self.extension_ast_nodes = (\n cast(FrozenList[ast.SchemaExtensionNode], extension_ast_nodes)\n if extension_ast_nodes\n else None\n )\n\n # Build type map now to detect any errors within this schema.\n initial_types: List[Optional[GraphQLNamedType]] = [\n query,\n mutation,\n subscription,\n introspection_types[\"__Schema\"],\n ]\n if types:\n initial_types.extend(types)\n\n # Keep track of all types referenced within the schema.\n type_map: TypeMap = {}\n # First by deeply visiting all initial types.\n type_map = reduce(self.type_map_reducer, initial_types, type_map)\n # Then by deeply visiting all directive types.\n type_map = reduce(self.type_map_directive_reducer, self.directives, type_map)\n # Storing the resulting map for reference by the schema\n self.type_map = type_map\n\n self._possible_type_map: Dict[str, Set[str]] = {}\n\n # Keep track of all implementations by interface name.\n self._implementations: Dict[str, List[GraphQLObjectType]] = {}\n setdefault = self._implementations.setdefault\n for type_ in self.type_map.values():\n if is_object_type(type_):\n type_ = cast(GraphQLObjectType, type_)\n for interface in type_.interfaces:\n if is_interface_type(interface):\n setdefault(interface.name, []).append(type_)\n elif is_abstract_type(type_):\n setdefault(type_.name, [])\n\n def to_kwargs(self) -> Dict[str, Any]:\n return dict(\n query=self.query_type,\n mutation=self.mutation_type,\n subscription=self.subscription_type,\n types=FrozenList(self.type_map.values()) or None,\n directives=None\n if self.directives is specified_directives\n else self.directives,\n ast_node=self.ast_node,\n extension_ast_nodes=self.extension_ast_nodes or None,\n assume_valid=self._validation_errors is not None,\n )\n\n def get_type(self, name: str) -> Optional[GraphQLNamedType]:\n return self.type_map.get(name)\n\n def get_possible_types(\n self, abstract_type: GraphQLAbstractType\n ) -> Sequence[GraphQLObjectType]:\n \"\"\"Get list of all possible concrete types for given abstract type.\"\"\"\n if is_union_type(abstract_type):\n abstract_type = cast(GraphQLUnionType, abstract_type)\n return abstract_type.types\n return self._implementations[abstract_type.name]\n\n def is_possible_type(\n self, abstract_type: GraphQLAbstractType, possible_type: GraphQLObjectType\n ) -> bool:\n \"\"\"Check whether a concrete type is possible for an abstract type.\"\"\"\n possible_type_map = self._possible_type_map\n try:\n possible_type_names = possible_type_map[abstract_type.name]\n except KeyError:\n possible_types = self.get_possible_types(abstract_type)\n possible_type_names = {type_.name for type_ in possible_types}\n possible_type_map[abstract_type.name] = possible_type_names\n return possible_type.name in possible_type_names\n\n def get_directive(self, name: str) -> Optional[GraphQLDirective]:\n for directive in self.directives:\n if directive.name == name:\n return directive\n return None\n\n @property\n def validation_errors(self):\n return self._validation_errors\n\n def type_map_reducer(\n self, map_: TypeMap, type_: GraphQLNamedType = None\n ) -> TypeMap:\n \"\"\"Reducer function for creating the type map from given types.\"\"\"\n if not type_:\n return map_\n if is_wrapping_type(type_):\n return self.type_map_reducer(\n map_, cast(GraphQLWrappingType[GraphQLNamedType], type_).of_type\n )\n name = type_.name\n if name in map_:\n if map_[name] is not type_:\n raise TypeError(\n \"Schema must contain uniquely named types but contains multiple\"\n f\" types named {name!r}.\"\n )\n return map_\n map_[name] = type_\n\n if is_union_type(type_):\n type_ = cast(GraphQLUnionType, type_)\n map_ = reduce(self.type_map_reducer, type_.types, map_)\n\n if is_object_type(type_):\n type_ = cast(GraphQLObjectType, type_)\n map_ = reduce(self.type_map_reducer, type_.interfaces, map_)\n\n if is_object_type(type_) or is_interface_type(type_):\n for field in cast(GraphQLInterfaceType, type_).fields.values():\n args = field.args\n if args:\n types = [arg.type for arg in args.values()]\n map_ = reduce(self.type_map_reducer, types, map_)\n map_ = self.type_map_reducer(map_, field.type)\n\n if is_input_object_type(type_):\n for field in cast(GraphQLInputObjectType, type_).fields.values():\n map_ = self.type_map_reducer(map_, field.type)\n\n return map_\n\n def type_map_directive_reducer(\n self, map_: TypeMap, directive: GraphQLDirective = None\n ) -> TypeMap:\n \"\"\"Reducer function for creating the type map from given directives.\"\"\"\n # Directives are not validated until validate_schema() is called.\n if not is_directive(directive):\n return map_\n directive = cast(GraphQLDirective, directive)\n return reduce(\n lambda prev_map, arg: self.type_map_reducer(\n prev_map, cast(GraphQLNamedType, arg.type)\n ),\n directive.args.values(),\n map_,\n )\n\n\ndef is_schema(schema: Any) -> bool:\n \"\"\"Test if the given value is a GraphQL schema.\"\"\"\n return isinstance(schema, GraphQLSchema)\n\n\ndef assert_schema(schema: Any) -> GraphQLSchema:\n if not is_schema(schema):\n raise TypeError(f\"Expected {inspect(schema)} to be a GraphQL schema.\")\n return cast(GraphQLSchema, schema)\n","sub_path":"env/lib/python3.7/site-packages/graphql/type/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":12893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"26023381","text":"from matplotlib import pyplot as plt\nimport numpy as np\n\nA1 = 0.5\nA2 = 1\nfn = 2\nfs = 100 # musi byc wieksze niz 2x fn\nM = 15 # ilosc bitow do przeslania\ntb = 1 #czas trwania bitu w sekundach\nN = 1\n\nfn1 = (N+1)/tb\nfn2 = (N+2)/tb\n\ndata_in = [1,1,0,0,1,0,1,0,1,1,1,0,1,0,0]\n# data_in = np.random.randint(2, size=M) ## losowe tworzenie tablicy z 0 lub 1 przy rozmiarze M podawanym wczesniej\n# dlatego wykresy są różne cały czas\n############## ASK\nza = []\nn = np.arange(M)\nd = np.arange(fs)\nfor b in n:\n for x in d:\n if data_in[b] == 0:\n za.append( A1 + np.sin(2 * np.pi * fn * x / fs))\n else:\n za.append(A2 + np.sin(2 * np.pi * fn * x / fs))\n###################FSK\nzf = []\nn = np.arange(M)\nd = np.arange(fs)\nfor b in n:\n for x in d:\n if data_in[b] == 0:\n zf.append(np.sin(2 * np.pi * fn1 * x / fs))\n else:\n zf.append(np.sin(2 * np.pi * fn2 * x / fs))\n###################PSK\nzp = []\nn = np.arange(M)\nd = np.arange(fs)\nfor b in n:\n for x in d:\n if data_in[b] == 0:\n zp.append(np.sin(2 * np.pi * fn * x / fs))\n else:\n zp.append(np.sin(np.pi + 2 * np.pi * fn * x / fs))\n\nplt.figure(1)\nplt.subplot(3,1,1)\nplt.title('zadanie 1 modulacje kolejno od góry: ASK, FSK, PSK')\nplt.xlabel('t')\nplt.ylabel('za(t)')\nplt.plot(za)\nplt.subplot(3,1,2)\nplt.xlabel('t')\nplt.ylabel('zf(t)')\nplt.plot(zf)\nplt.subplot(3,1,3)\nplt.xlabel('t')\nplt.ylabel('zp(t)')\nplt.plot(zp)\n# plt.savefig('lab4zad1')\n\n# F1 = np.fft.fft(za)\n# F2 = np.fft.fft(zf)\n# F3 = np.fft.fft(zp)\n# f3 = plt.figure(2)\n# plt.subplot(3,1,1)\n# plt.title('widma amplitudowe od góry ASK, FSK, PSK')\n# plt.ylabel('Za(t)')\n# plt.xlabel('t')\n# plt.plot(abs(F1))\n# plt.subplot(3,1,2)\n# plt.ylabel('Zf(t)')\n# plt.xlabel('t')\n# plt.plot(abs(F2))\n# plt.subplot(3,1,3)\n# plt.ylabel('Zp(t)')\n# plt.xlabel('t')\n# plt.plot(abs(F3))\n# plt.savefig('lab4zad2widma')\n\n\n# M = ('ASK','FSK','PSK')\n# def decyb(signal):\n# DB = [20 * np.log10(np.abs(signal))]\n# minim = np.amin(DB)\n# maxim = np.amax(DB)\n# w = ((maxim-3.0)-minim)\n# print('Wartość minimalna: {0}\\nwartość maksymalna: {1}\\noszacowana szerokość: {2}'.format(minim,maxim,w))\n#\n# print('ASK')\n# decyb(F1)\n# print('FSK')\n# decyb(F2)\n# print('PSK')\n# decyb(F3)\n#\n#\n#\n#\nplt.show()","sub_path":"PTD4/ptd4.py","file_name":"ptd4.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"105700982","text":"#####\n# \n# \n# \n#\n# In the paper, we have used inductions of July 23rd. Looking at the\n# metadata, the id of the presentations are 17 (banana) and 19 (wine).\n# \n#####\n\n## Importing libraries\nimport numpy as np\nimport pylab as pl\nimport pandas as pd\nimport matplotlib.gridspec as gridspec\n\n\n## Importing metadata and induction information\nmetadata = np.loadtxt('HT_Sensor_metadata.dat', skiprows=1, dtype=str)\nmetadata[ metadata[:,2] == \"wine\", 2 ] = 2\nmetadata[ metadata[:,2] == \"banana\", 2 ] = 2\nmetadata[ metadata[:,2] == \"background\", 2 ] = 0\nmetadata = np.array( metadata[:,[0,2,3,4]], dtype=float )\n\n## Loading the dataset\ndataset = np.loadtxt('HT_Sensor_dataset.dat', skiprows=1)\n\n\n## Useful definitions\n\ndeltaT = 1./6.\nonemin = 1./60.\n\ndef numWindows(tot, deltaT):\n \"\"\" Evaluates the number of windows that will be used\n given the total time (tot) of a particular induction.\n \"\"\"\n return int( (tot - deltaT)*60. )\n\n\n\n## Array to store features\nresult = []\nhashtable = np.zeros( (metadata.shape[0]), dtype = int )\n\n\n## Splitting\n\nfor ind in range(19): # metadata[:,0]\n\n # number of windows to be used\n nwin = numWindows(metadata[ind,3], deltaT)\n \n # restricting the dataset\n dataset_ = dataset[ dataset[:,0] == ind, 1: ]\n \n for j in range(nwin):\n\n # evaluating indices\n IDX = np.logical_and(\n dataset_[:,0] >= j*onemin, dataset_[:,0] < j*onemin + 10*onemin )\n \n result.append( np.reshape( dataset_[IDX, 1:] , (-1,1) ) )\n \n hashtable[ind] = len(result)\n\n\nnp.save(\"Dataset_Split10min\", result)\nnp.save(\"Dataset_SplitHash\", hashtable)\n","sub_path":"src/Features_split.py","file_name":"Features_split.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"122449138","text":"import torch\nimport argparse\n\nimport models.cifar as models\n\n\nmodel_names = sorted(name for name in models.__dict__\n if name.islower() and not name.startswith(\"__\")\n and callable(models.__dict__[name]))\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--arch\", \"-a\", metavar=\"ARCH\", default=\"resnet20\",\n choices=model_names,\n help=\"model architecture: \" +\n \" | \".join(model_names) +\n \" (default: resnet18)\")\nparser.add_argument(\"--depth\", type=int, default=29, help=\"Model depth.\")\nparser.add_argument(\"--block-name\", type=str, default=\"BasicBlock\",\n help=\"the building block for Resnet and Preresnet: BasicBlock, Bottleneck (default: Basicblock for cifar10/cifar100)\")\nparser.add_argument(\"--cardinality\", type=int, default=8, help=\"Model cardinality (group).\")\nparser.add_argument(\"--widen-factor\", type=int, default=4, help=\"Widen factor. 4 -> 64, 8 -> 128, ...\")\nparser.add_argument(\"--growthRate\", type=int, default=12, help=\"Growth rate for DenseNet.\")\nparser.add_argument(\"--compressionRate\", type=int, default=2, help=\"Compression Rate (theta) for DenseNet.\")\nparser.add_argument(\"--checkpoint\", type=str)\nparser.add_argument(\"--save-filepath\", type=str)\nparser.add_argument(\"--num-classes\", type=int)\nargs = parser.parse_args()\n\nif args.arch.startswith(\"resnext\"):\n model = models.__dict__[args.arch](\n cardinality=args.cardinality,\n num_classes=args.num_classes,\n depth=args.depth,\n widen_factor=args.widen_factor,\n dropRate=args.drop,\n )\nelif args.arch.startswith(\"densenet\"):\n model = models.__dict__[args.arch](\n num_classes=args.num_classes,\n depth=args.depth,\n growthRate=args.growthRate,\n compressionRate=args.compressionRate,\n dropRate=args.drop,\n )\nelif args.arch.startswith(\"wrn\"):\n model = models.__dict__[args.arch](\n num_classes=args.num_classes,\n depth=args.depth,\n widen_factor=args.widen_factor,\n dropRate=args.drop,\n )\nelif args.arch.endswith(\"resnet\"):\n model = models.__dict__[args.arch](\n num_classes=args.num_classes,\n depth=args.depth,\n block_name=args.block_name,\n )\nelse:\n model = models.__dict__[args.arch](num_classes=num_classes)\nmodel = torch.nn.DataParallel(model)\n\n\ncheckpoint = torch.load(args.checkpoint)\nprint(\"got model with acc: {}\".format(checkpoint[\"acc\"]))\nmodel.load_state_dict(checkpoint[\"state_dict\"])\ntorch.save(model, args.save_filepath)\n\n","sub_path":"test/make_teacher_model.py","file_name":"make_teacher_model.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"479626895","text":"from unityagents import UnityEnvironment\nimport numpy as np\nimport time\nfrom ddpg_agent import Agents\nfrom collections import deque\nimport torch\nimport matplotlib.pyplot as plt\nimport progressbar\n\n\nVIS = False\n\nTRAIN = True\nNUM_EPISODES = 6000\nMAX_T = 200\n\nTEST = True\nLOADNET = True\nACTORNET_PATH = './checkpoint_actor.pth'\nNUM_EPISODES_TEST = 100\nMAX_T_TEST = 200\n\n\ndef get_lr(optimizer):\n for param_group in optimizer.param_groups:\n return param_group['lr']\n\n\nif not VIS:\n path_prefix = '_NoVis'\nelse:\n path_prefix =''\n\nenv = UnityEnvironment(file_name='Tennis_Linux'+path_prefix+'/Tennis.x86_64')\n\n# get the default brain\nbrain_name = env.brain_names[0]\nbrain = env.brains[brain_name]\n\n# reset the environment\nenv_info = env.reset(train_mode=True)[brain_name]\n\n# number of agents\nnum_agents = len(env_info.agents)\nprint('Number of agents:', num_agents)\n\n# size of each action\naction_size = brain.vector_action_space_size\nprint('Size of each action:', action_size)\n\n# examine the state space\nstates = env_info.vector_observations\nstate_size = states.shape[1]\nprint('There are {} agents. Each observes a state with length: {}'.format(states.shape[0], state_size))\nprint('The state for the first agent looks like:', states[0])\nprint('The state for the second agent looks like:', states[1])\n\nagents = Agents(state_size=state_size, action_size=action_size,\n num_agents = num_agents, seed = 0) ## choosing num of agent 1 for compitibility\nif TRAIN:\n print('training...')\n scores = [] # list containing scores from each episode\n scores_window = deque(maxlen=100) # last 100 scores\n scores_window_25 = deque(maxlen=25) # last 25 scores\n last_mean_score = 0.001\n #actor_scheduler = torch.optim.lr_scheduler.StepLR(agents.actor_optimizer, step_size=75, gamma=0.25)\n #critic_scheduler = torch.optim.lr_scheduler.StepLR(agents.critic_optimizer, step_size=75, gamma=0.25)\n #last_actor_lr,last_critic_lr = 0,0\n\n for i_episode in progressbar.progressbar(range(1,NUM_EPISODES+1)):\n env_info = env.reset(train_mode=True)[brain_name]\n #agent.reset()\n states = env_info.vector_observations\n score = np.zeros(num_agents)\n for t in range(MAX_T):\n action = agents.act(states)\n env_info = env.step(action)[brain_name]\n next_states = env_info.vector_observations\n reward = env_info.rewards\n done = env_info.local_done\n agents.step(states, action, reward, next_states, done)\n score += np.amax(reward) ### ?\n states = next_states\n\n\n if np.any(done):\n break\n '''\n actor_scheduler.step()\n actor_lr = get_lr(agents.actor_optimizer)\n if actor_lr != last_actor_lr:\n print('\\nChanging actor lr from ', last_actor_lr, ' to: ', actor_lr)\n last_actor_lr = actor_lr\n critic_scheduler.step()\n critic_lr = get_lr(agents.critic_optimizer)\n if critic_lr != last_critic_lr:\n print('\\nChanging critic lr from ', last_critic_lr, ' to: ', critic_lr)\n last_critic_lr = critic_lr\n '''\n\n scores_window.append(score) # save most recent score\n scores_window_25.append(score) # save most recent score\n scores.append(np.mean(score)) # save most recent score\n if i_episode % 25 == 0:\n print('\\rEpisode {}\\tAverage Score (25): {:.2f}'.format(i_episode, np.mean(scores_window_25)))\n if i_episode % 100 == 0:\n print('\\rEpisode {}\\tAverage Score (100): {:.2f}'.format(i_episode, np.mean(scores_window)))\n if np.mean(scores_window) >= last_mean_score:\n last_mean_score = np.mean(scores_window)\n # print('\\nEnvironment solved in {:d} episodes!\\tAverage Score: {:.2f}'.format(i_episode-100, np.mean(scores_window)))\n print('Saving...')\n torch.save(agents.actor_local.state_dict(), 'checkpoint_actor.pth')\n torch.save(agents.critic_local.state_dict(), 'checkpoint_critic.pth')\n # break\n torch.save(agents.actor_local.state_dict(), 'last_checkpoint_actor.pth')\n torch.save(agents.critic_local.state_dict(), 'last_checkpoint_critic.pth')\n # plot the scores\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.plot(np.arange(len(scores)), scores)\n plt.ylabel('Score')\n plt.xlabel('Episode #')\n #plt.show()\n plt.savefig('trainRes.png')\n\n\nif TEST:\n print('testing...')\n if LOADNET:\n print('loading net...')\n agents.actor_local.load_state_dict(torch.load(ACTORNET_PATH))\n scores = [] # list containing scores from each episode\n scores_window = deque(maxlen=NUM_EPISODES_TEST) # last 100 scores\n\n for i_episode in progressbar.progressbar(range(1,NUM_EPISODES_TEST+1)):\n env_info = env.reset(train_mode=False)[brain_name]\n states = env_info.vector_observations\n score = np.zeros(num_agents)\n for t in range(MAX_T_TEST):\n actions = agents.act(states)\n env_info = env.step(actions)[brain_name]\n next_states = env_info.vector_observations\n rewards = env_info.rewards\n dones = env_info.local_done\n #score += rewards\n score += np.amax(rewards)\n states = next_states\n time.sleep(0.01)\n if np.any(dones): # exit loop if episode finished\n break\n scores_window.append(score) # save most recent score\n scores.append(np.mean(score)) # save most recent score\n # plot the scores\n fig = plt.figure()\n ax = fig.add_subplot(111)\n plt.plot(np.arange(len(scores)), scores)\n plt.ylabel('Score')\n plt.xlabel('Episode #')\n #plt.show()\n plt.savefig('testRes.png')\n print('Final Score: ==> ' + np.mean(scores))\n\nenv.close()\n\n''' # random \nfor i in range(5): # play game for 5 episodes\n env_info = env.reset(train_mode=False)[brain_name] # reset the environment\n states = env_info.vector_observations # get the current state (for each agent)\n scores = np.zeros(num_agents) # initialize the score (for each agent)\n while True:\n actions = np.random.randn(num_agents, action_size) # select an action (for each agent)\n actions = np.clip(actions, -1, 1) # all actions between -1 and 1\n env_info = env.step(actions)[brain_name] # send all actions to tne environment\n next_states = env_info.vector_observations # get next state (for each agent)\n rewards = env_info.rewards # get reward (for each agent)\n dones = env_info.local_done # see if episode finished\n scores += env_info.rewards # update the score (for each agent)\n states = next_states # roll over states to next time step\n if np.any(dones): # exit loop if episode finished\n break\n print('Total score (averaged over agents) this episode: {}'.format(np.mean(scores)))\n\nenv.close()\n'''","sub_path":"Collaboration_Competition.py","file_name":"Collaboration_Competition.py","file_ext":"py","file_size_in_byte":7383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"235890397","text":"import cv2\n\nface_cascader=cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\nimg=cv2.imread(\"photo2.jpg\")\ngray_image=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\nface=face_cascader.detectMultiScale(gray_image,\nscaleFactor=1.15,minNeighbors=12)\n\nfor x,y,w,h in face:\n\timg=cv2.rectangle(img,(x,y),(x+w,y+h),(0,244,5),12)\nresized_image=cv2.resize(img,(int(img.shape[1]/5),int(img.shape[0]/5)))\ncv2.imshow(\"Photo\",resized_image)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"face_detector.py","file_name":"face_detector.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"568507990","text":"import numpy as np\r\nimport cv2 as cv\r\nimport math\r\n\r\ntarget_image = \"Sample_A.png\"\r\nflip_blackwhite = False\r\ndisable_thresholding = False\r\n\r\n# This threshold provides good results.\r\nthreshold_value = 130\r\n# Decent denoising value to remove static.\r\nh_value = 40\r\ntarget_tilt = 6.0\r\n\r\n\r\ndef denoiseImage(img):\r\n return cv.fastNlMeansDenoising(img, None, h=h_value)\r\n\r\ndef thresholdBasic(img):\r\n # return cv.adaptiveThreshold(img, 255,\r\n # cv.ADAPTIVE_THRESH_GAUSSIAN_C,\r\n # cv.THRESH_BINARY, 23, -2)\r\n ret, target_img = cv.threshold(img, threshold_value, 255, cv.THRESH_BINARY)\r\n return target_img\r\n\r\ndef thresholdOtsu(img):\r\n blur = cv.GaussianBlur(img,(5,5),0)\r\n ret, target_img = cv.threshold(blur, 0, 255 , cv.THRESH_BINARY+cv.THRESH_OTSU)\r\n return target_img\r\n\r\ndef LoadImage(aImagePath : str):\r\n #print(\"Loading Image\")\r\n img = cv.imread(aImagePath)\r\n\r\n if flip_blackwhite:\r\n img = cv.bitwise_not(img)\r\n\r\n if img is None:\r\n print(\"Unable to load image.\")\r\n exit(-1)\r\n \r\n img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\r\n\r\n return img\r\n\r\ndef FindROI(img):\r\n height, width = img.shape\r\n\r\n # Set both values to some impossible dimesions\r\n x_min = 1000000\r\n y_min = 1000000\r\n \r\n x_max = -1\r\n y_max = -1\r\n\r\n # Now we can find the ROI\r\n for y in range(0, height):\r\n for x in range(0, width):\r\n if img[y,x] == 255:\r\n if x_max < x: \r\n x_max = x\r\n if y_max < y: \r\n y_max = y\r\n if x_min > x: \r\n x_min = x\r\n if y_min > y: \r\n y_min = y\r\n\r\n return (x_min, x_max, y_min, y_max)\r\n\r\ndef translocateROI(roi, base_image, center_height, center_width):\r\n roi_height, roi_width = roi.shape\r\n # print(center_height, center_width)\r\n try:\r\n base_image[center_height:roi_height+center_height, center_width:roi_width+center_width] = roi\r\n except ValueError as ex:\r\n raise ex\r\n return base_image\r\n #cv.imshow(\"Empty_\"+str(roi.shape)+\"_\"+str(center_height) + \"_\" + str(center_width), base_image)\r\n\r\ndef RefitIntoOriginalImage(img, roi_img):\r\n roi_height, roi_width = roi_img.shape\r\n\r\n roi_half_height = roi_height / 2\r\n roi_half_width = roi_width / 2\r\n\r\n height, width = img.shape\r\n base_image = np.zeros((height, width), np.uint8)\r\n\r\n half_height = height/2\r\n half_width = width/2\r\n\r\n position_height = math.floor(half_height-roi_half_height)\r\n position_width = math.floor(half_width-roi_half_width)\r\n\r\n try:\r\n return translocateROI(roi_img, base_image, position_height, position_width)\r\n except ValueError as ex:\r\n raise ex\r\n\r\n# https://www.tutorialkart.com/opencv/python/opencv-python-resize-image/\r\ndef CreateROIScaledImage(img, scalar):\r\n\r\n height, width = img.shape\r\n\r\n new_x_dim = math.floor(width * scalar)\r\n new_y_dim = math.floor(height * scalar)\r\n\r\n resized_img = cv.resize(img, (new_x_dim, new_y_dim))\r\n new_img = thresholdOtsu(resized_img)\r\n\r\n roi_dim = FindROI(new_img)\r\n \r\n try:\r\n new_img = RefitIntoOriginalImage(img, new_img[roi_dim[2]:roi_dim[3], roi_dim[0]:roi_dim[1]])\r\n except ValueError as ex:\r\n # cv.imshow(\"Original {}\".format(scalar), img)\r\n # cv.imshow(\"resized {}\".format(scalar), resized_img)\r\n # cv.imshow(\"Faulty {}\".format(scalar), new_img)\r\n new_img = thresholdBasic(resized_img)\r\n #cv.imshow(\"Resolved {}\".format(scalar), new_img)\r\n #cv.waitKey(0)\r\n #cv.destroyAllWindows()\r\n print(ex)\r\n print(\"\\tResolving with harsher thresholding.\")\r\n roi_dim = FindROI(new_img)\r\n new_img = RefitIntoOriginalImage(img, new_img[roi_dim[2]:roi_dim[3], roi_dim[0]:roi_dim[1]])\r\n\r\n #print(\"Original Dimensions: ({}, {})\".format(width, height))\r\n #print(\"New dimensions: ({}, {})\".format(new_x_dim, new_y_dim))\r\n \r\n #resized_img = cv.resize(img, (new_x_dim, new_y_dim))\r\n #denoised_img = denoiseImage(resized_img)\r\n #new_img = thresholdImage(denoised_img)\r\n\r\n #cv.imshow(\"Before {}\".format(scalar),img)\r\n #cv.imshow(\"Result {}\".format(scalar),new_img)\r\n\r\n #cv.waitKey(0)\r\n #cv.destroyAllWindows()\r\n\r\n #cv.imshow(\"Resizing ROI After {}\".format(scalar), new_img)\r\n\r\n return new_img\r\n\r\n\r\ndef CreateTiltedImage(img, tilt_value):\r\n image_center = tuple(np.array(img.shape)/2)\r\n\r\n #rotation_matrix = cv.getRotationMatrix2D(image_center, tilt_value, 1.0)\r\n #rotated_img = cv.warpAffine(img, rotation_matrix, img.shape)\r\n #denoise_img = denoiseImage(rotated_img)\r\n #new_img = thresholdImage(denoise_img)\r\n\r\n rotation_matrix = cv.getRotationMatrix2D(image_center, tilt_value, 1.0)\r\n rotated_img = cv.warpAffine(img, rotation_matrix, img.shape)\r\n new_img = thresholdOtsu(rotated_img)\r\n\r\n try:\r\n roi_dim = FindROI(new_img)\r\n new_img = RefitIntoOriginalImage(img, new_img[roi_dim[2]:roi_dim[3], roi_dim[0]:roi_dim[1]])\r\n except ValueError:\r\n # Backup method to use harsher thresholding.\r\n new_img = thresholdBasic(rotated_img)\r\n roi_dim = FindROI(new_img)\r\n new_img = RefitIntoOriginalImage(img, new_img[roi_dim[2]:roi_dim[3], roi_dim[0]:roi_dim[1]])\r\n\r\n #cv.imshow(\"Before {}\".format(tilt_value), img)\r\n #cv.imshow(\"After {}\".format(tilt_value), new_img)\r\n #cv.imshow(\"Tilting ROI with {}\".format(tilt_value), new_img)\r\n\r\n return new_img\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n img = LoadImage(\"11_A.png\")\r\n \r\n CreateROIScaledImage(img, .85)\r\n CreateROIScaledImage(img, 1.4)\r\n \r\n #CreateTiltedImage(img, -target_tilt)\r\n #CreateTiltedImage(img, target_tilt)\r\n\r\n cv.waitKey(0)\r\n cv.destroyAllWindows()\r\n\r\n","sub_path":"TransformationMethods.py","file_name":"TransformationMethods.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"374307274","text":"\n# coding: utf-8\n\n# In[1]:\n\nfrom brian2 import *\nimport numpy as np\n#get_ipython().magic('matplotlib inline')\n#from brian2.units.allunits import *\n\n\n# # Parameters\n\n# In[2]:\n\ndef reset_params1():\n global tau_u, tau_r, U, param_f, E_d, D_d, I_BAP, Delta_BAP, T_BAP, w_MS, w_DM, w_FS, w_SF, p_MS, p_DM, p_SF, p_FS\n global w_MF, w_FM, BG_bool\n tau_u = 500*ms\n tau_r = 125*ms\n U = 0.02\n param_f = 0.1\n E_d = -38*mV\n D_d = 6*mV\n I_BAP = 2600*pA\n Delta_BAP = 0.5 *ms \n T_BAP = 2*ms \n w_MS = 24300 * pA\n w_DM = -100000/50 * pA\n w_FS = 24300 * pA\n w_SF = -100000/50 * pA\n w_FM = -100000/50 * pA\n w_MF = -100000/50 * pA\n \n p_MS = 0.2\n p_DM = 1.0\n\n p_SF = 0.7\n p_FS = 0.4\n\n BG_bool = 1 # Turns on and off the background current (for all cell types)\n\n\n# # Pyramidal Cell Parameters\n\n# In[3]:\n\ndef reset_params2():\n global tau_S, tau_D, C_S, C_D, E_L_S, E_L_D, tau_w_S, tau_w_D, a_w_S, a_w_D, b_w_S, g_DS, g_DD, tau_OU_S, tau_OU_D\n global mu_S, mu_D, sigma_OU_S, sigma_OU_D, V_T_P\n tau_S = 17*ms\n tau_D = 8*ms\n C_S = 370*pF\n C_D = 170*pF\n E_L_S = -70*mV\n E_L_D = -70*mV\n tau_w_S = 100*ms\n tau_w_D = 30*ms\n a_w_S = 0 *nS\n a_w_D = 13 *nS\n b_w_S = -200 * pA\n g_DS = 1300/370 * mV / ms\n g_DD = 1200/170 * mV / ms\n\n tau_OU_S = 2 *ms\n tau_OU_D = 2 *ms\n mu_S = 70*pA\n mu_D = -270*pA\n sigma_OU_S = 450*pA\n sigma_OU_D = 450*pA\n\n V_T_P = -50*mV\n\n\n# # Pyramidal Cell Equations\n\n# In[4]:\n\nP_eqs = '''\n\nfvD = (1/(1+exp(-(V_D-E_d)/D_d))) : 1\ndV_S/dt = -(V_S - E_L_S)/tau_S + g_DS * fvD + I_S/C_S + w_S/C_S : volt (unless refractory)\ndw_S/dt = -w_S/tau_w_S : amp\nI_S = BG_bool*I_S_BG + P_I_S_BU(t,i) : amp\ndI_S_BG/dt = (mu_S-I_S_BG)/tau_OU_S + sigma_OU_S*xi_S/sqrt(tau_OU_S) : amp\n\ndV_D/dt = -(V_D - E_L_D)/tau_D + g_DD * fvD + I_D/C_D - w_D/C_D : volt \ndw_D/dt = -w_D/tau_w_D + a_w_D * (V_D - E_L_D)/tau_w_D : amp\n\nI_D = BG_bool*I_D_BG + P_I_D_TD(t,i) + ((t - lastspike)>Delta_BAP) * ((t - lastspike)<(Delta_BAP+T_BAP)) * I_BAP: amp\ndI_D_BG/dt = (mu_D-I_D_BG)/tau_OU_D + sigma_OU_D*xi_D/sqrt(tau_OU_D) : amp\n\nspike_counter : 1\n'''\n\n#V_S > V_T_P\nP_threshold = 'V_S > V_T_P'\n\n# BAP_timer = Delta_BAP + T_BAP\nP_reset = '''\nV_S = E_L_S\nw_S += b_w_S\nspike_counter += 1\n'''\n\nP_refractory = 3*ms \n\n\n\n# # Martinotti Cell Parameters\n\n# In[5]:\n\ndef reset_params3():\n global N_MC, E_L_M, tau_M, C_M, E_L_M, tau_w_M, a_w_M, b_w_M, tau_OU_M, mu_M, sigma_OU_M, V_T_M \n \n N_MC = 50\n \n tau_M = 20*ms\n C_M = 100*pF\n E_L_M = -70*mV\n tau_w_M = 100*ms\n a_w_M = 0 *nS\n b_w_M = -150 * pA\n\n tau_OU_M = 2 *ms\n mu_M = -50*pA\n sigma_OU_M = 50*pA\n\n V_T_M = -50*mV\n\n\n# # Martinotti Cell Equations\n\n# In[6]:\n\n# dxxi_M = sqrt(dt) * randn() : Hz**0.5\nM_eqs = '''\ndV/dt = -(V - E_L_M)/tau_M + I/C_M + w/C_M : volt (unless refractory)\ndw/dt = -w/tau_w_M : amp\nI = BG_bool*I_BG : amp\ndI_BG/dt = (mu_M-I_BG)/tau_OU_M + sqrt(2)*sigma_OU_M * xi_M /sqrt(tau_OU_M) : amp\n'''\n\nM_threshold = 'V > V_T_M'\n\nM_reset = '''\nV = E_L_M\nw += b_w_M\n'''\n\nM_refractory = 3*ms\n\n\n# # FS Cell Parameters\n\n# In[7]:\n\ndef reset_params4():\n global E_L_F, tau_F, C_F, E_L_F, tau_OU_F, mu_F, sigma_OU_F, V_T_F, g_gap, gap_bool\n tau_F = 10*ms\n C_F = 80*pF\n E_L_F = -70*mV\n\n tau_OU_F = 2 *ms\n mu_F = -50*pA\n sigma_OU_F = 50*pA\n\n V_T_F = -50*mV\n \n g_gap = 10000*nS\n gap_bool = 0\n\n\n# # FS Cell Equations\n\n# In[8]:\n\nF_eqs = '''\ndV/dt = -(V - E_L_F)/tau_F + I/C_F : volt (unless refractory)\nI = BG_bool * I_BG + gap_bool * I_gap : amp\ndI_BG/dt = (mu_F-I_BG)/tau_OU_F + sqrt(2)*sigma_OU_F * xi_F /sqrt(tau_OU_F) : amp\nI_gap : amp\n'''\n\nF_threshold = 'V > V_T_F'\n\nF_reset = '''\nV = E_L_F\n'''\n\nF_refractory = 3*ms\n\n\n# # FS Gap Junctoins\n\n# In[9]:\n\nFF_GJ_eqs = '''\nI_gap_post = g_gap * (V_pre - V_post) : amp (summed)\n'''\n\n\n# # Soma -> Martinotti Synapse Equations\n\n# In[10]:\n\nMS_S_eqs = '''\ndu/dt = -(u-U)/tau_u : 1 #(event-driven)\ndR/dt = (1-R)/tau_r : 1 #(event-driven)\n'''\n\nMS_S_pre = '''\nV_post += abs(randn()*(w_MS*u*R/2)+w_MS*u*R)*0.1*ms/C_M\nR += -u*R \nu += (1-u)*param_f \n'''\n\nMS_S_delay = 2*ms \n\n\n\n\n# # Martinotti -> Dendrite Synapse Equations\n\n# In[11]:\n\n#DM_S_eqs = \n\nDM_S_pre = '''\nV_D_post += w_DM*0.1*ms/C_D\n'''\n\nDM_S_delay = 2*ms\n\n\n# # Soma -> FS Synapse Equations\n\n# In[12]:\n\n#FS_S_eqs = \n\nFS_S_pre = '''\nV_post += w_FS*0.1*ms/C_F\n'''\n\nFS_S_delay = 2*ms \n\n\n\n\n# # FS -> Soma Synapse Equations\n\n# In[13]:\n\n#SF_S_eqs = \n\nSF_S_pre = '''\nV_S_post += w_SF*0.1*ms/C_S\n'''\n\nSF_S_delay = 2*ms\n\n\n# # Martinotti -> FS Synapse Equations\n\n# In[14]:\n\n#FS_S_eqs = \n\nFM_S_pre = '''\nV_post += w_FM*0.1*ms/C_F\n'''\n\nFM_S_delay = 2*ms \n\n\n\n\n# # FS -> Martinotti Synapse Equations\n\n# In[15]:\n\n#SF_S_eqs = \n\nMF_S_pre = '''\nV_post += w_MF*0.1*ms/C_M\n'''\n\nMF_S_delay = 2*ms\n\n\n# In[16]:\n\ndef reset_params_global():\n reset_params1()\n reset_params2()\n reset_params3()\n reset_params4()\nreset_params_global()\n\n\n# # Experiment E5\n\n# In[17]:\n\ndef bursting_analyzer(spike_train, ISI_threshold = 16*ms, details = False): \n '''\n INPUT\n spike_train\n 1D array of spike times (units of second)\n \n ISI_threshold\n minimum interval between two spikes for them to be considered\n as part of the same burst. Default: 16*ms. \n \n details\n if false, returns BF and average_number_of_AP_per_burst.\n if true, returns number of spikes, number of spikes in bursts and numbers of bursts.\n \n OUTPUT (details = False)\n BF\n Fraction of spikes that are part of a burst\n \n average_number_of_AP_per_burst\n \" \" \n \n OUTPUT (details = True)\n spikes_number \n Total numbers of spikes\n \n burst_spikes_number\n Total number of spikes within any burst\n \n burst_number\n Total number of bursts. \n \n '''\n spikes_number = len(spike_train)\n \n # No spikes case\n if spikes_number == 0:\n if details:\n return 0, 0, 0\n else:\n return 0, 0\n \n \n spike_train = np.sort(spike_train)\n \n \n ISI_train = np.zeros(len(spike_train)-1)*second\n for i in range(len(ISI_train)):\n ISI_train[i] = spike_train[i+1]-spike_train[i]\n \n burst_vector = ISI_train < ISI_threshold\n \n burst_number = 0\n burst_spikes_number = 0\n\n bursting_ = 0\n for B in burst_vector:\n if B:\n if not bursting_:\n burst_number += 1\n bursting_ = 1\n burst_spikes_number += 1\n else:\n bursting_ = 0\n \n burst_spikes_number += burst_number # number of spikes\n \n BF = burst_spikes_number / spikes_number # fraction of AP in a burst\n if burst_number:\n average_number_of_AP_per_burst = burst_spikes_number / burst_number\n else: \n average_number_of_AP_per_burst = 0\n \n if details:\n return spikes_number, burst_spikes_number, burst_number\n else:\n return BF, average_number_of_AP_per_burst\n\n\n# In[18]:\n\n#'''\nreset_params_global()\nE5_run_time = 500*ms\nex_stim_steps = 10*ms\nps_FM = arange(0.5,0.6,1) #arange(0,1.1,0.5)\nps_MF = arange(0.5,0.6,1) #arange(0,1.1,0.5)\n\nBG_bool = 0\n\nN_E5 = 400\n\nE5_Monitors = np.empty([len(ps_FM), len(ps_MF)], dtype=object)\nE5_S_Monitors = np.empty([len(ps_FM), len(ps_MF)], dtype=object)\n\nE5_MFR = np.zeros(E5_Monitors.shape)*Hz\n\n\nfor d_dex, p_FM in enumerate(ps_FM):\n for s_dex, p_MF in enumerate(ps_MF):\n start_scope()\n \n mu_D = 150*pA\n mu_S = 200*pA\n \n E5_P_G = NeuronGroup(N_E5, P_eqs, threshold=P_threshold, reset=P_reset, refractory=P_refractory)\n E5_P_G.V_S = -69.7*mV\n E5_P_G.V_D= -69.9*mV\n E5_P_G.w_D= 2*pA\n \n E5_M_N = 50\n E5_M_G = NeuronGroup(E5_M_N, M_eqs, threshold=M_threshold, reset=M_reset, refractory=M_refractory)\n E5_M_G.V = E_L_M\n E5_M_G.w= 0*pA\n\n E5_F_N = 100\n E5_F_G = NeuronGroup(E5_F_N, F_eqs, threshold=F_threshold, reset=F_reset, refractory=F_refractory)\n E5_F_G.V = E_L_F\n\n E5_MS_S = Synapses(E5_P_G, E5_M_G, MS_S_eqs, pre = MS_S_pre)\n E5_DM_S = Synapses(E5_M_G, E5_P_G, pre = DM_S_pre)\n E5_FS_S = Synapses(E5_P_G, E5_F_G, pre = FS_S_pre)\n E5_SF_S = Synapses(E5_F_G, E5_P_G, pre = SF_S_pre)\n E5_FM_S = Synapses(E5_M_G, E5_F_G, pre = FM_S_pre)\n E5_MF_S = Synapses(E5_F_G, E5_M_G, pre = MF_S_pre)\n \n E5_MS_S.connect(True, p=p_MS)\n E5_DM_S.connect(True, p=p_DM)\n E5_FS_S.connect(True, p=p_FS)\n E5_SF_S.connect(True, p=p_SF)\n E5_FM_S.connect(True, p=p_FM)\n E5_MF_S.connect(True, p=p_MF)\n\n \n \n E5_MS_S.delay = MS_S_delay\n E5_DM_S.delay = DM_S_delay\n E5_FS_S.delay = FS_S_delay\n E5_SF_S.delay = SF_S_delay\n E5_FM_S.delay = FM_S_delay\n E5_MF_S.delay = MF_S_delay\n\n \n stimulus_E5_sd = 20\n stimulus_s_slots_E5 = np.random.normal(mu_S/pA,stimulus_E5_sd,(E5_run_time/ex_stim_steps,N_E5))*pA\n stimulus_d_slots_E5 = np.random.normal(mu_D/pA,stimulus_E5_sd,(E5_run_time/ex_stim_steps,N_E5))*pA\n\n stimulus_BU_E5 = TimedArray(stimulus_s_slots_E5, dt=ex_stim_steps)\n stimulus_TD_E5 = TimedArray(stimulus_d_slots_E5, dt=ex_stim_steps)\n\n P_I_S_BU = stimulus_BU_E5\n P_I_D_TD = stimulus_TD_E5\n\n #S3_VS_monitor = StateMonitor(P_G, ('V_S', 'V_D', 'I_S','I_D','w_S', 'w_D'), record=arange(20))\n E5_Monitors[d_dex,s_dex] = StateMonitor(E5_P_G, ('V_S', 'V_D', 'I_S','I_D','w_S', 'w_D', 'spike_counter'), record=arange(20))\n E5_S_Monitors[d_dex,s_dex] = SpikeMonitor(E5_P_G)\n network_E5 = Network(collect())\n network_E5.add(E5_Monitors[d_dex,s_dex])\n network_E5.add(E5_S_Monitors[d_dex,s_dex])\n network_E5.run(E5_run_time)\n \n E5_MFR[d_dex,s_dex] = mean(E5_Monitors[d_dex,s_dex].spike_counter[:,-1])/(E5_run_time)\n \n #S3_Monitors[d_dex,s_dex] = S3_VS_monitor\n#'''\n\n\n# In[19]:\n\nE5_MFR = np.zeros(E5_Monitors.shape)*Hz\nfor d_dex, p_FM in enumerate(ps_FM):\n for s_dex, p_MF in enumerate(ps_MF):\n E5_MFR[d_dex,s_dex] = mean(E5_Monitors[d_dex,s_dex].spike_counter[:,-1])/(E5_run_time)\n\n\n# In[ ]:\n\n# Filling-in the BF and average spikes per burst data\n\nE5_BF = np.zeros(E5_Monitors.shape)\nE5_APiB = np.zeros(E5_Monitors.shape)\n\nE5_spikes = np.zeros(E5_Monitors.shape)\nE5_burst_spikes = np.zeros(E5_Monitors.shape)\nE5_bursts = np.zeros(E5_Monitors.shape)\n\n\nfor d_dex, p_FM in enumerate(ps_FM):\n for s_dex, p_MF in enumerate(ps_MF):\n for i in range(len(E5_S_Monitors[d_dex,s_dex].spike_trains())):\n spike_train = E5_S_Monitors[d_dex,s_dex].spike_trains()[i]\n if spike_train.any():\n bursting_analyzer_results = bursting_analyzer(spike_train, ISI_threshold = 16*ms, details = True)\n E5_spikes[d_dex,s_dex] += bursting_analyzer_results[0]\n E5_burst_spikes[d_dex,s_dex] += bursting_analyzer_results[1]\n E5_bursts[d_dex,s_dex] += bursting_analyzer_results[2]\n\n E5_BF[d_dex,s_dex] = E5_burst_spikes[d_dex,s_dex] / E5_spikes[d_dex,s_dex]\n E5_APiB[d_dex,s_dex] = E5_burst_spikes[d_dex,s_dex] / E5_bursts[d_dex,s_dex]\n\n\n# In[ ]:\n\nfigure(figsize=(18,6))\n'''\nsubplot(131)\nplt.imshow(flipud(E5_MFR.T)/Hz, cmap=plt.cm.Reds, interpolation='none', extent=[-350,-100,0,300])\nplot(-270, 70, '.k') # the star in the paper\nplt.colorbar()\nlevels = np.arange(0,8)\nCS = plt.contour(E5_MFR.T/Hz, levels,\n origin='lower',\n linewidths=2,\n extent=[-350,-100,0,300])\nplt.title(\"Mean firing rate\")\nplt.colorbar()\n'''\n\nalt_mean_firing = E5_spikes / N_E5/ E5_run_time\n\nsubplot(131)\nplt.imshow(flipud(alt_mean_firing.T)/Hz, cmap=plt.cm.Reds, interpolation='none', extent=[0,1,0,1])\n#plot(-270, 70, '.k') # the star in the paper\nplt.colorbar()\nlevels = np.arange(0,8)\nCS = plt.contour(alt_mean_firing.T/Hz, levels,\n origin='lower',\n linewidths=2,\n extent=[0,1,0,1])\n\nplt.title(\"Mean firing rate\")\nplt.colorbar()\n\nsubplot(132)\nplt.imshow(flipud(E5_BF.T), cmap=plt.cm.Blues, interpolation='none', extent=[0,1,0,1])\n#plot(-270, 70, '.k') # the star in the paper\nplt.colorbar()\nlevels = np.arange(0,1.1,0.1)\nCS = plt.contour(E5_BF.T, levels,\n origin='lower',\n linewidths=2,\n extent=[0,1,0,1])\n\nplt.title(\"BF [Fraction of AP in a burst]\")\nplt.colorbar()\n\n\nsubplot(133)\nplt.imshow(flipud(E5_APiB.T), cmap=plt.cm.Greens, interpolation='none', extent=[0,1,0,1])\n#plot(-270, 70, '.k') # the star in the paper\nplt.colorbar()\nlevels = np.arange(2,3.4,0.2)\nCS = plt.contour(E5_APiB.T, levels,\n origin='lower',\n linewidths=2,\n extent=[0,1,0,1])\nplt.title(\"Average number of AP per burst\")\nplt.colorbar()\nplt.show()\n\n#E5_BF[d_dex,s_dex] = E5_burst_spikes[d_dex,s_dex] / E5_spikes[d_dex,s_dex]\n#E5_APiB[d_dex,s_dex] = E5_burst_spikes[d_dex,s_dex] / E5_bursts[d_dex,s_dex]\n\n\n# In[ ]:\n\nE5_APiB\n\n\n# In[ ]:\n\nflipud(E5_BF.T)\n\n\n# In[ ]:\n\nmean(E5_Monitors[2,2].spike_counter[:,-1])/(E5_run_time)\n\n\n# In[ ]:\n\n#'''\nfigure(figsize=(18,6))\n\n\n\ncolor_wheel = ['b','g','r','c','m','y','k']\n\n\n\nindSp = 2, 2\n#print(\"mu_D = \"+str(mus_d[indSp[0]]))\n#print(\"mu_S = \"+str(mus_s[indSp[1]]))\nfor i in range(7):\n #figure(figsize=(18,6))\n if not i:\n #plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].V_S[i]/mV, label='V_S',c='k')\n #plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].V_D[i]/mV, label='V_D',c='b')\n plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].V_S[i]/mV, label='V_S',c=color_wheel[i%7])\n plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].V_D[i]/mV, ls='-.', label='V_D',c=color_wheel[i%7])\n ##plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].I_S[i]/pA, label='I_S',c=color_wheel[i%7])\n ##plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].I_D[i]/pA, ls='-.', label='I_D',c=color_wheel[i%7])\n else:\n #plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].V_S[i]/mV,c='k')\n #plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].V_D[i]/mV,c='b')\n plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].V_S[i]/mV,c=color_wheel[i%7])\n plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].V_D[i]/mV, ls='-.', c=color_wheel[i%7])\n ##plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].I_S[i]/pA,c=color_wheel[i%7])\n ##plot(E5_Monitors[indSp].t/ms, E5_Monitors[indSp].I_D[i]/pA, ls='-.',c=color_wheel[i%7])\n #plot(E5_Monitors[2,2].t/ms, E5_Monitors[2,3].I_S[i]/pA, label='I_S',c='k')\n #plot(E5_Monitors[2,2].t/ms, E5_Monitors[2,3].I_D[i]/pA, label='I_D',c='b')\n #plot(E5_Monitors[2,2].t/ms, E5_Monitors[2,3].I_S[i]/pA, label='w_S',c='k')\n #plot(E5_Monitors[2,2].t/ms, E5_Monitors[2,3].I_D[i]/pA, label='w_D',c='b')\n #plot(E5_Monitors[2,2].t/ms, E5_Monitors[2,3].spike_counter[i], label='spikes',c='r')\n #plot(Vmon.t/ms, Vmon.V_D[i+4]/mV, label='V_D')\n for t in E5_S_Monitors[indSp].spike_trains()[i]:\n axvline(t/ms, ls='--', c=color_wheel[i%7], lw=1)\n #axvline(t/ms, ls='--', c='r', lw=1)\n legend(loc='best')\n #plt.show()\n color_wheel[i%7]\n #plot([0, E5_run_time/ms], [mus_d[indSp[0]]/pA, mus_d[indSp[0]]/pA], color='r', linestyle='-', linewidth=2)\n #plot([0, E5_run_time/ms], [mus_s[indSp[1]]/pA, mus_s[indSp[1]]/pA], color='g', linestyle='-', linewidth=2)\n plt.ylim((-100,0)) # for V\n #plt.ylim((-1300,1300)) # for I\n#''' \n\n\n# In[ ]:\n\narange(0.5,0.6,1)\n\n\n# In[ ]:\n\n\n\n","sub_path":"SDM_Network_Extention_E5.py","file_name":"SDM_Network_Extention_E5.py","file_ext":"py","file_size_in_byte":15561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"594835804","text":"import unittest\nimport hailtop.batch.genetics.regenie as br\nimport os\nfrom shutil import which, rmtree\nfrom hailtop.config import get_user_config\nimport google.cloud.storage\nfrom google.cloud.storage.blob import Blob\nimport uuid\n\n\ndef read(file):\n with open(file, 'r') as f:\n return f.read()\n\n\ndef assert_same_file(file1, file2):\n assert read(file1) == read(file2)\n\n\nclass LocalBackendTests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n rdir = \"hailtop/batch/genetics/regenie\"\n\n cls.cwd = os.getcwd()\n os.chdir(rdir)\n os.system(\"git clone --depth 1 --branch v1.0.5.6 https://github.com/rgcgithub/regenie.git\")\n\n cls.outdir = \"out\"\n cls.step2_out_prefix = f'{cls.outdir}/test_bin_out_firth'\n\n @classmethod\n def tearDownClass(cls):\n rmtree('regenie')\n os.chdir(cls.cwd)\n\n @unittest.skipIf(not which(\"docker\"), \"docker command is missing\")\n def test_regenie(self):\n args = br.parse_input_args([\"--demo\"])\n br.run(**args)\n\n out_log = f\"{self.step2_out_prefix}.log\"\n out1 = f\"{self.step2_out_prefix}.Y1.regenie\"\n out2 = f\"{self.step2_out_prefix}.Y2.regenie\"\n expected = \"regenie/example/example.test_bin_out_firth_Y1.regenie\"\n\n assert len(read(out_log)) > 0\n assert_same_file(out1, expected)\n assert len(read(out2)) > 0\n\n rmtree(self.outdir)\n\n @unittest.skipIf(not which(\"docker\"), \"docker command is missing\")\n def test_regenie_1pheno(self):\n args = br.parse_input_args([\"--local\", \"--step1\", \"example/step1.txt\", \"--step2\",\n \"example/step2-phenoCol.txt\"])\n br.run(**args)\n\n out1 = f\"{self.step2_out_prefix}.Y1.regenie\"\n out2 = f\"{self.step2_out_prefix}.Y2.regenie\"\n expected = \"regenie/example/example.test_bin_out_firth_Y1.regenie\"\n\n assert_same_file(out1, expected)\n assert not os.path.isfile(out2)\n\n rmtree(self.outdir)\n\n args = br.parse_input_args([\"--local\", \"--step1\", \"example/step1.txt\", \"--step2\",\n \"example/step2-phenoColList.txt\"])\n br.run(**args)\n\n assert len(read(out2)) > 0\n assert not os.path.isfile(out1)\n\n rmtree(self.outdir)\n\n @unittest.skipIf(not which(\"docker\"), \"docker command is missing\")\n def test_regenie_nosplit(self):\n args = br.parse_input_args([\"--local\", \"--step1\", \"example/step1.txt\", \"--step2\",\n \"example/step2-nosplit.txt\"])\n br.run(**args)\n\n out1 = f\"{self.step2_out_prefix}.regenie\"\n\n assert len(read(out1)) > 0\n\n rmtree(self.outdir)\n\n\nclass ServiceBackendTests(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n os.system(\"git clone --depth 1 --branch v1.0.5.6 https://github.com/rgcgithub/regenie.git\")\n\n cls.bucket_name = get_user_config().get('batch', 'bucket')\n\n input_folder = 'batch-tests/resources/regenie-v1.0.5.6'\n cls.gcs_input_dir = f'gs://{cls.bucket_name}/{input_folder}'\n\n in_cluster_key_file = os.environ.get('HAIL_GSA_KEY_FILE')\n if in_cluster_key_file:\n credentials = google.oauth2.service_account.Credentials.from_service_account_file(\n in_cluster_key_file)\n else:\n credentials = None\n cls.gcs_client = google.cloud.storage.Client(project='hail-vdc', credentials=credentials)\n cls.bucket = cls.gcs_client.bucket(cls.bucket_name)\n for file_name in os.listdir('regenie/example/'):\n file_path = os.path.join('regenie/example/', file_name)\n blob = cls.bucket.blob(f'{input_folder}/{file_name}')\n if not blob.exists():\n blob.upload_from_filename(file_path)\n\n token = uuid.uuid4()\n cls.gcs_output_path = f'batch-tests/{token}'\n cls.gcs_output_dir = f'gs://{cls.bucket_name}/{cls.gcs_output_path}'\n cls.step2prefix = f\"{cls.gcs_output_dir}/test_bin_out_firth\"\n\n step1 = f\"\"\"\n --step 1\n --threads 0.125\n --memory 375Mi\n --storage 1Gi\n --bed {cls.gcs_input_dir}/example\n --exclude {cls.gcs_input_dir}/snplist_rm.txt\n --covarFile {cls.gcs_input_dir}/covariates.txt\n --phenoFile {cls.gcs_input_dir}/phenotype_bin.txt\n --remove {cls.gcs_input_dir}/fid_iid_to_remove.txt\n --bsize 100\n --bt\n --out fit_bin_out\n \"\"\"\n step1lowmen = f\"{step1}\\n--lowmem\\n--lowmem-prefix tmp_rg\"\n\n cls.step2 = f\"\"\"\n --step 2\n --threads 0.125\n --memory 375Mi\n --storage 1Gi\n --bgen {cls.gcs_input_dir}/example.bgen\n --covarFile {cls.gcs_input_dir}/covariates.txt\n --phenoFile {cls.gcs_input_dir}/phenotype_bin.txt\n --remove {cls.gcs_input_dir}/fid_iid_to_remove.txt\n --bsize 200\n --bt\n --firth --approx\n --pThresh 0.01\n --pred fit_bin_out_pred.list\n \"\"\"\n cls.step2_split = f\"{cls.step2}\\n--split\"\n\n cls.step1 = \"step1-svc.txt\"\n cls.step1low = \"step1low-svc.txt\"\n\n with open(cls.step1, 'w') as f:\n f.write(step1)\n\n with open(cls.step1low, 'w') as f:\n f.write(step1lowmen)\n\n def tearDown(self):\n blobs = self.bucket.list_blobs(prefix=self.gcs_output_dir)\n for blob in blobs:\n blob.delete()\n os.remove('step2.txt')\n\n @classmethod\n def read(cls, path):\n blob = Blob.from_string(path, cls.gcs_client)\n return blob.download_as_string().decode(\"utf-8\")\n\n @classmethod\n def exists(cls, path):\n blob = Blob.from_string(path, cls.gcs_client)\n return blob.exists()\n\n def test_regenie_nosplit(self):\n step2prefix = f'{self.gcs_output_dir}/nosplit'\n with open('step2.txt', 'w') as f:\n f.write(f\"{self.step2}\\n--out {step2prefix}\")\n\n args = br.parse_input_args([\"--step1\", self.step1, \"--step2\", 'step2.txt', \"--wait\"])\n res = br.run(**args)\n assert res.status()['state'] == \"success\"\n\n outpath = f\"{step2prefix}.regenie\"\n assert len(self.read(outpath)) > 0\n\n def test_regenie_nosplit_lowmem(self):\n step2prefix = f'{self.gcs_output_dir}/nosplit-lowmem'\n with open('step2.txt', 'w') as f:\n f.write(f\"{self.step2}\\n--out {step2prefix}\")\n\n args = br.parse_input_args([\"--step1\", self.step1low, \"--step2\", 'step2.txt', \"--wait\"])\n res = br.run(**args)\n assert res.status()['state'] == \"success\"\n\n outpath = f\"{step2prefix}.regenie\"\n assert len(self.read(outpath)) > 0\n\n def test_regenie(self):\n step2prefix = f'{self.gcs_output_dir}/split'\n with open('step2.txt', 'w') as f:\n f.write(f\"{self.step2_split}\\n--out {step2prefix}\")\n\n args = br.parse_input_args([\"--step1\", self.step1low, \"--step2\", 'step2.txt', \"--wait\"])\n res = br.run(**args)\n assert res.status()['state'] == \"success\"\n\n out_log = f\"{step2prefix}.log\"\n out1 = f\"{step2prefix}.Y1.regenie\"\n out2 = f\"{step2prefix}.Y2.regenie\"\n expected = \"regenie/example/example.test_bin_out_firth_Y1.regenie\"\n\n assert len(self.read(out_log)) > 0\n assert self.read(out1) == read(expected)\n assert len(self.read(out2)) > 0\n\n def test_regenie_1pheno(self):\n step2prefix = f'{self.gcs_output_dir}/phenoCol'\n with open('step2.txt', 'w') as f:\n f.write(f\"{self.step2_split}\\n--phenoCol Y1\\n--out {step2prefix}\")\n\n args = br.parse_input_args([\"--step1\", self.step1low, \"--step2\", 'step2.txt', \"--wait\"])\n br.run(**args)\n\n out1 = f\"{step2prefix}.Y1.regenie\"\n out2 = f\"{step2prefix}.Y2.regenie\"\n expected = \"regenie/example/example.test_bin_out_firth_Y1.regenie\"\n\n assert self.read(out1) == read(expected)\n assert not self.exists(out2)\n\n def test_regenie_phenoList(self):\n step2prefix = f'{self.gcs_output_dir}/phenoColList'\n with open('step2.txt', 'w') as f:\n f.write(f\"{self.step2_split}\\n--phenoColList Y2\\n--out {step2prefix}\")\n\n args = br.parse_input_args([\"--step1\", self.step1low, \"--step2\", 'step2.txt', \"--wait\"])\n br.run(**args)\n\n out1 = f\"{step2prefix}.Y1.regenie\"\n out2 = f\"{step2prefix}.Y2.regenie\"\n\n assert len(self.read(out2)) > 0\n assert not self.exists(out1)\n","sub_path":"hail/python/test/hailtop/batch/test_regenie.py","file_name":"test_regenie.py","file_ext":"py","file_size_in_byte":8433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"390808977","text":"# -*- coding: utf-8 -*-\n\"\"\"\nÉditeur de Spyder\n\n\"\"\"\n\nimport openraster\nimport scipy as sp\nimport scipy.ndimage\n\n\"\"\"\n\n\"\"\"\nim,proj,geo=openraster.open_data('map.tif')\n[nl,nc,d]=im.shape\nout = sp.empty((nl,nc,d),dtype=im.dtype.name)\n\n\n\n\n\"\"\"\nFilter class to isolate the forest and delete lines and names.\nATTRIBUTES :\ninmin\ninshape:\nMETHODS :\nfiltergreyclose\nfiltermedian\n\n\"\"\"\n\n\ndef maxfilter(inim,inshape=11):\n for i in range(d):\n out[:,:,i]=sp.ndimage.filters.maximum_filter(inim[:,:,i],size=(inshape,inshape))\n return out.astype(im.dtype.name) \n \ndef minfilter(inim,inshape=3):\n for i in range(d):\n out[:,:,i]=sp.ndimage.filters.minimum_filter(inim[:,:,i],size=(inshape,inshape))\n return out.astype(im.dtype.name)\n \ndef greyclose(inim,inshape=11):\n for i in range(d):\n out[:,:,i]=sp.ndimage.morphology.grey_closing(inim[:,:,i],size=(inshape,inshape))\n return out.astype(im.dtype.name)\n\ndef median(inim,inshape=11):\n for i in range(d):\n out[:,:,i]=sp.ndimage.filters.median_filter(inim[:,:,i],size=(inshape,inshape))\n return out.astype(im.dtype.name)\n \n\n#greyclose=greyclose(im)\n\n#medianfilter=median(im)\n#minfilter=minfilter(medianfilter)\nmaxfilter=maxfilter(im)\nminfilter=minfilter(maxfilter)\nmedianfilter=median(minfilter)\n#greyfilter=greyclose(medianfilter)\n#openraster.write_data('grey',greyclose,proj,geo)\nopenraster.write_data('min',medianfilter,proj,geo)\n#median=filtermedian(greyclose)\n\n\n# grey=sp.ndimage.morphology.grey_closing(levelone)","sub_path":"historicalmap.py","file_name":"historicalmap.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"288412988","text":"from sklearn.datasets import fetch_mldata\nimport numpy as np\nimport os\nfrom pylab import *\nimport pdb\nimport random\nfrom sklearn.preprocessing import PolynomialFeatures\nfrom sklearn.utils import shuffle\nfrom sklearn.cross_validation import KFold\nfrom collections import defaultdict\nfrom collections import Counter\n\n#\n#This function loads MNIST into to np arrays x and y.\n#Params: two class true if only two classes d degree (for mapping)\n#Returns: nparray x with feature information and nparray y with label information\ndef load_data(two_class=False,d=1):\n\tpoly = PolynomialFeatures(degree=d)\n\tmnist = fetch_mldata('MNIST original')\n\tmnist.data.shape\n\tmnist.target.shape\n\tnp.unique(mnist.target)\n\n\tX, y = mnist.data / 255., mnist.target\n\tif two_class:\n\t\tind = [ k for k in range(len(y)) if (y[k]==0 or y[k]==1) ]\n\t\tX=X[ind,:]\n\t\ty=y[ind]\n\ty=[int(p) for p in y]\n\tX=poly.fit_transform(X)\n\n\treturn np.array(X),np.array(y)\n\n#\n#This function loads iris dataset into to np arrays x and y.\n#Params: two class true if only two classes d degree (for mapping)\n#Returns: nparray x with feature information and nparray y with label information\ndef load_iris(two_class=False,d=1):\n\tpoly = PolynomialFeatures(degree=d)\n\tfile = open(\"./data/iris.data.txt\",'r').readlines()\n\trandom.shuffle(file)\n\tlabels={'Iris-setosa\\n':0,'Iris-versicolor\\n':1,'Iris-virginica\\n':2}\n\tx=[]\n\ty=[]\n\ti=0\n\tfor line in file:\n\t l=line.split(',')\n\t if(len(l)>1):\n\t\t xi=[]\n\t\t for i in range(1,len(l)-1):\n\t\t xi.append(float(l[i]))\n\t\t yi=labels[l[-1]]\n\t\t if two_class and yi<2:\n\t\t y.append(yi)\n\t\t x.append(xi)\n\t\t elif not two_class:\n\t\t \ty.append(yi)\n\t\t \tx.append(xi)\n\n\tx=poly.fit_transform(x)\n\treturn np.array(x), np.array(y)\n\n#This function computes the parameters for the logistic regression with two classes\n#X y data\n#Returns theta vector\ndef gradient_descent_two_class(X,y):\t\n\ttheta = [0.01]*len(X[0])\n\tdiff=10\n\tstep=0.0005\n\twhile(diff>1e-3):\n\t\tsumm=0\n\t\tfor i in range(0,len(y)):\n\t\t\tsumm+=np.dot(h(X[i],theta)-y[i],X[i])\n\t\ttheta_o = theta\n\t\ttheta = theta - step*summ\n\t\tdiff=np.average(np.absolute(theta_o-theta))\n\t\t# to=np.average(theta_o)\n\t\t# t=np.average(theta)\n\t\t# if t1e-3):\n\t\tsumm=defaultdict(float)\n\t\tfor i in range(0,len(y)):\n\t\t\th_ = h_k(X[i],theta_i)\n\t\t\tfor j in k:\n\t\t\t\ty_1=0\n\t\t\t\tif(j==y[i]):\n\t\t\t\t\ty_1=1\n\t\t\t\tsumm[j]+=np.dot(h_[j]-y_1,X[i])\n\t\t\t\n\t\ttheta_o = np.copy(theta_i)\n\t\tfor j in range(0,len(theta_i)):\n\t\t\ttheta_i[j] = theta_i[j] - step*summ[j]\n\t\tdiff=np.average(np.absolute(theta_o-theta_i))\n\treturn theta_i\n\n#\n#Params: feature vector x, theta vector\n#Computes the sigmoid function\n#Returns: vector of h values for each class\ndef h_k(x,theta):\n\texps = [] \n\tfor j in range(0,len(theta)):\n\t\tex = np.dot(np.transpose(theta[j]),x)\n\t\texps.append(np.exp(ex))\n\tsumm = sum(exps)\n\treturn [x / summ for x in exps]\n\n#\n#Params: feature vector x, theta vector\n#Computes the softmax function\n#Returns: h value\ndef h(x,theta):\n\th = - np.dot(np.transpose(theta),x)\n\th = np.exp(h)\n\th= 1/(1+h)\n\treturn h\n\n#\n#Classifies an x in one of two classes\ndef classify(x,theta):\n\th_ = h(x,theta)\n\tif h_<0.5:\n\t\treturn 0\n\telse:\n\t\treturn 1\n\n#Theta is a vector\n#Classifies an x example in one of k classes\ndef classify_k(x,theta):\n\ty_hat=defaultdict(float)\n\tfor j in range(len(theta)):\n\t\ty_hat[j] = np.dot(np.transpose(theta[j]),x)\n\n\ts= sorted(y_hat.items(), key=lambda x: x[1], reverse=True)\n\treturn s[0][0]\n\n#\n#Computes classifier performance evaluators given the parameters and the featue (x) and\n#original label data (y).\n#Parameters: x: feature matrix or vector. y: label vector. mean: mean vector.\n#covar: covariance matrix. priori: priori class vector. uni: defines if the data\n#is univariable or not. False by default.\n#Return: confusion matrix, precision, recall, f_measuer and accuracy.\ndef confusion_matrix_2(X,y,theta):\n tp=0\n tn=0\n fp=0\n fn=0\n i=0\n for i in range(0,len(X)):\n h_=classify(X[i],theta)\n if h_ == y[i]:\n if y[i]==0:\n tn+=1\n else:\n tp+=1\n else:\n if y[i]==0:\n fp+=1\n else:\n fn+=1\n\n confusion_matrix = [[tp,fp],[fn,tn]]\n precision = 0 if (tp+fp)==0 else tp/(tp+fp) \n recall = 0 if (tp+fn)==0 else tp/(tp+fn)\n f_measure = 0 if (precision==0 or recall==0) else 2/((1/precision)+(1/recall))\n accuracy = (tp+tn)/(tp+tn+fp+fn)\n\n return confusion_matrix, precision, recall, f_measure, accuracy\n\n#\n#Computes classifier performance evaluators given the parameters and the featue (x) and\n#original label data (y).\n#Parameters: x: feature matrix or vector. y: label vector. theta: theta vector.\n#Return: confusion matrix, precision, recall, f_measuer and accuracy.\ndef confusion_matrix_k(X,y,theta,k):\n\tconfusion_matrix = np.zeros((len(k),len(k)), dtype=float)\n\n\tfor i in range(0,len(X)):\n\t\ty_hat = classify_k(X[i],theta)\n\t\t#pdb.set_trace()\n\t\tconfusion_matrix[y_hat][y[i]]+=1\n\n\tprecision = defaultdict(float)\n\trecall = defaultdict(float)\n\tf_measure = defaultdict(float)\n\taccuracy = defaultdict(float)\n\n\ttotal = confusion_matrix.sum()\n\trow_sum = confusion_matrix.sum(axis=1)\n\tcolumn_sum = confusion_matrix.sum(axis=0)\n\taccuracy = 0\n\tfor j in range(0,len(k)):\n\t accuracy+=confusion_matrix[j][j]\n\taccuracy/=total\n\tfor j in k:\n\t precision[j]=confusion_matrix[j][j]/row_sum[j]\n\t recall[j]=confusion_matrix[j][j]/column_sum[j]\n\t f_measure[j] = 2* (precision[j]*recall[j])/(precision[j]+recall[j])\n\n\n\treturn confusion_matrix, dict(precision), dict(recall), dict(f_measure), accuracy\n\n#\n#This function performs crossvalidation to find the average training and testing evaluators\n#given data , given a degree and a k-factor.\n#Parameters: x - vector or matrix, y - vector\n#Returns: accuracies\ndef cross_validation(X,y,k_f=10):\n\tk=set(y)\n\tif len(k)==2:\n\t traine={'p':0,'r':0,'f_m':0,'a':0}\n\t teste={'p':0,'r':0,'f_m':0,'a':0}\n\telse:\n\t traine={'p':Counter({}),'r':Counter({}),'f_m':Counter({}),'a':0}\n\t teste={'p':Counter({}),'r':Counter({}),'f_m':Counter({}),'a':0}\n\t \n\n\tkf = KFold(len(X),k_f)\n\tfor train, test in kf:\n\n\t\tif len(k)==2:\n\t\t\ttheta = (gradient_descent_two_class(X[train],y[train]))\n\t\t\trest=confusion_matrix_2(X[train],y[train],theta)\n\t\t\trese=confusion_matrix_2(X[test],y[test],theta)\n\t\t\t\n\t\t\ttraine[\"p\"]+=rest[1]\n\t\t\ttraine[\"r\"]+=rest[2]\n\t\t\ttraine[\"f_m\"]+=rest[3]\n\t\t\ttraine[\"a\"]+=rest[4]\n\n\t\t\tteste[\"p\"]+=rese[1]\n\t\t\tteste[\"r\"]+=rese[2]\n\t\t\tteste[\"f_m\"]+=rese[3]\n\t\t\tteste[\"a\"]+=rese[4]\n\t\telse:\n\t\t\ttheta = (gradient_descent_k_class(X[train],y[train]))\n\t\t\trest=confusion_matrix_k(X[train],y[train],theta,k)\n\t\t\trese=confusion_matrix_k(X[test],y[test],theta,k)\n\n\t\t\ttraine[\"p\"]=traine['p']+Counter(rest[1])\n\t\t\ttraine[\"r\"]=traine['r']+Counter(rest[2])\n\t\t\ttraine[\"f_m\"]=traine['f_m']+Counter(rest[3])\n\t\t\ttraine[\"a\"]+=rest[4]\n\n\t\t\tteste[\"p\"]=teste['p']+Counter(rese[1])\n\t\t\tteste[\"r\"]=teste['r']+Counter(rese[2])\n\t\t\tteste[\"f_m\"]=teste['f_m']+Counter(rese[3])\n\t\t\tteste[\"a\"]+=rese[4]\n\n\tif len(k)==2:\n\t traine[\"p\"]/=k_f\n\t traine[\"r\"]/=k_f\n\t traine[\"f_m\"]/=k_f\n\t traine[\"a\"]/=k_f\n\n\t teste[\"p\"]/=k_f\n\t teste[\"r\"]/=k_f\n\t teste[\"f_m\"]/=k_f\n\t teste[\"a\"]/=k_f\n\n\telse:\n\t traine[\"p\"]=dict(traine['p'])\n\t traine[\"r\"]=dict(traine['r'])\n\t traine[\"f_m\"]=dict(traine['f_m'])\n\t traine[\"a\"]/=k_f\n\n\t teste[\"p\"]=dict(teste['p'])\n\t teste[\"r\"]=dict(teste['r'])\n\t teste[\"f_m\"]=dict(teste['f_m'])\n\t teste[\"a\"]/=k_f\n\n\t for key in traine['p']:\n\t traine[\"p\"][key]/=k_f\n\t traine[\"r\"][key]/=k_f\n\t traine[\"f_m\"][key]/=k_f\n\n\t for key in teste['p']:\n\t teste[\"p\"][key]/=k_f\n\t teste[\"r\"][key]/=k_f\n\t teste[\"f_m\"][key]/=k_f\n\n\treturn traine, teste\n\n\ndef print_result(two_class=False,d=1,iris=True):\n\tif iris:\n\t\tX,y=load_iris(two_class=two_class,d=d)\n\telse:\n\t\tX,y=load_data(two_class=two_class,d=d)\n\t\tX, y = shuffle(X, y, random_state=0)\n\t\tX=X[:100,:5]\n\t\ty=y[:100]\n\tk=set(y)\n\tif(len(k)==2):\n\t\tp=cross_validation(X,y)\n\t\tprint (\"The training performance evaluators are:\\n\"\\\n\t\t\"Precision: %f\\n Recall: %f\\n F_measure: %f\\n Accuracy: %f\\n\\n\"\\\n\t\t\"The tesing performance evaluators are:\\n\"\\\n\t\t\"Precision: %f\\n Recall: %f\\n F_measure: %f\\n Accuracy: %f\\n\\n\" % (p[0]['p'],p[0]['r'],p[0]['f_m'],p[0]['a'],p[1]['p'],p[1]['r'],p[1]['f_m'],p[1]['a']))\n\telse:\n\t\tp=cross_validation(X,y)\n\t\tfor j in k:\n\t\t\tprint(\"Results for class %d\"%j)\n\t\t\tprint (\"The training performance evaluators are:\\n\"\\\n\t\t\t\"Precision: %f\\n Recall: %f\\n F_measure: %f\\n\\n\"\\\n\t\t\t\"The tesing performance evaluators are:\\n\"\\\n\t\t\t\"Precision: %f\\n Recall: %f\\n F_measure: %f\\n\\n\" % (p[0]['p'][j],p[0]['r'][j],p[0]['f_m'][j],p[1]['p'][j],p[1]['r'][j],p[1]['f_m'][j]))\n\t\tprint (\"Training Accuracy: %f\\nTesting Accuracy: %f\"%(p[0]['a'],p[1]['a']))\n\nprint(\"\\n\\nTwo class logistic regression:\")\nprint_result(True)\nprint(\"\\n\\nTwo class logistic regression with second degre\")\nprint_result(True,2)\nprint(\"\\n\\nK class logistic regression\")\nprint_result(False)\n\n\n\n\n\n\n\n","sub_path":"as3/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":9275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"471283489","text":"import tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\n\nmnist = keras.datasets.mnist.load_data()\n(train_x, train_y), (test_x, test_y) = mnist\n\nprint(train_x.shape, train_y.shape)\n# print(train_x[0], train_y[0])\ntrain_y = keras.utils.to_categorical(train_y, num_classes=10)\n\n\nmodel = keras.models.Sequential([\n keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(10, activation=tf.nn.softmax)\n]\n)\n\nmodel.compile(optimizer=tf.train.RMSPropOptimizer(0.001),\n loss=keras.losses.categorical_crossentropy,\n metrics=['accuracy'])\n\nhistory = model.fit(train_x, train_y, batch_size=32, epochs=10)\n# loss, accuracy = model.evaluate(test_x, test_y, batch_size=32)\n# print(\"The loss: {}, accuracy: {}\".format(loss, accuracy))\n","sub_path":"mnist_test.py","file_name":"mnist_test.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"206082519","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.template import loader\nfrom django.shortcuts import get_object_or_404\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.decorators import user_passes_test\nfrom django.db import connection\n\nimport nltk\nfrom nltk.data import load\n\nimport json\nfrom ComSemApp.models import *\n\n#TODO: is the user a teacher or Admin\n\n@login_required\ndef corpus_search(request):\n tags = Tag.objects.all()\n template = loader.get_template('ComSemApp/corpus/corpus_search.html')\n return HttpResponse(template.render({'tags': tags, 'offsetRange':[i for i in range(-8,8+1)]}, request))\n\n@login_required\ndef populate_word_tag(request):\n val = request.POST.get('val', None).strip()\n search_type = request.POST.get('type', None)\n output = request.POST.get('output', None)\n\n context = {}\n id_list = []\n if(search_type == 'word'):\n template = loader.get_template('ComSemApp/corpus/word_table.html')\n words = Word.objects.filter(form=val)\n context = {'val': val, 'words': words} # for html\n id_list = []\n for word in words:\n id_list.append(word.id)\n json_response = {'val': val, 'id_list': id_list} # for json\n\n else:\n template = loader.get_template('ComSemApp/corpus/tag_table.html')\n if val == \"ALL\":\n tags = Tag.objects.all()\n else:\n tags = Tag.objects.filter(tag=val)\n context = {'val': val, 'tags': tags} # for html\n for tag in tags:\n id_list.append(tag.id)\n json_response = {'val': val, 'id_list': id_list} # for json\n\n if output == 'html':\n return HttpResponse(template.render(context, request))\n else:\n return JsonResponse(json_response)\n\n\n@login_required\ndef search_results(request):\n sequential_search = request.POST.get('searchType') == '1'\n search_criteria = request.POST.get('searchCriteria', None)\n\n if not search_criteria:\n return HttpResponse('No search criteria provided', status=401)\n\n search_criteria = json.loads(search_criteria)\n\n for item in search_criteria:\n if item['type'] == 'word' and \" \" in item['val'].rstrip().lstrip():\n return HttpResponse('Invalid input: one word only per entry');\n\n query = build_query(search_criteria, sequential_search)\n\n with connection.cursor() as cursor:\n expression_ids = []\n cursor.execute(query)\n for row in cursor.fetchall():\n expression_ids.append(row[0])\n\n # grab the information we want about the expressions\n expressions = Expression.objects.filter(id__in=expression_ids)\n\n context = {\n 'expressions': expressions,\n 'sequential_search': sequential_search,\n 'search_criteria': search_criteria,\n }\n template = loader.get_template('ComSemApp/corpus/search_results.html')\n return HttpResponse(template.render(context, request))\n\n# This query builder makes the following assumptions about the search criteria:\n# there is one word, either a tag or a second word, and there may be an offset.\ndef build_query(search_criteria, sequential_search):\n words = []\n tags = []\n offset = 0\n for item in search_criteria:\n if item['type'] == 'word':\n words.append(item)\n elif item['type'] == 'tag':\n tags.append(item)\n elif item['type'] == 'offset' and sequential_search == True:\n offset = item['val']\n\n if len(words) == 0:\n return \"\"\n\n query = \"SELECT SW.expression_id\"\n if sequential_search:\n query += \", SW.position\"\n query += \" FROM ComSemApp_sequentialwords as SW\"\n\n if len(words) > 1 or len(tags) > 0:\n query += \", (SELECT SW2.expression_id\"\n if sequential_search:\n query += \", SW2.position\"\n query += \" from ComSemApp_sequentialwords as SW2\"\n if len(tags) > 0:\n query += \", ComSemApp_word as W where W.tag_id in (\" + ','.join([str(id) for id in tags[0]['id_list']])\n query += \") and SW2.word_id = W.id\"\n else:\n query += \" where SW2.word_id in (\" + ','.join([str(id) for id in words[1]['id_list']])\n query += \")\"\n query += \") as derived2\"\n query += \" where SW.word_id in (\" + ','.join([str(id) for id in words[0]['id_list']])\n query += \")\"\n\n if len(words) > 1 or len(tags) > 0:\n query += \" and SW.expression_id = derived2.expression_id\"\n\n if offset > 0:\n query += \" and derived2.position <= (SW.position + \" + str(offset) + \") and SW.position < derived2.position\"\n elif offset < 0:\n query += \" and SW.position <= (derived2.position + \" + str(abs(offset)) + \") and derived2.position < SW.position\"\n\n return query\n","sub_path":"ComSemApp/corpus/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"53098294","text":"from setuptools import setup\nimport spotlob\n\n\nwith open('README.md') as readme_file:\n readme = readme_file.read()\n\nsetup(\n name=spotlob.__name__,\n version=spotlob.__version__,\n author=spotlob.__author__,\n author_email=spotlob.__email__,\n description=spotlob.__summary__,\n license=\"BSD 3-clause\",\n url=spotlob.__url__,\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Science/Research',\n 'License :: OSI Approved :: BSD License',\n 'Natural Language :: English',\n 'Programming Language :: Python :: 3 :: Only',\n 'Topic :: Scientific/Engineering :: Image Recognition',\n ],\n long_description=readme,\n long_description_content_type='text/markdown'\n)\n","sub_path":"pypi_install_script/spotlob-0.9.0a1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"318098629","text":"'''\n\tSamples random probability vectors for use as player ranges.\n'''\nimport numpy as np\n\nfrom Settings.arguments import arguments\nfrom Game.Evaluation.evaluator import evaluator\nfrom Game.card_tools import card_tools\n\nclass RangeGenerator():\n\tdef __init__(self):\n\t\tpass\n\n\tdef _generate_recursion(self, cards, mass):\n\t\t''' Recursively samples a section of the range vector.\n\t\t@param cards an (N,J) section of the range tensor, where N is the batch size\n\t\t\t\tand J is the length of the range sub-vector\n\t\t@param mass a vector of remaining probability mass for each batch member\n\t\t\t\t@see generate_range\n\t\t'''\n\t\tbatch_size = cards.shape[0]\n\t\tassert(mass.shape[0] == batch_size)\n\t\tcard_count = cards.shape[1]\n\t\tCC, BS = card_count, batch_size\n\t\t# we terminate recursion at size of 1\n\t\tif CC == 1:\n\t\t\tcards[ : , 0 ] = mass.copy() # (10,1) <- (10,)\n\t\telse:\n\t\t\trand = np.random.rand(batch_size)\n\t\t\tmass1 = mass.copy() * rand\n\t\t\tmass2 = mass - mass1\n\t\t\thalfSize = card_count / 2\n\t\t\t# if the tensor contains an odd number of cards,\n\t\t\t# randomize which way the middle card goes\n\t\t\tif halfSize % 1 != 0:\n\t\t\t\t# if end is .5 then init randomly between two numbers\n\t\t\t\thalfSize = int(halfSize - 0.5)\n\t\t\t\thalfSize = halfSize + np.random.randint(2) # (0 or 1)\n\t\t\thalfSize = int(halfSize)\n\n\t\t\tself._generate_recursion(cards[ : , :halfSize ], mass1)\n\t\t\tself._generate_recursion(cards[ : , halfSize: ], mass2)\n\n\n\tdef _generate_sorted_range(self, ranges):\n\t\t''' Samples a batch of ranges with hands sorted by strength on the board.\n\t\t@param: range a (N,K) tensor in which to store the sampled ranges, where N is\n\t\t\t\tthe number of ranges to sample and K is the range size\n\t\t@see generate_range\n\t\t'''\n\t\tbatch_size = ranges.shape[0]\n\t\tBS = batch_size\n\t\tmass = np.ones([BS], dtype=arguments.dtype)\n\t\tself._generate_recursion(ranges, mass)\n\n\n\tdef set_board(self, board):\n\t\t''' Sets the (possibly empty) board cards to sample ranges with.\n\t\t\tThe sampled ranges will assign 0 probability to any private hands that\n\t\t\tshare any cards with the board.\n\t\t@param: board a possibly empty vector of board cards\n\t\t'''\n\t\thand_strengths = evaluator.batch_eval(board) # (CC,)\n\t\tpossible_hand_indexes = card_tools.get_possible_hand_indexes(board) # (CC,) dtype=bool\n\t\tself.possible_hands_count = possible_hand_indexes.sum(axis=0)\n\t\tPH = self.possible_hands_count\n\t\tself.possible_hands_mask = possible_hand_indexes.reshape([1,-1]) # (1,CC)\n\t\tnon_coliding_strengths = np.zeros([PH], dtype=hand_strengths.dtype)\n\t\tnon_coliding_strengths = hand_strengths[self.possible_hands_mask.reshape([-1])]\n\t\torder = np.argsort(non_coliding_strengths)\n\t\tself.reverse_order = np.argsort(order)\n\t\tself.reverse_order = self.reverse_order.reshape([1,-1]) # (1,PH) # ? - :long()\n\t\t# self.reordered_range = np.zeros([]) # ?\n\t\t# self.sorted_range = np.zeros([])\n\n\n\tdef generate_range(self, ranges):\n\t\t''' Samples a batch of random range vectors.\n\t\t\tEach vector is sampled indepently by randomly splitting the probability\n\t\t\tmass between the bottom half and the top half of the range, and then\n\t\t\trecursing on the two halfs.\n\t\t@{set_board} must be called first.\n\t\t@param: range a (N,K) tensor in which to store the sampled ranges, where N is\n\t\t\t\tthe number of ranges to sample and K is the range size\n\t\t'''\n\t\tbatch_size = ranges.shape[0]\n\t\tBS, PH = batch_size, self.possible_hands_count\n\t\tself.sorted_range = np.zeros([BS,PH], dtype=arguments.dtype)\n\t\tself._generate_sorted_range(self.sorted_range)\n\t\t# we have to reorder the the range back to undo the sort by strength\n\t\tindex = self.reverse_order * np.ones_like(self.sorted_range, dtype=arguments.int_dtype)\n\t\tself.reordered_range = np_gather(self.sorted_range, 1, index)\n\t\tmask = self.possible_hands_mask * np.ones_like(ranges, dtype=bool)\n\t\tranges.fill(0)\n\t\tranges[mask] = self.reordered_range.reshape([-1])\n\n\n\n\ndef np_gather(a, dim, index):\n\t''' Does gather operation: https://github.com/torch/torch7/blob/master/doc/tensor.md#tensor-gatherdim-index '''\n\texpanded_index = []\n\tfor i in range(a.ndim):\n\t\tif dim==i:\n\t\t\texpanded_index.append( index )\n\t\telse:\n\t\t\tshape = [-1 if i==j else 1 for j in range(a.ndim)]\n\t\t\texpanded_index.append( np.arange(a.shape[i]).reshape(shape) )\n\treturn a[expanded_index]\n\n\n\n\n#\n","sub_path":"DataGeneration/range_generator.py","file_name":"range_generator.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"325529544","text":"#!/usr/bin/python3\n\"\"\"\nrequest an url and display custom header tag\n\"\"\"\nimport urllib.request\nimport urllib.error\nimport sys\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2:\n try:\n with urllib.request.urlopen(sys.argv[1]) as res:\n header = res.info()['X-Request-Id']\n print(header)\n except urllib.error.URLError as e:\n print(e.reason)\n","sub_path":"0x11-python-network_1/1-hbtn_header.py","file_name":"1-hbtn_header.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"371034599","text":"# coding:utf-8\n# author:Coding\n# version:python 2.7\n\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\nimport csv\nimport sys\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\nreload(sys)\nsys.setdefaultencoding('utf8')\n\n'''\n基于Python 爬虫--适用于(浙经院)正方教务处\n需要安装2个第三方库\n请下载安装即可\npip install requests\npip install BeautifulSoup4\n'''\n\n\nclass zfspider(object):\n\n def __init__(self, name, password):\n self.s = requests.session()\n self.name = name\n self.password = password\n\n def ssl_login(self): # 尝试登陆SSL_VPN\n\n ssl_url = 'https://120.199.18.174/por/login_psw.csp?#http%3A%2F%2Fe.zjtie.edu.cn%2F'\n data = {\n 'mitm_result': '',\n 'svpn_name': self.name,\n 'svpn_password': self.password,\n 'svpn_rand_code': '',\n }\n self.s.post(ssl_url, data=data, verify=False)\n\n return self.s\n\n def zf_login(self): # 尝试登陆教务处\n global login_page\n lt = self.s.get(\n 'https://120.199.18.174/web/1/https/1/ca.zjtie.edu.cn/zfca/login', verify=False).text\n lt = re.findall(r'', lt)\n\n head = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'zh-CN,zh;q=0.8',\n 'Cache-Control': 'max-age=0',\n 'Connection': 'keep-alive',\n 'Host': '120.199.18.174',\n 'Referer': 'https://120.199.18.174/web/1/https/0/ca.zjtie.edu.cn/zfca/login',\n 'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'\n }\n pin_url = \"https://120.199.18.174/web/1/https/1/ca.zjtie.edu.cn/zfca/login\" # 验证码地址\n\n data = {\n 'useValidateCode': '0',\n 'isremenberme': '0',\n 'ip': '',\n 'username': self.name,\n 'password': self.password,\n 'losetime': '30',\n 'lt': lt[0],\n '_eventId': 'submit',\n 'submit1': ''\n }\n\n login_page = self.s.post(pin_url, headers=head,\n verify=False, data=data).text\n return login_page\n\n def zf_get_cj(self): # 获取成绩单\n\n get_url = re.findall(\n r'
  • ', login_page)\n\n get_url = get_url[1]\n get_url = get_url.replace(\"xs_main.aspx\", \"xscj_gc.aspx\")\n url = 'https://120.199.18.174' + get_url\n head = {\n 'Referer': 'https://120.199.18.174/web/1/http/0/e.zjtie.edu.cn/portal.do'\n }\n res = self.s.get(url,\n headers=head, verify=False)\n\n view = r'name=\"__VIEWSTATE\" value=\"(.+)\" '\n view = re.compile(view)\n rview = view.findall(res.text)[0] # 获取需要提交的表单值\n\n data = {\n '__VIEWSTATE': rview,\n 'ddlXN': '',\n 'ddlXQ': '',\n 'Button2': '',\n }\n Referer_url = 'https://120.199.18.174/web/1/http/1/dean.zjtie.edu.cn/xscj_gc.aspx?xh=' + \\\n self.name + '&type=1'\n head = {'Referer': Referer_url}\n url = 'https://120.199.18.174/web/1/http/2/dean.zjtie.edu.cn/xscj_gc.aspx?xh=' + \\\n self.name + '&type=1'\n cj = self.s.post(url, headers=head, data=data)\n xncj = cj.content\n score_list = []\n soup = BeautifulSoup(xncj, \"html.parser\")\n score_table = soup.find('table', id='Datagrid1').find_all('tr')\n\n score_list = []\n score_dict = {}\n info = []\n for score_row in score_table:\n if 'class' in score_row.attrs:\n if score_row.attrs['class'] == ['datelisthead']:\n continue\n cells = score_row.find_all('td')\n\n xn = cells[0].text\n xq = cells[1].text\n # kcdm = cells[2].text.strip()\n kcmc = cells[3].text.strip()\n kcxz = cells[4].text.strip()\n xf = cells[6].text\n cj = cells[8].text.strip()\n bkcj = cells[10].text.strip()\n cxcj = cells[11].text.strip()\n score_dict = {\"xn\": xn, \"xq\": xq, \"kcmc\": kcmc, \"cj\": cj}\n\n score_list.append(score_dict)\n\n return score_list\n","sub_path":"toweb/main/jw.py","file_name":"jw.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"12688324","text":"def solution():\n n = int(input())\n x, y = 1, 1\n plans = input().split()\n\n dx = [0, 0, -1, 1]\n dy = [-1, 1, 0, 0]\n types = ['L', 'R', 'U', 'D']\n\n for plan in plans:\n index = types.index(plan)\n nx = x + dx[index]\n ny = y + dy[index]\n if nx <= 0 or nx > n or ny <= 0 or ny > n:\n continue\n x = nx\n y = ny\n return str(x) + ' ' + str(y)\n\n\nprint(solution())\n","sub_path":"grouping/implementation/LRUD.py","file_name":"LRUD.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"511179498","text":"from __future__ import absolute_import, unicode_literals\n\nfrom django.conf.urls import url\n\nfrom . import views\n\n\nurlpatterns = [\n # URL pattern for viewing converter (/converter/)\n url(\n regex=r'^(?P\\d+)/$',\n view=views.ConverterDetailView.as_view(),\n name='detail',\n ),\n\n # URL pattern for add new converter (/converter/add)\n url(\n regex=r'^add/$',\n view=views.ConverterCreateView.as_view(),\n name='add',\n ),\n\n # URL pattern for updating specific converter (/converter//update)\n url(\n regex=r'^(?P\\d+)/update/$',\n view=views.ConverterUpdateView.as_view(),\n name='update',\n ),\n\n # URL pattern for list all converters (/converter/list)\n url(\n regex=r'^list/$',\n view=views.ConverterListView.as_view(),\n name='list',\n ),\n\n # URL pattern for delete specific converter (/converter//delete)\n url(\n regex=r'(?P\\d+)/delete/$',\n view=views.ConverterDeleteView.as_view(),\n name='delete',\n ),\n]\n","sub_path":"converters/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"227136086","text":"from flask import Blueprint\r\nfrom flask import flash\r\nfrom flask import render_template_string\r\nfrom flask import request\r\nfrom flask import views\r\n\r\nfrom app.forms import PostForm\r\nfrom flask_login import current_user\r\nfrom flask import render_template\r\nfrom app.extensions import db, cache\r\nfrom app.models import Post\r\nfrom app.utils import custom_paginator\r\n\r\npost = Blueprint('post', __name__)\r\n\r\n\r\n@post.route('/post_weibo/', methods=['POST', 'GET'])\r\n@cache.cached(timeout=90, key_prefix='weibo')\r\ndef post_weibo():\r\n form = PostForm()\r\n if form.validate_on_submit() and current_user.is_authenticated:\r\n # 判断用户是否登录\r\n # user = current_user._get_current_object\r\n # 取出数据\r\n content = form.content.data\r\n weibo = Post(content=content, user_id=current_user.id)\r\n db.session.add(weibo)\r\n form.content.data = ''\r\n flash(\"发表成功\")\r\n # weibo_list = Post.query.filter_by(rid=0).order_by(Post.timestamp.desc()).all()\r\n\r\n # 分页的逻辑,,这是页码\r\n '''\r\n args获得的是地址栏的参数,不管是post还是get方法。\r\n '''\r\n page = int(request.args.get('page') or 1)\r\n pagination = Post.query.paginate(page, per_page=3, error_out=False)\r\n weibo_list = pagination.items\r\n start, end = custom_paginator(page, pagination.pages, 10)\r\n page_range = range(start, end + 1)\r\n return render_template('post/content.html', form=form, weibo_list=weibo_list, pagination=pagination,\r\n page_range=page_range)\r\n\r\n\r\n@post.route('/user/')\r\ndef user():\r\n addr = request.remote_addr\r\n key = addr + 'user'\r\n result = cache.get(key)\r\n if result:\r\n print('从缓存中加载数据')\r\n return result\r\n result = render_template_string('

    时间简史

    ')\r\n cache.set(key, result, timeout=90)\r\n print(addr, '从数据库中加载数据')\r\n return result\r\n\r\n\r\n@post.route('/delete/', methods=['POST', 'GET'])\r\ndef delete(post_id):\r\n # 判断用户是否登录\r\n if current_user.is_authenticated:\r\n # 取出数据\r\n weibo = Post.query.filter_by(id=post_id).first()\r\n db.session.delete(weibo)\r\n db.session.commit()\r\n flash(\"删除成功\")\r\n\r\n\r\n'''\r\n标准函数需要继承flask.views.View,必须实现dispatch_request.\r\n'''\r\n\r\n\r\nclass BaseView(views.View):\r\n def get_template_name(self):\r\n raise NotImplementedError()\r\n\r\n def render_template(self, context):\r\n return render_template(self.get_template_name(), **context)\r\n\r\n def dispatch_request(self):\r\n if request.method != 'GET':\r\n return 'UNSUPPORTED'\r\n context = {'users': self.get_users()}\r\n return self.render_template(context)\r\n","sub_path":"weibo/app/views/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"217401426","text":"import datetime\nimport numpy as np\nimport pandas as pd\nimport config as cfg\nfrom decimal import Decimal\nfrom queue import Queue\nfrom brokerage import Brokerage\n\nfrom abc import ABCMeta, abstractmethod\nfrom math import floor\n\nfrom event import FillEvent, OrderEvent\nimport libs\n\nclass Portfolio(object):\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def update_signal(self, event):\n \"\"\"\n Acts on a SignalEvent to generate new orders \n based on the portfolio logic.\n \"\"\"\n raise NotImplementedError(\"Should implement update_signal()\")\n\n @abstractmethod\n def update_fill(self, event):\n \"\"\"\n Updates the portfolio current positions and holdings \n from a FillEvent.\n \"\"\"\n raise NotImplementedError(\"Should implement update_fill()\")\n \nclass NaivePortfolio(Portfolio):\n def __init__(self, bars, events, start_date, initial_capital=Decimal('100000.00')):\n self.sizing = {'crypto':Decimal('0.8'),'crypto_locked':Decimal('0'),\n 'stock':Decimal('0.2'),'stock_locked':Decimal('0')} \n self.bars = bars\n self.events = events\n self.symbol_list = self.bars.symbol_list\n self.start_date = start_date\n self.initial_capital = initial_capital\n self.start_date = start_date\n \n self.hist_positions = None\n self.cursor_positions = None\n\n def construct_all_positions(self):\n # if portfolio is empty, create it wiht 1 line of record given the cash position\n if self.cursor_positions is None:\n self.cursor_positions = pd.DataFrame.from_dict({'ts_code':['cash'],'quantity':[self.initial_capital],'available':[self.initial_capital],\n 'unsettled':[0],'cost':[1],'value':[self.initial_capital],'trade_date':[self.bars.cursorTime.trade_date]})\n # if the portfolio is already existing, append the latest one to the end of table as history, update the trade date of the current one to cursor datetime\n else:\n self.hist_positions = self.cursor_positions.copy() if self.hist_positions is None else pd.concat([self.hist_positions, self.cursor_positions])\n self.cursor_positions['trade_date'] = self.bars.cursorTime.trade_date\n self.update_position_values()\n\n def update_position_values(self):\n ''' update position cost and market value given the quantities and cursor bar price info '''\n # remove all rows with 0 holding quantity (and nothing on the way)\n self.cursor_positions = self.cursor_positions.loc[(self.cursor_positions['quantity']!=0) | (self.cursor_positions['unsettled']!=0)\\\n |(self.cursor_positions['ts_code']=='cash')]\n # cash value of cash is the quatity of cash \n self.cursor_positions['value'] = np.where(self.cursor_positions['ts_code']=='cash', self.cursor_positions['quantity'],\n self.cursor_positions['value'])\n # latest market value of the holdings is calculated and updated\n for symbol in self.cursor_positions['ts_code']:\n if symbol!='cash':\n try:\n price = libs.toPrec(self.bars.cursorBar.loc[self.bars.cursorBar['ts_code']==symbol]['close'].values[0],2,'r')\n except:\n price = np.nan\n if price is not np.nan:\n # self.cursor_positions.loc[self.cursor_positions['ts_code']==symbol,'value'] = \\\n # libs.toPrec(price * self.cursor_positions.loc[self.cursor_positions['ts_code']==symbol]['quantity'],2,'r')\n self.cursor_positions.loc[self.cursor_positions['ts_code']==symbol,'value'] = \\\n price * self.cursor_positions.loc[self.cursor_positions['ts_code']==symbol]['quantity']\n self.cursor_positions['value'] = self.cursor_positions['value'].apply(lambda x: libs.toPrec(x,2,'r'))\n\n\n def update_positions_from_fill(self, fill): \n # determine buy or sell coefficient, buy is + sell is minus, naive strategy will have a coeffecient of 1\n fill_dir = 0\n if fill.direction == 'BUY':\n fill_dir = 1\n self.sizing['crypto_locked'] = 0\n if fill.direction == 'SELL':\n fill_dir = -1\n\n delta_cash = fill_dir*fill.fill_cost\n # if there is already a holding pisition in the portfolio\n if len(self.cursor_positions.loc[self.cursor_positions['ts_code']==fill.symbol])>0:\n quantity_held = self.cursor_positions.loc[self.cursor_positions['ts_code']==fill.symbol]['quantity'].values[0]\n cost_held = self.cursor_positions.loc[self.cursor_positions['ts_code']==fill.symbol]['cost'].values[0]\n delta_quantity = libs.toPrec(fill_dir*fill.quantity,fill.fill_quantprec,'d')\n tobe_quantity = quantity_held + delta_quantity\n new_cost = (cost_held * quantity_held + delta_cash) / tobe_quantity if tobe_quantity !=0 else None\n new_cost = libs.toPrec(new_cost,2,'u')\n if fill.direction == 'BUY':\n self.cursor_positions.loc[self.cursor_positions['ts_code']=='cash','quantity'] += -delta_cash \n self.cursor_positions.loc[self.cursor_positions['ts_code']==fill.symbol,'quantity'] += delta_quantity\n # settling holding quanty\n self.cursor_positions.loc[self.cursor_positions['ts_code']==fill.symbol,'unsettled'] += -delta_quantity\n self.cursor_positions.loc[self.cursor_positions['ts_code']==fill.symbol,'available'] += delta_quantity\n if fill.direction == 'SELL': \n self.cursor_positions.loc[self.cursor_positions['ts_code']=='cash','quantity'] += -delta_cash\n self.cursor_positions.loc[self.cursor_positions['ts_code']=='cash','available'] += -delta_cash\n # settling holding quanty\n self.cursor_positions.loc[self.cursor_positions['ts_code']==fill.symbol,'quantity'] += delta_quantity\n self.cursor_positions.loc[self.cursor_positions['ts_code']==fill.symbol,'unsettled'] += -delta_quantity\n else:\n # new line item should have already been added to portfolio when order generated\n pass\n self.update_position_values()\n \n def update_fill(self, event):\n \"\"\"\n Updates the portfolio current positions and holdings \n from a FillEvent.\n \"\"\"\n if event.type == 'FILL':\n self.update_positions_from_fill(event)\n\n def generate_order(self, signal, order_type='MKT'):\n order = None\n curPrice = libs.toPrec(self.bars.cursorBar.loc[self.bars.cursorBar['ts_code']==signal.symbol]['close'].values[0],2,'r')\n secType = self.bars.cursorBar.loc[self.bars.cursorBar['ts_code']==signal.symbol]['sec_type'].values[0]\n commissionfee = Brokerage.commisions[secType]\n quantPrec = Brokerage.quant_prec[secType]\n symbol = signal.symbol\n direction = signal.signal_type\n # calculate valid sizing based on locked percentage\n sizing = self.sizing['crypto'] - self.sizing['crypto'] * self.sizing['crypto_locked']\n # sizing = self.sizing['crypto']\n cash_position = self.cursor_positions.loc[self.cursor_positions['ts_code']=='cash']['quantity'].values[0]\n cash_available = self.cursor_positions.loc[self.cursor_positions['ts_code']=='cash']['available'].values[0]\n crypto_position = self.cursor_positions.loc[self.cursor_positions['ts_code']!='cash']['value'].sum()\n total_position = cash_position + crypto_position\n \n if direction == 'LONG':\n sizing_residual = max(libs.toPrec((total_position * sizing),2,'d') - crypto_position, 0)\n cash_tospend = min(sizing_residual,cash_available)\n mkt_quantity = cash_tospend/(curPrice * (1+commissionfee)) if cash_tospend>0 else 0\n mkt_quantity = libs.toPrec(mkt_quantity,quantPrec,'d')\n # print('debug: code={}, unit_price={}, quantity={}'.format(symbol,curPrice,mkt_quantity))\n if mkt_quantity > 0:\n self.cursor_positions.loc[self.cursor_positions['ts_code']=='cash','available'] += -cash_tospend\n if len(self.cursor_positions.loc[self.cursor_positions['ts_code']==symbol]) == 0:\n record = pd.DataFrame.from_dict({'ts_code':[symbol],'quantity':[0],'available':[0],'unsettled':[mkt_quantity],\n 'cost':[0],'value':[0],'trade_date':[self.bars.cursorTime.trade_date]})\n self.cursor_positions = pd.concat([self.cursor_positions, record])\n else:\n self.cursor_positions.loc[self.cursor_positions['ts_code']==symbol,'unsettled'] += mkt_quantity\n # locking the sizing, to unlock/release it when BUY order is fullfiled\n self.sizing['crypto_locked'] = 1\n order = OrderEvent(symbol, order_type, mkt_quantity, 'BUY')\n print('order generated to BUY {} using cash {}'.format(symbol,cash_tospend))\n else:\n print('cannot LONG {} because - sizing remaining: {}, cash remaining: {}'.format(signal.symbol,sizing_residual,cash_available))\n elif direction == 'SHORT':\n try:\n mkt_quantity = self.cursor_positions.loc[self.cursor_positions['ts_code']==signal.symbol]['available'].values[0]\n except:\n mkt_quantity = 0\n if mkt_quantity > 0:\n self.cursor_positions.loc[self.cursor_positions['ts_code']==signal.symbol,'available'] += -mkt_quantity\n self.cursor_positions.loc[self.cursor_positions['ts_code']==signal.symbol,'unsettled'] += -mkt_quantity\n order = OrderEvent(symbol, order_type, mkt_quantity, 'SELL')\n print('order generated to SELL {} of {}'.format(symbol,mkt_quantity)) \n else:\n print('cannot SHORT {} because no holding available'.format(signal.symbol))\n return order\n\n def update_signal(self, event):\n \"\"\"\n Acts on a SignalEvent to generate new orders \n based on the portfolio logic.\n \"\"\"\n if event.type == 'SIGNAL':\n order_event = self.generate_order(event)\n if order_event is not None:\n self.events.put(order_event)\n\n def equity_curve(self,benchmarkcode='BTC.USD.bitfinex'):\n benchmark = self.bars.allArchivedBars.loc[self.bars.allArchivedBars['ts_code']==benchmarkcode]\n \n totalPortfolio = pd.concat([self.hist_positions, self.cursor_positions])\n targetCash = totalPortfolio.loc[totalPortfolio['ts_code']=='cash']\n target = totalPortfolio.groupby('trade_date')['value'].sum().reset_index(name ='value') \n target['perc_return'] = (target['value']-self.initial_capital)*100/self.initial_capital\n # target['perc_return'] = target['perc_return'].apply(lambda x: libs.toPrec(x,2,'r'))\n target['perc_return'] = target['perc_return'].astype(float).round(2)\n \n result = pd.merge(self.bars.df_calTbl, benchmark, how='left', on='trade_date')\n result = pd.merge(result, targetCash, how='left', on='trade_date')\n result = pd.merge(result, target, how='left', on='trade_date', suffixes=['_cash',''])\n result.set_index('trade_date')\n result['close'].fillna(method='ffill',inplace=True)\n \n benchmarkStartValue = result[:1]['close'].values[0]\n result['mkt_performance'] = (result['close']-benchmarkStartValue)*100/benchmarkStartValue\n # result['mkt_performance'] = result['mkt_performance'].apply(lambda x: libs.toPrec(x,2,'r'))\n result['mkt_performance'] = result['mkt_performance'].astype(float).round(2)\n \n result['equity_ratio'] = (result['value']-result['value_cash'])*100/result['value']\n result['equity_ratio'] = result['equity_ratio'].astype(float).round(2)\n result = result[['trade_date','equity_ratio','value','close','perc_return','mkt_performance']]\n \n overlap = Overlap()\n linechart = Line()\n linechart2 = Line()\n\n lst_xaxis = ['{}/{}/{}'.format(i[:4],i[4:6],i[6:8]) for i in result['trade_date'].values.astype('str')]\n \n linename = 'Market Performance in % {}'.format(benchmarkcode)\n lst_values = list(result['mkt_performance'])\n linechart.add(\n linename,\n lst_xaxis,\n lst_values,\n is_step=False,\n is_splitline_show=False,\n is_legend_show=True,\n is_yaxis_show=True,\n is_datazoom_show=True,\n datazoom_type='both',\n datazoom_range=[0,100],\n tooltip_trigger='axis',\n tooltip_axispointer_type='cross',\n tooltip_formatter=None,\n )\n overlap.add(linechart)\n\n linename = 'Portfolio Performance in %'\n lst_values = list(result['perc_return'])\n linechart.add(\n linename,\n lst_xaxis,\n lst_values,\n is_step=False,\n is_splitline_show=False,\n is_legend_show=True,\n is_yaxis_show=True,\n is_datazoom_show=True,\n datazoom_type='both',\n datazoom_range=[0,100],\n mark_point=['max', 'min'],\n tooltip_trigger='axis',\n tooltip_axispointer_type='cross',\n tooltip_formatter=None,\n )\n overlap.add(linechart)\n \n linename = 'Equity Holiding Ration in %'\n lst_values = list(result['equity_ratio'])\n linechart2.add(\n linename,\n lst_xaxis,\n lst_values,\n is_step=False,\n is_splitline_show=False,\n is_legend_show=True,\n is_yaxis_show=True,\n is_datazoom_show=True,\n datazoom_type='both',\n datazoom_range=[0,100],\n tooltip_trigger='axis',\n tooltip_axispointer_type='cross',\n tooltip_formatter=None,\n )\n overlap.add(linechart2,yaxis_index=1,is_add_yaxis=True)\n fname = '{}{}.html'.format(cfg.PATH_CPTFILE,'backtest')\n overlap.render(fname)","sub_path":"tsaisendo/portfolio.py","file_name":"portfolio.py","file_ext":"py","file_size_in_byte":14296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"260111264","text":"from django.db import models\nimport json\nimport csv\n\nclass Book(models.Model):\n book_title = models.CharField (max_length = 250)\n author = models.CharField (max_length = 250)\n publication_date = models.CharField (max_length = 25)\n plot_summary = models.TextField ()\n \n\ndef __str__ (self):\n return self.book_title\n\nobjects = models.Manager()\n\n\nclass Autocomplete(models.TextField):\n\n def __init__(self, sentences, times):\n self.search = ''\n self.history = defaultdict(int)\n for i in range (len(sentences)):\n self.history[sentences[i]] = times [i]\n self.matches = []\n\n def input (self,C):\n if C == '#':\n self.history [self.search] +=1 \n self.search = ''\n self.matches = []\n return\n\n if not self.search:\n for sentence in self.history:\n if sentence [0] == C:\n self.matches.append([sentence, self.history[sentence]])\n\n self.matches.sort(key=lambda x: (-x[1], x[0]))\n self.matches = [x[0] for x in self.matches]\n\n if self.search:\n \n i = len (self.search)\n self.matches = [match for match in self.matches if len(match)> i and match[i] == C ]\n\n self.search += C\n return self.matches[:3]\n\n ","sub_path":"entries/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"352905767","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('winequality-red.csv')\n\ndataset.quality.describe()\n\n#Working with Numeric Features\nnumeric_features = dataset.select_dtypes(include=[np.number])\n\ncorr = numeric_features.corr()\n\nprint (corr['quality'].sort_values(ascending=False)[:4], '\\n')\n#print (corr['quality'].sort_values(ascending=False)[-5:])\n\n##Null values\nnulls = pd.DataFrame(dataset.isnull().sum().sort_values(ascending=False)[:12])\nnulls.columns = ['Null Count']\nnulls.index.name = 'Feature'\nprint(nulls)\n\n##handling missing value\ndata = dataset.select_dtypes(include=[np.number]).interpolate().dropna()\nprint(sum(data.isnull().sum() != 0))\n\n##Build a linear model\ny = np.log(dataset.quality)\nX = data.drop(['quality', 'alcohol','sulphates'], axis=1)\n\n#X = data.drop(['fixed acidity','volatile acidity','citric acid','residual sugar','chlorides','free sulfur dioxide','total sulfur dioxide','density','pH','sulphates','alcohol'], axis=1)\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=.33)\nfrom sklearn import linear_model\nlr = linear_model.LinearRegression()\nmodel = lr.fit(X_train, y_train)\n\n##Evaluate the performance and visualize results\nprint (\"R^2 is: \\n\", model.score(X_test, y_test))\npredictions = model.predict(X_test)\nfrom sklearn.metrics import mean_squared_error\nprint ('RMSE is: \\n', mean_squared_error(y_test, predictions))\n\n##visualize\n\nactual_values = y_test\nplt.scatter(predictions, actual_values, alpha=.75, color='g')\nplt.xlabel('Predicted Quality')\nplt.ylabel('Actual Quality')\nplt.title('Regression Model')\nplt.show()","sub_path":"ICP-5/Source/ICP5_2.py","file_name":"ICP5_2.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"326410875","text":"import time\n\nLOOPS = 20\n\n# Decorator to calculate runtime of any function\ndef calculate_time(func):\n\n def inner1(*args, **kwargs):\n begin = time.time()\n for i in range(LOOPS):\n func(*args, **kwargs) # run function\n end = time.time()\n timetaken = round((end - begin)/LOOPS, 3)\n print(\"Total time taken for {} : {}s\".format(func.__name__, timetaken))\n \n return inner1","sub_path":"src/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"318080738","text":"import time\nfrom socket import *\nimport sys\nimport Utils\n\n\nPORT = 25565\nplayer1score = 0\nplayer2score = 0\n\n\ndef init_con():\n PLAYERSIP = Utils.playersIp()\n s = socket(AF_INET, SOCK_STREAM)\n s.bind((PLAYERSIP, PORT))\n print(\"\\nWaiting for a connection...\\n\")\n s.listen(1)\n global conn\n global addr\n conn, addr = s.accept() # accept the connection\n print(\"connected to \", addr)\n Utils.play_sound(\"sounds\\connected.wav\")\n time.sleep(2)\n Utils.clear(\"Host\")\n\n\ndef reset_variables():\n global board\n global updateRequired\n global boardFull\n global player\n global playersTurn\n global change\n global enemysMove\n\n board = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n updateRequired = True\n boardFull = False\n player = \"Player One (x)\"\n playersTurn = \"Player One (x)\"\n change = \"false\"\n enemysMove = \"\"\n\n\ndef check_for_line(char, s1, s2, s3):\n if board[s1] == char and board[s2] == char and board[s3] == char:\n global spot1\n global spot2\n global spot3\n\n spot1 = s1\n spot2 = s2\n spot3 = s3\n\n return True\n\n\ndef check_all(char):\n if check_for_line(char, 0, 1, 2):\n return True\n if check_for_line(char, 3, 4, 5):\n return True\n if check_for_line(char, 6, 7, 8):\n return True\n if check_for_line(char, 0, 3, 6):\n return True\n if check_for_line(char, 1, 4, 7):\n return True\n if check_for_line(char, 2, 5, 8):\n return True\n if check_for_line(char, 0, 4, 8):\n return True\n if check_for_line(char, 2, 4, 6):\n return True\n\n\ndef play_again():\n Utils.clear(\"Host\")\n global boardFull\n\n print(\"Scores:\")\n print(\"Player 1- \", player1score)\n print(\"Player 2- \", player2score)\n print(\"\\nResult:\\n\")\n\n if not boardFull:\n if playersTurn == \"Player One (x)\":\n board[spot1] = \"'x'\"\n board[spot2] = \"'x'\"\n board[spot3] = \"'x'\"\n else:\n board[spot1] = \"'o'\"\n board[spot2] = \"'o'\"\n board[spot3] = \"'o'\"\n\n Utils.show_board(board)\n\n while True:\n try:\n playAgain = int(input(\"\\n\\n1- Play again\\n0 - Exit\\n\\n\"))\n\n if playAgain != 1 and playAgain != 0:\n print(\"Please enter either ' 1 ' or ' 2 '\")\n continue\n else:\n break\n except ValueError:\n print(\"Please enter either ' 1 ' or ' 2 '\")\n continue\n\n if playAgain == 0:\n Utils.clear(\"Host\")\n print(\"Thanks for playing - Bye!\")\n conn.send(\"Disconnected\".encode())\n input(\"\\n\\nPress any key to exit\")\n Utils.clear()\n sys.exit()\n else:\n conn.send(\"Still Connected\".encode())\n print(\"\\nWaiting for client to proceed...\")\n clientleft = conn.recv(1024).decode()\n if clientleft == \"Disconnected\":\n Utils.clear(\"Host\")\n print(\"Client disconnected...\\n\\n\")\n time.sleep(1)\n print(\"Thanks for playing - Bye!\")\n input(\"\\n\\nPress any key to exit\")\n Utils.clear()\n sys.exit()\n\n reset_variables()\n main_loop()\n\n\ndef check_for_winner():\n global player1score\n global player2score\n global playersTurn\n global boardFull\n\n if check_all(\"x\"): # Checks if player has won\n Utils.clear(\"Host\")\n Utils.show_board(board)\n print(\"\\nPLAYER 1 (x) WINS!\")\n playersTurn = \"Player One (x)\"\n time.sleep(2)\n player1score += 1\n play_again()\n elif check_all(\"o\"):\n Utils.clear(\"Host\")\n Utils.show_board(board)\n print(\"\\nPLAYER 2 (o) WINS!\")\n playersTurn = \"Player Two (o)\"\n time.sleep(2)\n player2score += 1\n play_again()\n else:\n for i in range(len(board) + 1): # Checks for a stalemate\n if board[i-1] == i:\n boardFull = False\n break\n else:\n boardFull = True\n\n\ndef main_loop():\n\n global updateRequired\n global boardFull\n global player\n global player1score\n global player2score\n global playersTurn\n global change\n global enemysMove\n\n while True: # Main game loop\n\n if updateRequired:\n Utils.clear(\"Host\")\n Utils.show_board(board)\n updateRequired = False\n time.sleep(0.01)\n\n if not boardFull:\n\n if playersTurn == \"Player Two (o)\":\n print(\"\\nIt's player Twos (o) turn! - Please wait...\")\n enemysMove = conn.recv(1024).decode()\n while True:\n change = conn.recv(1024).decode()\n if change == \"true\":\n playersTurn = \"Player One (x)\"\n Utils.clear(\"Host\")\n Utils.show_board(board)\n change = \"false\"\n break\n time.sleep(0.1)\n\n if enemysMove != \"\":\n Utils.plot_enemys_move(board, \"Host\", enemysMove)\n\n if playersTurn == \"Player One (x)\":\n check_for_winner()\n\n if not boardFull:\n if playersTurn == \"Player One (x)\":\n while True:\n chooseAgain = False\n try:\n gridNum = int(input(\"\\n\" + player + \" choose a place: \"))\n if gridNum > 9 or gridNum < 1:\n print(\"\\nYou must enter a valid number (1-9)\")\n continue\n\n for i in range(len(board)):\n if board[i-1] == \"x\" or board[i-1] == \"o\":\n if gridNum == i:\n print(\"\\nPlace already taken\")\n chooseAgain = True\n continue\n if not chooseAgain:\n break\n else:\n continue\n except ValueError:\n print(\"\\nPlease enter a valid number\")\n\n for i in range(len(board)):\n if gridNum == board[i]:\n if player == \"Player One (x)\":\n board[i] = \"x\"\n conn.send(str(gridNum).encode())\n updateRequired = True\n break\n else:\n board[i] = \"o\"\n updateRequired = True\n break\n else:\n print(\"\\nBoard full, stalemate.\")\n time.sleep(2)\n play_again()\n continue\n\n if playersTurn == \"Player One (x)\":\n playersTurn = \"Player Two (o)\"\n\n change = \"true\"\n conn.send(change.encode())\n\n check_for_winner()\n\nUtils.get_connection_info(\"Host\", \"(Host leave blank)\") # Playing online or offline? if online get ip etc.\n\nif Utils.playOnline:\n init_con() # starts the connection\nelse:\n Utils.clear(\"Host\")\n print(\"Single player currently not supported\\n\")\n input(\"Press any key to exit\")\n\nreset_variables() # Sets the variables to default starting value\n\nmain_loop() # start the game\n\n","sub_path":"Host.py","file_name":"Host.py","file_ext":"py","file_size_in_byte":7328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"378683840","text":"import os\n\nfrom pyvivado import signal, config, builder\n\nclass AxiUtilsBuilder(builder.Builder):\n \n def __init__(self, params):\n super().__init__(params, package_name='axi_utils')\n self.simple_filenames = [\n os.path.join(config.hdldir, 'axi', 'axi_utils.vhd'),\n ]\n\nassert('axi_utils' not in builder.package_register)\nbuilder.package_register['axi_utils'] = AxiUtilsBuilder\n\n","sub_path":"hdl/axi/axi_utils.py","file_name":"axi_utils.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"402349990","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nb=[]\nfor i in range(0,b.shape[0],1):\n for j in range(0,b.shape[1],1):\n b[i,j]==a[j,i]\n b[i,j]=int(input('elemento:'))\nn=int(input('digite o numero de linhas:'))\nm=int(input('digite o numero de colunas:'))\nb=b.zeros((n,m))\nprint(transposta)","sub_path":"moodledata/vpl_data/59/usersdata/195/61789/submittedfiles/testes.py","file_name":"testes.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"110678527","text":"#!/usr/bin/python3\nimport socket, sys, time\n\n# create a socket object\n# seguimos trabajando con red inet\n# DATAGRAMA es el nombre pu de ip\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n#get local machine name\nhost = socket.gethostname()\n# host = \"\" atiende en todas las ip locales\nport = int(sys.argv[1])\n\n# bind to the port\nserversocket.socket.bind((host, port))\n\n# no tenemos el listen por que no tenemos el seteo del backlog de tcp \n# que servia para acumular las conexiones pendientes hasta que hagan el hanshake\n# por que simplemente aca no tenemos hanshake\n# las conexiones que entran son datos que voy trabajando directamente\n\nwhile True:\n # establish a connection\n # me quedo escuchando un dato remoto en vez de escuchar una conexion\n data, addr = serversocket.recvfrom(1024)\n # imprimo la lista de dos elementos\n print(addr)\n # direccion ip\n address = addr[0]\n # puerto\n port = addr[1]\n print(\"Address: %s - Port %d\" % (address, port))\n print(\"Receiving data: \" + data.decode())\n msg = input(\"Enter message to send: \").encode()\n serversocket.sendto(msg, addr)\n time.sleep(1)","sub_path":"alumnos/58003-Martin-Ruggeri/socket/servidores/server_dgram.py","file_name":"server_dgram.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"513288764","text":"import pprint\nfrom datetime import datetime\nfrom dataclasses import dataclass\nfrom typing import List\n\nimport requests\n\npp = pprint.PrettyPrinter(indent=4)\n\n\n@dataclass\nclass LunarPhase:\n phase: str\n datetime: datetime\n\ndef parse_api_response(year: int, month: int, phase_data: dict) -> List[LunarPhase]:\n accepted_events = [\"Full moon\", \"New Moon\", \"First quarter\", \"Last quarter\"]\n recorded_events = []\n for day, phase in phase_data.items():\n if phase[\"phaseName\"] in accepted_events:\n event = LunarPhase(\n phase=phase[\"phaseName\"],\n datetime=datetime(year=year, month=month, day=int(day))\n )\n recorded_events.append(event)\n return recorded_events\n\n\ndef get_data_for_month(year: int, month: int) -> List[LunarPhase]:\n given_date = datetime(year=year, month=month, day=1)\n epoch = datetime.utcfromtimestamp(0)\n seconds_from_epoch = (given_date - epoch).total_seconds()\n\n url = \"https://www.icalendar37.net/lunar/api/\"\n params = {\"month\": month, \"year\": year, \"LDZ\": seconds_from_epoch}\n response = requests.get(url, params=params)\n if not response.ok:\n raise Exception(f\"Something went wrong when retrieving data: {str(e)}\")\n lunar_events = parse_api_response(year, month, response.json()[\"phase\"])\n # pp.pprint(lunar_events)\n return lunar_events\n\n\ndef get_data_for_year(year: int) -> List[LunarPhase]:\n recorded_events = []\n for month in range(1, 13):\n recorded_events.extend(get_data_for_month(year, month))\n return recorded_events\n\n\ndef submit_events(phase_events: List[LunarPhase]) -> None:\n phase_events = sorted(phase_events, key=lambda x: x.datetime)\n cur_cycle = 0\n for event in phase_events:\n if event.phase == 'New Moon':\n cur_cycle = int(event.datetime.strftime('%Y%m%d'))\n cleaned_event = {\n \"cycle\": cur_cycle,\n \"datetime\": event.datetime.isoformat(),\n \"phase\": event.phase\n }\n response = requests.post('http://localhost:8000/event', json=cleaned_event)\n if not response.status_code == 200:\n raise Exception(\"something went wrong\")\n\n\nif __name__ == \"__main__\":\n phases = get_data_for_year(2020)\n phases.extend(get_data_for_year(2021))\n submit_events(phases)\n","sub_path":"scripts/add_lunar_events.py","file_name":"add_lunar_events.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"505004428","text":"#!/usr/bin/env python\n\n'''\nUsage: build_dict.py -o -s \n'''\n\n\n\nfrom .tagger import Stemmer\nfrom .extras import SimpleReader\n\ndef build_dict(corpus, stopwords=None, measure='IDF'):\n '''\n @param corpus: a list of documents, represented as lists of (stemmed)\n words\n @param stopwords: the list of (stemmed) words that should have zero weight\n @param measure: the measure used to compute the weights ('IDF'\n i.e. 'inverse document frequency' or 'ICF' i.e.\n 'inverse collection frequency'; defaults to 'IDF')\n\n @returns: a dictionary of weights in the interval [0,1]\n '''\n\n import collections\n import math\n from collections import Counter\n\n dictionary = {}\n\n if measure == 'ICF':\n words = [w for doc in corpus for w in doc]\n\n term_count = Counter(words)\n total_count = len(words)\n scale = math.log(total_count)\n\n for w, cnt in term_count.items():\n dictionary[w] = math.log(total_count / (cnt + 1)) / scale\n\n elif measure == 'IDF':\n corpus_size = len(corpus)\n scale = math.log(corpus_size)\n\n term_count = collections.defaultdict(int)\n\n for doc in corpus:\n words = set(doc)\n for w in words:\n term_count[w] += 1\n\n for w, cnt in term_count.items():\n dictionary[w] = math.log(corpus_size / (cnt + 1)) / scale\n\n if stopwords:\n for w in stopwords:\n dictionary[w] = 0.0\n\n return dictionary\n\n\ndef build_dict_from_files(output_file, corpus_files, stopwords_file=None,\n reader=SimpleReader(), stemmer=Stemmer(),\n measure='IDF', verbose=False):\n '''\n @param output_file: the name of the file where the dictionary should be\n saved\n @param corpus_files: a list of files with words to process\n @param stopwords_file: a file containing a list of stopwords\n @param reader: the L{Reader} object to be used\n @param stemmer: the L{Stemmer} object to be used\n @param measure: the measure used to compute the weights ('IDF'\n i.e. 'inverse document frequency' or 'ICF' i.e.\n 'inverse collection frequency'; defaults to 'IDF')\n @param verbose: whether information on the progress should be\n printed on screen\n '''\n\n import pickle\n\n if verbose: print('Processing corpus...')\n corpus = []\n for filename in corpus_files:\n with open(filename, 'r') as doc:\n corpus.append(reader(doc.read()))\n corpus = [[w.stem for w in map(stemmer, doc)] for doc in corpus]\n\n stopwords = None\n if stopwords_file:\n if verbose: print('Processing stopwords...')\n with open(stopwords_file, 'r') as sw:\n stopwords = reader(sw.read())\n stopwords = [w.stem for w in map(stemmer, stopwords)]\n\n if verbose: print('Building dictionary... ')\n dictionary = build_dict(corpus, stopwords, measure)\n with open(output_file, 'wb') as out:\n pickle.dump(dictionary, out, protocol=2)\n\n\nif __name__ == '__main__':\n\n import getopt\n import sys\n\n try:\n options = getopt.getopt(sys.argv[1:], 'o:s:')\n output_file = options[0][0][1]\n stopwords_file = options[0][1][1]\n corpus = options[1]\n except:\n print(__doc__)\n exit(1)\n\n build_dict_from_files(output_file, corpus, stopwords_file, verbose=True)\n\n\n\n","sub_path":"build_dict.py","file_name":"build_dict.py","file_ext":"py","file_size_in_byte":3586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"558048458","text":"from openpyxl.reader.excel import load_workbook\n\nmoen_wb = load_workbook(\"Moen List Prices 2020.xlsx\")\npri_wb = load_workbook(\"Copy of Final Pricing Sheets.xlsx\")\n\npri_st = pri_wb[\"Copy of Final Pricing Sheets\"]\nmoen_st = moen_wb[\"All SKUs\"]\n\n\nfor cell in pri_st['I']:\n if cell.value is None:\n continue\n for mcell in moen_st[\"E\"]:\n if mcell.value is None:\n continue\n if str(cell.value) in str(mcell.value):\n print(cell.value)\n print(moen_st.cell(row=mcell.row, column=6).value)\n pri_st.cell(row=cell.row, column=11).value = moen_st.cell(row=mcell.row, column=6).value\npri_wb.save(\"test.xlsx\")\n","sub_path":"sscaf.py","file_name":"sscaf.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"126384450","text":"import nltk\nimport string\nfrom nltk.corpus import stopwords\nimport heapq\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\n\n#returns a list of sentences tokenized from any number of paragraphs\ndef tokenizeParagraphs(paragraphs):\n \n sentences = []\n for para in paragraphs:\n sentences += nltk.sent_tokenize(para)\n \n return sentences\n\n#returns a list of words tokenized from a list of any number of sentences\ndef tokenizeSentences(sentences):\n \n words = []\n for sent in sentences:\n sent = sent.lower()\n sent = sent.translate(str.maketrans('', '', string.punctuation))\n \n words += nltk.word_tokenize(sent)\n \n words = [w for w in words if w not in stopwords.words(\"english\")]\n \n return words\n\n#returns a list of the top 5 words from a list of words\ndef getTop5Words(words):\n \n word2count = {} \n lemmatizer = nltk.WordNetLemmatizer()\n stemmer = nltk.PorterStemmer()\n \n for word in words: \n \n if word == \"'\" or word == \"’\":\n continue\n\n #lemmatize or stem word depending on the ending of the word\n if lemmatizer.lemmatize(word).endswith('e') or lemmatizer.lemmatize(word).endswith('y'):\n word = lemmatizer.lemmatize(word)\n else:\n word = stemmer.stem(word)\n \n #keep count of the amount of times each word appears in word2count dictionary (BAG OF WORDS)\n if word not in word2count.keys(): \n word2count[word] = 1\n else: \n word2count[word] += 1\n\n return heapq.nlargest(5, word2count, key = word2count.get) #find and return the 5 most frequent words\n\ndef getTopNoun(words):\n \n word2count = {}\n \n nouns = []\n nounTags = [\"NN\", \"NNS\", \"NNP\", \"NNPS\"]\n genericWords = [\"anything\", \"something\", \"well\", \"okay\", \"things\", \"probably\", \"say\", \"bit\", \"place\", \"right\"]\n tagged = nltk.pos_tag(words)\n for pair in tagged:\n if pair[1] in nounTags and pair[0].lower() not in genericWords:\n nouns.append(pair[0].lower())\n\n for word in nouns: \n \n if word == \"'\" or word == \"’\":\n continue\n \n #keep count of the amount of times each word appears in word2count dictionary (BAG OF WORDS)\n if word not in word2count.keys(): \n word2count[word] = 1\n else: \n word2count[word] += 1\n\n return heapq.nlargest(1, word2count, key = word2count.get) #return the most frequent noun\n\ndef getSentiment(sentences, list=True):\n sentimentA = SentimentIntensityAnalyzer()\n \n if(list):\n sumSentiment = 0\n totalSents = 0\n \n for sent in sentences:\n totalSents += 1\n sentiment = sentimentA.polarity_scores(sent)\n sumSentiment += sentiment['compound']\n \n return sumSentiment/totalSents\n \n else:\n sentiment = sentimentA.polarity_scores(sentences)\n return sentiment['compound']\n\n#returns the first word of a sentence\ndef getFirstWord(sent):\n \n words = nltk.word_tokenize(sent)\n return words[0]\n\n#returns true if a given sentence is a question\ndef isAQuestion(sentence):\n sentence = sentence.lower()\n questionWords = [\"what\", \"who\", \"why\", \"when\", \"which\", \"whose\", \"where\", \"how\", \"is\", \"are\", \"do\", \"can\", \"can't\", \"should\", \"have\", \"was\"]\n \n if sentence.endswith('?'):\n return True\n \n elif getFirstWord(sentence) in questionWords:\n return True\n \n else:\n return False\n\nclass sentenceObj:\n \n def __init__(self, sentence, topic, topicWords):\n self.sentence = sentence\n self.topic = topic\n self.keyWords = topicWords\n #self.pos = nltk.pos_tag(nltk.word_tokenize(sentence))\n \nclass responseObj:\n \n def __init__(self):\n self.response = \"\"\n self.topic = \"\"\n self.sentiment = 0\n\n####################################################################################\ntransportation = [\"transportation\", \"bike\", \"bus\", \"car\", \"train\", \"drive\", \"ride\", \"walk\", \"passenger\", \"traffic\", \"far\", \"long distance\", \"ticket\", \"delay\", \"slowly\", \"carpool\", \"uber\", \"lyft\", \"taxi\", \"gas\", \"pulled over\", \"speeding\", \"accident\", \"crash\", \"tow\", \"subway\", \"late\"]\nnutrition = [\"workout\", \"nutrition\", \"food pantry\", \"food\", \"hungry\", \"groceries\", \"grocery shopping\", \"starving\", \"eat\", \"fresh\", \"healthy\", \"unhealthy\", \"malnourished\", \"obese\", \"overeat\", \"overweight\", \"weight\", \"fat\", \"rotten\", \"stale\", \"expired\", \"balanced\", \"organic\", \"vitamin\", \"fast food\", \"homemade\", \"calories\", \"cook\", \"diet\", \"water\", \"drink\", \"beverage\", \"soda\", \"pop\", \"juice\", \"fruit\", \"vegetable\", \"vegetarian\", \"vegan\", \"meat\", \"staple\", \"bread\", \"grain\", \"processed\", \"nutrient\", \"allergy\"]\nhousing = [\"home\", \"housing\", \"rent\", \"mortgage\", \"family\", \"house\", \"apartment\", \"condo\", \"sleep\", \"comfortable\", \"uncomfortable\", \"hot\", \"cold\", \"bedroom\", \"bed\", \"roommate\", \"visitor\", \"heat\", \"air conditioning\", \"kitchen\", \"bathroom\", \"move\", \"moving\", \"lawn\", \"garden\", \"backyard\", \"front yard\", \"loud\", \"quiet\", \"homeless\", \"shelter\"]\nfinance = [\"finance\", \"poor\", \"job\", \"work\", \"money\", \"bills\", \"pay\", \"expense\", \"bank\", \"debt\", \"broke\", \"wealth\", \"donate\", \"deposit\", \"down payment\", \"mortgage\", \"savings\", \"cash\", \"cheap\", \"budget\", \"afford\", \"save\", \"borrow\", \"bankrupt\", \"lend\", \"loan\", \"apartment\", \"house\", \"home\", \"trailer\", \"hotel\", \"tenant\", \"landlord\", \"evict\", \"income\"]\nhealth = [\"doctor\", \"hospital\", \"hurt\", \"pain\", \"sick\", \"ill\", \"feeling\", \"feel\", \"headache\", \"head\", \"back\", \"ache\", \"pulled\", \"fell\", \"fall\", \"strain\", \"workout\"]\n####################################################################################\ninterviewFile = open(r\"patientInterview3.txt\", \"r\") #CHANGE FILE HERE\ninterviewTranscript = interviewFile.read()\n\n#split the input text file into two lists, one for lines spoken by the worker\n#and one for lines spoken by the patient\nworkerLines = []\npatientLines = []\ncounter = 2\nsplit = interviewTranscript.split('\\n\\n')\n\nfor line in split:\n if counter%2 == 0:\n workerLines.append(line)\n else:\n patientLines.append(line)\n \n counter += 1\n \n####################################################################################\n\n#sort the entirety of the transcript into sentences and words based on who said them\nworkerSents = []\nworkerWords = []\npatientSents = []\npatientWords = []\n\nworkerSents = tokenizeParagraphs(workerLines)\nworkerWords = tokenizeSentences(workerSents)\npatientSents = tokenizeParagraphs(patientLines)\npatientWords = tokenizeSentences(patientSents)\n####################################################################################\n\n#create a dictionary where the keys are questions, and the values are the answer to each question\ncurrQuestion = \"\"\nq2Responses = {}\ninterviewSentences = nltk.sent_tokenize(interviewTranscript)\n\nfor sent in interviewSentences:\n if isAQuestion(sent) and sent in workerSents:\n currQuestion = sent\n \n if currQuestion is not \"\" and sent != currQuestion:\n if sent in patientSents:\n if currQuestion not in q2Responses.keys():\n q2Responses[currQuestion] = responseObj()\n q2Responses[currQuestion].response = sent\n else:\n q2Responses[currQuestion].response += \" \" + sent\n####################################################################################\n \n#create topic for a question and answer based on the most frequent noun\nfor key in q2Responses.keys():\n words = nltk.word_tokenize(key)\n \n words += nltk.word_tokenize(q2Responses[key].response)\n \n q2Responses[key].topic = getTopNoun(words)\n####################################################################################\n\n#gather sentiment for the answer to each question use vader\nfor key in q2Responses.keys():\n q2Responses[key].sentiment = getSentiment(q2Responses[key].response, False)\n####################################################################################\n \n#go through each sentence and identify the sentences that contain a key word\n#from one of the categories. if it contains a word, note which category\nimportantSents = []\n\nfor sent in patientSents:\n topic = \"none\"\n topicWords = []\n \n #check each word to see if it fits in a category\n words = nltk.word_tokenize(sent)\n for w in words:\n '''\n if w in health:\n topic = \"health\"\n topicWords.append(w)\n '''\n if w in housing:\n topic = \"housing\"\n topicWords.append(w)\n elif w in nutrition:\n topic = \"food\"\n topicWords.append(w)\n elif w in finance:\n topic = \"finances\"\n topicWords.append(w)\n elif w in transportation:\n topic = \"transportion\"\n topicWords.append(w)\n \n #if a key word was found add the sentence to the list of \"important\" sentences\n if topic != \"none\":\n importantSents.append(sentenceObj(sent, topic, topicWords))\n####################################################################################\n\n#----------print out key information-------\n\nprint(\"---------OVERALL SENTIMENT OF PATIENT RESPONSE---------\")\nprint(\"sentiment score (min of -1, max of 1): \", getSentiment(patientSents), \"\\n\")\n\nprint(\"---------QUESTIONS AND RESPONSES---------\")\nfor key in q2Responses.keys():\n print(\"question:\", key)\n print(\"response:\", q2Responses[key].response, \"\\n\")\n \nprint(\"---------QUESTIONS, TOPICS, AND SENTIMENT OF ANSWER---------\")\nfor key in q2Responses.keys():\n print(\"question:\", key)\n print(\"topic:\", q2Responses[key].topic)\n print(\"sentiment of patient response:\", q2Responses[key].sentiment, \"\\n\")\n \nprint(\"---------SENTENCES CONTAINING KEYWORDS---------\")\nfor sent in importantSents:\n print(sent.sentence, \"\\ntopic:\", sent.topic, \"\\ntopic words:\", sent.keyWords, \"\\n\")\n\n\n","sub_path":"transcriptAnalyzer.py","file_name":"transcriptAnalyzer.py","file_ext":"py","file_size_in_byte":10041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"497632365","text":"from django.urls import path\nfrom interface.views.server import (\n ServerListView,\n ServerDetailView,\n ServerServiceListView,\n)\nfrom interface.views.service import (\n ServiceListView,\n ServiceDetailView\n)\nfrom interface.views.proxy import (\n ProxyListView,\n ProxyDetailView\n)\nfrom interface.views.proxy_ctl import (\n ProxyServiceCtlView\n)\nfrom interface.views.index import index_view\n\nurlpatterns = [\n\n # 服务器\n path('servers/', ServerListView.as_view()),\n path('server/', ServerDetailView.as_view()),\n path('server/services/', ServerServiceListView.as_view()),\n\n # 服务\n path(\"services/\", ServiceListView.as_view()),\n path(\"service/\", ServiceDetailView.as_view()),\n\n # 代理\n path(\"proxys/\", ProxyListView.as_view()),\n path(\"proxy/\", ProxyDetailView.as_view()),\n\n path(\"proxy/service/\", ProxyServiceCtlView.as_view()),\n]\n","sub_path":"port_proxy/interface/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"603571956","text":"\"\"\"1.7 Rotate Matrix\n\nGiven an image represented by an NxN matrix, write a method to rotate the image by 90 degrees.\nEach pixel in the image is 4 bytes.\nCan you do this in place?\n\"\"\"\n\ndef rotate_matrix(matrix):\n \"\"\"Rotate passed-in matrix by 90 degrees clockwise.\n Flip over diagonal from (0,0) to (N-1,N-1), then flip over vertical across center.\n\n matrix - Array to rotate.\n\n Time: O(N^2), for iterating over the array\n Space: O(1), as the rotation is done in place\n \"\"\"\n N = len(matrix)\n\n # Flip over diagonal\n for i in range(N - 1):\n for j in range(1, N):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\n # Flip over vertical across center\n for i in range(N):\n for j in range(N // 2):\n matrix[i][j], matrix[i][N-j-1] = matrix[i][N-j-1], matrix[i][j]","sub_path":"Chapter 1 - Arrays and Strings/RotateMatrix.py","file_name":"RotateMatrix.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"85603898","text":"#!/usr/bin/env python3\n\n# Challenge 03\n# Pablo Martinez Abrego Gonzalez\n\nimport sys\n\n# Find the pivot point to divide into two sub arrays\ndef search_pivot(v):\n start = 0\n end = len(v) - 1\n while start < end:\n middle = (start + end) // 2\n if v[middle] > v[end]:\n start = middle + 1\n else:\n end = middle - 1\n if v[middle] < v[middle+1] and v[middle] < v[middle-1]:\n return middle\n return start\n\n# Binary Search in the subarray where target is located\ndef binary_search(v, start, end, target):\n if start > end:\n return -1\n middle = (start + end) // 2\n if v[middle] == target:\n return middle\n if target > v[middle]:\n return binary_search(v, middle + 1, end, target)\n return binary_search(v, start, middle - 1, target)\n\n# Search in which sub array the target is and apply binary search\ndef search_target(v, target, pivot):\n if target > v[len(v)-1] and target <= v[pivot-1]:\n return binary_search(v, 0, pivot-1, target)\n return binary_search(v, pivot, len(v)-1, target)\n\n# Main function\ndef main():\n line_num = 0\n for line in sys.stdin:\n line_num += 1\n if line_num % 2 != 0:\n v = list(map(int, line.strip().split()))\n else:\n target = int(line.strip())\n pivot = search_pivot(v)\n index = search_target(v, target, pivot)\n if index != -1 and pivot != -1:\n print(str(target) + \" found at index \" + str(index))\n else:\n print(str(target) + \" was not found\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"challenge03/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"539844448","text":"class FogNode():\n def __init__(self, index, C, U, switch, type, position):\n self.index = index\n self.C = C\n self.U = U\n self.position = position\n self.highestBid = 0\n self.highestBidder = None\n self.type = type\n self.switch = switch\n def setBid(self, bidderIndex, bid):\n# print('\\tNode {}-> New Bid: {} from: {}'.format(self.index, bid, bidderIndex))\n if (self.highestBid < bid):\n# print('\\t\\tHighest bid changed from {}:{} to {}:{}'.format(self.highestBidder, self.highestBid, bidderIndex, bid))\n self.highestBid = bid\n self.highestBidder = bidderIndex\n def reset(self):\n self.highestBid = 0\n self.highestBidder = None\n","sub_path":"6/fog_node/fog_node.py","file_name":"fog_node.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"297261675","text":"import re\nimport numpy as np\nimport sys\n\nwith open(sys.argv[1], \"r\") as f:\n lines = f.readlines()\n\n\nl = (\"\").join(lines).split(\"nthread\")[1:]\n\n\nimport pandas as pd\n\nres = {\"n_thread\":[], \"mean\": [], \"std\": []}\n\n\nfor i in range(len(l)):\n time = re.findall(r\"(\\d+) ms\", l[i])\n\n if l[i].find(\"differ\") != -1:\n print(i, \"error\")\n res[\"n_thread\"].append(l[i][:2].strip())\n res[\"mean\"].append(np.mean([int(x) for x in time]))\n res[\"std\"].append(np.std([int(x) for x in time]))\n\ndf = pd.DataFrame(res)\ndf = df[[\"n_thread\", \"mean\", \"std\"]]\ndf.to_csv(sys.argv[1].split('.')[0] + \".csv\", index = False)\n\n","sub_path":"src/get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"508499693","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"test_data.py\n\nTests for `data.py` module.\n\"\"\"\n\nimport unittest\nimport nose\nimport sys\n\nfrom .context import data, paths\n\n# CATALOGS_DIR = paths.TEST_CATALOGS_DIR\n\n\nclass GetDataTestCase(unittest.TestCase):\n \"\"\"Tests for GetData class.\"\"\"\n\n def test_get_series(self):\n serie = data.get_series(\n \"sspm\", \"1\", \"1.1\", \"oferta_global_pbi\", fmt=\"serie\")\n\n self.assertEqual(len(serie), 20)\n self.assertEqual(serie[-1], 468301.014942)\n\n # @unittest.skip(\"skip\")\n def test_get_series_by_id(self):\n serie = data.get_series_by_id(\"1.1_OGP_D_1993_A_17\", fmt=\"serie\")\n\n self.assertEqual(len(serie), 20)\n self.assertEqual(serie[-1], 468301.014942)\n\n # @unittest.skip(\"skip\")\n def test_get_series_pct_change(self):\n serie = data.get_series(\n \"sspm\", \"1\", \"1.1\", \"oferta_global_pbi\", fmt=\"serie\", pct_change=1)\n\n self.assertEqual(len(serie), 20)\n self.assertEqual(round(serie[-1], 6), 0.018996)\n\n\nif __name__ == '__main__':\n nose.run(defaultTest=__name__)\n","sub_path":"scripts/tests/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"85693594","text":"from pathlib import Path\nfrom ipywidgets import Output, Layout\nimport ipyvuetify as v\n\nimport sepal_ui.sepalwidgets as sw\nimport sepal_ui.scripts.utils as su\n\nimport component.widget as cw\nfrom component.message import cm\nimport component.parameter as param\n\nfrom component.scripts.filter_closing_smm import run_filter\n\n__all__ = [\"FilterTile\"]\n\n\nclass FilterTile(v.Layout, sw.SepalWidget):\n def __init__(self, *args, **kwargs):\n\n self.class_ = \"d-block\"\n self._metadata = {\"mount_id\": \"filter\"}\n\n super().__init__(*args, **kwargs)\n\n self.filter_view = FilterView()\n\n self.children = [\n v.Card(\n class_=\"mb-2\",\n children=[\n v.CardTitle(children=[sw.Markdown(cm.filter_tile.title)]),\n v.CardText(children=[sw.Markdown(cm.filter_tile.desc)]),\n ],\n ),\n self.filter_view,\n ]\n\n\nclass FilterView(v.Card):\n def __init__(self, *args, **kwargs):\n\n self.min_height = \"600px\"\n self.class_ = \"pa-2\"\n\n super().__init__(*args, **kwargs)\n\n self.output = Output()\n self.btn = sw.Btn(\"Apply morphological filter\", class_=\"mb-2\")\n self.alert = sw.Alert()\n\n self.w_selector_view = cw.FolderSelectorView(\n folder=param.RAW_DIR, wildcard=\"[!.]*.tif\"\n )\n self.w_selector = self.w_selector_view.w_selector\n\n self.children = [\n v.Row(\n children=[\n v.Col(\n children=[\n self.w_selector_view,\n ]\n ),\n v.Col(\n children=[\n v.Card(\n children=[\n v.CardTitle(children=[\"Process\"]),\n self.btn,\n self.output,\n self.alert,\n ]\n )\n ]\n ),\n ]\n )\n ]\n\n self.btn.on_event(\"click\", self.on_click)\n\n @su.loading_button()\n def on_click(self, widget, event, data):\n \"\"\"Run filter script\"\"\"\n recursive = self.w_selector_view.w_recursive.v_model\n run_filter(self.w_selector.v_model, recursive, self.alert, self.output)\n\n self.alert.add_msg(f\"All the images were correctly processed.\", type_=\"success\")\n","sub_path":"component/tiles/filter_tile.py","file_name":"filter_tile.py","file_ext":"py","file_size_in_byte":2550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"415320143","text":"import os \ndef parse_args():\n import argparse\n parser = argparse.ArgumentParser(description='Correlation of reserved stars')\n \n parser.add_argument('--tausjnfile',\n default='/home/dfa/sobreira/alsina/alpha-beta-gamma/code/correlations/alltausp_jk.fits',\n help='Full Path to the Only stars Piff catalog')\n parser.add_argument('--xim', default=False,\n action='store_const', const=True,\n help='trecorr return xim instead of xip')\n parser.add_argument('--outpath', default='/home/dfa/sobreira/alsina/alpha-beta-gamma/code/correlations/',\n help='location of the output of the files')\n \n \n args = parser.parse_args()\n\n return args\ndef main():\n import sys\n import fitsio\n from astropy.io import fits\n import itertools\n import numpy as np\n sys.path.insert(0, '/home/dfa/sobreira/alsina/alpha-beta-gamma/code/src')\n #sys.path.insert(0, '/global/cscratch1/sd/alsina/alpha-beta-gamma/code/src')\n\n \n \n args = parse_args()\n\n #Make directory where the ouput data will be\n outpath = os.path.expanduser(args.outpath)\n try:\n if not os.path.exists(outpath):\n os.makedirs(outpath)\n except OSError:\n if not os.path.exists(outpath): raise\n\n namesout=[ 'TAU0','TAU2','TAU5']\n if args.xim:\n args.tausjnfile = '/home/dfa/sobreira/alsina/alpha-beta-gamma/code/correlations/alltausm_jk.fits'\n alldata = fitsio.read(args.tausjnfile, ext=1)\n\n names=['BIN1', 'BIN2','ANGBIN', 'VALUE', 'ANG']\n forms = ['i4', 'i4', 'i4', 'f8', 'f8']\n dtype = dict(names = names, formats=forms)\n nrows = 20\n outdata = np.recarray((nrows, ), dtype=dtype)\n\n a=[i for i in range(0,nrows)]\n b=[j for j in range(0,nrows)]\n bin_pairs=[]\n for p in itertools.product(a, b):\n bin_pairs.append(p)\n\n for nam in namesout:\n corr = []\n covmat = np.zeros(shape=(nrows, nrows))\n for i,j in bin_pairs:\n bin1 = (alldata['ANGBIN']==i)\n bin2 = (alldata['ANGBIN']==j)\n a = alldata[nam][bin1]; b = alldata[nam][bin2];\n covmat[i,j] = np.cov(a,b)[0][1]\n if (i==j):\n corr.append(np.mean(alldata[nam][bin1]))\n\n hdu = fits.PrimaryHDU()\n hdul = fits.HDUList([hdu])\n covmathdu = fits.ImageHDU(covmat, name='COVMAT')\n hdul.insert(1, covmathdu)\n \n\n angarray = alldata['THETA'][alldata['JKR']==0]\n valuearray = np.array(corr)\n bin1array = np.array([ -999]*nrows)\n bin2array = np.array([ -999]*nrows)\n angbinarray = np.arange(nrows)\n array_list = [bin1array, bin2array, angbinarray, valuearray, angarray ]\n for array, name in zip(array_list, names): outdata[name] = array \n\n corrhdu = fits.BinTableHDU(outdata, name=nam)\n hdul.insert(2, corrhdu)\n if args.xim:\n hdul.writeto(outpath + nam + 'm.fits', clobber=True)\n else:\n hdul.writeto(outpath + nam + 'p.fits', clobber=True)\n \n \n \n\n \nif __name__ == \"__main__\":\n main()\n\n","sub_path":"code/buildtaus.py","file_name":"buildtaus.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"502672362","text":"\"\"\"Unit tests for testing support\n\n\"\"\"\n\nimport logging\nimport unittest\n\nfrom data_models.parameters import arl_path\nfrom processing_components.image.gradients import image_gradients\nfrom processing_components.image.operations import export_image_to_fits, show_image, import_image_from_fits\n\nlog = logging.getLogger(__name__)\n\n\nclass TestPrimaryBeams(unittest.TestCase):\n def setUp(self):\n from data_models.parameters import arl_path\n self.dir = arl_path('test_results')\n \n def test_create_gradient(self):\n real_vp = import_image_from_fits(arl_path('data/models/MID_GRASP_VP_real.fits'))\n gradx, grady = image_gradients(real_vp)\n \n gradxx, gradxy = image_gradients(gradx)\n gradyx, gradyy = image_gradients(grady)\n\n gradx.data *= real_vp.data\n grady.data *= real_vp.data\n gradxx.data *= real_vp.data\n gradxy.data *= real_vp.data\n gradyx.data *= real_vp.data\n gradyy.data *= real_vp.data\n\n import matplotlib.pyplot as plt\n plt.clf()\n show_image(gradx, title='gradx')\n plt.show()\n plt.clf()\n show_image(grady, title='grady')\n plt.show()\n export_image_to_fits(gradx, \"%s/test_image_gradients_gradx.fits\" % (self.dir))\n export_image_to_fits(grady, \"%s/test_image_gradients_grady.fits\" % (self.dir))\n\n plt.clf()\n show_image(gradxx, title='gradxx')\n plt.show()\n plt.clf()\n show_image(gradxy, title='gradxy')\n plt.show()\n plt.clf()\n show_image(gradyx, title='gradyx')\n plt.show()\n plt.clf()\n show_image(gradyy, title='gradyy')\n plt.show()\n export_image_to_fits(gradxx, \"%s/test_image_gradients_gradxx.fits\" % (self.dir))\n export_image_to_fits(gradxy, \"%s/test_image_gradients_gradxy.fits\" % (self.dir))\n export_image_to_fits(gradyx, \"%s/test_image_gradients_gradyx.fits\" % (self.dir))\n export_image_to_fits(gradyy, \"%s/test_image_gradients_gradyy.fits\" % (self.dir))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/processing_components/test_image_gradients.py","file_name":"test_image_gradients.py","file_ext":"py","file_size_in_byte":2082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"643761293","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 8 08:25:55 2017\n\n@author: christopherdavid\n\"\"\"\n\n\n\"\"\"\n==========================\nPlotting Validation Curves\n==========================\n\nIn this plot you can see the training scores and validation scores of an estimator\nfor different values of an estimator parameter. \n\n1) training score and the validation score are low. -> This is called underfitting.\n2) high values for both scores -> the classifier is performing fairly well.\n3) training score is good but the validation score is poor -> the classifier will overfit\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import validation_curve\n\ndef plot_validation_curve(estimator, title, X, y, ylim=None, cv=None,\n n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):\n plt.figure()\n plt.title(title)\n plt.xlabel(\"$\\gamma$\")\n plt.ylabel(\"Score\")\n\n param_range = np.linspace(1, 10000, num=10)\n train_scores, test_scores = validation_curve(estimator, X, y, param_name=\"C\", param_range=param_range, cv=cv, scoring=\"accuracy\", n_jobs=n_jobs)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n \n lw = 2\n plt.semilogx(param_range, train_scores_mean, label=\"Training score\",\n color=\"darkorange\", lw=lw)\n plt.fill_between(param_range, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.2,\n color=\"darkorange\", lw=lw)\n plt.semilogx(param_range, test_scores_mean, label=\"Cross-validation score\",\n color=\"navy\", lw=lw)\n plt.fill_between(param_range, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.2,\n color=\"navy\", lw=lw)\n plt.legend(loc=\"best\")\n return plt\n \n","sub_path":"plot_validation_curve_over_parameter.py","file_name":"plot_validation_curve_over_parameter.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"416458639","text":"import discord\nfrom discord.ext import commands\nfrom discord import Webhook, AsyncWebhookAdapter\nimport aiohttp\nimport random\n\nrules = [\":one: **No Harassment**, threats, hate speech, inappropriate language, posts or user names!\", \":two: **No spamming** in chat or direct messages!\", \":three: **No religious or political topics**, those don’t usually end well!\", \":four: **Keep pinging to a minimum**, it is annoying!\", \":five: **No sharing personal information**, it is personal for a reason so keep it to yourself!\", \":six: **No self-promotion or advertisement outside the appropriate channels!** Want your own realm channel? **Apply for one!**\", \":seven: **No realm or server is better than another!** It is **not** a competition.\", \":eight: **Have fun** and happy crafting!\", \":nine: **Discord Terms of Service apply!** You must be at least **13** years old.\"]\n\n\nclass MiscCMD(commands.Cog):\n def __init__(self,bot):\n self.bot = bot\n\n #DM Command\n @commands.command()\n @commands.has_role(\"Moderator\")\n async def DM(self, ctx, user: discord.User, *, message=None):\n message = message or \"This Message is sent via DM\"\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used DM \\n\")\n logfile.close()\n await user.send(message)\n await user.send(\"Sent by: \" + author.name)\n \n @DM.error\n async def DM_error(self,ctx, error):\n if isinstance(error, commands.MissingRole):\n await ctx.send(\"Uh oh, looks like you don't have the Moderator role!\")\n\n #Ping Command\n @commands.command()\n async def ping(self, ctx):\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used PING \\n\")\n logfile.close()\n #await ctx.send(f'**__Latency is__ ** {round(client.latency * 1000)}ms')\n pingembed = discord.Embed(title = \"Pong! ⌛\", color = 0xb10d9f, description=\"Current Discord API Latency\")\n pingembed.add_field(name = \"Current Ping:\" , value = f'{round(self.bot.latency * 1000)}ms')\n await ctx.send(embed = pingembed)\n\n #Uptime Command\n @commands.command()\n async def uptime(self,ctx):\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used UPTIME \\n\")\n logfile.close()\n await ctx.send(\"Really long time, lost track. \")\n\n #Purge Command\n @commands.command()\n @commands.has_permissions(manage_messages = True)\n async def clear(self, ctx,amount=2):\n author = ctx.message.author\n await ctx.channel.purge(limit = amount)\n\n #Say Command\n @commands.command()\n @commands.has_permissions(manage_channels = True)\n async def say(self, ctx,*,reason):\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used SAY \\n\")\n logfile.close()\n await ctx.channel.purge(limit = 1)\n await ctx.send(reason) \n\n #Embed Command\n @commands.command()\n @commands.has_permissions(manage_channels = True)\n async def embed(self, ctx, channel : discord.TextChannel, color : discord.Color , *, body):\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used EMBED \\n\")\n logfile.close()\n title , bottom = body.split(\" | \")\n embed = discord.Embed(title = title, description = bottom, color = color)\n await channel.send(embed = embed)\n \n #Nick Commamd\n @commands.command()\n @commands.has_role(\"Moderator\")\n async def nick(self, ctx, user :discord.Member, channel : discord.TextChannel):\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used NICK \\n\")\n logfile.close()\n name = user.display_name\n channel = channel.name.split('-')\n if len(channel) == 2: # #real-emoji\n realm, emoji = channel\n else: # #realm-name-emoji \n realm, emoji = channel[0], channel[-1]\n await user.edit(nick=str(name) + \" \" + str(emoji))\n await ctx.send(\"Changed nickname!\")\n\n @nick.error\n async def nick_error(self,ctx, error):\n if isinstance(error, commands.MissingRole):\n await ctx.send(\"Uh oh, looks like you don't have the Moderator role!\")\n\n #Removes your nickname. \n @commands.command()\n async def rememoji(self, ctx):\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used REMEMOJI \\n\")\n logfile.close()\n name = author.name\n await author.edit(nick = str(author.name))\n await ctx.send(\"Removed your nickname!\")\n\n #Add's an emoji to your nickname.\n @commands.command()\n async def addemoji(self, ctx, channel : discord.TextChannel):\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used ADDEMOJI \\n\")\n logfile.close()\n name = author.display_name\n channel = channel.name.split('-')\n if len(channel) == 2: # #real-emoji\n realm, emoji = channel\n else: # #realm-name-emoji \n realm, emoji = channel[0], channel[-1]\n await author.edit(nick=str(name) + str(emoji))\n await ctx.send(\"Changed your nickname!\")\n \n @addemoji.error\n async def addemoji_error(self,ctx, error):\n if isinstance(error, commands.BadArgument):\n await ctx.send(\"Hmm, you didn't give me all the arguments.\")\n\n #Rule Command [INT]\n @commands.command()\n async def rule(self, ctx,*,number):\n author = ctx.message.author\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used RULE \\n\")\n logfile.close()\n await ctx.send(rules[int(number)-1])\n\n\n #Add's a gamertag to the database. \n @commands.command()\n async def gamertag(self, ctx, gamertag):\n author = ctx.message.author\n channel = ctx.message.channel\n logfile = open(\"commandlog.txt\", \"a\")\n logfile.write(str(author.name) + \" used GAMERTAG \\n\")\n logfile.close()\n GamerTag = open(\"Gamertags.txt\", \"a\")\n GamerTag.write(gamertag + \" \" + str(author.id) + \"\\n\")\n def check(m):\n return m.content is not None and m.channel == channel and m.author is not self.bot.user\n await channel.send(\"Success! \\nWould you like to change your nickname to your gamertag? (If so, you may have to add your emojis to your nickname again!)\\n> *Reply with:* **YES** or **NO**\")\n answer7 = await self.bot.wait_for('message', check=check)\n\n if answer7.content == \"YES\":\n await author.edit(nick = gamertag)\n await ctx.send(\"Success!\")\n\n elif answer7.content == \"NO\":\n await ctx.send(\"Okay, canceled it...\")\n\n @gamertag.error\n async def gamertag_error(self, ctx, error):\n if isinstance(error, commands.BadArgument):\n await ctx.send(\"Uh oh, you didn't include all the arguments! \")\n\n\n #Tag command, extra commands basically. \n @commands.command()\n async def tag(self, ctx, tagnum):\n if tagnum == \"1\":\n text_channel = self.bot.get_channel(\"587502693246042112\")\n text_channel2 = self.bot.get_channel(\"587632638819434507\")\n contentc = discord.Embed(title = \"Content Creators\", description = f\"Minecraft Related Content may go in the <#587632638819434507> channel while other content can go in <#587502693246042112>! \\n**Make content?** Feel free to ask a Moderator to give you the Content Creator role!\", color = 0xfc0303)\n await ctx.send(embed = contentc)\n elif tagnum == \"2\":\n text_channel2 = self.bot.get_channel(\"587850399759990794\")\n realm = discord.Embed(title = \"Realm Applications\", description = f\"Welcome! I see you've asked about joining a realm! The Realm Portal has a ton of realms you can choose from. Each having their own application process, if you would like to join one check out the Realms and Server tab! You can view details about each realm by checking its pins and channel description! Please remember that there is no 'better' realm! \\n**Community Realm** Don't know what to join? Consider joining the MRP Community Realm! \\n**Apply for a Realm Channel!** Have a realm you would like to advertise? Once you reach Zombie Slayer, you should be able to fill out the application in <#587850399759990794>!\", color = 0xeb07cc)\n await ctx.send(embed = realm)\n elif tagnum == \"3\":\n realm = discord.Embed(title = \"Realm Applications\", description = \"Hello! It looks like you wanted to join a realm! Please not that all realms that are shown in the Realm Portal are **BEDROCK**! If you would like to join a realm, please take a moment and read the channel's description **and** the pins! You can find things like their application, realm details, etc in there. \\n**NOTE:** Please do not contact Moderators or Admins if you have a question regarding a realm. It's best to contact the realm owners/operators as we are not a representative for that specific realm! \")\n \n elif tagnum == \"help\":\n await ctx.send(\"**Tag Numbers:** \\n1: Content Related \\n2: Realm Applications\")\n\n else:\n await ctx.send(\"That number isn't a valid response!\")\n\n #OfO command. \n @commands.command()\n async def webhook(self, ctx, *, reason):\n return\n async with aiohttp.ClientSession() as session:\n url = 'https://discord.com/api/webhooks/783135151155970049/nTOU4H3ch2Q3Z3lLEDUGj8jq-tNZ-cZFRvBPdjphl5aMYtM5j3Urv7p1KtTMxXfrwZmo'\n webhook = Webhook.from_url(url, adapter=AsyncWebhookAdapter(session)) #something here to cycle through url's\n author = ctx.message.author\n await webhook.send(reason ,username=author.name, avatar_url = author.avatar_url)\n\n @commands.command(description=\"Rock Paper Scissors\")\n async def rps(self, msg: str):\n \"\"\"Rock paper scissors. Example : /rps Rock if you want to use the rock.\"\"\"\n # Les options possibles\n t = [\"rock\", \"paper\", \"scissors\"]\n # random choix pour le bot\n computer = t[random.randint(0, 2)]\n player = msg.lower()\n print(msg)\n if player == computer:\n await self.bot.say(\"Tie!\")\n elif player == \"rock\":\n if computer == \"paper\":\n await self.bot.say(\"You lose! {0} covers {1}\".format(computer, player))\n else:\n await self.bot.say(\"You win! {0} smashes {1}\".format(player, computer))\n elif player == \"paper\":\n if computer == \"scissors\":\n await self.bot.say(\"You lose! {0} cut {1}\".format(computer, player))\n else:\n await self.bot.say(\"You win! {0} covers {1}\".format(player, computer))\n elif player == \"scissors\":\n if computer == \"rock\":\n await self.bot.say(\"You lose! {0} smashes {1}\".format(computer, player))\n else:\n await self.bot.say(\"You win! {0} cut {1}\".format(player, computer))\n else:\n await self.bot.say(\"That's not a valid play. Check your spelling!\")\n\n\ndef setup(bot):\n bot.add_cog(MiscCMD(bot))\n","sub_path":"cogs/MiscCMD.py","file_name":"MiscCMD.py","file_ext":"py","file_size_in_byte":10819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"101766485","text":"from flask import request\nfrom flask_restplus import Namespace, fields, Resource\nfrom rest_api.models import db_accessor\n\n\nuser_ns = Namespace('user', description='End point of ToDo users.')\n\n\nuser = user_ns.model('User', {\n 'id': fields.Integer(\n required=True,\n description='A user ID',\n example=1\n ),\n 'name': fields.String(\n required=True,\n description='A user name.',\n example='taro'\n ),\n 'email': fields.String(\n required=True,\n description='A user e-mail address.',\n example='taro@example.com'\n )\n})\n\n@user_ns.route('/')\nclass UserController(Resource):\n @user_ns.marshal_with(user)\n def get(self, id):\n return db_accessor.db.user.find_one_or_404({'id': id})\n\n def post(self, id):\n parser = user_ns.parser()\n parser.add_argument('name', type=str)\n parser.add_argument('email', type=str)\n args = parser.parse_args()\n db_accessor.db.user.insert({\n \"id\": id,\n \"name\": request.json[\"name\"],\n \"email\": request.json[\"email\"]\n })\n return \"ok\"\n\n","sub_path":"Python/Starting/chapxx/rest-api/rest_api/apis/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"451736946","text":"# /usr/bin/python\n# codeing=utf-8\n\nclass Solution(object):\n def containsNearbyDuplicate(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: bool\n \"\"\"\n hashdict = {}\n\n for i in range(0, len(nums)):\n if hashdict.has_key(nums[i]):\n if i - hashdict[nums[i]] <= k:\n return True\n else:\n hashdict[nums[i]] = i\n else:\n hashdict[nums[i]] = i\n\n return False\n","sub_path":"Array/219_Contains_Duplicate_II.py","file_name":"219_Contains_Duplicate_II.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"104618254","text":"#encoding: utf-8\nfrom OpenOrange import *\nfrom Routine import Routine\n\nclass ExportSettingRecord(Routine):\n \n def run(self):\n filename = getSaveFileName()\n if filename:\n import cPickle\n record = self.getRecord() \n query = Query()\n query.sql = \"SELECT {internalId} FROM [%s]\" % record.RecordName\n reclist = []\n rec = NewRecord(record.RecordName)\n if query.open():\n for r in query:\n rec.internalId = r.internalId\n rec.load()\n reclist.append(rec)\n f = open(filename,\"w\")\n cPickle.dump(reclist, f)\n f.close()\n ","sub_path":"standard/routines/ExportSettingRecord.py","file_name":"ExportSettingRecord.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"145249277","text":"import random\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport networkx as nx\nimport numpy as np\nimport time\nimport pdb\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nTARGET_NODE = 1000001\nDIFF_COSTS = True\nDIFF_ALPHA = 5.0\n# DIFF_BETA = 1.0\n\ndef constructG(subsetg, preds):\n '''\n '''\n N = len(subsetg.nodes()) - 1\n M = len(subsetg.edges())\n G = to_variable(np.zeros((N,N))).float()\n Q = to_variable(np.zeros((M,N))).float()\n Gv = to_variable(np.zeros(N)).float()\n\n node_dict = {}\n edge_dict = {}\n\n nodes = list(subsetg.nodes())\n nodes.remove(TARGET_NODE)\n assert len(nodes) == N\n nodes.sort()\n for i, node in enumerate(nodes):\n node_dict[node] = i\n\n edges = list(subsetg.edges())\n edges.sort()\n for i, edge in enumerate(edges):\n edge_dict[edge] = i\n\n # node with all tables is source, node with no tables is target\n ## FIXME: need to set it appropriately.\n source_node = 0\n Gv[node_dict[source_node]] = 1.0\n # target_node = TARGET_NODE\n # Gv[node_dict[target_node]] = -1.0\n\n for i, node in enumerate(nodes):\n # going to set G[i,:]\n in_edges = subsetg.in_edges(node)\n out_edges = subsetg.out_edges(node)\n for edge in in_edges:\n assert edge[1] == node\n cost = preds[edge_dict[edge]]\n cost = 1.0 / cost\n cur_node_idx = node_dict[edge[1]]\n other_node_idx = node_dict[edge[0]]\n G[i,cur_node_idx] += cost\n G[i,other_node_idx] -= cost\n\n for edge in out_edges:\n assert edge[0] == node\n cost = preds[edge_dict[edge]]\n cost = 1.0 / cost\n cur_node_idx = node_dict[edge[0]]\n G[i,cur_node_idx] += cost\n\n other_node = edge[1]\n if other_node in node_dict:\n other_node_idx = node_dict[other_node]\n G[i,other_node_idx] -= cost\n\n for i, edge in enumerate(edges):\n cost = preds[edge_dict[edge]]\n cost = 1.0 / cost\n\n head_node = edge[0]\n tail_node = edge[1]\n hidx = node_dict[head_node]\n Q[i,hidx] = cost\n if tail_node in node_dict:\n tidx = node_dict[tail_node]\n Q[i,tidx] = -cost\n\n return edges, G, Gv, Q\n\ndef sp_loss(graph, preds, true_vals):\n edges = list(graph.edges())\n edges.sort()\n for i, e in enumerate(edges):\n graph[e[0]][e[1]][\"true_cost\"] = true_vals[i].item()\n opt_path = nx.shortest_path(graph, 0, TARGET_NODE, weight=\"true_cost\")\n\n for i, e in enumerate(edges):\n graph[e[0]][e[1]][\"est_cost\"] = preds[i].item()\n\n est_path = nx.shortest_path(graph, 0, TARGET_NODE, weight=\"est_cost\")\n if np.array_equal(est_path, opt_path):\n return 0.0\n else:\n return 1.0\n\ndef flow_loss(graph, preds, true_vals):\n edges,G,Gv,Q = constructG(graph, preds)\n trueC = torch.eye(len(true_vals))\n for i, y in enumerate(true_vals):\n trueC[i,i] = y\n invG = torch.inverse(G)\n left = (Gv @ torch.transpose(invG,0,1)) @ torch.transpose(Q, 0, 1)\n right = Q @ (invG @ Gv)\n\n print(torch.min(right))\n if torch.min(right) < 0.0:\n print(torch.min(right))\n pdb.set_trace()\n\n loss = left @ trueC @ right\n if loss.item() == 0.0:\n print(true_vals)\n print(preds)\n pdb.set_trace()\n # print(loss)\n # print(G.shape, Gv.shape, Q.shape)\n # print(loss)\n # pdb.set_trace()\n return loss\n\ndef eval_loss(loss_fn, net, X, Y, samples=None):\n start = time.time()\n losses = []\n l1 = []\n l2 = []\n for i, xbatch in enumerate(X):\n ybatch = Y[i]\n if net is None:\n pred = ybatch\n else:\n pred = net(xbatch).squeeze(1)\n # sample = samples[i]\n # loss = loss_fn(sample, ybatch, ybatch)\n # losses.append(loss.item())\n # continue\n # pred = net(xbatch).squeeze(1)\n\n if samples:\n sample = samples[i]\n loss = loss_fn(sample, pred, ybatch)\n else:\n loss = loss_fn(pred, ybatch)\n\n if \"MSE\" in str(loss_fn):\n losses_all = (pred-ybatch)**2\n losses_all = losses_all.detach().numpy()\n cur_l1 = [l for i,l in enumerate(losses_all) if i % 2 == 0]\n cur_l2 = [l for i,l in enumerate(losses_all) if i % 2 == 1]\n l1.append(np.mean(cur_l1))\n l2.append(np.mean(cur_l2))\n\n if isinstance(loss, torch.Tensor):\n loss = loss.item()\n\n losses.append(loss)\n\n if \"MSE\" in str(loss_fn):\n print(\"eval loss took: \", time.time() - start)\n print(\"l1: {}, l2: {}, l: {}\".format(np.mean(l1), np.mean(l2),\n np.mean(losses)))\n # pdb.set_trace()\n\n return np.mean(losses)\n\ndef get_training_features(samples, min_val, max_val, max_cost):\n train_features = []\n train_y = []\n for G in samples:\n feats, y = get_features(G, min_val, max_val, max_cost)\n train_features.append(feats)\n train_y.append(y)\n train_features = to_variable(train_features).float()\n train_y= to_variable(train_y).float()\n return train_features, train_y\n\ndef get_features(G, min_val, max_val, max_cost):\n '''\n feature vector for each edge in G.\n '''\n feats = []\n y = []\n edges = list(G.edges())\n edges.sort()\n for edge in edges:\n n1_val = G.nodes()[edge[0]][\"val\"]\n n2_val = G.nodes()[edge[1]][\"val\"]\n cost = G[edge[0]][edge[1]][\"cost\"]\n if min_val is not None:\n n1_val = (n1_val - min_val) / (max_val - min_val)\n n2_val = (n2_val - min_val) / (max_val - min_val)\n cost = cost / max_cost\n # assert cost >= 0.0 and cost <= 1.00\n feats.append([n1_val, n2_val])\n y.append(cost)\n return feats, y\n\ndef update_all_nodes(G, min_val, max_val):\n target = TARGET_NODE\n G.add_node(target)\n\n # add a value to each source node\n random.seed(1234)\n for node in G.nodes():\n G.nodes()[node][\"val\"] = float(random.randint(min_val, max_val))\n if G.out_degree(node) == 0 and node != target:\n G.add_edge(node, target)\n\ndef compute_costs(G, DIFF_COSTS=True):\n '''\n '''\n for i, edge in enumerate(G.edges()):\n n1_val = G.nodes()[edge[0]][\"val\"]\n n2_val = G.nodes()[edge[1]][\"val\"]\n\n if DIFF_COSTS:\n if i % 2 == 0:\n G[edge[0]][edge[1]][\"cost\"] = n1_val + n2_val\n # G[edge[0]][edge[1]][\"cost\"] = n1_val*n2_val\n elif i % 2 == 1:\n G[edge[0]][edge[1]][\"cost\"] = DIFF_ALPHA*n1_val\n\n # if i % 3 == 0:\n # G[edge[0]][edge[1]][\"cost\"] = n1_val + n2_val\n # elif i % 3 == 1:\n # G[edge[0]][edge[1]][\"cost\"] = DIFF_ALPHA*n1_val\n # else:\n # G[edge[0]][edge[1]][\"cost\"] = DIFF_BETA*n2_val\n else:\n G[edge[0]][edge[1]][\"cost\"] = n1_val + n2_val\n # G[edge[0]][edge[1]][\"cost\"] = n1_val*n2_val\n\ndef gen_dataset(N, width, height, min_val=1, max_val=100):\n samples = []\n for i in range(N):\n if i % 100 == 0:\n print(\"sample: \", i)\n G = nx.balanced_tree(width,height,create_using=nx.DiGraph())\n update_all_nodes(G, min_val=min_val, max_val=max_val)\n compute_costs(G, DIFF_COSTS=DIFF_COSTS)\n samples.append(G)\n return samples\n\nclass SimpleRegression(torch.nn.Module):\n # TODO: add more stuff?\n def __init__(self, input_width, hidden_width_multiple,\n n_output, num_hidden_layers=1, hidden_layer_size=None):\n super(SimpleRegression, self).__init__()\n if hidden_layer_size is None:\n n_hidden = int(input_width * hidden_width_multiple)\n else:\n n_hidden = hidden_layer_size\n\n self.layers = []\n self.layer1 = nn.Sequential(\n nn.Linear(input_width, n_hidden, bias=True),\n nn.LeakyReLU()\n ).to(device)\n self.layers.append(self.layer1)\n\n for i in range(0,num_hidden_layers-1,1):\n layer = nn.Sequential(\n nn.Linear(n_hidden, n_hidden, bias=True),\n nn.LeakyReLU()\n ).to(device)\n self.layers.append(layer)\n\n self.final_layer = nn.Sequential(\n nn.Linear(n_hidden, n_output, bias=True),\n nn.Sigmoid()\n ).to(device)\n self.layers.append(self.final_layer)\n\n def forward(self, x):\n output = x\n for layer in self.layers:\n output = layer(output)\n return output\n\ndef to_variable(arr, use_cuda=True, requires_grad=False):\n if isinstance(arr, list) or isinstance(arr, tuple):\n arr = np.array(arr)\n if isinstance(arr, np.ndarray):\n arr = Variable(torch.from_numpy(arr), requires_grad=requires_grad).to(device)\n else:\n arr = Variable(arr, requires_grad=requires_grad).to(device)\n\n # if torch.cuda.is_available() and use_cuda:\n # print(\"returning cuda array!\")\n # arr = arr.cuda()\n # else:\n # pdb.set_trace()\n return arr\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"628283316","text":"\"\"\"Tests for scheduler\"\"\"\nfrom unittest import TestCase\n\nfrom mock import Mock\n\nfrom timerdaemon.core import Task\nfrom timerdaemon.scheduler.scheduler import Scheduler\n\n\nclass SchedulerTest(TestCase):\n \"\"\"Test case for scheudler\"\"\"\n def setUp(self):\n \"\"\"Initialize test case\"\"\"\n self.scheduler_mock = Mock()\n self.scheduler = Scheduler()\n self.scheduler.scheduler = self.scheduler_mock\n\n def test_start(self):\n \"\"\"Test starting of scheduler\"\"\"\n self.scheduler.start()\n self.scheduler_mock.start.assert_called_once_with()\n\n def test_shutdown(self):\n \"\"\"Test shutdown of scheduler\"\"\"\n self.scheduler.shutdown()\n self.scheduler_mock.shutdown.assert_called_once_with()\n\n def test_defer(self):\n \"\"\"Test defering task\"\"\"\n self.scheduler.defer('123abc', 14)\n args_list = self.scheduler_mock.reschedule_job.call_args_list\n self.assertEqual(1, len(args_list))\n args, _ = args_list[0]\n self.assertEqual('123abc', args[0])\n\n def test_remove(self):\n \"Test removing task\"\"\"\n task_id = '123abc'\n self.scheduler.tasks_map[task_id] = Mock()\n\n self.assertTrue(task_id in self.scheduler.tasks_map)\n self.scheduler.remove_task(task_id)\n\n self.assertFalse(task_id in self.scheduler.tasks_map)\n self.scheduler_mock.remove_job.assert_called_with(task_id)\n\n def test_add(self):\n \"\"\"Test adding task\"\"\"\n task_id = '123abc'\n task = Task(None)\n self.scheduler_mock.add_job = Mock(return_value=Mock(id=task_id))\n\n self.assertFalse(task_id in self.scheduler.tasks_map)\n self.assertNotEqual(task_id, task.job_id)\n self.scheduler.add_task(task)\n\n args_list = self.scheduler_mock.add_job.call_args_list\n self.assertEqual(1, len(args_list))\n args, _ = args_list[0]\n self.assertEqual(task.call, args[0])\n self.assertEqual(task_id, task.job_id)\n self.assertEqual(task, self.scheduler.tasks_map[task_id])\n\n def test_update(self):\n \"\"\"Test updating task\"\"\"\n task_id = '123abc'\n task = Task(None)\n task.job_id = task_id\n self.scheduler.tasks_map[task_id] = task\n\n self.assertTrue(task_id in self.scheduler.tasks_map)\n self.scheduler.update_task(task)\n\n args_list = self.scheduler_mock.reschedule_job.call_args_list\n self.assertEqual(1, len(args_list))\n args, _ = args_list[0]\n self.assertEqual(task_id, args[0])\n self.assertEqual(task, self.scheduler.tasks_map[task_id])\n","sub_path":"timerdaemon/scheduler/tests/test_scheduler.py","file_name":"test_scheduler.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"631972233","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom py_opt_control import min_time_bvp\n\n# Constants\nv_min = -10\nv_max = 10\na_min = -5\na_max = 5\nj_min = -100\nj_max = 100\n\n# Hard coded initial and final state.\np0 = np.array([0, 2])\nv0 = np.array([0, 0])\na0 = np.array([0, 0])\np1 = np.array([3, 1])\nv1 = np.array([1, 0])\na1 = np.array([0, 0])\n\n# Compute the jerk input sequence. The initial state (p0, v0, a0) and input\n# sequence (t, j) is the smallest description of a solution trajectory.\n(t, j) = min_time_bvp.min_time_bvp(\n p0, v0, a0,\n p1, v1, a1,\n v_min, v_max, a_min, a_max, j_min, j_max,\n sync_w=False)\n\n# Analytically integrate the full state at the switching times. Then densely\n# sample the trajectory over time for plotting purposes.\na, v, p = min_time_bvp.switch_states(p0, v0, a0, t, j)\nst, sj, sa, sv, sp = min_time_bvp.uniformly_sample(p0, v0, a0, t, j, dt=0.001)\n\n# Plot the state over time.\nfig, axes = plt.subplots(4, 1, sharex=True)\nfor i in range(sp.shape[0]):\n for ax, s, l in zip(axes, [sp, sv, sa, sj], ('pos', 'vel', 'acc', 'jerk')):\n ax.plot(st, s[i,:])\n ax.set_ylabel(l)\naxes[3].set_xlabel('time')\nfig.suptitle('Full State over Time')\n\n# Show plots.\nplt.show()\n","sub_path":"python/tests/eval_example.py","file_name":"eval_example.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"541278997","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom PyQt5.QtWidgets import (QMainWindow, QApplication, QPushButton, QWidget, QAction, QTabWidget, QVBoxLayout,\n QPushButton, QLabel, QHBoxLayout, QSizePolicy, QLineEdit)\nfrom PyQt5.QtCore import QRect, Qt\nfrom PyQt5.QtGui import QFont\n\n\nclass App(QMainWindow):\n def __init__(self):\n super().__init__()\n self.title = 'Редактирование рекламы'\n self.left = 0\n self.top = 0\n self.width = 840\n self.height = 680\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n\n self.page = AdEditPage2(self)\n self.setCentralWidget(self.page)\n\n self.show()\n\n\nclass AdEditPage2(QWidget):\n def __init__(self, parent):\n super().__init__(parent)\n self.initUI()\n\n def initUI(self):\n self.UiComponents()\n\n def UiComponents(self):\n self.adEditBlock = QWidget(self)\n\n self.adEditBlock.setMaximumSize(500, 250)\n\n self.adEditBlockVbox = QVBoxLayout()\n\n self.header = QLabel('

    Редактирование ключевых слов

    ')\n self.header.setAlignment(Qt.AlignCenter)\n\n self.adEditBlockVbox.addStretch()\n self.adEditBlockVbox.addWidget(self.header)\n\n self.keywordsLabel = QLabel()\n self.keywordsLabel.setText('Ключевые слова:')\n self.keywordsEditLine = QLineEdit()\n self.keywordsHbox = QHBoxLayout()\n self.keywordsHbox.addWidget(self.keywordsLabel)\n self.keywordsHbox.addWidget(self.keywordsEditLine)\n\n self.adEditBlockVbox.addStretch()\n self.adEditBlockVbox.addLayout(self.keywordsHbox)\n\n self.saveAsButton = QPushButton(\"Сохранить как...\")\n self.saveAsButton.setMaximumWidth(100)\n self.saveAsButtonHbox = QHBoxLayout()\n self.saveAsButtonHbox.addStretch(1)\n self.saveAsButtonHbox.addWidget(self.saveAsButton)\n\n self.adEditBlockVbox.addStretch()\n self.adEditBlockVbox.addLayout(self.saveAsButtonHbox)\n self.adEditBlockVbox.addStretch()\n self.adEditBlockVbox.setSpacing(30)\n\n self.adEditBlock.setLayout(self.adEditBlockVbox)\n\n self.pageVbox = QVBoxLayout(self)\n self.pageHbox = QHBoxLayout()\n self.pageHbox.addWidget(self.adEditBlock)\n self.pageVbox.addLayout(self.pageHbox)\n\n self.setLayout(self.pageVbox)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = App()\n sys.exit(app.exec_())\n","sub_path":"ad_edit_page_2.py","file_name":"ad_edit_page_2.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"465155922","text":"from inspect import getmembers, getmro, isclass\n\ntry:\n from zope.interface import classImplements\n from zope.interface import implementedBy\n ZOPE_INTERFACE_AVAILABLE = True\nexcept ImportError: # pragma NO COVERAGE\n ZOPE_INTERFACE_AVAILABLE = False # pragma NO COVERAGE\n\nfrom metachao._instructions import Instruction\nfrom metachao._instructions import overwrite\nfrom metachao.exceptions import AspectCollision\nfrom metachao.prototype import prototype_property\nfrom metachao.tools import Bases, Partial, boundproperty\n\n\nDICT_KEYS_OF_PLAIN_CLASS = ['__dict__', '__doc__', '__module__', '__weakref__']\n\n\n# XXX: derive from list/UserList and store self on aspect?\nclass Instructions(object):\n \"\"\"Adapter to store instructions on a aspect\n\n >>> class P(object): pass\n >>> instrs = Instructions(P)\n >>> instrs.append(1)\n >>> instrs.instructions\n [1]\n >>> instrs = Instructions(P)\n >>> instrs.instructions\n [1]\n \"\"\"\n attrname = \"__metachao_instructions__\"\n\n @property\n def instructions(self):\n return getattr(self.aspect, self.attrname)\n\n def __call__(self, workbench):\n if type(workbench.origin) is AspectMeta:\n curinstr = workbench.dct[self.attrname]\n workbench.dct[self.attrname] = curinstr + self.instructions\n else:\n for instr in self.instructions:\n instr(workbench)\n\n def __contains__(self, name):\n for x in self:\n if x.name == name:\n return True\n else:\n return False\n\n def __getattr__(self, name):\n return getattr(self.instructions, name)\n\n # XXX: needed explicitly to make it iterable?\n def __iter__(self):\n return self.instructions.__iter__()\n\n def __init__(self, aspect):\n self.aspect = aspect\n if self.attrname not in aspect.__dict__:\n setattr(aspect, self.attrname, [])\n\n def __repr__(self):\n return repr(\n [(x.name, x.__class__, x.payload) for x in self.instructions]\n )\n\n\nclass Workbench(object):\n def __init__(self, origin, **kw):\n self.origin = origin\n self.kw = kw\n self.dct = dict()\n if isclass(origin):\n self.name = origin.__name__\n blacklist = DICT_KEYS_OF_PLAIN_CLASS + [\n '__metachao_origin__',\n ]\n self.dct.update(((k, v)\n for k, v in origin.__dict__.iteritems()\n if k not in blacklist))\n # XXX: fix naming (also see self.baseclasses)\n self.bases = Bases(origin)\n self.baseclasses = origin.__bases__\n self.type = type(origin)\n self.dct['__metachao_origin__'] = origin\n else:\n # we are pretty much creating an object that uses origin\n # as prototype.\n self.name = \"Prototyper\"\n self.baseclasses = ()\n self.type = type\n\n # bound methods found on origin, except if blacklisted\n blacklist = (\n '__class__', '__delattr__', '__doc__', '__format__',\n '__getattr__', '__getattribute__', '__hash__',\n '__init__', '__metachao_origin__',\n '__metachao_prototype__', '__new__', '__reduce__',\n '__reduce_ex__', '__repr__', '__setattr__',\n '__sizeof__', '__str__', '__subclasshook__',\n )\n self.dct.update(((k, getattr(origin, k))\n for k, v in getmembers(origin)\n if callable(v) and not k in blacklist))\n\n # properties bound to origin for all properties found on\n # origin's class\n self.dct.update(((k, prototype_property(origin, v))\n for k, v in getmembers(origin.__class__)\n if type(v) is property))\n\n # getattr fallback to origin, setattr and delattr on new\n self.dct['__getattr__'] = lambda _, name: getattr(origin, name)\n\n # empty __init__ needed if a later aspects plumbs it\n self.dct['__init__'] = lambda *a, **kw : None\n self.dct['__metachao_prototype__'] = origin\n\n\nclass AspectMeta(type):\n \"\"\"meta class for aspects\n \"\"\"\n def __call__(aspect, origin=None, *args, **kw):\n if kw.get('pdb'):\n import pdb;pdb.set_trace()\n\n # if called without positional arg, return partially applied\n # aspect\n if origin is None:\n if not kw:\n raise NeedKw\n return Partial(aspect, **kw)\n\n workbench = Workbench(origin, **kw)\n Instructions(aspect)(workbench)\n\n #raise AspectCollision(instr.name, aspect, target)\n\n # in case of instances functions need to be bound\n # if not x_is_class and (type(instr) is types.FunctionType):\n # instr = instr.__get__(x)\n\n # build a new class, with the same name and bases as the\n # target class, but a new dictionary with the aspect applied.\n cls = workbench.type(workbench.name, workbench.baseclasses,\n workbench.dct)\n if ZOPE_INTERFACE_AVAILABLE:\n classImplements(cls, *tuple(implementedBy(aspect)))\n if isclass(origin):\n if type(cls) is AspectMeta and kw:\n return Partial(cls, **kw)\n return cls\n return cls()\n\n def __init__(aspect, name, bases, dct):\n \"\"\"Will be called when a aspect class is created\n\n Parse the aspects dictionary and generate instructions from it.\n Undecorated attributes are understood as finalize instructions.\n\n >>> class P(Aspect):\n ... a = Instruction(1)\n ... b = 2\n >>> Instructions(P)\n [('a', , 1),\n ('b', , 2)]\n \"\"\"\n super(AspectMeta, aspect).__init__(name, bases, dct)\n\n # Get the aspect's instructions list\n instructions = Instructions(aspect)\n\n # walk the mro, w/o object, gathering/creating instructions\n for cls in getmro(aspect)[:-1]:\n for name, item in cls.__dict__.iteritems():\n # ignored attributes\n if name.startswith('__metachao_'):\n continue\n if name in (\n '__implemented__', '__metaclass__',\n '__provides__', '__providedBy__',\n ): continue\n if name in DICT_KEYS_OF_PLAIN_CLASS:\n continue\n if name in instructions:\n continue\n\n # XXX: rethink this\n # undecorated items are understood as overwrite\n if not isinstance(item, Instruction):\n item = overwrite(item)\n item.__name__ = name\n item.__parent__ = aspect\n instructions.append(item)\n\n # # An existing docstring is an implicit plumb instruction for __doc__\n # if aspect.__doc__ is not None:\n # instructions.append(plumb(aspect.__doc__, name='__doc__'))\n\n # # XXX: introduce C3 resolution\n # # check our bases for instructions we don't have already and which\n # # are not overwritten by our instructions (stage1)\n # for base in bases:\n # # XXX: I don't like this code\n # for instr in Instructions(base):\n # # skip instructions we have already\n # if instr in instructions:\n # continue\n # # stage1 instructions with the same name are ignored\n # if instr.__name__ in [x.__name__ for x in instructions if\n # x.__stage__ == 'stage1']:\n # continue\n # instructions.append(instr)\n\n\nclass Aspect(object):\n \"\"\"base class for aspects, just to set the metaclass\n \"\"\"\n __metaclass__ = AspectMeta\n","sub_path":"src/metachao/_aspect.py","file_name":"_aspect.py","file_ext":"py","file_size_in_byte":8077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"427616188","text":"#!/usr/bin/python\r\n#-*- coding:utf-8 -*-\r\n\r\nimport re, codecs, nltk\r\nimport utilsOs\r\n\r\n\r\n##################################################################################\r\n#ENCODING\r\n##################################################################################\r\n\r\ndef toUtf8(stringOrUnicode):\r\n\t'''\r\n\tReturns the argument in utf-8 encoding\r\n\tUnescape html entities???????\r\n\t'''\r\n\ttypeArg = type(stringOrUnicode)\r\n\ttry:\r\n\t\tif typeArg is str:\r\n\t\t\treturn stringOrUnicode.decode(u'utf8')\r\n\t\telif typeArg is unicode:\r\n\t\t\treturn stringOrUnicode.encode(u'utf8').decode(u'utf8', u'replace')\r\n\texcept AttributeError:\r\n\t\treturn stringOrUnicode\r\n\r\n\r\n##################################################################################\r\n#REGEX\r\n##################################################################################\r\n\r\ndef findAcronyms(string):\r\n\t'''\r\n\tReturns the acronyms found in the string.\r\n\tvariant : \r\n\tacronyms = re.compile(r'((?= 2:\r\n\t\treturn re.findall(acronyms, string)\r\n\treturn None\r\n\r\n\r\ndef removeStopwords(tokenList, language=u'english'):\r\n\tfrom nltk.corpus import stopwords\t\t\r\n\t#stopwords\r\n\tto_remove = set(stopwords.words(\"english\") + ['', ' ', '&'])\r\n\treturn list(filter(lambda tok: tok not in to_remove, tokenList))\r\n\r\n\r\ndef naiveRegexTokenizer(string, caseSensitive=True, eliminateEnStopwords=False):\r\n\t'''\r\n\treturns the token list using a very naive regex tokenizer\r\n\t'''\r\n\tplainWords = re.compile(r'(\\b\\w+\\b)', re.UNICODE)\r\n\ttokens = re.findall(plainWords, string)\r\n\t#if we don't want to be case sensitive\r\n\tif caseSensitive != True:\r\n\t\ttokens = [tok.lower() for tok in tokens]\r\n\t#if we don't want the stopwords\r\n\tif eliminateEnStopwords != False:\r\n\t\ttokens = removeStopwords(tokens, language='english')\r\n\treturn tokens\r\n\r\n\r\ndef tokenizeAndExtractSpecificPos(string, listOfPosToReturn, caseSensitive=True, eliminateEnStopwords=False):\r\n\t'''\r\n\tusing nltk pos tagging, tokenize a string and extract the\r\n\ttokens corresponding to the specified pos\r\n\tThe pos labels are:\t\r\n\t\t- cc coordinating conjunction\r\n\t\t- cd cardinal digit\r\n\t\t- dt determiner\r\n\t\t- in preposition/subordinating conjunction\r\n\t\t- j adjective\r\n\t\t- n noun\r\n\t\t- np proper noun\r\n\t\t- p pronoun\r\n\t\t- rb adverb\r\n\t\t- vb verb\r\n\t'''\r\n\tposDict = {u'cc': [u'CC'], u'cd': [u'CD'], u'dt': [u'DT', u'WDT'], u'in': [u'IN'], u'j': [u'JJ', u'JJR', u'JJS'], u'n': [u'NN', u'NNS'], u'np': [u'NNP', u'NNPS'], u'p': [u'PRP', u'PRP$', u'WP$'], u'rb': [u'RB', u'RBR', u'RBS', u'WRB'], u'vb': [u'MD', u'VB', u'VBD', u'VBG', u'VBN', u'VBZ']}\r\n\tlistPos = []\r\n\t#tokenize\r\n\ttokens = nltk.word_tokenize(string)\r\n\t#we replace the general pos for the actual nltk pos\r\n\tfor generalPos in listOfPosToReturn:\r\n\t\tlistPos = listPos + posDict[generalPos]\r\n\t#pos tagging\r\n\ttokensPos = nltk.pos_tag(tokens)\r\n\t#reseting the tokens list\r\n\ttokens = []\r\n\t#selection of the pos specified tokens\r\n\tfor tupleTokPos in tokensPos:\r\n\t\t#if they have the right pos\r\n\t\tif tupleTokPos[1] in listPos:\r\n\t\t\ttokens.append(tupleTokPos[0])\r\n\t#if we don't want to be case sensitive\r\n\tif caseSensitive != True:\r\n\t\ttokens = [tok.lower() for tok in tokens]\r\n\t#if we don't want the stopwords\r\n\tif eliminateEnStopwords != False:\r\n\t\ttokens = removeStopwords(tokens, language='english')\r\n\treturn tokens\r\n\r\n\r\n##################################################################################\r\n#LANGUAGE\r\n##################################################################################\r\n\r\ndef englishOrFrench(string):\r\n\t'''guesses the language of a string between english and french'''\r\n\t#presence of french specific diacriticals\r\n\tdiacriticals = [u'à', u'â', u'è', u'é', u'ê', u'ë', u'ù', u'û', u'ô', u'î', u'ï', u'ç', u'œ']\r\n\tfor char in diacriticals:\r\n\t\tif char in string:\r\n\t\t\treturn u'fr'\r\n\t#token detection\r\n\tunkTokendict = tokenDictMaker(string)\r\n\t#ngram char detection\r\n\tunkNgramDict = trigramDictMaker(string.replace(u'\\n', u' ').replace(u'\\r', u''))\r\n\t#if the obtained dict is empty, unable to detect (probably just noise)\r\n\tif len(unkTokendict) == 0 or len(unkNgramDict) == 0:\r\n\t\treturn 'unknown'\r\n\t#token scores\r\n\tfrenchTokScore = langDictComparison(unkTokendict, utilsOs.openJsonFileAsDict(u'./utilsString/frTok.json'))\r\n\tenglishTokScore = langDictComparison(unkTokendict, utilsOs.openJsonFileAsDict(u'./utilsString/enTok.json'))\r\n\t#ngram scores\r\n\tfrenchNgramScore = langDictComparison(unkNgramDict, utilsOs.openJsonFileAsDict(u'./utilsString/fr3gram.json'))\r\n\tenglishNgramScore = langDictComparison(unkNgramDict, utilsOs.openJsonFileAsDict(u'./utilsString/en3gram.json'))\r\n\t#the smaller the string (in tokens), the more we want to prioritize the token score instead of the ngram score\r\n\tif len(unkTokendict) < 5:\r\n\t\tratioNgram = float(len(unkTokendict))/10.0\r\n\t\tfrenchTokScore = frenchTokScore * (1.0-ratioNgram)\r\n\t\tfrenchNgramScore = frenchNgramScore * ratioNgram\r\n\t\tenglishTokScore = englishTokScore * (1.0-ratioNgram)\r\n\t\tenglishNgramScore = englishNgramScore * ratioNgram\r\n\t#we compare the sum of the language scores\r\n\tif (frenchTokScore+frenchNgramScore) < (englishTokScore+englishNgramScore):\r\n\t\treturn u'fr'\r\n\treturn u'en'\r\n\r\n\r\n##################################################################################\r\n#SPECIAL DICTS\r\n##################################################################################\r\n\r\ndef trigramDictMaker(string):\r\n\t'''\r\n\ttakes a string, makes a dict of 3grams with their cooccurrence\r\n\t'''\r\n\ttrigramDict = {}\r\n\tfor i in range(len(string)-2):\r\n\t\ttrigramDict[string[i:i+3]] = trigramDict.get(string[i:i+3],0.0)+1.0\r\n\treturn trigramDict\r\n\r\n\r\ndef quadrigramDictMaker(string):\r\n\t'''\r\n\ttakes a string, makes a dict of 4grams with their cooccurrence\r\n\t'''\r\n\tquadrigramDict = {}\r\n\tfor i in range(len(string)-3):\r\n\t\tquadrigramDict[string[i:i+4]] = quadrigramDict.get(string[i:i+4],0.0)+1.0\r\n\treturn quadrigramDict\r\n\r\n\r\ndef trigramDictMakerFromFile(inputFilePath, outputFilePath=None):\r\n\t'''\r\n\ttakes a corpus file, makes a dict of 3grams with their cooccurrence\r\n\tand dumps the result in a json file\r\n\t'''\r\n\ttrigramDict = {}\r\n\tstringList = utilsOs.readAllLinesFromFile(inputFilePath, True)\r\n\tlangString = u' '.join(stringList)\r\n\tfor i in range(len(langString)-2):\r\n\t\ttrigramDict[langString[i:i+3]] = trigramDict.get(langString[i:i+3],0.0)+(1.0/len(stringList))\r\n\tif outputFilePath == None:\r\n\t\toutputFilePath = utilsOs.safeFilePath(inputFilePath.replace(inputFilePath.split(u'/')[-1], 'trigrams.json'))\r\n\tutilsOs.dumpDictToJsonFile(trigramDict, outputFilePath)\r\n\treturn trigramDict\r\n\r\n\r\ndef quadrigramDictMakerFromFile(inputFilePath, outputFilePath=None):\r\n\t'''\r\n\ttakes a corpus file, makes a dict of 4grams with their cooccurrence\r\n\tand dumps the result in a json file\r\n\t'''\r\n\tquadrigramDict = {}\r\n\tstringList = utilsOs.readAllLinesFromFile(inputFilePath, True)\r\n\tlangString = u' '.join(stringList)\r\n\tfor i in range(len(langString)-3):\r\n\t\tquadrigramDict[langString[i:i+4]] = quadrigramDict.get(langString[i:i+4],0.0)+(1.0/len(stringList))\r\n\tif outputFilePath == None:\r\n\t\toutputFilePath = utilsOs.safeFilePath(inputFilePath.replace(inputFilePath.split(u'/')[-1], 'quadrigrams.json'))\r\n\tutilsOs.dumpDictToJsonFile(quadrigramDict, outputFilePath)\r\n\treturn quadrigramDict\r\n\r\n\r\ndef tokenDictMaker(string):\r\n\t'''\r\n\ttakes a string, makes a dict of tokens with their cooccurrence\r\n\t'''\r\n\ttokenDict = {}\r\n\tfor token in naiveRegexTokenizer(string):\r\n\t\ttokenDict[token] = tokenDict.get(token, 0.0)+1.0\r\n\treturn tokenDict\r\n\r\n\r\ndef tokenDictMakerFromFile(inputFilePath, outputFilePath=None):\r\n\t'''\r\n\ttakes a corpus file, makes a dict of tokens with their cooccurrence\r\n\tand dumps the result in a json file\r\n\t'''\r\n\ttokenDict = {}\r\n\tstringList = utilsOs.readAllLinesFromFile(inputFilePath, True)\r\n\tfor string in stringList:\r\n\t\ttokenList = naiveRegexTokenizer(string.replace(u'/', u' '))\r\n\t\tfor token in tokenList:\r\n\t\t\ttokenDict[token] = tokenDict.get(token,0.0)+(1.0/len(stringList))\r\n\t\t\t#we also add the lowercase version if there is an uppercase in the token\r\n\t\t\tif any(c.isupper() for c in token):\r\n\t\t\t\ttokenDict[token.lower()] = tokenDict.get(token.lower(),0.0)+(1.0/len(stringList))\r\n\tif outputFilePath == None:\r\n\t\toutputFilePath = utilsOs.safeFilePath(inputFilePath.replace(inputFilePath.split(u'/')[-1], 'tokens.json'))\r\n\tutilsOs.dumpDictToJsonFile(tokenDict, outputFilePath)\r\n\treturn tokenDict\r\n\r\n\r\n##################################################################################\r\n#COMPARISONS AND EVALUATIONS\r\n##################################################################################\r\n\r\ndef langDictComparison(dictUnk,dictLang):\r\n\t'''\r\n\tcompares 2 dictionnaries and returns the distance between its keys\r\n\t'''\r\n\tdistance=0\r\n\tmaxUnk = max(dictUnk.values())\r\n\tfor key in dictUnk:\r\n\t\tdistance+=abs((dictUnk[key]/maxUnk) - dictLang.get(key,0))\r\n\treturn distance\r\n","sub_path":"utilsString.py","file_name":"utilsString.py","file_ext":"py","file_size_in_byte":9306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"244271013","text":"def censor(phrase):\n\n \"\"\" This function changes any 4 letter word in the phrase to '@*$%' and prints the new phrase.\"\"\"\n\n for i in range(len(phrase)):\n if len(phrase[i]) == 4:\n phrase[i] = \"@*$%\"\n censoredPhrase = \"\"\n for i in phrase:\n censoredPhrase = censoredPhrase + i + \" \"\n print(\"Your censored phrase:\",censoredPhrase)\n\n\ndef main():\n\n \"\"\"This is the main function, which takes in an input and feeds it to the censor function.\"\"\"\n \n phrase = input(\"What phrase do you want to censor?\")\n phrase = phrase.split(\" \")\n censor(phrase)\n\n\nmain()\n","sub_path":"4_3_15.py","file_name":"4_3_15.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"583982224","text":"# Copyright 2017 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nDEPS = [\n 'chromium_android',\n 'recipe_engine/properties',\n]\n\n\ndef RunSteps(api):\n api.chromium_android.set_config('main_builder')\n api.chromium_android.incremental_coverage_report()\n\n\ndef GenTests(api):\n yield (\n api.test('basic') +\n api.properties(\n buildbotURL='https://example/url',\n buildername='test_buildername',\n buildnumber=123)\n )\n","sub_path":"scripts/slave/recipe_modules/chromium_android/tests/incremental_coverage_report.py","file_name":"incremental_coverage_report.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"169310953","text":"import os, shutil\n\n\ndef cd(path):\n try:\n os.chdir(path)\n print(os.getcwd())\n except FileNotFoundError:\n print(\"Error: Path does not exist.\")\n\n\ndef pwd():\n print(os.getcwd())\n\n\ndef mkdir(path):\n try:\n os.mkdir(path)\n except FileExistsError:\n print(\"Error: File exists.\")\n\n\ndef rmdir(path):\n try:\n os.rmdir(path)\n except OSError:\n print(\"Error: Directory not empty.\")\n\n\ndef rmtree(path):\n print(\"WARNING: UNTESTED\")\n print(\"WARNING: DESTRUCTIVE\")\n print(\"WILL REMOVE DIRECTORY AND ALL CONTAINED FILES\")\n print(\"THIS CANNOT BE UNDONE\")\n cont = input(\"ARE YOU SURE YOU WOULD LIKE TO CONTINUE?\").lower()\n if cont == 'y' or cont == 'yes':\n shutil.rmtree(path, True)\n else:\n print(\"Aborted\")\n","sub_path":"commands/directory.py","file_name":"directory.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"434373160","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/2/4 16:09\n# @Author : Lynn\n# @Site : \n# @Software: PyCharm\nimport time\nimport pytest\nfrom PageObjects.nmb_index import IndexPage\n# 默认是用例级别可以不传,如果不是需要传 @pytest.fixture(scope=\"function\")\n# 前置条件 使用yield 在yield返回值\n@pytest.fixture\ndef init_driver(init_drd):\n lp = IndexPage(init_drd)\n yield {\"lp\":lp}\n\nclass Test_Nmb_index():\n @pytest.mark.usefixtures('demo')\n @pytest.mark.usefixtures('init_driver')\n def test_index(self,init_driver):\n init_driver[\"lp\"].cl()\n init_driver[\"lp\"].jiner(2000)\n time.sleep(2)\n assert (\"查看并激活\"==init_driver[\"lp\"].tb_successful())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"TestCase/test_nmb_index.py","file_name":"test_nmb_index.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"167961184","text":"import datetime\nfrom pathlib import Path\nfrom strelka.scanners.scan_gif import ScanGif\n\n\ndef test_scan_gif(mocker):\n \"\"\"\n This tests the ScanGif scanner.\n It attempts to validate a given GIFs \"trailer index\" value.\n\n Pass: Trailer index matches specified value.\n Failure: Unable to load file or trailer index does not match specified value.\n \"\"\"\n\n scanner = ScanGif(\n {\n \"name\": \"ScanGif\",\n \"key\": \"scan_gif\",\n \"limits\": {\"scanner\": 10}\n },\n \"test_coordinate\",\n )\n\n mocker.patch.object(ScanGif, \"upload_to_coordinator\", return_value=None)\n scanner.scan_wrapper(\n Path(Path(__file__).parent / \"fixtures/test.gif\").read_bytes(),\n {\n \"uid\": \"12345\",\n \"name\": \"somename\"\n },\n {\n \"scanner_timeout\": 5\n },\n datetime.date.today(),\n )\n assert scanner.event.get(\"trailer_index\") == 3806\n","sub_path":"src/python/strelka/tests/test_scan_gif.py","file_name":"test_scan_gif.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"45652874","text":"#!/usr/bin/env python3\nimport copy\nimport glob\nimport os\nfrom collections import deque\nfrom pathlib import Path\n\nimport click\nimport numpy as np\nimport open3d as o3d\n\nfrom puma.mesh import create_mesh_from_map\nfrom puma.preprocessing import preprocess\nfrom puma.registration import register_scan_to_mesh, run_icp\nfrom puma.utils import (\n get_progress_bar,\n load_config_from_yaml,\n print_progress,\n save_config_yaml,\n # save_poses,\n load_poses,\n vel2cam,\n)\n\n\n@click.command()\n@click.option(\n \"--config\",\n \"-c\",\n type=click.Path(exists=True),\n default=\"config/puma.yml\",\n help=\"Path to the config file\",\n)\n@click.option(\n \"--dataset\",\n \"-d\",\n type=click.Path(exists=True),\n default=os.environ[\"HOME\"] + \"/data/kitti-odometry/ply/\",\n help=\"Location of the KITTI-like dataset\",\n)\n@click.option(\n \"--n_scans\",\n \"-n\",\n type=int,\n default=-1,\n required=False,\n help=\"Number of scans to integrate\",\n)\n@click.option(\n \"--sequence\",\n \"-s\",\n type=str,\n default=None,\n required=False,\n help=\"Sequence number\",\n)\n@click.option(\n \"--odometry_only\",\n is_flag=True,\n default=False,\n help=\"Run odometry only pipeline\",\n)\ndef main(config, dataset, n_scans, sequence, odometry_only):\n \"\"\"This script to run the full puma pipeline as described in the paper. It\n assumes you have the data in the kitti-like format and all the scans where\n already pre-converted to '.ply', for example:\n\n \\b\n kitti/ply\n ├── poses\n │   └── 00.txt\n └── sequences\n └── 00\n ├── calib.txt\n ├── poses.txt\n ├── times.txt\n └── velodyne\n ├── 000000.ply\n ├── 000001.ply\n └── ...\n\n How to run it and check a quick example:\n\n \\b\n $ ./slam/puma_pipeline.py -d ./data/ -s 00 -n 40\n \"\"\"\n config = load_config_from_yaml(config)\n if config.debug:\n o3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Debug)\n dataset = os.path.join(dataset, \"\")\n os.makedirs(config.out_dir, exist_ok=True)\n\n save_plys = False\n\n if save_plys == True:\n out_w_ply_dir = config.out_dir + 'w_ply/'\n out_ply_raw_dir = config.out_dir + 'ply_raw/'\n out_w_ply_raw_dir = config.out_dir + 'w_ply_raw/'\n os.makedirs(out_w_ply_dir, exist_ok=False)\n os.makedirs(out_ply_raw_dir, exist_ok=False)\n os.makedirs(out_w_ply_raw_dir, exist_ok=False)\n\n map_name = Path(dataset).name\n if sequence:\n map_name += \"_\" + sequence\n map_name += \"_depth_\" + str(config.depth)\n map_name += \"_cropped\" if config.min_density else \"\"\n map_name += \"_\" + config.method\n map_name += \"_\" + config.strategy\n\n # Save config\n config_file = map_name + \".yml\"\n config_file = os.path.join(config.out_dir, config_file)\n save_config_yaml(config_file, dict(config))\n\n poses_file = Path(dataset).parents[0].joinpath(\"poses.txt\")\n poses = load_poses(poses_file)\n print(\"Loaded poses from\", poses_file)\n\n if sequence:\n scans = os.path.join(dataset, \"sequences\", sequence, \"velodyne\", \"\")\n else:\n scans = os.path.join(dataset)\n scan_names = sorted(glob.glob(scans + \"*.ply\"))\n\n # Use the whole sequence if -1 is specified\n n_scans = len(scan_names) if n_scans == -1 else n_scans\n\n # Create data containers to store the map\n mesh = o3d.geometry.TriangleMesh()\n\n # Create a circular buffer, the same way we do in the C++ implementation\n local_map = deque(maxlen=config.acc_frame_count)\n\n # Mapping facilities\n global_mesh = o3d.geometry.TriangleMesh()\n mapping_enabled = not odometry_only\n\n # Start the Odometry and Mapping pipeline\n scan_count = 0\n map_count = 0\n pbar = get_progress_bar(1, n_scans)\n for idx in pbar:\n str_size = print_progress(pbar, idx, n_scans)\n raw_scan = o3d.io.read_point_cloud(scan_names[idx])\n scan = preprocess(raw_scan, config)\n scan.transform(poses[idx])\n local_map.append(scan)\n\n if save_plys == True:\n stem = os.path.splitext(scan_names[idx].split(\"/\")[-1])[0]\n o3d.io.write_point_cloud(out_w_ply_dir + stem + \".ply\", scan)\n o3d.io.write_point_cloud(out_ply_raw_dir + stem + \".ply\", raw_scan)\n raw_scan.transform(poses[idx])\n o3d.io.write_point_cloud(out_w_ply_raw_dir + stem + \".ply\", raw_scan)\n\n scan_count += 1\n if scan_count >= config.acc_frame_count or idx == n_scans - 1:\n scan_count = 0\n msg = \"[scan #{}] Running PSR over local_map\".format(idx)\n pbar.set_description(msg.rjust(str_size))\n mesh, _ = create_mesh_from_map(\n local_map, config.depth, config.n_threads, config.min_density\n )\n\n global_mesh += mesh\n global_mesh = global_mesh.remove_duplicated_triangles()\n global_mesh = global_mesh.remove_duplicated_vertices()\n\n map_count += 1\n if map_count >= config.acc_map_count:\n map_count = 0\n mesh_map_file = os.path.join(config.out_dir, map_name + \"_iterm.ply\")\n print(\"Saving Map to\", mesh_map_file)\n o3d.io.write_triangle_mesh(mesh_map_file, global_mesh)\n\n if mapping_enabled:\n # Save map to file\n mesh_map_file = os.path.join(config.out_dir, map_name + \".ply\")\n print(\"Saving Map to\", mesh_map_file)\n o3d.io.write_triangle_mesh(mesh_map_file, global_mesh)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"apps/pipelines/slam/puma_pipeline.py","file_name":"puma_pipeline.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"122661000","text":"import cv2\nimport numpy as np\nimport pandas as pd\nimport torch\nimport math\nimport pandas as pd\nimport numpy as np\nimport feat.au_detectors.JAANet.JAANet_model as network\nimport torch.nn as nn\nfrom PIL import Image\nfrom torchvision import transforms\nfrom feat.utils import get_resource_path, convert68to49\nimport os\n\n\nclass JAANet(nn.Module):\n def __init__(self) -> None:\n \"\"\"\n Initialize.\n Args:\n img_data: numpy array image data files of shape (N,3,W,H)\n land_data: numpy array landmark data of shape (N, 49*2)\n \"\"\"\n # self.imgs = img_data\n # self.land_data = land_data\n super(JAANet,self).__init__()\n \n self.params = {\n \"config_unit_dim\": 8,\n \"config_crop_size\": 176,\n \"config_map_size\": 44,\n \"config_au_num\": 12,\n \"config_land_num\": 49,\n \"config_fill_coeff\": 0.56,\n \"config_write_path_prefix\": get_resource_path(),\n }\n \n config_unit_dim = self.params[\"config_unit_dim\"]\n config_crop_size = self.params[\"config_crop_size\"]\n config_map_size = self.params[\"config_map_size\"]\n config_au_num = self.params[\"config_au_num\"]\n config_land_num = self.params[\"config_land_num\"]\n config_fill_coeff = self.params[\"config_fill_coeff\"]\n config_write_path_prefix = self.params[\"config_write_path_prefix\"]\n\n self.region_learning = network.network_dict[\"HMRegionLearning\"](\n input_dim=3, unit_dim=config_unit_dim\n )\n self.align_net = network.network_dict[\"AlignNet\"](\n crop_size=config_crop_size,\n map_size=config_map_size,\n au_num=config_au_num,\n land_num=config_land_num,\n input_dim=config_unit_dim * 8,\n fill_coeff=config_fill_coeff,\n )\n self.local_attention_refine = network.network_dict[\"LocalAttentionRefine\"](\n au_num=config_au_num, unit_dim=config_unit_dim\n )\n self.local_au_net = network.network_dict[\"LocalAUNetv2\"](\n au_num=config_au_num,\n input_dim=config_unit_dim * 8,\n unit_dim=config_unit_dim,\n )\n self.global_au_feat = network.network_dict[\"HLFeatExtractor\"](\n input_dim=config_unit_dim * 8, unit_dim=config_unit_dim\n )\n self.au_net = network.network_dict[\"AUNet\"](\n au_num=config_au_num, input_dim=12000, unit_dim=config_unit_dim\n )\n \n self.use_gpu = torch.cuda.is_available()\n\n\n if self.use_gpu:\n self.region_learning = self.region_learning.cuda()\n self.align_net = self.align_net.cuda()\n self.local_attention_refine = self.local_attention_refine.cuda()\n self.local_au_net = self.local_au_net.cuda()\n self.global_au_feat = self.global_au_feat.cuda()\n self.au_net = self.au_net.cuda()\n # Load parameters\n # load_map = 'cpu' if True else 'false'\n # au_occur_model_path = os.path.join(\n # config_write_path_prefix , '/region_learning' , '.pth')\n # print(\"should load data at \",os.path.join(config_write_path_prefix , 'region_learning.pth'))\n # print(\"Directory Files:\")\n # print(os.listdir(config_write_path_prefix))\n self.region_learning.load_state_dict(\n torch.load(\n os.path.join(config_write_path_prefix, \"region_learning.pth\")\n )\n )\n self.align_net.load_state_dict(\n torch.load(os.path.join(config_write_path_prefix, \"align_net.pth\"))\n )\n self.local_attention_refine.load_state_dict(\n torch.load(\n os.path.join(config_write_path_prefix, \"local_attention_refine.pth\")\n )\n )\n self.local_au_net.load_state_dict(\n torch.load(os.path.join(config_write_path_prefix, \"local_au_net.pth\"))\n )\n self.global_au_feat.load_state_dict(\n torch.load(os.path.join(config_write_path_prefix, \"global_au_feat.pth\"))\n )\n self.au_net.load_state_dict(\n torch.load(os.path.join(config_write_path_prefix, \"au_net.pth\"))\n )\n else:\n self.region_learning.load_state_dict(\n torch.load(\n os.path.join(config_write_path_prefix, \"region_learning.pth\"),\n map_location={\"cuda:0\": \"cpu\"},\n )\n )\n self.align_net.load_state_dict(\n torch.load(\n os.path.join(config_write_path_prefix, \"align_net.pth\"),\n map_location={\"cuda:0\": \"cpu\"},\n )\n )\n self.local_attention_refine.load_state_dict(\n torch.load(\n os.path.join(\n config_write_path_prefix, \"local_attention_refine.pth\"\n ),\n map_location={\"cuda:0\": \"cpu\"},\n )\n )\n self.local_au_net.load_state_dict(\n torch.load(\n os.path.join(config_write_path_prefix, \"local_au_net.pth\"),\n map_location={\"cuda:0\": \"cpu\"},\n )\n )\n self.global_au_feat.load_state_dict(\n torch.load(\n os.path.join(config_write_path_prefix, \"global_au_feat.pth\"),\n map_location={\"cuda:0\": \"cpu\"},\n )\n )\n self.au_net.load_state_dict(\n torch.load(\n os.path.join(config_write_path_prefix, \"au_net.pth\"),\n map_location={\"cuda:0\": \"cpu\"},\n )\n )\n\n self.region_learning.eval()\n self.align_net.eval()\n self.local_attention_refine.eval()\n self.local_au_net.eval()\n self.global_au_feat.eval()\n self.au_net.eval()\n\n\n def align_face_49pts(self, img, img_land, box_enlarge=2.9, img_size=200):\n \"\"\"\n code from:\n https://github.com/ZhiwenShao/PyTorch-JAANet/blob/master/dataset/face_transform.py\n Did some small modifications to fit into our program.\n The function performs preproecessing transformations on pictures.\n Args:\n img: iamges loaded by cv2. Shape: (3,H,W)\n img_land: landmark file for the img. Shape()\n box_enlarge: englarge factor for the face transform, centered at face\n img_size: size of the desired output image\n Return:\n aligned_img: aligned images by cv2\n new_land: transformed landmarks\n biocular: biocular distancxe\n \"\"\"\n leftEye0 = (\n img_land[2 * 19]\n + img_land[2 * 20]\n + img_land[2 * 21]\n + img_land[2 * 22]\n + img_land[2 * 23]\n + img_land[2 * 24]\n ) / 6.0\n leftEye1 = (\n img_land[2 * 19 + 1]\n + img_land[2 * 20 + 1]\n + img_land[2 * 21 + 1]\n + img_land[2 * 22 + 1]\n + img_land[2 * 23 + 1]\n + img_land[2 * 24 + 1]\n ) / 6.0\n rightEye0 = (\n img_land[2 * 25]\n + img_land[2 * 26]\n + img_land[2 * 27]\n + img_land[2 * 28]\n + img_land[2 * 29]\n + img_land[2 * 30]\n ) / 6.0\n rightEye1 = (\n img_land[2 * 25 + 1]\n + img_land[2 * 26 + 1]\n + img_land[2 * 27 + 1]\n + img_land[2 * 28 + 1]\n + img_land[2 * 29 + 1]\n + img_land[2 * 30 + 1]\n ) / 6.0\n deltaX = rightEye0 - leftEye0\n deltaY = rightEye1 - leftEye1\n l = math.sqrt(deltaX * deltaX + deltaY * deltaY)\n sinVal = deltaY / l\n cosVal = deltaX / l\n mat1 = np.mat([[cosVal, sinVal, 0], [-sinVal, cosVal, 0], [0, 0, 1]])\n\n mat2 = np.mat(\n [\n [leftEye0, leftEye1, 1],\n [rightEye0, rightEye1, 1],\n [img_land[2 * 13], img_land[2 * 13 + 1], 1],\n [img_land[2 * 31], img_land[2 * 31 + 1], 1],\n [img_land[2 * 37], img_land[2 * 37 + 1], 1],\n ]\n )\n\n mat2 = (mat1 * mat2.T).T\n\n cx = float((max(mat2[:, 0]) + min(mat2[:, 0]))) * 0.5\n cy = float((max(mat2[:, 1]) + min(mat2[:, 1]))) * 0.5\n\n if float(max(mat2[:, 0]) - min(mat2[:, 0])) > float(\n max(mat2[:, 1]) - min(mat2[:, 1])\n ):\n halfSize = 0.5 * box_enlarge * float((max(mat2[:, 0]) - min(mat2[:, 0])))\n else:\n halfSize = 0.5 * box_enlarge * float((max(mat2[:, 1]) - min(mat2[:, 1])))\n\n scale = (img_size - 1) / 2.0 / halfSize\n mat3 = np.mat(\n [\n [scale, 0, scale * (halfSize - cx)],\n [0, scale, scale * (halfSize - cy)],\n [0, 0, 1],\n ]\n )\n mat = mat3 * mat1\n\n aligned_img = cv2.warpAffine(\n img,\n mat[0:2, :],\n (img_size, img_size),\n cv2.INTER_LINEAR,\n borderValue=(128, 128, 128),\n )\n\n land_3d = np.ones((int(len(img_land) / 2), 3))\n land_3d[:, 0:2] = np.reshape(np.array(img_land), (int(len(img_land) / 2), 2))\n mat_land_3d = np.mat(land_3d)\n new_land = np.array((mat * mat_land_3d.T).T)\n new_land = np.reshape(new_land[:, 0:2], len(img_land))\n\n return aligned_img, new_land\n\n def detect_au(self, imgs, land_data):\n \n lenth_index = [len(ama) for ama in land_data]\n lenth_cumu = np.cumsum(lenth_index)\n\n flat_faces = np.array([item for sublist in land_data for item in sublist]) # Flatten the faces\n flat_faces = flat_faces.transpose(0,2,1)\n pt49_array = None\n \n img_transforms = transforms.Compose(\n [\n transforms.CenterCrop(176),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]\n )\n\n input_torch = None\n land_torch = None\n for i in range(flat_faces.shape[0]):\n \n frame_assignment = np.where(i<=lenth_cumu)[0][0] # which frame is it?\n\n land_convert = convert68to49(flat_faces[i]).T\n new_land_data = land_convert.flatten()\n new_img, new_land = self.align_face_49pts(imgs[frame_assignment], new_land_data)\n new_img = cv2.cvtColor(new_img, cv2.COLOR_BGR2RGB)\n im_pil = Image.fromarray(new_img) \n input = img_transforms(im_pil)\n if len(input.shape) < 4:\n input.unsqueeze_(0)\n new_land = torch.from_numpy(new_land)\n\n if input_torch is None:\n input_torch = input\n else:\n input_torch = torch.cat((input_torch,input),0)\n if land_torch is None:\n land_torch = new_land\n else:\n land_torch = torch.cat((land_torch,new_land),0)\n\n if self.use_gpu:\n input_torch, land_torch = input_torch.cuda(), land_torch.cuda()\n\n region_feat = self.region_learning(input_torch)\n align_feat, align_output, aus_map = self.align_net(region_feat)\n if self.use_gpu:\n aus_map = aus_map.cuda()\n output_aus_map = self.local_attention_refine(aus_map.detach())\n local_au_out_feat, local_aus_output = self.local_au_net(region_feat, output_aus_map)\n local_aus_output = (local_aus_output[:, 1, :]).exp()\n global_au_out_feat = self.global_au_feat(region_feat)\n concat_au_feat = torch.cat(\n (align_feat, global_au_out_feat, local_au_out_feat.detach()), 1\n )\n aus_output = self.au_net(concat_au_feat)\n aus_output = (aus_output[:, 1, :]).exp()\n all_output = aus_output.data.cpu().float()\n AUoccur_pred_prob = all_output.data.numpy()\n return AUoccur_pred_prob\n","sub_path":"feat/au_detectors/JAANet/JAA_test.py","file_name":"JAA_test.py","file_ext":"py","file_size_in_byte":12087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"311843361","text":"import pafy\nimport numpy as np\nimport time\nfrom tqdm import tqdm\nimport tensorflow as tf\nfrom tensorflow.keras.applications.mobilenet_v2 import preprocess_input\nprint('tensorflow.__version__', tf.__version__)\n#print('GPU name test',tf.test.gpu_device_name())\nimport cv2\nprint('cv2 version',cv2.__version__)\nimport imutils\n\n\n#Get youtube stream url by IDT\nurl = 'fdqOdTvGc9I'\nvPafy = pafy.new(url)\nplay = vPafy.getbest()\nprint(play.resolution, play.extension, play.get_filesize())\n\n\n# initialize the video stream\ncap = cv2.VideoCapture(play.url)\n\nframe_width = int( cap.get(cv2.CAP_PROP_FRAME_WIDTH))\nframe_height =int( cap.get( cv2.CAP_PROP_FRAME_HEIGHT))\nfps = int( cap.get(cv2.CAP_PROP_FPS))\n\nfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\nout = cv2.VideoWriter(\"output.mov\", fourcc, fps, (frame_width,frame_height))\n\nret, frame1 = cap.read()\nret, frame2 = cap.read()\nret, frame3 = cap.read()\nprint(frame1.shape)\n\n#Load NN\nmp='./KersModel.h5'\nmodel=tf.keras.models.load_model(mp)\ntargetxy = (96,96)\nprint('NN model loaded')\n\ndef statslambda(stat, cf,fm):\n s = stat[cv2.CC_STAT_AREA]\n (x, y, w, h) = (stat[cv2.CC_STAT_LEFT], stat[cv2.CC_STAT_TOP], stat[cv2.CC_STAT_WIDTH], stat[cv2.CC_STAT_HEIGHT])\n if s < 50 or s > 500 or (h / w) > 2 or (w / h) > 2:\n pass\n else:\n if fm[x, y] > 0:\n for l in enumerate(cf):\n if (x, y, w, h) == l[1]:\n fm[x, y] += 1\n break\n elif fm[x, y] == 0:\n fm[x, y] += 1\n cf.append((x, y, w, h))\n return cf,fm\n\nfor i in tqdm(range(700)):\n#while cap.isOpened():\n\n ret, frame4 = cap.read()\n\n diffm1 = cv2.absdiff(cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY),\n cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY))\n diff = cv2.absdiff(cv2.cvtColor(frame4, cv2.COLOR_BGR2GRAY),\n cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY))\n diffp1 = cv2.absdiff(cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY),\n cv2.cvtColor(frame3, cv2.COLOR_BGR2GRAY))\n\n ret, dbp = cv2.threshold(diffp1, 10, 255, cv2.THRESH_BINARY)\n ret, dbm = cv2.threshold(diffm1, 10, 255, cv2.THRESH_BINARY)\n ret, db0 = cv2.threshold(diff, 10, 255, cv2.THRESH_BINARY)\n diff = cv2.bitwise_and(dbm, db0)\n\n num, labels, stats, centroids = cv2.connectedComponentsWithStats(diff, ltype=cv2.CV_16U, connectivity=8)\n\n difffast = cv2.bitwise_and(cv2.bitwise_and(dbm, db0),\n cv2.bitwise_not(dbp))\n numf, labelsf, statsf, centroidsf = cv2.connectedComponentsWithStats(difffast, ltype=cv2.CV_16U, connectivity=8)\n\n contoursFilered = []\n contoursBall = []\n frame_contur = frame1.copy()\n fm = np.zeros((frame_width, frame_height), np.int16)\n\n for stat in stats:\n contoursFilered,fm=statslambda(stat,contoursFilered,fm)\n for stat in statsf:\n contoursFilered,fm=statslambda(stat,contoursFilered,fm)\n\n crop_imgs = []\n for l in enumerate(contoursFilered):\n (x, y, w, h) = l[1]\n if fm[x, y] == 1:\n rectcolor = (255, 255, 255)\n else:\n rectcolor = (0, 255, 255)\n cv2.rectangle(frame_contur, (x, y), (x + w, y + h), rectcolor, 2)\n crop_img = frame_contur[y:y + h, x:x + w].copy()\n crop_img =cv2.cvtColor(cv2.resize(crop_img, targetxy), cv2.COLOR_BGR2RGB)\n crop_imgs.append(preprocess_input(crop_img))\n X = np.array(crop_imgs)\n if X.shape[0]>0:\n Y = model.predict(X)\n rectcolor = (0, 0, 255)\n for p in enumerate(Y.reshape(-1)):\n if p[1]>0.8:\n (x, y, w, h) = contoursFilered[p[0]]\n cv2.circle(frame_contur, (x+ w//2, y+h//2), (h+w)//2, rectcolor, 2)\n cv2.putText(frame_contur, str(p), (x, y - 5),cv2.FONT_HERSHEY_SIMPLEX, 0.5, rectcolor, 2)\n out.write(frame_contur)\n frame1 = frame2\n frame2 = frame3\n frame3 = frame4\n\ncv2.destroyAllWindows()\ncap.release()\nout.release()","sub_path":"MotionDetectionsKeras.py","file_name":"MotionDetectionsKeras.py","file_ext":"py","file_size_in_byte":3958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"17329281","text":"import numpy as np\nfrom itertools import repeat\nimport scipy\nfrom scipy import interpolate\nimport pandas\nimport pyoorb as oo\n\nfrom lsst.sims.maf.db import OpsimDatabase\nfrom lsst.sims.utils import haversine\n\n\ndef packOorbElem(sso):\n oorbelems = [sso['!!ObjID'], sso['q'], sso['e'], np.radians(sso['i']), np.radians(sso['Omega/node']), \n np.radians(sso['omega/argperi']), sso['t_p'], 2, sso['t_0'], 3, sso['magHv'], 0.15]\n oorbelems = np.column_stack(oorbelems)\n return oorbelems\n\ndef unpackEphs(oorbephem):\n # oorbephem = single ephem - i.e. for single object. \n # then swap time/ephemeris element, so that we can get easy arrays of things like 'ra', 'dec'.\n oorbephem = np.swapaxes(oorbephem, 0, 1)\n dist = oorbephem[0]\n ra = oorbephem[1]\n dec = oorbephem[2]\n magV = oorbephem[3]\n time = oorbephem[4]\n dradt = oorbephem[6]\n ddecdt = oorbephem[7]\n phaseangle = oorbephem[8]\n solarelon = oorbephem[9]\n ephs = np.rec.fromarrays([time, ra, dec, dradt, ddecdt, dist, magV, phaseangle, solarelon], \n names=['time', 'ra', 'dec', 'dradt', 'ddecdt', 'dist', 'magV', 'phaseangle', 'solarelon'])\n return ephs\n\ndef interpolateEphs(ephs):\n interpfuncs = {}\n for n in ephs.dtype.names:\n if n == 'time':\n continue\n interpfuncs[n] = interpolate.interp1d(ephs['time'], ephs[n], kind='linear', assume_sorted=True, copy=False)\n return interpfuncs\n\ndef ssoInFov(interpfuncs, simdata, rFov=np.radians(1.75), raCol='fieldRA', decCol='fieldDec'):\n raSso = np.radians(interpfuncs['ra'](simdata['expMJD']))\n decSso = np.radians(interpfuncs['dec'](simdata['expMJD']))\n sep = haversine(raSso, decSso, simdata[raCol], simdata[decCol])\n tObs = simdata['expMJD'][np.where(sep> outfile, writestring\nfor sso in orbits:\n oorbelems = packOorbElem(sso)\n oorbephems, err = oo.pyoorb.oorb_ephemeris(in_orbits = oorbelems, in_obscode=807, in_date_ephems=ephTimes)\n ephs = unpackEphs(oorbephems[0])\n interpfuncs = interpolateEphs(ephs)\n tvis = ssoInFov(interpfuncs, simdata)\n obs = np.recarray([len(tvis)], dtype=ephs.dtype)\n for n in interpfuncs:\n obs[n] = interpfuncs[n](tvis)\n obs['time'] = tvis\n for i in range(len(obs['time'])):\n writestring = '%s' %(sso['!!ObjID'])\n for n in names:\n writestring += ' %f' %(obs[n][i])\n print >> outfile, writestring\noutfile.close()\n","sub_path":"proto.py","file_name":"proto.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"649413325","text":"\n\nclass Line():\n\n\tdef __init__(self,x1=0,y1=0,x2=0,y2=0):\n\t\tself.x1 = x1\n\t\tself.y1 = y1\n\t\tself.x2 = x2\n\t\tself.y2 = y2\n\t\tself.k = (y2-y1) / (x2-x1) \n#\t\tprint(self.x, self.y)\n\t\tprint(self)\n\n\tdef __str__(self):\n\t\treturn ' ((%d , %d ) ,(%d , %d )) k = %d' % (self.x1, self.y1 ,self.x2, self.y2 , self.k)\n\na = Line(5,3,6,7)\n#a.show()\n\n\n#b=Line(1,100)\n\n\n","sub_path":"python核心编程 第二版/第十三章/练习6.py","file_name":"练习6.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"462445443","text":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"In-memory representation of the schema of a dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport abc\nimport collections\nimport six\n\nimport tensorflow as tf\n\n\n_TF_EXAMPLE_ALLOWED_TYPES = [tf.string, tf.int64, tf.float32, tf.bool]\n\n\nclass Schema(object):\n \"\"\"The schema of a dataset.\n\n This is an in-memory representation that may be serialized and deserialized to\n and from a variety of disk representations.\n\n Args:\n column_schemas: A dict from logical column names to `ColumnSchema`s.\n \"\"\"\n\n\n def __init__(self, column_schemas=None):\n if not column_schemas:\n column_schemas = {}\n if not isinstance(column_schemas, dict):\n raise ValueError('column_schemas must be a dict.')\n self._column_schemas = column_schemas\n\n @property\n def column_schemas(self):\n return self._column_schemas\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self.__dict__ == other.__dict__\n return NotImplemented\n\n def __ne__(self, other):\n return not self == other\n\n def __getitem__(self, index):\n return self.column_schemas[index]\n\n def merge(self, other):\n # possible argument: resolution strategy (error or pick first and warn?)\n for key, value in six.iteritems(other.column_schemas):\n if key in self.column_schemas:\n self.column_schemas[key].merge(value)\n else:\n self.column_schemas[key] = value\n\n\n def as_feature_spec(self):\n \"\"\"Returns a representation of this Schema as a feature spec.\n\n A feature spec (for a whole dataset) is a dictionary from logical feature\n names to one of `FixedLenFeature`, `SparseFeature` or `VarLenFeature`.\n\n Returns:\n A representation of this Schema as a feature spec.\n \"\"\"\n return {key: column_schema.as_feature_spec()\n for key, column_schema in six.iteritems(self.column_schemas)}\n\n def as_batched_placeholders(self):\n \"\"\"Returns a representation of this Schema as placeholder Tensors.\n\n Returns:\n A representation of this Schema as placeholder Tensors.\n \"\"\"\n return {key: column_schema.as_batched_placeholder()\n for key, column_schema in six.iteritems(self.column_schemas)}\n\n\nclass ColumnSchema(collections.namedtuple(\n 'ColumnSchema', ['domain', 'axes', 'representation'])):\n \"\"\"The schema for a single column in a dataset.\n\n The schema contains two parts: the logical description of the column, which\n describes the nature of the actual data in the column (particularly this\n determines how this will ultimately be represented as a tensor) and the\n physical representation of the column, i.e. how the column's data is\n represented in memory or on disk.\n\n Fields:\n domain: a Domain object, providing the dtype and possibly other constraints.\n axes: a list of axes describing the intrinsic shape of the data,\n irrespective of its representation as dense or sparse.\n representation: A `ColumnRepresentation` that describes how the data is\n represented.\n \"\"\"\n\n def __new__(cls, domain, axes, representation):\n if not isinstance(domain, Domain):\n domain = _dtype_to_domain(domain)\n if not (axes and isinstance(axes[0], Axis)):\n axes = _tf_shape_to_axes(axes)\n\n return super(ColumnSchema, cls).__new__(\n cls, domain=domain, axes=axes, representation=representation)\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self._asdict() == other._asdict()\n return NotImplemented\n\n def __ne__(self, other):\n return not self == other\n\n def as_feature_spec(self):\n \"\"\"Returns a representation of this ColumnSchema as a feature spec.\n\n A feature spec (for a specific column) is one of a FixedLenFeature,\n SparseFeature or VarLenFeature.\n\n Returns:\n A representation of this ColumnSchema as a feature spec.\n \"\"\"\n return self.representation.as_feature_spec(self)\n\n def as_batched_placeholder(self):\n \"\"\"Returns a representation of this ColumnSchema as a placeholder Tensor.\n\n Returns:\n A representation of this ColumnSchema as a placeholder Tensor.\n \"\"\"\n return self.representation.as_batched_placeholder(self)\n\n def tf_shape(self):\n \"\"\"Represent the shape of this column as a `TensorShape`.\"\"\"\n if self.axes is None:\n return tf.TensorShape(None)\n return tf.TensorShape([axis.size for axis in self.axes])\n\n def is_fixed_size(self):\n if self.axes is None:\n return False\n for axis in self.axes:\n if axis.size is None:\n return False\n return True\n\n def merge(self, other):\n raise NotImplementedError('Merge not implemented yet.')\n\n\nclass Domain(object):\n \"\"\"A description of the valid values that a column can take.\"\"\"\n\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, dtype):\n self._dtype = tf.as_dtype(dtype)\n\n def __eq__(self, other):\n if other.__class__ == self.__class__:\n return self.__dict__ == other.__dict__\n return NotImplemented\n\n def __ne__(self, other):\n return not self == other\n\n def __repr__(self):\n return '%s(%r)' % (self.__class__.__name__, self._dtype)\n\n @property\n def dtype(self):\n return self._dtype\n\n # Serialize the tf.dtype as a string so that it can be unpickled on DataFlow.\n def __getstate__(self):\n return self._dtype.name\n\n def __setstate__(self, state):\n self._dtype = tf.as_dtype(state)\n\n\n\n\nclass FloatDomain(Domain):\n \"\"\"A domain for a floating-point type.\"\"\"\n\n def __init__(self, dtype):\n super(FloatDomain, self).__init__(dtype)\n if not self.dtype.is_floating:\n raise ValueError(\n 'FloatDomain must be initialized with an floating point dtype.')\n\n\nclass IntDomain(Domain):\n \"\"\"A domain for an integral type.\"\"\"\n\n def __init__(self, dtype, min_value=None, max_value=None,\n is_categorical=None):\n super(IntDomain, self).__init__(dtype)\n if not self.dtype.is_integer:\n raise ValueError('IntDomain must be initialized with an integral dtype.')\n # NOTE: Because there is no uint64 or 128 bit ints, the following values\n # are always in the int64 range, which is important for the proto\n # representation.\n self._min_value = min_value if min_value is not None else self.dtype.min\n self._max_value = max_value if max_value is not None else self.dtype.max\n # Parsing a non-existing value from JSON will return None make sure it is\n # translated to False.\n self._is_categorical = (is_categorical\n if is_categorical is not None\n else False)\n\n @property\n def min_value(self):\n return self._min_value\n\n @property\n def max_value(self):\n return self._max_value\n\n @property\n def is_categorical(self):\n return self._is_categorical\n\n\nclass StringDomain(Domain):\n \"\"\"A domain for a string type.\"\"\"\n\n def __init__(self, dtype):\n super(StringDomain, self).__init__(dtype)\n if self.dtype != tf.string:\n raise ValueError('StringDomain must be initialized with a string dtype.')\n\n\nclass BoolDomain(Domain):\n \"\"\"A domain for a boolean type.\"\"\"\n\n def __init__(self, dtype):\n super(BoolDomain, self).__init__(dtype)\n if self.dtype != tf.bool:\n raise ValueError('BoolDomain must be initialized with a boolean dtype.')\n\n\ndef _dtype_to_domain(dtype):\n \"\"\"Create an appropriate Domain for the given dtype.\"\"\"\n if dtype.is_integer:\n return IntDomain(dtype)\n if dtype.is_floating:\n return FloatDomain(dtype)\n if dtype == tf.string:\n return StringDomain(dtype)\n if dtype == tf.bool:\n return BoolDomain(dtype)\n raise ValueError('Schema cannot accommodate dtype: {}'.format(dtype))\n\n\nclass Axis(collections.namedtuple('Axis', ['size'])):\n \"\"\"An axis representing one dimension of the shape of a column.\n\n Elements are:\n size: integer. The length of the axis. None = unknown.\n \"\"\"\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self._asdict() == other._asdict()\n return NotImplemented\n\n def __ne__(self, other):\n return not self == other\n\n\nclass ColumnRepresentation(object):\n \"\"\"A description of the representation of a column in memory or on disk.\"\"\"\n\n __metaclass__ = abc.ABCMeta\n\n def __eq__(self, other):\n if other.__class__ == self.__class__:\n return self.__dict__ == other.__dict__\n return NotImplemented\n\n def __ne__(self, other):\n return not self == other\n\n @abc.abstractmethod\n def as_feature_spec(self, column):\n \"\"\"Returns the representation of this column as a feature spec.\n\n Args:\n column: The column to be represented.\n \"\"\"\n raise NotImplementedError()\n\n @abc.abstractmethod\n def as_batched_placeholder(self, column):\n \"\"\"Returns the representation of this column as a placeholder Tensor.\n\n Args:\n column: The column to be represented.\n \"\"\"\n raise NotImplementedError()\n\n# note we don't provide tf.FixedLenSequenceFeature yet, because that is\n# only used to parse tf.SequenceExample.\n\n\nclass FixedColumnRepresentation(ColumnRepresentation):\n \"\"\"Represent the column using a fixed size.\"\"\"\n\n def __init__(self, default_value=None):\n super(FixedColumnRepresentation, self).__init__()\n self._default_value = default_value\n\n @property\n def default_value(self):\n \"\"\"Default value may be None, but then missing data produces an error.\"\"\"\n return self._default_value\n\n def __repr__(self):\n return '%s(%r)' % (self.__class__.__name__, self._default_value)\n\n def as_feature_spec(self, column):\n if not column.is_fixed_size():\n raise ValueError('A column of unknown size cannot be represented as '\n 'fixed-size.')\n if column.domain.dtype not in _TF_EXAMPLE_ALLOWED_TYPES:\n raise ValueError('tf.Example parser supports only types {}, so it is '\n 'invalid to generate a feature_spec with type '\n '{}.'.format(\n _TF_EXAMPLE_ALLOWED_TYPES,\n repr(column.domain.dtype)))\n return tf.FixedLenFeature(column.tf_shape().as_list(),\n column.domain.dtype,\n self.default_value)\n\n def as_batched_placeholder(self, column):\n if not column.is_fixed_size():\n raise ValueError('A column of unknown size cannot be represented as '\n 'fixed-size.')\n return tf.placeholder(column.domain.dtype,\n [None] + column.tf_shape().as_list())\n\n\nclass ListColumnRepresentation(ColumnRepresentation):\n \"\"\"Represent the column using a variable size.\"\"\"\n\n def __init__(self):\n super(ListColumnRepresentation, self).__init__()\n\n def __repr__(self):\n return '%s()' % (self.__class__.__name__,)\n\n def as_feature_spec(self, column):\n if column.domain.dtype not in _TF_EXAMPLE_ALLOWED_TYPES:\n raise ValueError('tf.Example parser supports only types {}, so it is '\n 'invalid to generate a feature_spec with type '\n '{}.'.format(\n _TF_EXAMPLE_ALLOWED_TYPES,\n repr(column.domain.dtype)))\n return tf.VarLenFeature(column.domain.dtype)\n\n def as_batched_placeholder(self, column):\n return tf.sparse_placeholder(\n column.domain.dtype,\n [None] + column.tf_shape().as_list())\n\n\nclass SparseColumnRepresentation(ColumnRepresentation):\n \"\"\"Sparse physical representation of a logically fixed-size column.\"\"\"\n\n def __init__(self, value_field_name, index_fields):\n super(SparseColumnRepresentation, self).__init__()\n self._value_field_name = value_field_name\n self._index_fields = index_fields\n\n @property\n def value_field_name(self):\n return self._value_field_name\n\n @property\n def index_fields(self):\n # SparseIndexes\n return self._index_fields\n\n def __repr__(self):\n return '%s(%r, %r)' % (self.__class__.__name__,\n self._value_field_name, self._index_fields)\n\n def as_feature_spec(self, column):\n ind = self.index_fields\n if len(ind) != 1 or len(column.axes) != 1:\n raise ValueError('tf.Example parser supports only 1-d sparse features.')\n index = ind[0]\n\n if column.domain.dtype not in _TF_EXAMPLE_ALLOWED_TYPES:\n raise ValueError('tf.Example parser supports only types {}, so it is '\n 'invalid to generate a feature_spec with type '\n '{}.'.format(\n _TF_EXAMPLE_ALLOWED_TYPES,\n repr(column.domain.dtype)))\n\n return tf.SparseFeature(index.name,\n self._value_field_name,\n column.domain.dtype,\n column.axes[0].size,\n index.is_sorted)\n\n def as_batched_placeholder(self, column):\n return tf.sparse_placeholder(\n column.domain.dtype,\n [None] + column.tf_shape().as_list())\n\n\nclass SparseIndexField(collections.namedtuple('SparseIndexField',\n ['name', 'is_sorted'])):\n pass\n\n\ndef from_feature_spec(feature_spec):\n \"\"\"Convert a feature_spec to a Schema.\n\n Args:\n feature_spec: a features specification in the format expected by\n tf.parse_example(), i.e.\n `{name: FixedLenFeature(...), name: VarLenFeature(...), ...'\n\n Returns:\n A Schema representing the provided set of columns.\n \"\"\"\n return Schema({\n key: _from_parse_feature(parse_feature)\n for key, parse_feature in six.iteritems(feature_spec)\n })\n\n\ndef _from_parse_feature(parse_feature):\n \"\"\"Convert a single feature spec to a ColumnSchema.\"\"\"\n\n # FixedLenFeature\n if isinstance(parse_feature, tf.FixedLenFeature):\n representation = FixedColumnRepresentation(parse_feature.default_value)\n return ColumnSchema(parse_feature.dtype, parse_feature.shape,\n representation)\n\n # FixedLenSequenceFeature\n if isinstance(parse_feature, tf.FixedLenSequenceFeature):\n raise ValueError('DatasetSchema does not support '\n 'FixedLenSequenceFeature yet.')\n\n # VarLenFeature\n if isinstance(parse_feature, tf.VarLenFeature):\n representation = ListColumnRepresentation()\n return ColumnSchema(parse_feature.dtype, [None], representation)\n\n # SparseFeature\n if isinstance(parse_feature, tf.SparseFeature):\n index_field = SparseIndexField(name=parse_feature.index_key,\n is_sorted=parse_feature.already_sorted)\n representation = SparseColumnRepresentation(\n value_field_name=parse_feature.value_key,\n index_fields=[index_field])\n return ColumnSchema(parse_feature.dtype, [parse_feature.size],\n representation)\n\n raise ValueError('Cannot interpret feature spec: {}'.format(parse_feature))\n\n\ndef infer_column_schema_from_tensor(tensor):\n \"\"\"Infer a ColumnSchema from a tensor.\"\"\"\n if isinstance(tensor, tf.SparseTensor):\n # For SparseTensor, there's insufficient information to distinguish between\n # ListColumnRepresentation and SparseColumnRepresentation. So we just guess\n # the former, and callers are expected to handle the latter case on their\n # own (e.g. by requiring the user to provide the schema). This is a policy\n # motivated by the prevalence of VarLenFeature in current tf.Learn code.\n axes = [Axis(None)]\n representation = ListColumnRepresentation()\n else:\n axes = _tf_shape_to_axes(tensor.get_shape(),\n remove_batch_dimension=True)\n representation = FixedColumnRepresentation()\n return ColumnSchema(tensor.dtype, axes, representation)\n\n\ndef _tf_shape_to_axes(tf_shape, remove_batch_dimension=False):\n \"\"\"Create axes for the given shape.\n\n Args:\n tf_shape: A `TensorShape` or anything that can be converted to a\n `TensorShape`.\n remove_batch_dimension: A boolean indicating whether to remove the 0th\n dimension.\n\n Returns:\n A list of axes representing the given shape.\n\n Raises:\n ValueError: If `remove_batch_dimension` is True and the given shape does not\n have rank >= 1.\n \"\"\"\n if not isinstance(tf_shape, tf.TensorShape):\n tf_shape = tf.TensorShape(tf_shape)\n if tf_shape.dims is None:\n axes = None\n else:\n axes = [Axis(axis_size) for axis_size in tf_shape.as_list()]\n if remove_batch_dimension:\n if len(axes) < 1:\n raise ValueError('Expected tf_shape to have rank >= 1')\n axes = axes[1:]\n return axes\n","sub_path":"tensorflow_transform/tf_metadata/dataset_schema.py","file_name":"dataset_schema.py","file_ext":"py","file_size_in_byte":17026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"392278456","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUtilities to load datasets from the `dataset` package.\n\"\"\"\n# Author: bertrand-l\n# License: BSD\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport os\nimport numpy as np\nfrom .dataset import DataSet\n\n\n__all__ = ('load_faithful', 'load_iris', 'load_women')\n\n\nDATAPATH = os.path.join(os.path.dirname(__file__), 'data')\n\n\ndef filepath(fname):\n \"\"\"Returns the complete file path to the file.\"\"\"\n\n return os.path.join(DATAPATH, fname)\n\n\ndef load(fname, xcol=None, xfmt='f', ycol=None, yfmt='f', sep=None,\n missing='NaN', tolerant=True):\n \"\"\"\n Read data from a flat (tabulated or delimiter-separated) ascii file with a\n header and return a `DataSet` object.\n\n Everything before the line starting with 'DATA>' is considered the header.\n 'DATA>' may be followed by variables names separated by `sep`. After that,\n everything is considered data. Each data column can have its own type.\n `X` and `y` are returned as numpy.ndarray only if all columns in `X`\n have the same type (i.e. xfmt='f' or 'i' or 's' but not something like\n 'f,s'). Otherwise they are left as lists.\n\n Parameters\n ----------\n fname : str\n name of a file in the `data` directory\n xcol, ycol : str or None\n column numbers for X or y data, e.g. '0 1 2' or '0-2'. If `xcol` is\n None, all columns are assumed to belong to `X`.\n xfmt, yfmt : str\n data format for each column: {'i', 'f', 's'} or a combination such\n as 'iffs'.\n sep : str or None\n tolerant : boleean\n just ignore data lines that cannot be converted\n \"\"\"\n # FIXME: ugly\n def convert(string, fmt):\n \"\"\"Tries to convert a string to a given format.\"\"\"\n string = string.strip()\n if string == missing:\n return np.nan\n else:\n if fmt == 'f':\n return float(string)\n elif fmt == 'i':\n return int(string)\n else:\n return string\n\n def readline(words):\n \"\"\"Reads line split into 'words' and returns a tuple.\"\"\"\n imax = len(xfmt) - 1\n if ix is None:\n X = tuple(convert(words[i], xfmt[min(i, imax)])\n for i in range(len(words)))\n else:\n X = tuple(convert(words[ix[i]], xfmt[min(i, imax)])\n for i in range(len(ix)))\n if iy is not None:\n return X, convert(words[iy], yfmt)\n else:\n return X, None\n\n # form column indices and formats\n if isinstance(sep, basestring) and sep.strip() == '':\n sep = None\n if xcol is None:\n ix = None\n else:\n xcol = str(xcol)\n if xcol.find('-') > 0:\n beg, end = xcol.split('-')\n ix = range(int(beg), int(end) + 1)\n else:\n ix = [int(i) for i in xcol.split(sep)]\n if ycol is None or ycol == '' or xcol is None:\n iy = None\n else:\n iy = int(ycol)\n if sep is None:\n xfmt = '{}'.format(xfmt).replace(' ', '')\n else:\n xfmt = '{}'.format(xfmt).replace(' ', '').replace(sep, '')\n xfmt = [xf for xf in xfmt]\n yfmt = '{}'.format(yfmt).lstrip()[0]\n\n # read line by line\n with open(filepath(fname), 'rU') as fp:\n\n X, y = [], []\n title, Xlabel, ylabel = None, None, None\n header, reading_header = \"\", True\n for line in fp:\n line = line.rstrip('\\n').strip()\n if line.startswith(\"DATA>\"):\n # data starts here\n reading_header = False\n label = line[5:].split(sep)\n if ix is None:\n Xlabel = tuple([lab.strip() for lab in label])\n elif len(label) >= len(ix):\n Xlabel = tuple([label[i].strip() for i in ix])\n if iy is not None:\n ylabel = label[iy].strip()\n elif reading_header:\n # reading header\n if title is None and len(line) > 0:\n title = line\n header += \"\\n{0}\".format(line)\n elif len(line) > 0:\n # reading data\n words = line.split(sep)\n try:\n X_, y_ = readline(words)\n except (IndexError, TypeError, ValueError) as err:\n if not tolerant:\n raise err\n else:\n if len(X) == 0 or len(X_) == len(X[0]):\n X.append(X_)\n if y_ is not None:\n y.append(y_)\n\n if len(y) != len(X):\n y = None\n if xfmt == [xfmt[0]] * len(xfmt):\n X = np.array(X)\n if y is not None:\n y = np.array(y)\n return DataSet(X, Xlabel=Xlabel, y=y, ylabel=ylabel,\n info=header, title=title)\n\n\ndef load_faithful():\n \"\"\"\n Old Faithful Geyser Data.\n\n Waiting time between eruptions and the duration of the eruption\n for the Old Faithful geyser in Yellowstone National Park, Wyoming,\n USA.\n\n 272 observations on 2 variables.\n \"\"\"\n return load(\"faithful.data\", xcol='1 2', xfmt='f', sep=None)\n\n\ndef load_iris():\n \"\"\"\n Edgar Anderson's Iris Data.\n\n This famous (Fisher's or Anderson's) iris data set gives the measurements\n in centimeters of the variables sepal length and width and petal length and\n width, respectively, for 50 flowers from each of 3 species of iris. The\n species are Iris setosa, versicolor, and virginica.\n\n 150 observations (50 in each of three classes) on 4 attributes and\n the class.\n \"\"\"\n return load(\"iris.data\", xcol='0-3', xfmt='f', ycol=4, yfmt='s', sep=',')\n\n\ndef load_women():\n \"\"\"\n Average Heights and Weights for American Women.\n\n This data set gives the average heights and weights for American women\n aged 30–39.\n\n 15 observations on 2 variables.\n \"\"\"\n return load(\"women.data\", xcol=1, xfmt='f', ycol=2, yfmt='f',\n sep=None)\n","sub_path":"learnml/datasets/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":6085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"296896126","text":"import torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.autograd import Function\n\n\nclass AttributeMapper(nn.Module):\n def __init__(self, style_dim):\n super().__init__()\n\n layers = []\n\n for i in range(3):\n layers.append(nn.Linear(style_dim, style_dim))\n layers.append(nn.ReLU(True))\n\n self.fc = nn.Sequential(*layers[:-1])\n\n def forward(self, latent):\n residual = latent\n\n latent = self.fc(latent)\n\n latent = latent + residual\n\n return latent\n","sub_path":"models/attribute_mapping_net.py","file_name":"attribute_mapping_net.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"35796447","text":"\nfrom flask import Flask, request, jsonify, render_template, make_response, Response\n\n\nfrom util import *\nfrom util.master import Master\n\nmaster = Master()\napp = Flask(__name__)\n\n\n@app.route('/ontime', methods=['GET'])\ndef ontime():\n return render_template('ontime.html')\n\n\n@app.route('/search', methods=['GET'])\ndef search():\n return render_template('search.html')\n\n\n@app.route('/dashboard', methods=['GET'])\ndef dashboard():\n return render_template('dashboard.html')\n\n@app.route('/tracker', methods=['GET'])\ndef tracker():\n return dashboard()\n\n@app.route('/mapsearch', methods=['GET'])\ndef mapsearch():\n return render_template('mapsearch.html')\n\n@app.route('/lookup')\ndef lookup():\n city = \"San Francisco\"\n keyword = \"is\"\n date_time = current_milli_time()\n index = 1\n if \"city\" in request.args:\n city = request.args.get('city')\n if \"keyword\" in request.args:\n keyword = request.args.get('keyword')\n if \"date_time\" in request.args:\n date_time = long(float(request.args.get('date_time')))\n if \"type\" in request.args:\n type = request.args.get('type')\n if \"index\" in request.args:\n index = 0\n return json.dumps(master.itasca.lookup(city, keyword, date_time, type, index))\n\n@app.route('/light')\ndef light():\n keyword = \"Python\"\n if \"keyword\" in request.args:\n keyword = request.args.get('keyword')\n return json.dumps(master.itasca.lookup_light(keyword))\n\n@app.route('/more', methods=['GET', 'POST'])\ndef more():\n data = {'group_category_name': \"writing\",\n 'group_name': \"Writers\",\n 'name': \"Left Coast Writers Presents\",\n 'utc_time': 1462816800000,\n 'venue_address': \"1 Ferry Building\",\n 'venue_city': \"San Francisco\"}\n if request.method == 'POST':\n if 'group_category_name' in request.form and 'group_name' in request.form \\\n and 'name' in request.form and 'utc_time' in request.form \\\n and 'venue_address' in request.form and 'venue_city' in request.form:\n data['group_category_name'] = request.form['group_category_name']\n data['group_name'] = request.form['group_name']\n data['name'] = request.form['name']\n data['utc_time'] = int(request.form['utc_time'])\n data['venue_address'] = request.form['venue_address']\n data['venue_city'] = request.form['venue_city']\n elif request.method == 'GET':\n if 'group_category_name' in request.args and 'group_name' in request.args \\\n and 'name' in request.args and 'utc_time' in request.args \\\n and 'venue_address' in request.args and 'venue_city' in request.args:\n data['group_category_name'] = request.args['group_category_name']\n data['group_name'] = request.args['group_name']\n data['name'] = request.args['name']\n data['utc_time'] = int(request.args['utc_time'])\n data['venue_address'] = request.args['venue_address']\n data['venue_city'] = request.args['venue_city']\n\n return json.dumps((master.itasca.more_data(data)))\n\n@app.route('/next', methods=['GET'])\ndef nextdata():\n privous_end = -1\n if \"privous_end\" in request.args:\n privous_end = long(float(request.args.get('privous_end')))\n\n res = master.get_next_data(privous_end)\n return res\n\n\n@app.route('/workers', methods=['GET', 'POST', 'PUT'])\ndef workers():\n res_code = 0\n if request.method == 'POST':\n if 'worker_name' in request.form and 'password' in request.form:\n if request.form['password'] == '111111':\n res_code = master.add_worker(request.form['worker_name'])\n else:\n res_code = WORKER_ADDED_NO_AUTHORITY\n else:\n res_code = WORKER_ADDED_NO_DATA\n return add_worker_status_text(res_code)\n elif request.method == 'PUT':\n if 'worker_name' in request.form and 'worker_status' in request.form:\n res_code = master.update_worker(request.form['worker_name'], int(request.form['worker_status']))\n else:\n res_code = WORKER_UPDATED_NO_DATA\n return add_worker_status_text(res_code)\n else:\n worker_list = master.hashring.get_workers()\n if 'worker_name' in request.args:\n worker_status = WORKER_STATUS_NOTEXIST\n for worker in worker_list:\n if worker is not None and worker['worker_name'] == request.args['worker_name']:\n worker_status = int(worker['worker_status'])\n return json.dumps({'worker_status':str(worker_status)})\n else:\n return json.dumps({'workers': worker_list})\n\n@app.route('/distribute', methods=['GET'])\ndef distribute():\n if 'privous_end' in request.args:\n return master.itasca.project_distribution(int(request.args['privous_end']))\n else:\n return master.itasca.project_distribution()\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n itascastatus = get_itasca_status_text(master.itasca.status)\n if request.method == 'POST':\n if 'itascarequest' in request.form:\n request_code = int(request.form['itascarequest'])\n if request_code == 1:\n master.start_itasca()\n elif request_code == -1:\n master.stop_itasca()\n itascastatus = get_itasca_status_text(master.itasca.status)\n\n return render_template('index.html',\n workers_number=str(master.hashring.count_workers()),\n workers_status=master.hashring.get_workers(),\n itasca_status=itascastatus)\n\n\n@app.route('/itasca', methods=['GET'])\ndef itasca():\n if request.method == 'GET':\n if 'do' in request.args:\n method_code = int(request.args['do'])\n if method_code == 1:\n master.start_itasca()\n elif method_code == 0:\n master.stop_itasca()\n return str(master.itasca.status)\n\nif __name__ == '__main__':\n app.debug = False\n app.run(use_debugger='False', debug='False',use_reloader='False', host='0.0.0.0')\n\n\n","sub_path":"final/master/flaskapp.py","file_name":"flaskapp.py","file_ext":"py","file_size_in_byte":6156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"541405493","text":"\nfrom accounts.validators.valuevalidator import ValueValidator\nfrom accounts.validators.validator import EmailValidator, PhoneValidator, NamingValidator;\nfrom accounts.data.user import User\n\n\nclass UserValidator(ValueValidator):\n\n def __init__(self):\n super().__init__(\"\");\n self.__Validators = dict();\n self.Validators['email'] = EmailValidator();\n self.Validators['phone'] = PhoneValidator();\n namingValidator = NamingValidator();\n self.Validators['firstname'] = namingValidator;\n self.Validators['lastname'] = namingValidator;\n self.__Errors = None;\n\n @property\n def Errors(self):\n return self.__Errors;\n\n @property\n def Validators(self):\n return self.__Validators\n\n def Validate(self, user: User) ->bool:\n \"\"\"\n :type user :User\n :param user:\n :return:\n \"\"\"\n error = dict();\n for field in self.Validators:\n if field == 'email':\n if (self.Validators[field].Validate(user.Email)) is not True:\n error[field] = False;\n elif field == 'firstname' :\n if (self.Validators[field].Validate(user.Firstname)) is not True:\n error[field] = False;\n elif field == 'lastname':\n if (self.Validators[field].Validate(user.Lastname)) is not True:\n error[field] = False;\n elif field == 'phone':\n if (self.Validators['phone'].Validate(user.PhoneNumber)) is not True:\n error[field] = False;\n success = (len(error) == 0);\n if success is not True:\n self.__Errors = error if (len(error) > 0) else None;\n return success;\n\n\nif __name__ == \"__main__\":\n\n user = User(phone=\"07501348124\", firstname='Obaro', lastname=\"Johnson\", gender='mr',email='obaro.johnson@hotmail.com');\n validator = UserValidator();\n if (validator.Validate(user)) is not True:\n print(validator.Errors);\n print(\"Not validated\")\n else:\n print(\"Validated : successful\")\n print(user)\n","sub_path":"accounts/validators/uservalidator.py","file_name":"uservalidator.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"281132303","text":"import sys\nimport datetime\n\nfrom mock import ANY, patch, MagicMock\n\nfrom hadoopimport.ingestion_job_status import IngestionJobStatus\n\nsys.modules['hadoopimport.config'] = MagicMock()\nfrom decimal import Decimal\nfrom base_test_case import BaseTestCase\nfrom hadoopimport.ingestion_job_repository import IngestionJobRepository\n\n\nclass IngestionJobRepositoryTest(BaseTestCase):\n def setUp(self):\n self.mock_mssql_db_mgr = self.get_mock(\"hadoopimport.ingestion_job_repository.MsSqlDbManager\")\n self.mock_config = self.get_mock(\"hadoopimport.ingestion_job_repository.Config\")\n\n def test_non_cleanup_ingestion_job_query(self):\n # Given\n self.mock_mssql_db_mgr.execute_query.return_value = [\n {u'Status': Decimal('1'), u'UpdateTime': datetime.datetime(2018, 4, 12, 15, 49, 39, 43000), u'DbType': Decimal('1'), u'TableName': u'PaymentType', u'PreviousVersion': 0, u'CustomerId': 10590, u'IngestionJobID': 126, u'Version': 0, u'CreateTime': datetime.datetime(2018, 4, 12, 15, 49, 39, 43000), u'StartTime': datetime.datetime(2018, 4, 12, 15, 49, 39, 43000), u'IngestionType': Decimal('1'), u'IngestionJobType': Decimal('3'), u'DbName': u'christiancustomer'}\n ]\n\n # When\n ingest_repo = IngestionJobRepository()\n test_customer_id_list = ingest_repo.get_last_non_cleanup_job_customers()\n\n # Then\n self.assertIsNotNone(test_customer_id_list )\n self.assertTrue(len(test_customer_id_list ) > 0)\n\n def test_cleanup_ingestion_job_insert(self):\n # Given\n self.mock_mssql_db_mgr.execute_query.return_value = 123\n customer_ids = set([10590, 19631])\n failed_customer_ids = set([10590])\n\n # When\n ingest_repo = IngestionJobRepository()\n ingest_repo.create_customer_cleanup_jobs(customer_ids, failed_customer_ids)\n\n # Then\n self.assertEqual(self.mock_mssql_db_mgr.execute_query.call_count, 2)\n\n def test_failure_ingestion_job_query(self):\n # Given\n self.mock_mssql_db_mgr.execute_query.return_value = [\n {u'TableName': u'PatientCaseDate', u'CustomerId': 10590, u'IngestionType': Decimal('1')}\n ]\n\n # When\n ingest_repo = IngestionJobRepository()\n test_failure_job_list = ingest_repo.get_last_ingestion_jobs_by_status(IngestionJobStatus.FAIL)\n\n # Then\n self.assertIsNotNone(test_failure_job_list)\n self.assertTrue(len(test_failure_job_list) > 0)\n","sub_path":"Projects/hadoop_import/hadoopimport/tests/test_ingestion_job_repository.py","file_name":"test_ingestion_job_repository.py","file_ext":"py","file_size_in_byte":2456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"427219815","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nimport csv\n\nfrom django.db import models, migrations\n\nfrom ratings.models import Movie, Tag, Rater\n\ndef import_tags(apps, schema_editor):\n with open(\"../ml-20m/tags.csv\") as file:\n csv_reader = csv.DictReader(file)\n for row in csv_reader:\n userId = int(row[\"userId\"])\n movie = Movie.objects.get(id=int(row[\"movieId\"]))\n tag = row[\"tag\"]\n timestamp = int(row[\"timestamp\"])\n tagger = Rater.objects.get_or_create(rater=userId, id=userId)[0]\n Tag.objects.create(movie=movie, tag=tag, timestamp=timestamp, rater=tagger)\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('ratings', '0003_auto_20150701_1358'),\n ]\n\n operations = [\n migrations.RunPython(import_tags),\n ]\n","sub_path":"movieratings/ratings/temp_data_migrations/0004_auto_20150701_1441.py","file_name":"0004_auto_20150701_1441.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"481131103","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 18 17:20:16 2018\n\n@author: averma\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\n#Native Python dates and times\n# datetime and dateutil\n\nfrom datetime import datetime\ndatetime(year=2015, month=7, day=4)\n\nfrom dateutil import parser\ndate = parser.parse(\"4th of July, 2015\")\ndate\n\ndate.strftime('%A')\n\n#TYPED ARRAYS OF TIMES: NumPy's\n#datetime64\n# encodes dates as 64-bit integers, \n# and thus allows arrays of dates to be represented very compactly.\n\ndate = np.array('2015-07-04', dtype=np.datetime64)\ndate\n\ndate + np.arange(12) # we can quickly do vectorized operations on it\n\nnp.datetime64('2015-07-04')\nnp.datetime64('2015-07-04 12:00') #Here is a minute-based datetime\nnp.datetime64('2015-07-04 12:59:59.50', 'ns') #nanosecond-based time\n\n\n'''\nCode\tMeaning\tTime span (relative)\tTime span (absolute)\nY\tYear\t± 9.2e18 years\t[9.2e18 BC, 9.2e18 AD]\nM\tMonth\t± 7.6e17 years\t[7.6e17 BC, 7.6e17 AD]\nW\tWeek\t± 1.7e17 years\t[1.7e17 BC, 1.7e17 AD]\nD\tDay\t± 2.5e16 years\t[2.5e16 BC, 2.5e16 AD]\nh\tHour\t± 1.0e15 years\t[1.0e15 BC, 1.0e15 AD]\nm\tMinute\t± 1.7e13 years\t[1.7e13 BC, 1.7e13 AD]\ns\tSecond\t± 2.9e12 years\t[ 2.9e9 BC, 2.9e9 AD]\nms\tMillisecond\t± 2.9e9 years\t[ 2.9e6 BC, 2.9e6 AD]\nus\tMicrosecond\t± 2.9e6 years\t[290301 BC, 294241 AD]\nns\tNanosecond\t± 292 years\t[ 1678 AD, 2262 AD]\nps\tPicosecond\t± 106 days\t[ 1969 AD, 1970 AD]\nfs\tFemtosecond\t± 2.6 hours\t[ 1969 AD, 1970 AD]\nas\tAttosecond\t± 9.2 seconds\t[ 1969 AD, 1970 AD]\n'''\n\n#Dates and times in pandas: best of both worlds\ndate = pd.to_datetime(\"4th of July, 2015\")\ndate\ndate.strftime('%A')\n\n#we can do NumPy-style vectorized operations directly on this same object:\ndate + pd.to_timedelta(np.arange(12), 'D') \n\n#PANDAS TIME SERIES: INDEXING BY TIME\n\n#we can construct a Series object that has time indexed data.\nindex = pd.DatetimeIndex(['2014-07-04', '2014-08-04',\n '2015-07-04', '2015-08-04'])\ndata = pd.Series([0, 1, 2, 3], index=index)\ndata\ndata['2014-07-04':'2015-07-04'] #you can slice like that\ndata['2015'] #get all the data from 2015\n\n#PANDAS TIME SERIES DATA STRUCTURES\n#Timestamp \n#Period \n#Timedelta \ndates = pd.to_datetime([datetime(2015, 7, 3), '4th of July, 2015',\n '2015-Jul-6', '07-07-2015', '20150708'])\ndates\n\n#Any DatetimeIndex can be converted to a PeriodIndex; 'D' for daily frequency:\ndates.to_period('D') \n#A TimedeltaIndex is created, for example, when a date is subtracted from another:\ndates - dates[0]\n\n#REGULAR SEQUENCES: ranges\n#pd.date_range() for timestamps, \n#pd.period_range() for periods, and \n#pd.timedelta_range() for time deltas\n\npd.date_range('2015-07-03', '2015-07-10')\npd.date_range('2015-07-03', periods=8) #default is day\npd.date_range('2015-07-03', periods=8, freq='H') #H is hour\npd.period_range('2015-07', periods=8, freq='M')\npd.timedelta_range(0, periods=10, freq='H')\n\n#Frequencies and Offsets\n'''\nCode\tDescription\nD\tCalendar day\t\nW\tWeekly\t\t\nM\tMonth end\t\nQ\tQuarter end\t\nA\tYear end\t\nH\tHours\t\nT\tMinutes\t\t\nS\tSeconds\t\t\nL\tMilliseonds\t\t\nU\tMicroseconds\t\t\nN\tnanoseconds\t\t\nB\tBusiness day\nBM\tBusiness month end\nBQ\tBusiness quarter end\nBA\tBusiness year end\nBH\tBusiness hours\n\n#By adding an S suffix to any of these, they instead will be marked at the beginning\n\nCode\tDescription\nMS\tMonth start\t\t\nQS\tQuarter start\t\t\nAS\tYear start\t\t\nBMS\t Business month start\nBQS\t Business quarter start\nBAS\t Business year start\n\n'''\npd.timedelta_range(0, periods=9, freq=\"2H30T\") #2hrs 30 min\n\n#Resampling, Shifting, and Windowing\n#THIS IS NOT WORKING, THE DATA IS NOT GETTING IMPORTED.\nfrom pandas_datareader import data\n\ngoog = data.DataReader('GOOG', start='2017', end='2018',\n data_source='google')\ngoog.head()\n\n#we'll use just the closing price\ngoog = goog['Close']\n\n\nimport matplotlib.pyplot as plt\nimport seaborn; seaborn.set()\ngoog.plot();\n\n#Resampling and converting frequencies\n#resample() is fundamentally a data aggregation, while asfreq() is fundamentally a data selection.\ngoog.plot(alpha=0.5, style='-')\ngoog.resample('BA').mean().plot(style=':')\ngoog.asfreq('BA').plot(style='--');\nplt.legend(['input', 'resample', 'asfreq'],loc='upper left');\n\n#Notice the difference: at each point, resample reports the average of the previous year,\n# while asfreq reports the value at the end of the year.\n# filled with NA values. Just as with the pd.fillna() function discussed previously,\n# asfreq() accepts a method argument to specify how values are imputed. \n# Here, we will resample the business day data at a daily frequency (i.e., including weekends):\nfig, ax = plt.subplots(2, sharex=True)\ndata = goog.iloc[:10]\n\ndata.asfreq('D').plot(ax=ax[0], marker='o')\n\ndata.asfreq('D', method='bfill').plot(ax=ax[1], style='-o')\ndata.asfreq('D', method='ffill').plot(ax=ax[1], style='--o')\nax[1].legend([\"back-fill\", \"forward-fill\"]);\n\n###### TIME-SHIFTS #####\n#shift() shifts the data, while tshift() shifts the index. \n# In both cases, the shift is specified in multiples of the frequency.\n\n#Here we will both shift() and tshift() by 900 days;\n# apply a frequency to the data\ngoog = goog.asfreq('D', method='pad')\n\ngoog.plot(ax=ax[0])\ngoog.shift(900).plot(ax=ax[1])\ngoog.tshift(900).plot(ax=ax[2])\n\n#ROLLING WINDOWS\n\n\n#EXAMPLE: VISUALIZING SEATTLE BICYCLE COUNTS\ndataFilePatch=\"C:/JDeveloper/EclipseWS/PythonDataScienceHandbook/notebooks/data/\"\ndata = pd.read_csv(dataFilePatch+'FremontBridge.csv', index_col='Date', parse_dates=True)\ndata.head()\n\n#shortening the coulmn names\ndata.columns = ['West', 'East']\ndata['Total'] = data.eval('West + East') #add total coulmn\n\ndata.dropna().describe()\n\n#Visualizing the data\n#%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn; seaborn.set()\ndata.plot()\nplt.ylabel('Hourly Bicycle Count');\n\n#resample by week:\nweekly = data.resample('W').sum()\nweekly.plot(style=[':', '--', '-'])\nplt.ylabel('Weekly bicycle count');\n\ndaily = data.resample('D').sum()\n#Here we'll do a 30 day rolling mean of our data, making sure to center the window.\ndaily.rolling(30, center=True).sum().plot(style=[':', '--', '-'])\nplt.ylabel('mean hourly count');\n\n#The following code specifies both the width of the window (we chose 50 days)\n# and the width of the Gaussian within the window (we chose 10 days)\ndaily.rolling(50, center=True, win_type='gaussian').sum(std=10).plot(style=[':', '--', '-']);\nplt.ylabel('mean hourly count 1');\n\n####DIGGING INTO THE DATA###\n#we might want to look at the average traffic as a function of the time of day. \nby_time = data.groupby(data.index.time).mean()\nhourly_ticks = 4 * 60 * 60 * np.arange(6)\nby_time.plot(xticks=hourly_ticks, style=[':', '--', '-']);\n\n# based on the day of the week. Again, we can do this with a simple groupby:\nby_weekday = data.groupby(data.index.dayofweek).mean()\nby_weekday.index = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']\nby_weekday.plot(style=[':', '--', '-']);\n\n#let's do a compound GroupBy and look at the hourly trend on weekdays versus weekends. \n# We'll start by grouping by both a flag marking the weekend, and the time of day:\nweekend = np.where(data.index.weekday < 5, 'Weekday', 'Weekend')\nby_time = data.groupby([weekend, data.index.time]).mean()\n\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(1, 2, figsize=(14, 5))\nby_time.ix['Weekday'].plot(ax=ax[0], title='Weekdays', xticks=hourly_ticks, style=[':', '--', '-'])\nby_time.ix['Weekend'].plot(ax=ax[1], title='Weekends', xticks=hourly_ticks, style=[':', '--', '-']);\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pandas/TimeSeries.py","file_name":"TimeSeries.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"93044590","text":"import os\nimport json\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nimport matplotlib.image as img\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\n\nimport viz\nimport data_utils\n\n\ndef get_3d_lines(frame):\n I = np.array([1,2,3,1,7,8,1, 13,14,15,14,18,19,14,26,27])-1 # start points\n J = np.array([2,3,4,7,8,9,13,14,15,16,18,19,20,26,27,28])-1 # end points\n\n lines = []\n for i in np.arange( len(I) ):\n x, y, z = [np.array( [frame[I[i], j], frame[J[i], j]] ) for j in range(3)]\n lines.append((x, z, -y))\n\n return lines\n\n\ndef draw_3d_pose(frame, axes=[], ax=None):\n LR = np.array([1,1,1,0,0,0,0, 0, 0, 0, 0, 0, 0, 1, 1, 1], dtype=bool)\n lcolor=\"#3498db\"\n rcolor=\"#e74c3c\"\n\n lines = get_3d_lines(frame)\n\n if axes is None or len(axes) == 0:\n for i, line in enumerate(lines):\n axes.append(ax.plot(line[0], line[1], line[2], lw=2, c=lcolor if LR[i] else rcolor)[0])\n else:\n for i, line in enumerate(lines):\n axes[i].set_data(line[0], line[1])\n axes[i].set_3d_properties(line[2])\n\n return axes\n\n\n\ndef plot_skeleton(points, points_2d, image_paths):\n if (points.shape[1] != 32 or points.shape[2] != 3):\n raise ValueError(\"Expected points.shape to be (?, 32, 3), got \" + str(points.shape))\n\n fig = plt.figure()\n ax_2d = fig.add_subplot(131)\n ax = fig.add_subplot(132, projection='3d')\n ax.view_init(18, -70)\n ax.set_aspect(1)\n ax.set_xlim(-500, 500)\n ax.set_ylim(-500, 500)\n ax.set_zlim(-500, 500)\n ax_img = fig.add_subplot(133)\n ax_img.axis('off')\n\n points_2d = data_utils.process_stacked_hourglass(points_2d)\n viz.show2Dpose(np.reshape(points_2d[0][0], (64,1)), ax_2d)\n axes_3d = draw_3d_pose(points[0], ax=ax)\n ax_img = plt.imshow(img.imread(image_paths[0]), animated=True)\n\n def update(frame_enumerated):\n img_i, frame = frame_enumerated\n ax_img.set_data(img.imread(image_paths[img_i]))\n\n ax_2d.clear()\n viz.show2Dpose(np.reshape(points_2d[0][img_i], (64,1)), ax_2d)\n ax_2d.invert_yaxis()\n\n ax.clear()\n viz.show3Dpose(frame, ax)\n # draw_3d_pose(frame, axes=axes_3d)\n\n ani = FuncAnimation(fig, update, frames=enumerate(points))\n\n plt.show()\n\ndef image_path(id, i, root, ext):\n return os.path.join(root, id + \"-\" + str(i) + ext)\n\ndef preview_first_clip():\n config = {}\n with open('config.json') as config_file:\n config = json.load(config_file)\n image_root = config['image_root']\n image_extension = config['image_extension']\n clip = config['clips'][0]\n images = [image_path(clip['id'], i + 1, image_root, image_extension) for i in range(clip['end'] - clip['start'])]\n\n points_2d = np.array(clip['points_2d'])\n\n plot_skeleton(np.array(clip['points_3d']),\n points_2d,\n images)\n\npreview_first_clip()\n","sub_path":"src/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"437553964","text":"import requests\nimport re\nfrom flask import request, current_app\nfrom flask_restful import Resource\nfrom cms.schema.api import ApiSchema\nfrom cms.models.api import Api\n\napi_schema = ApiSchema()\n\nclass GatewayResource(Resource):\n\n def _get_matching_api(self, uri):\n apis = Api.query.all()\n for api in apis:\n if re.match(api.endpoint, f\"/{uri}\"):\n return api\n\n def _get_headers(self, api):\n headers = dict(Authorization=f\"Bearer {api.secret_key}\")\n current_app.logger.info(headers)\n return headers\n\n def get(self, uri):\n api = self._get_matching_api(uri)\n headers = self._get_headers(api)\n url = f\"{api.host}/{uri}\"\n current_app.logger.info(url)\n res = requests.get(url,\n params=request.args,\n headers=headers)\n current_app.logger.info(res.text)\n return res.json()\n\n def post(self, uri):\n api = self._get_matching_api(uri)\n headers = self._get_headers(api)\n url = f\"{api.host}/{uri}\"\n current_app.logger.info(url)\n res = requests.post(url,\n json=request.get_json(force=True),\n headers=headers)\n current_app.logger.info(res.text)\n return res.json()\n","sub_path":"cms/resources/gateway/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"337655918","text":"\"\"\"\nTests for pvmodules.\n\"\"\"\n\nfrom nose.tools import ok_\nfrom pvmismatch.pvmismatch_lib.pvmodule import PVmodule, TCT492, PCT492\nimport numpy as np\nfrom copy import copy\n\n\ndef test_calc_mod():\n pvmod = PVmodule()\n ok_(isinstance(pvmod, PVmodule))\n return pvmod\n\n\ndef test_calc_tct_mod():\n pvmod = PVmodule(cell_pos=TCT492)\n isc = np.interp(np.float64(0), pvmod.Vmod, pvmod.Imod)\n voc = np.interp(np.float64(0), np.flipud(pvmod.Imod), np.flipud(pvmod.Vmod))\n ok_(np.isclose(isc, 37.8335982026))\n ok_(np.isclose(voc, 55.2798357318))\n return pvmod\n\n\ndef test_calc_pct_mod():\n pvmod = PVmodule(cell_pos=PCT492)\n isc = np.interp(np.float64(0), pvmod.Vmod, pvmod.Imod)\n voc = np.interp(np.float64(0), np.flipud(pvmod.Imod), np.flipud(pvmod.Vmod))\n ok_(np.isclose(isc, 37.8335982026))\n ok_(np.isclose(voc, 55.2798357318))\n return pvmod\n\n\ndef test_calc_pct_bridges():\n pct492_bridges = copy(PCT492)\n pct492_bridges[0][0][2]['crosstie'] = True\n pct492_bridges[0][2][2]['crosstie'] = True\n pct492_bridges[0][4][2]['crosstie'] = True\n pvmod = PVmodule(cell_pos=pct492_bridges)\n return pvmod\n\nif __name__ == \"__main__\":\n test_calc_mod()\n test_calc_tct_mod()\n test_calc_pct_mod()\n test_calc_pct_bridges()\n","sub_path":"pvmismatch/tests/test_pvmodule.py","file_name":"test_pvmodule.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"584088121","text":"#Run this before commit (UNIX Devs)\nimport os\nimport subprocess\nimport time\n\nCURRENT_DIRECTORY = os.getcwd()\ndirectories = os.listdir(CURRENT_DIRECTORY)\nNON_ANGULAR_DIRS = ['static', 'templates', 'venv']\n\nANGULAR_PROJECT_PATH = 'frontend'\nDIST_PATH = 'frontend/dist/frontend'\n\nFLASK_STATIC_PATH = os.path.join(CURRENT_DIRECTORY, 'static')\nFLASK_TEMPLATES_PATH = os.path.join(CURRENT_DIRECTORY, 'templates')\n\nsubprocess.call(('cd ' + ANGULAR_PROJECT_PATH + ' && ng build --base-href /static/'), shell=True)\n\ntry:\n files = os.listdir(DIST_PATH)\n static_files = []\n html_files = []\n for file in files:\n if '.js' in file or '.js.map' in file or '.ico' in file:\n static_files.append(file)\n if '.html' in file:\n html_files.append(file)\n if len(static_files) > 0:\n for stat in static_files:\n subprocess.call(('cd ' + DIST_PATH + ' &&' + ' mv ' + stat + \" \" + FLASK_STATIC_PATH), shell=True)\n\n if len(html_files) > 0:\n for html in html_files:\n subprocess.call(('cd ' + DIST_PATH + ' &&' + ' mv ' + html + \" \" + FLASK_TEMPLATES_PATH), shell=True)\nexcept Exception as e:\n print(e)","sub_path":"build-dev-unix.py","file_name":"build-dev-unix.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"253901548","text":"#!/usr/bin/python\n\nimport rospy\nimport numpy as np\nimport sys, select, termios, tty\n\nfrom std_msgs.msg import Float64\nfrom geometry_msgs.msg import Twist\nfrom rospy.numpy_msg import numpy_msg\nfrom kobuki_msgs.msg import MotorPower\nfrom nav_msgs.msg import Odometry\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\nfrom dynamic_reconfigure.server import Server\nfrom kobuki_exer2.cfg import Kobuki_Exer2Config\n\n\nclass move_pub:\n\n def __init__(self):\n\n\n #ATRIBUTOS PARA PUBLICADORES\n self.vel = Twist()\n self.mot = MotorPower()\n\n #ATRIBUTOS PARA PARAMETROS DESDE EL SERVER\n self.angle = None\n self.positionx = None\n self.positiony = None\n\n #CAMBIO DE COORDENADA\n\n self.theta = -np.pi\n self.R = np.array([(np.cos(self.theta), -np.sin(self.theta),0,-0.2),(np.sin(self.theta),np.cos(self.theta),0,0),(0,0,1,0),(0,0,0,1)])\n self.R1 = np.linalg.inv(self.R)\n\n #ATRIBUTOS PARA PROGRAMA EN PYTHON\n self.angle_meas = 0.0\n self.posx_meas = 0.0\n self.posy_meas = 0.0\n\n self.angle_meas2 = 0.0\n self.posx_meas2 = 0.0\n self.posy_meas2 = 0.0\n \n self.angle_to_py = 45\n self.posx_to_py = 0.0\n self.posy_to_py = 0.0\n\n self.error_angle = 1\n self.error_linearx = 1\n self.error_lineary = 1\n self.error_hip = 1\n\n self.coord_act = False\n self.cont = 1\n\n self.target = np.array([(-3.5),(0),(0),(1)]) # coordenadas de meta en el marco de ref del mundo\n self.angle_init = -np.pi\n\n\n key_timeout = rospy.get_param(\"~key_timeout\", 0.0)\n if key_timeout == 0.0:\n key_timeout = None\n\n \n\n self.getParameters()\n\n if((self.angle is None) or (self.positionx is None) or (self.positiony is None)):\n rospy.signal_shutdown(\"Parameters not declared\")\n else:\n rospy.loginfo(\"Parameters found\")\n\n \n \n\n #DEFINICION DE LOS PUBLICADORES\n self.nameTopic_mot = \"/mobile_base/commands/motor_power\"\n self.nameTopic_vel = \"/mobile_base/commands/velocity\"\n self.nameTopic_pose = \"/odom\"\n \n self.pubvel = rospy.Publisher(self.nameTopic_vel,numpy_msg(Twist),queue_size=10)\n self.pubmot = rospy.Publisher(self.nameTopic_mot,MotorPower,queue_size=10)\n\n\n #SE DEFINE EL SUSCRIPTOR PARA RECIBIR LA POSE (ODOMETRIA)\n self.subpose = rospy.Subscriber(self.nameTopic_pose, Odometry, self.callback)\n\n\n #INICIAMOS SERVIDOR PARA PARAMETROS\n srv = Server(Kobuki_Exer2Config, self.DynConfCB)\n\n\n #INICIAMOS EL MOTOR\n self.turn_on_mot()\n\n #################################PROGRAMA PRINCIPAL#################################################3------------------------------\n \n while True:\n if self.coord_act:\n if self.cont == 1:\n \n self.linear_control([-3.5,0])\n self.angle_control(-np.pi/2)\n self.linear_control([-3.5,3.5])\n self.angle_control(-np.pi)\n self.linear_control([1.5,3.5])\n self.angle_control(np.pi/2)\n self.linear_control([1.5,-1.5])\n self.angle_control(np.pi)\n self.linear_control([3.5,-1.5])\n self.angle_control(np.pi/2)\n self.linear_control([3.5,-8])\n self.angle_control(0)\n self.linear_control([-2.5,-8])\n self.angle_control(-np.pi/2)\n self.linear_control([-2.5,-5.5])\n self.angle_control(-np.pi)\n self.linear_control([1.5,-5.5])\n self.angle_control(-np.pi/2)\n self.linear_control([1.5,-3.5])\n self.angle_control(0)\n self.linear_control([-1,-3.5])\n ''' self.ctrl_diag(self.target)\n self.ctrl_diag(np.array([(-3.5),(3.5),(0),(1)]))\n self.ctrl_diag(np.array([(1.5),(3.5),(0),(1)]))\n self.ctrl_diag(np.array([(1.5),(-1.5),(0),(1)]))\n self.ctrl_diag(np.array([(2),(1),(0),(1)]))\n self.ctrl_diag(np.array([(2),(1),(0),(1)]))\n self.ctrl_diag(np.array([(2),(1),(0),(1)])) '''\n self.cont = 0\n print(self.angle_meas2)\n\n \n \n \n\n\n\n def getParameters(self):\n \n if rospy.has_param('~angle'):\n self.angle = rospy.get_param('~angle')\n\n if rospy.has_param('~positionx'):\n self.positionx = rospy.get_param('~positionx')\n\n if rospy.has_param('~positiony'):\n self.positiony = rospy.get_param('~positiony')\n\n rospy.set_param('~angle', self.angle)\n rospy.set_param('~positionx', self.positionx)\n rospy.set_param('~positiony', self.positiony)\n\n\n\n #CALLBACK PARA ACTUALIZACION DE PARAMETROS\n def DynConfCB(self, config, level):\n #self.angle_to_py = config.angle\n self.posx_to_py = config.positionx\n self.posy_to_py = config.positiony\n return config\n\n #ENCENDER EL MOTOR\n def turn_on_mot(self):\n\n rate = rospy.Rate(30)\n self.mot.state = 1\n self.pubmot.publish(self.mot)\n rate.sleep()\n\n #---CALLBACK DISPARADO CUANDO SE RECIBE UN MENSAJE DEL TOPICO SUSCRITO\n def callback(self,data):\n \n self.angle_meas = euler_from_quaternion([data.pose.pose.orientation.x,data.pose.pose.orientation.y,data.pose.pose.orientation.z,data.pose.pose.orientation.w])[2]\n self.posx_meas = data.pose.pose.position.x\n self.posy_meas = data.pose.pose.position.y\n self.tf()\n #print((180/np.pi)*self.angle_meas2)\n #self.R = np.array([(np.cos(self.angle_meas2), -np.sin(self.angle_meas2),0,-0.2),(np.sin(self.angle_meas2),np.cos(self.angle_meas2),0,0),(0,0,1,0),(0,0,0,1)])\n #self.R1 = np.linalg.inv(self.R)\n\n\n\n\n \n \n def angle_control(self,ang):\n \n self.error_angle = (ang)-self.angle_meas\n while np.abs(self.error_angle) >= 0.0001:\n \n control_signal = 2*self.error_angle\n\n if control_signal >= np.pi/6:\n control_signal = np.pi/6\n if control_signal <= (-1)*np.pi/6:\n control_signal = (-1)*np.pi/6\n \n self.vel.angular.z = control_signal\n self.pubvel.publish(self.vel)\n self.error_angle = (ang)-self.angle_meas\n self.vel.angular.z = 0.0\n self.pubvel.publish(self.vel)\n \n\n def linear_control(self,target):\n #self.error_linearx = (dist) - self.posx_meas\n dist = np.sqrt(np.power((self.posx_meas2-target[0]),2)+np.power((self.posy_meas2-target[1]),2))\n #la distancia ente el punto donde estoy y el punto destino es el error\n while dist >= 0.07:\n \n control_signal = 1 * dist\n \n if control_signal >= 0.3:\n control_signal = 0.3 \n if control_signal <= -0.3:\n control_signal = -0.3 \n\n self.vel.linear.x = control_signal\n self.pubvel.publish(self.vel)\n dist = np.sqrt(np.power((self.posx_meas2-target[0]),2)+np.power((self.posy_meas2-target[1]),2))\n self.vel.linear.x = 0.0\n self.pubvel.publish(self.vel)\n \n\n\n ''' def linear_controly(self,yval):\n self.error_lineary = (yval) - (np.abs(self.posy_meas))\n while np.abs(self.error_lineary) >= 0.01:\n #error = self.error_lineary\n control_signal = 1 * self.error_lineary\n \n if control_signal >= 0.3:\n control_signal = 0.3 \n if control_signal <= -0.3:\n control_signal = -0.3 \n\n self.vel.linear.x = control_signal\n self.pubvel.publish(self.vel)\n self.error_lineary = (yval) - (np.abs(self.posy_meas)) '''\n\n def tf(self):\n pose_R = np.array([(self.posx_meas),(self.posy_meas),(0),(1)])\n pose_L = np.matmul(self.R1,pose_R)\n self.posx_meas2 = pose_L[0]\n self.posy_meas2 = pose_L[1]\n a = self.angle_meas + self.theta\n if a > np.pi:\n a = a - 2*np.pi\n if a < -np.pi:\n a = a + 2*np.pi\n self.angle_meas2 = a\n\n self.coord_act = True\n\n\n\n def tf_to_robot(self,v,t):\n self.R = np.array([(np.cos(t), -np.sin(t),0,self.posx_meas2),(np.sin(t),np.cos(t),0,self.posy_meas2),(0,0,1,0),(0,0,0,1)])\n R1 = np.linalg.inv(self.R)\n b = np.matmul(R1,v)\n return b\n\n def tf_to_world(self,v):\n b = np.matmul(self.R1,v)\n return b \n\n\n def ctrl_diag(self,target):\n \n print(\"anglemeas2 is: \",self.angle_meas2)\n print(\"pos x 2 is: \",self.posx_meas2)\n print(\"pos y 2 is: \",self.posy_meas2)\n target_robot = self.tf_to_robot(target,self.angle_meas2)\n print(\"target robot is\",target_robot)\n angulo2 = np.arctan2(target_robot[1],target_robot[0])\n print(\"angulo entre punto y target: \",(180/np.pi)*angulo2)\n \n self.angle_control(angulo2)\n self.linear_control(target)\n","sub_path":"Talleres/kobuki_exer2/scripts/move_cmd.py","file_name":"move_cmd.py","file_ext":"py","file_size_in_byte":9527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"356008060","text":"def detect_anagrams( word, word_list):\r\n \"\"\"Return all words in word_list which are anagrams of word\r\n Anagrams may be upper or lower case.\r\n Return first version of word found in mixed case. \r\n Detect duplicates by storing uppercase version of matches.\r\n \"\"\"\r\n \r\n list = [] # List of anagrams (first found in original case )\r\n upperMatches = [] # Uppercase verion of matches already found.\r\n upperWord = word.upper() # wOrD -> WORD\r\n sortedWord = \"\".join(sorted(upperWord)) # WORD -> [W,O,R,D] -> [D,O,R,W] -> \"DORW\"\r\n # For each candidate word in list, compare uppercase sorted form with sortedWord.\r\n for candidate in word_list:\r\n \r\n # Ignore words which match the input word (when converted to uppercase)\r\n # Ignore words which exist in uppercase in the uppMatches array.\r\n \r\n upperCandidate = candidate.upper()\r\n if upperCandidate == upperWord or upperCandidate in upperMatches:\r\n continue\r\n sortedCandidate = \"\".join( sorted(upperCandidate))\r\n if sortedCandidate == sortedWord:\r\n upperMatches.append(sortedCandidate)\r\n list.append(candidate)\r\n return list;\r\n","sub_path":"assignments/python/anagram/src/280.py","file_name":"280.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"321302325","text":"# Script to get stock price from google finance\r\nimport re\r\nimport urllib.request\r\nurl=\"https://www.google.com/finance?q=\"\r\nstock= input(\"Enter your stock\")\r\nurl = url + stock\r\ndata = urllib.request.urlopen(url).read()\r\ndata1 = data.decode(\"utf-8\")\r\nm = re.search('meta itemprop=\"price\"',data1)\r\nstart=m.start()\r\n\r\n\"\"\"print(data1[start:m.end()])\r\nprint(\"______________________________\")\r\nprint(data1[start:start+50])\r\nprint(\"______________________________\")\"\"\"\r\n\r\nend=start + 50\r\nnewstr=data1[start:end]\r\nm=re.search('content=\"',newstr)\r\nstart=m.end()\r\nnewstr1=newstr[start:]\r\nm=re.search(\"/\",newstr1)\r\nstart=0\r\nend=m.end()-3\r\nfinal=newstr1[0:end]\r\nprint(\"Value of stock=\" + final)\r\n","sub_path":"Basic Python/Simple Python Programs/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"284527323","text":"import torch\n# import torch.nn as nn\n# from torch.autograd import Variable\n# from torch.utils.data import DataLoader\n# from torchvision import datasets, transforms\nimport numpy as np\nimport pandas as pd\n\n\nclass PytorchUtil(object):\n random_seed = 7942\n\n @classmethod\n def init_random_seed(cls, random_seed=None):\n if random_seed is None:\n random_seed = cls.random_seed\n\n np.random.seed(random_seed)\n torch.manual_seed(random_seed)\n torch.cuda.manual_seed_all(random_seed)\n\n @staticmethod\n def equal_distribution(df, indexes: pd.Series, test_rate=0.1, valid_rate=0.1, shuffle=True):\n df_train, df_valid, df_test = None, None, None\n sums = [i.sum() for i in indexes]\n min_count = min(sums)\n # print('min: %s in %s' % (min_count, sums))\n\n for index in indexes:\n df_part = df[index]\n df_part = df_part[:min_count]\n if shuffle:\n df_part = df_part.sample(frac=1, random_state=7942)\n\n n_test = max(1, int(len(df_part) * test_rate))\n n_valid = max(1, int(len(df_part) * valid_rate))\n n_train = len(df_part) - n_test - n_valid\n # print('n_train/n_valid/n_test:', n_train, n_valid, n_test)\n if df_train is None:\n df_train = df_part[:n_train]\n else:\n df_train = df_train.append(df_part[:n_train])\n\n if df_valid is None:\n df_valid = df_part[n_train:n_train + n_valid]\n else:\n df_valid = df_valid.append(df_part[n_train:n_train + n_valid])\n\n if df_test is None:\n df_test = df_part[n_train + n_valid:]\n else:\n df_test = df_test.append(df_part[n_train + n_valid:])\n\n return df_train, df_valid, df_test\n\n @staticmethod\n def exp_learing_rate_decay(optimizer, epoch, init_lr=0.001, lr_decay_epoch=1):\n \"\"\"Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.\"\"\"\n lr = init_lr * (0.1 ** (epoch // lr_decay_epoch))\n\n if epoch % lr_decay_epoch == 0:\n # print('LR is set to {}'.format(lr))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n return optimizer\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"bage_utils/pytorch_util.py","file_name":"pytorch_util.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"631646917","text":"#!/usr/bin/env python3\nimport argparse\nimport pathlib\nimport re\nimport os\nimport string\nimport subprocess\nimport sys\nimport tempfile\n\nimport hypothesis.strategies as st\nfrom hypothesis import example, given\n\n\nclass KeptTemporaryDirectory:\n def __init__(self, *args, **kwargs):\n self.name = tempfile.mkdtemp(*args, **kwargs)\n\n def __enter__(self):\n return pathlib.Path(self.name)\n\n def __exit__(self, *args):\n pass\n\n\nclass BaseFile:\n repr_attributes = ['name']\n repr_star = None\n default_permissions = 0o600\n\n def __init__(self, name, permissions=None):\n self.name = name\n if permissions is not None:\n self.permissions = permissions\n else:\n self.permissions = self.default_permissions\n\n if name is not None:\n if '/' in name:\n raise ValueError('Files may not contain / in the name')\n if name in ('.', '..'):\n raise ValueError('Names may not be \".\" or \"..\"')\n\n def count_expected_errors(self):\n return 0\n\n def __repr__(self):\n return \"{}({})\".format(\n self.__class__.__name__,\n ', '.join(\n [*(repr(getattr(self, attr, '???')) for attr in self.repr_attributes),\n *(map(repr, getattr(self, self.repr_star))\n if self.repr_star else ()),\n *(('permissions=0o{:o}'.format(self.permissions),)\n if self.permissions != self.default_permissions else ())]))\n\n\nclass File(BaseFile):\n default_permissions = 0o400\n\n def __init__(self, name, contents='', permissions=None):\n self.contents = contents\n super().__init__(name, permissions=permissions)\n\n def create(self, base_dir):\n full_path = base_dir / self.name\n with open(full_path, 'w') as f:\n f.write(self.contents)\n full_path.chmod(self.permissions)\n\n def __eq__(self, other):\n return isinstance(other, File) and self.name == other.name\n\n\nclass Dir(BaseFile):\n repr_attributes = ['name']\n repr_star = 'entries'\n default_permissions = 0o700\n\n def __init__(self, name, *entries, permissions=None):\n entry_names = [e.name for e in entries]\n if len(entry_names) != len(set(entry_names)):\n raise ValueError(\n \"Directories cannot contain entries with non-unique names\")\n self.entries = entries\n super().__init__(name, permissions=permissions)\n\n def create(self, base_dir):\n full_path = base_dir / self.name\n full_path.mkdir(mode=self.permissions)\n for entry in self.entries:\n entry.create(full_path)\n\n def count_expected_errors(self):\n if self.permissions & 0o400:\n return sum(e.count_expected_errors() for e in self.entries)\n return 1\n\n def max_path_length(self):\n max_len = 0\n for e in self.entries:\n sublen = len(e.name)\n if isinstance(e, Dir):\n sublen = e.max_path_length()\n if sublen > max_len:\n max_len = sublen\n self_len = 0\n if self.name is not None:\n self_len = len(self.name) + 1\n return max_len + self_len\n\n def as_dict(self):\n return {e.name: e for e in self.entries}\n\n def __eq__(self, other):\n if not isinstance(other, Dir):\n return False\n\n return self.name == other.name and self.as_dict() == other.as_dict()\n\n\nclass FileOrEmptyDir(File, Dir):\n default_permissions = 0\n\n def __init__(self, name):\n super().__init__(name)\n\n def create(self, base_dir):\n raise NotImplementedError('FileOrEmptyDir should not be created')\n\n def __eq__(self, other):\n if isinstance(other, Dir):\n return self.name == other.name and not other.entries\n if isinstance(other, File):\n return self.name == other.name\n return False\n\n\nclass RootDir(Dir):\n repr_attributes = []\n\n def __init__(self, *entries, permissions=None):\n super().__init__(None, *entries, permissions=permissions)\n\n def create(self, base_dir):\n # Directory is assumed to exist for root directory.\n base_dir.chmod(self.permissions)\n for entry in self.entries:\n entry.create(base_dir)\n\n def tempdir(self):\n if os.environ.get('KEEP_TEMPFILES'):\n t = KeptTemporaryDirectory()\n else:\n t = tempfile.TemporaryDirectory()\n\n self.create(pathlib.Path(t.name))\n return t\n\n def __eq__(self, other):\n if not isinstance(other, RootDir):\n return False\n\n return self.as_dict() == other.as_dict()\n\n\n\nclass Symlink(BaseFile):\n repr_attributes = ['name', 'target']\n default_permissions = 0\n\n def __init__(self, name, target):\n self.target = target\n super().__init__(name)\n\n def create(self, base_dir):\n full_path = base_dir / self.name\n full_path.symlink_to(self.target)\n\n def __eq__(self, other):\n return (isinstance(other, Symlink)\n and other.name == self.name\n and other.target == self.target)\n\n\nclass PeekableIterator:\n def __init__(self, it):\n self.it = iter(it)\n self.has_top = False\n self.top = None\n\n def peek(self):\n if not self.has_top:\n self.top = next(self.it)\n self.has_top = True\n return self.top\n\n def __next__(self):\n if self.has_top:\n self.has_top = False\n self.top = None\n return self.top\n return next(self.it)\n\n\nclass OutputFormatError(Exception):\n pass\n\n\ndef tabs_to_levels(lines):\n linum = 1\n for line in lines:\n line = line.rstrip('\\n')\n tabs = 0\n while line.startswith('\\t'):\n line = line[1:]\n tabs += 1\n yield linum, tabs, line\n linum += 1\n\n\ndef levels_to_tree(levels):\n def _rec(p_levels, depth):\n while True:\n try:\n linum, tabs, text = p_levels.peek()\n except StopIteration:\n return\n if tabs < depth:\n return\n if tabs == depth:\n children = None\n next(p_levels)\n try:\n _, next_tabs, _ = p_levels.peek()\n except StopIteration:\n pass\n else:\n if next_tabs == tabs + 1:\n children = list(_rec(p_levels, depth + 1))\n yield text, children\n else:\n raise OutputFormatError(\n 'Line {} of output: too many tabs! (expected at most {} tabs)'.format(\n linum, depth + 1))\n\n yield from _rec(PeekableIterator(levels), 0)\n\n\ndef upgrade_tree(basic_tree):\n def _rec(elem):\n name, children = elem\n if children is not None:\n return Dir(name, *map(_rec, children))\n m = re.fullmatch(r'SYM (.*) -> (.*)', name)\n if m:\n return Symlink(m.group(1), m.group(2))\n return FileOrEmptyDir(name)\n return RootDir(*map(_rec, basic_tree))\n\n\nfilename_chars = set(string.printable)\nfilename_chars.remove('/')\nfilename_chars.remove('\\t')\nfilename_chars.remove('\\n')\nfilename_chars.remove('\\r')\nfilename_chars.remove('\\v')\nfilename_chars.remove('\\x0c')\n\nst_random_contents = st.text(min_size=0, max_size=1 << 16)\nst_filename = st.text(\n alphabet=filename_chars,\n min_size=1,\n max_size=254).filter(lambda x: x not in ('.', '..'))\nst_relative_path = st.builds(\n lambda parts: '/'.join(parts),\n st.iterables(\n st.one_of(st_filename, st.just('.'), st.just('..')),\n min_size=1,\n max_size=16))\nst_absolute_path = st.builds(\n lambda path: '/{}'.format(path),\n st_relative_path)\nst_path = st.one_of(st_relative_path, st_absolute_path)\n\nst_file = st.builds(File, st_filename, st_random_contents)\nst_symlink = st.builds(Symlink, st_filename, st_path)\nst_dir = st.deferred(\n lambda: st.builds(\n lambda name, entries: Dir(name, *entries),\n st_filename,\n st.iterables(\n st.one_of(st_dir, st_file, st_symlink),\n unique_by=lambda f: f.name)))\nst_rootdir = st.builds(lambda d: RootDir(*d.entries),\n st_dir).filter(lambda d: d.max_path_length() <= 4000)\n\nst_dir_no_symlinks = st.deferred(\n lambda: st.builds(\n lambda name, entries: Dir(name, *entries),\n st_filename,\n st.iterables(\n st.one_of(st_dir_no_symlinks, st_file),\n unique_by=lambda f: f.name)))\nst_rootdir_no_symlinks = st.builds(lambda d: RootDir(*d.entries),\n st_dir_no_symlinks).filter(\n lambda d: d.max_path_length() <= 4000)\n\nst_rootdir_only_files = st.builds(\n lambda entries: RootDir(*entries),\n st.iterables(st_file, unique_by=lambda f: f.name))\n\nst_rootdir_only_files_and_symlinks = st.builds(\n lambda entries: RootDir(*entries),\n st.iterables(st.one_of(st_file, st_symlink), unique_by=lambda f: f.name))\n\nst_dir_with_opendir_error = st.builds(\n Dir, st_filename, permissions=st.just(0o300))\nst_dir_maybe_with_errors = st.deferred(\n lambda: st.builds(\n lambda name, entries: Dir(name, *entries),\n st_filename,\n st.iterables(\n st.one_of(st_file, st_symlink, st_dir_with_opendir_error,\n st_dir_maybe_with_errors),\n min_size=2,\n max_size=10,\n unique_by=lambda f: f.name)))\nst_rootdir_with_errors = st.builds(lambda d: RootDir(*d.entries),\n st_dir_maybe_with_errors).filter(\n lambda d: d.count_expected_errors() > 0)\n\nst_random_system_path = st.one_of(\n st.just('/'),\n st.just('/etc'),\n st.just('/usr'),\n st.just('/tmp'),\n st.just('/usr/lib'),\n st.just('/usr/bin'))\n\n\ndef run_tree(args, cwd=None, expected_errors=0):\n args = [os.environ['PROGRAM_PATH']] + args\n if 'WRAP_EXEC' in os.environ:\n args = [os.environ['WRAP_EXEC']] + args\n result = subprocess.run(args, cwd=cwd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, stdin=subprocess.DEVNULL,\n encoding='utf-8', env={})\n errors = result.stderr.splitlines()\n if expected_errors:\n assert result.returncode != 0\n assert expected_errors == len(errors)\n return None, errors\n else:\n assert result.returncode == 0\n assert len(errors) == 0\n output = result.stdout\n levels = list(tabs_to_levels(output.splitlines()))\n try:\n tree = list(levels_to_tree(levels))\n except OutputFormatError as e:\n raise OutputFormatError(f'''There was an error counting the tabs in your output:\n {e}\n\nThe output of your program is given below, for reference:\n{output}''') from e\n try:\n upgraded_tree = upgrade_tree(tree)\n except ValueError as e:\n raise OutputFormatError(f'''There is a semantical issue in the files of your tree:\n {e}\n\nThe output of your program is given below, for reference:\n{output}''') from e\n return upgraded_tree, errors\n\n\n@given(st_rootdir_only_files)\ndef test_no_args_no_symlinks_no_recursion(case):\n with case.tempdir() as d:\n tree, errors = run_tree([], cwd=d)\n assert case == tree\n\n\n@given(st_rootdir_only_files_and_symlinks)\ndef test_no_args_no_recursion(case):\n with case.tempdir() as d:\n tree, errors = run_tree([], cwd=d)\n assert case == tree\n\n\n@given(st_rootdir_no_symlinks)\ndef test_no_args_no_symlinks(case):\n with case.tempdir() as d:\n tree, errors = run_tree([], cwd=d)\n assert case == tree\n\n\n@given(st_rootdir)\n@example(RootDir(\n File('a.tar.bz2'),\n Dir('projects',\n Symlink('teleportation', '/tmp/foo/bar'),\n File('TOP_SECRET')),\n Dir('bar',\n File('fib.c'),\n File('prog.c'),\n Dir('baz',\n Dir('bip', File('zip.txt')),\n Dir('bam', File('b.files'), File('a.out'))))))\ndef test_no_args(case):\n with case.tempdir() as d:\n tree, errors = run_tree([], cwd=d)\n assert case == tree\n\n\n@given(st_rootdir)\ndef test_one_arg_absolute_and_cwd(case):\n with case.tempdir() as d:\n p = pathlib.Path(d).resolve()\n tree, errors = run_tree([p], cwd=p)\n assert case == tree\n\n\n@given(st_rootdir)\ndef test_one_arg_relative_cwd_is_parent(case):\n with case.tempdir() as d:\n p = pathlib.Path(d)\n tree, errors = run_tree([p.name], cwd=p.parent)\n assert case == tree\n\n\n@given(st_rootdir, st_random_system_path)\ndef test_one_arg_absolute_cwd_is_random(case, random_path):\n with case.tempdir() as d:\n p = pathlib.Path(d).resolve()\n tree, errors = run_tree([p], cwd=random_path)\n assert case == tree\n\n\n@given(st_rootdir_with_errors)\ndef test_dir_with_errors(case):\n with case.tempdir() as d:\n run_tree([], cwd=d, expected_errors=case.count_expected_errors())\n\n\ndef test_dir_does_not_exist():\n run_tree(['/this/path/does/not/exist'], cwd='/', expected_errors=1)\n\n\ndef test_dir_is_file():\n f = File('foo.txt', 'bar\\n', permissions=0o700)\n case = RootDir(f)\n with case.tempdir() as d:\n run_tree([f.name], cwd=d, expected_errors=1)\n\n\ndef main(argv):\n parser = argparse.ArgumentParser(\n description='Integration tests for the project.',\n epilog='Any extra arguments will be passed to pytest. See \"pytest --help\".',\n )\n parser.add_argument(\n '-c', '--compile',\n action='store_true',\n help='Run \"make\" in the directory of the program before starting tests.',\n )\n parser.add_argument(\n '-p', '--program',\n type=pathlib.Path,\n default=pathlib.Path(__file__).parent / 'tree',\n help='Path to the tree program to test. Defaults to \"tree\" in the directory next to this file.',\n )\n parser.add_argument(\n '--wrap-exec',\n type=pathlib.Path,\n help='Wrap all executions of the program to test with this binary. '\n 'This could be useful, for example, to jail the program.')\n parser.add_argument(\n '-k', '--keep-tempfiles',\n action='store_true',\n help='Keep all temporary directories created.')\n opts, pytest_args = parser.parse_known_args(argv)\n program_path = opts.program.resolve()\n\n if opts.compile:\n try:\n subprocess.run(['make'], check=True, cwd=program_path.parent)\n except subprocess.CalledProcessError:\n print('Compile failed!', file=sys.stderr)\n return 1\n\n if not program_path.is_file():\n print('The program {} does not exist.'.format(program_path),\n file=sys.stderr)\n if opts.compile:\n print('Note: \"make\" ran and succeeded. Perhaps the name of the file created is incorrect?',\n file=sys.stderr)\n else:\n print('Did you remember to run \"make\" first?', file=sys.stderr)\n print('Hint: try passing --compile and I will run \"make\" for you.', file=sys.stderr)\n return 1\n\n pytest_args.append('--')\n pytest_args.append(__file__)\n\n env = {'PROGRAM_PATH': str(program_path)}\n if opts.keep_tempfiles:\n env['KEEP_TEMPFILES'] = '1'\n if opts.wrap_exec:\n env['WRAP_EXEC'] = str(opts.wrap_exec.resolve())\n proc = subprocess.run([sys.executable, '-m', 'pytest'] + pytest_args,\n env=env)\n return proc.returncode\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","sub_path":"run_tests.py","file_name":"run_tests.py","file_ext":"py","file_size_in_byte":15597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"426396350","text":"import click\nimport h5py\nimport numpy as np\nimport csv\n\n\n@click.command()\n@click.argument(\"filename\", type=click.Path(exists=True))\n@click.argument(\"indname\", type=click.Path(exists=True))\n@click.argument(\"outputname\", type=click.Path())\ndef main(filename, indname, outputname):\n dataset = h5py.File(filename)[\"postprocessing/dpc_reconstruction\"]\n visibility = h5py.File(filename)[\"postprocessing/visibility\"]\n ind = np.load(indname)\n print(ind)\n absorption = dataset[..., 0]\n differential_phase = dataset[..., 1]\n dark_field = dataset[..., 2]\n with open(outputname, \"w\") as outputfile:\n writer = csv.writer(outputfile)\n writer.writerow([\"A\", \"P\", \"B\", \"R\", \"v\"])\n for a, p, b, v in zip(\n absorption[ind],\n differential_phase[ind],\n dark_field[ind],\n visibility[ind],\n ):\n writer.writerow([a, p, b, np.log(b) / np.log(a), v])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"lung_data.py","file_name":"lung_data.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"6930629","text":"#!/usr/bin/python\n\nimport time\n\ndef report_letter(c):\n print(chr(ord('z') - c))\n\ncount = 10\n#! results in a en endless loop. why?\n#! Antwort: weil es diesen Operator in Python nicht gibt.\nwhile count > 0:\n count -= 1\n report_letter(count)","sub_path":"05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"184501855","text":"import paddle\nimport paddlefsl.datasets as datasets\nimport paddlefsl.backbones as backbones\nfrom paddlefsl.model_zoo import siamese\n\n\n# Set computing device\npaddle.set_device('gpu:1')\n\n\n# \"\"\" ---------------------------------------------------------------------------------\n# Config: Siamese, Few-Rel, Conv1D, 10 Ways, 1 Shot\nmax_len = 128\nembedding_dim = 50\ninit_vector = backbones.GloVeRC(embedding_dim=embedding_dim)\nTRAIN_DATASET = datasets.FewRel(mode='train', max_len=max_len, vector_initializer=init_vector)\nVALID_DATASET = datasets.FewRel(mode='valid', max_len=max_len, vector_initializer=init_vector)\nTEST_DATASET = datasets.FewRel(mode='valid', max_len=max_len, vector_initializer=init_vector)\nWAYS = 10\nSHOTS = 5\nQUERY_NUM = 5\nposition_emb = backbones.RCPositionEmbedding(max_len=max_len, embedding_dim=embedding_dim)\nconv1d = backbones.RCConv1D(max_len=max_len, embedding_size=position_emb.embedding_size, hidden_size=500)\nnorm = paddle.nn.Sequential(paddle.nn.LayerNorm(normalized_shape=conv1d.hidden_size), paddle.nn.Dropout(0.2))\nMODEL = paddle.nn.Sequential(position_emb, conv1d, norm)\nMODEL._full_name = 'glove50_cnn'\nLR = 0.001\nOPTIMIZER = paddle.optimizer.Adam(learning_rate=LR, parameters=MODEL.parameters())\nEPOCHS = 50\nTEST_EPOCHS = 10\nEPISODES = 1000\nREPORT_EPOCH = 1\nLR_STEP_EPOCH = None\nSAVE_MODEL_EPOCH = 10\nSAVE_MODEL_ROOT = '~/trained_models'\nTEST_PARAM_FILE = 'epoch50.params'\n# ----------------------------------------------------------------------------------\"\"\"\n\n\ndef main():\n train_dir = siamese.meta_training(\n train_dataset=TRAIN_DATASET,\n valid_dataset=VALID_DATASET,\n model=MODEL,\n lr=LR,\n optimizer=OPTIMIZER,\n epochs=EPOCHS,\n episodes=EPISODES,\n ways=WAYS,\n shots=SHOTS,\n query_num=QUERY_NUM,\n report_epoch=REPORT_EPOCH,\n lr_step_epoch=LR_STEP_EPOCH,\n save_model_epoch=SAVE_MODEL_EPOCH,\n save_model_root=SAVE_MODEL_ROOT\n )\n print(train_dir)\n state_dict = paddle.load(train_dir + '/' + TEST_PARAM_FILE)\n MODEL.load_dict(state_dict)\n siamese.meta_testing(\n model=MODEL,\n test_dataset=TEST_DATASET,\n epochs=TEST_EPOCHS,\n episodes=EPISODES,\n ways=WAYS,\n shots=SHOTS,\n query_num=QUERY_NUM\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"PaddleFSL/examples/relation_classification/siamese_relation_classification.py","file_name":"siamese_relation_classification.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"144445503","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib as mpl\nimport types\nimport glob\nimport os.path\nimport tarfile\nimport h5py\nclass extents():\n def __init__(self,value=None, nonzeromin=False):\n self.minmax=[]\n self.errors=[]\n self.nonzeromin=nonzeromin\n if value is not None:\n self(value)\n def __call__(self,array):\n if self.nonzeromin:\n array_min = array[ array>0].min()\n else:\n array_min = array.min()\n array_max = array.max()\n if len(self.minmax):\n self.minmax[0] =np.min([array_min,self.minmax[0]])\n self.minmax[1] =np.max([array_max,self.minmax[1]])\n else:\n self.minmax=np.array([array_min,array_max])\n def __getitem__(self,index):\n return self.minmax[index]\n def __str__(self):\n if len(self.minmax) == 2:\n out= \"[%0.2e, %0.2e]\"%tuple(self.minmax)\n else:\n out = \"undef\"\n return out\n def __repr__(self):\n if len(self.minmax) == 2:\n out= \"[%0.2e, %0.2e]\"%tuple(self.minmax)\n else:\n out = \"undef\"\n return out\n def check(self,array):\n if array.min() < self.minmax[0]:\n self.errors.append(array.min())\n print(\"Extent error: min\")\n if array.max() > self.minmax[1]:\n self.errors.append(array.max())\n print(\"Extent error: max\")\n\n\ndef axbonk(ax,xscale='linear',yscale='linear',xlabel='X',ylabel='Y',xlim=None,ylim=None,\n linthreshx=0.1,linthreshy=0.1,title=None):\n ax.set_xscale(xscale)\n ax.set_yscale(yscale)\n if xscale == 'symlog':\n ax.set_xscale(xscale,linthreshx=linthreshx)\n if yscale == 'symlog':\n ax.set_yscale(yscale,linthreshy=linthreshy)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n ax.set_xlim(xlim)\n ax.set_ylim(ylim)\n if title:\n ax.set_title(title)\ndef lim_down(value):\n return 10**(np.floor(np.log10(value)))\ndef lim_up(value):\n return 10**(np.ceil(np.log10(value)))\ndef dumb_plt(plot,X,Y,xlabel,ylabel,outname,scale=('linear','linear'), clobber=False, scatter=False,**kwargs):\n if scatter:\n verb = plot.scatter\n else:\n verb= plot.plot\n if clobber:\n plot.clf()\n\n if X is None:\n X = np.arange(Y.size)\n print(\"WTF\")\n if hasattr(plot,'savefig'):\n output=verb(X,Y,**kwargs)\n plot.xscale(scale[0])\n plot.yscale(scale[1])\n plot.xlabel(xlabel)\n plot.ylabel(ylabel)\n plot.savefig(outname)\n else:\n output=verb(X,Y,**kwargs)\n plot.set_xscale(scale[0])\n plot.set_yscale(scale[1])\n plot.set_xlabel(xlabel)\n plot.set_ylabel(ylabel)\n plot.figure.savefig(outname)\n print(scale)\n plot.yscale('log')\n print(outname)\n return output\n #return line\ndef collect_extrema(a,b=None):\n \"\"\"b collects the extrema of a\"\"\"\n if b is None:\n b=np.array([min(a),max(a)])\n b[0] = min([min(a),min(b)])\n b[1] = max([max(a),max(b)])\n return b\n\n\ndef ensure_list(obj):\n \"\"\"\n This function ensures that *obj* is a list. Typically used to convert a\n string to a list, for instance ensuring the *fields* as an argument is a\n list.\n \"\"\"\n if obj is None:\n return [obj]\n if type(obj) is not list:\n return [obj]\n return obj\n\ndef quarts(array, lower=0.25, upper=0.75, take_log=True):\n print(\"quarts doesn't work\")\n ok = array >0\n pdb.set_trace()\n if take_log:\n hist_for_cbar = np.histogram( np.log10( array[ok].flatten() ),bins=100, normed=True )\n else:\n hist_for_cbar = np.histogram( array[ok].flatten() ,bins=100, normed=True )\n\n cum = np.cumsum(hist_for_cbar[0])/hist_for_cbar[0].sum()\n first_quart = cum-lower\n if (first_quart == 0).any():\n first_ind = np.where( first_quart == 0 ) [0]\n else:\n first_ind = np.where( first_quart[:-1]*first_quart[1:] <= 0 ) [0]\n last_quart = cum-upper\n if (last_quart == 0).any():\n last_ind = np.where(last_ind == 0 )[0]\n else:\n last_ind = np.where( last_quart[:-1]*last_quart[1:] < 0 ) [0]\n if take_log:\n low_value = 10**np.floor( hist_for_cbar[1][first_ind] )\n high_value = 10**np.ceil( hist_for_cbar[1][last_ind] )\n else:\n low_value = np.floor( hist_for_cbar[1][first_ind] )\n high_value = np.ceil( hist_for_cbar[1][last_ind] )\n return low_value, high_value\n\n\ndef tff(g_code=None,pf=None):\n if pf is not None:\n g_code = pf['GravitationalConstant']\n\n return np.sqrt(3.*np.pi*4*np.pi/(32*g_code))\n\ndef sci(number):\n return \"%0.2e\"%(number)\n\ndef to_tar_gz(source_dir, destination):\n \"\"\"\n param source_dir: Source directory name.\n param destination: Destination filename.\n (TAR-GZ-Archive *.tar.gz)\n Stolen from http://www.velocityreviews.com/forums/t370204-create-tarfile-using-python.html\n \"\"\"\n\n t = tarfile.open(name = destination, mode = 'w:gz')\n t.add(source_dir, os.path.basename(source_dir))\n t.close()\n\n return True\n\ndef no_whites(something):\n \"\"\"Removes any empty charachters\"\"\"\n out = []\n for s in something:\n if s != '':\n out.append(s)\n return out\n\nimport shutil\ndef no_trailing_comments(file):\n nbackups = len(glob.glob('%s.backup*'%file))\n backup_name = '%s.backup%d'%(file,nbackups)\n shutil.move(file, backup_name)\n iptr = open(backup_name,'r')\n optr = open(file,'w')\n for line in iptr:\n if \"//\" in line:\n optr.write(line[:line.index(\"//\")]+\"\\n\")\n else:\n optr.write(line)\n iptr.close()\n optr.close()\n\ndef ImRoot():\n \"\"\"\n This function accepts a *func*, a set of *args* and *kwargs* and then only\n on the root processor calls the function. All other processors get \"None\"\n handed back.\n \"\"\"\n from yt.config import ytcfg\n if not ytcfg.getboolean(\"yt\",\"__parallel\"):\n return True\n try:\n if ytcfg.getint(\"yt\", \"__parallel_rank\") > 0: return False\n except:\n if ytcfg.getint(\"yt\",\"__topcomm_parallel_rank\") > 0: return False\n return True\n\ndef rainbow_01():\n norm = mpl.colors.Normalize()\n norm.autoscale([0.0,1.0])\n cmap = mpl.cm.jet\n color_map = mpl.cm.ScalarMappable(norm=norm,cmap=cmap)\n return color_map.to_rgba\n\nclass rainbow_map():\n def __init__(self,n=None, vmin=None,vmax=None, cmap='jet'):\n norm = mpl.colors.Normalize()\n if vmin is not None and vmax is not None:\n norm.autoscale([vmin,vmax])\n else:\n norm.autoscale(np.arange(n))\n #cmap = mpl.cm.jet\n self.color_map = mpl.cm.ScalarMappable(norm=norm,cmap=cmap)\n def __call__(self,val,n_fields=0):\n this_value = self.color_map.to_rgba(val)\n if n_fields > 0:\n this_value = [this_value]*n_fields\n return this_value\n\n #return color_map.to_rgba\n\ntry:\n algae = mpl.cm.get_cmap(\"algae\")\nexcept:\n pass\ndef algae_map(n):\n norm = mpl.colors.Normalize()\n norm.autoscale(np.arange(n))\n #cmap = mpl.cm.__dict__['algae']\n color_map = mpl.cm.ScalarMappable(norm=norm,cmap='algae')\n return color_map.to_rgba\n\ndef trans(array,dim):\n \"\"\"returns the elements of array that aren't dim\n array must be a numpy array.\n trans([a,b,c],1) -> [a,c]\"\"\"\n return array[filter(lambda x: x != dim,range(len(array)) ) ]\n\ndef relerr(a,b):\n \"\"\"returns (b-a)/\"\"\"\n return (b-a)/(0.5*(a+b))\n\ndef relerr0(a,b):\n \"\"\"returns (b-a)/\"\"\"\n return (b-a)/a\n\ndef psave(ax,name):\n print( name)\n ax.savefig(name)\n\ndef dsave(ax,name,field_name=None,pf_list=None,tar=True,script_name=None,plt_format='dave'):\n if plt_format != 'dave':\n if plt_format not in name:\n name += \".\"+plt_format\n psave(ax,name)\n return\n\n basename = name.split(\".\")\n #pdb.set_trace()\n if len(basename) > 1:\n format = basename[-1]\n basename = basename[:-1]\n basename = (\"%s.\"*len(basename)%tuple(basename))[:-1] #the last [:-1] is for the extra .\"\n else:\n basename = basename[0]\n format = 'whatever'\n\n if format not in ['png','pdf','eps','whatever','dave']:\n print(\"Unclear format string:\",format)\n directory = \"figs/\"+basename\n if field_name is not None:\n directory += \"_%s\"%field_name\n\n try:\n os.mkdir(\"figs\")\n except:\n pass\n try:\n os.mkdir(directory)\n except:\n pass\n for form in ['png','eps','pdf']:\n if hasattr(ax,'savefig'):\n ax.savefig(\"%s/%s.%s\"%(directory,basename,form))\n if hasattr(ax,'save'):\n ax.save(\"%s/%s\"%(directory,basename), format=form)\n\n d_html(directory,basename,field_name,pf_list,script_name)\n print(\"open %s/%s.png\"%(directory,basename))\n print(\"get %s.tar\"%(directory))\n to_tar_gz(directory,directory+\".tar\")\n\n\ndef d_html(directory,basename,field_name,pf_list=None,script_name=None):\n \"\"\"write meta html.\"\"\"\n field_to_add = \"\"\n if field_name is not None:\n field_to_add = \"_%s\"%field_name\n pname = basename+field_to_add+\".png\"\n bname = basename\n hname = basename+field_to_add+\".html\"\n dname = directory\n full_hname = \"%s/%s\"%(dname,hname)\n print(full_hname)\n\n hptr = open(full_hname,\"w\")\n hptr.write(\"
    \\n\")\n hptr.write('
    '%(pname,pname))\n hptr.write('

    \\n'%pname)\n machine = \"unknown\"\n if 'machine' in os.environ:\n machine = os.environ['machine']\n hptr.write(\"Plotted on: %s
    \\n\"%machine)\n if script_name is not None:\n hptr.write('Script Name:%s
    \\n'%script_name)\n if pf_list is not None and len(pf_list) > 0:\n hptr.write(\"PF list:
    \\n\")\n for pf in pf_list:\n hptr.write(\"%s
    \"%pf)\n else:\n hptr.write(\"unknown PF
    \")\n hptr.close()\n\n\n\ndef dpy(filename,fields):\n \"\"\"Open hdf5 file *filename* and return *field*, then close the file.\n Collapses 3 function calls into 1.\"\"\"\n if glob.glob(filename) == []:\n print(\"No such file\", filename)\n return None\n fptr = h5py.File(filename,'r')\n output = []\n try:\n if hasattr(fptr,'listnames'):\n field_list = fptr.listnames()\n elif hasattr(fptr,'keys'):\n field_list = fptr.keys()\n\n for field in ensure_list(fields):\n if field not in field_list:\n print(\"No field\", field, \"in file\",filename)\n return None\n else:\n if len(fptr[field].shape) > 0:\n output.append(fptr[field][:])\n else:\n output.append(fptr[field].value)\n except:\n pdb.set_trace()\n raise\n finally:\n fptr.close()\n return output\n\ndef dpy_save(filename,object,fields):\n \"\"\"Write all *object*[*fields*] to hdf5 file *filename*\"\"\"\n fptr = h5py.File(filename,'w')\n for field in fields:\n set = object[field]\n fptr.create_dataset(field,set.shape,data=set)\n fptr.close()\n\ndef expform(float_in, format = \"%0.1e\"):\n \"\"\"exponent format: 1.5e+03 goes to $1.5 \\times 10^{3}$\"\"\"\n str1 = format%float_in\n tex_string = \"$\"\n try:\n exp_pos = str1.index(\"e\")\n exponent_shift = 1\n if str1[exp_pos+1] == \"+\":\n exponent_shift+1\n mantissa = str1[0:exp_pos]\n exponent = str1[exp_pos+exponent_shift:]\n if float(mantissa) != 1:\n tex_string += mantissa + \"\\\\times \"\n tex_string += \"10^{\" \n tex_string += str(int(exponent))\n tex_string += \"}$\"\n except:\n tex_string += str1\n tex_string += \"$\"\n return '%s'%tex_string\n\ndef grep(lookfor,obj):\n if isinstance(obj, types.ListType):\n my_list = obj\n else: my_list = dir(obj)\n for i in my_list:\n if lookfor.upper() in i.upper(): print(i)\n\ndef stat(array,strin='', format='%0.16e'):\n template = '['+format+','+format+'] %s %s'\n print(template%(array.min(),array.max(),array.shape,strin))\n\ndef nonzerostat(array,strin=''):\n\n print('[%0.4e,%0.4e] %s %s'%(array[array>0].min(),array[array>0].max(),array.shape,strin))\n\ndef morestat(array,strin='',log=False):\n if log:\n mean = 10**(meanRMS(np.log10(array)))\n else:\n mean = meanRMS(array)\n print('[%0.4e,%0.4e \\pm %0.4e, %0.4e] %s %s'%(array.min(),mean[0],mean[1],array.max(),array.shape,strin))\n\ndef psave(ax,name):\n print(name)\n ax.savefig(name)\n\ndef plave(array,filename,axis=None,ax=None,colorbar=True, zlim=None, label=\"Value\",scale='linear',ticks_off=False,\n linthresh=1.):\n \"\"\"plot and save. Takes *array*, saves an image and saves it in *filename*\n *zlim* = [a,b] scales the colorbar form a to b.\"\"\"\n save_fig = False\n if ax is None:\n fig, ax = plt.subplots(1,1)\n save_fig=True\n\n if len(array.shape) == 2:\n array_2d = array\n else:\n if axis == None:\n print(\"Must provide an axis: 3d array\")\n return\n #array_2d = np.flipud(np.sum( array , axis=axis).transpose())\n array_2d = np.sum( array , axis=axis)\n\n norm = None\n cmap = mpl.cm.gray\n if zlim is None:\n zlim = [array_2d.min(),array_2d.max()]\n if scale == 'linear':\n norm=mpl.colors.Normalize(vmin=zlim[0], vmax=zlim[1])\n elif scale == 'log':\n norm=mpl.colors.LogNorm(vmin=zlim[0], vmax=zlim[1])\n elif scale == 'symlog':\n norm=mpl.colors.SymLogNorm(linthresh,vmin=zlim[0], vmax=zlim[1])\n plot = ax.imshow(array_2d, interpolation='nearest', origin='lower', norm=norm,cmap=cmap)\n if not ticks_off:\n ax.set_yticks(range(0,array_2d.shape[0],5))\n ax.set_xticks(range(0,array_2d.shape[1],5))\n else:\n ax.set_xticks([])\n ax.set_yticks([])\n print(filename)\n norm = None\n if colorbar:\n colorbar = plt.colorbar(plot, norm=norm)\n colorbar.set_label(label)\n if zlim is not None:\n colorbar.set_clim(zlim[0], zlim[1])\n\n\n if save_fig:\n fig.savefig(filename)\n plt.close(fig)\n print(filename)\n\ndef wp(axes,number,index_only=False):\n \"\"\"Which Plot. Takes 2d list *axes* and returns the row-major *number* element.\n *index_only* returns (i,j)\"\"\"\n nx = len(axes[0])\n i = int(number/nx)\n j = number%nx\n if index_only:\n output = i,j\n else:\n output = axes[i][j]\n #output.text(1e-2,1e-1,'bn %d (%d,%d)'%(number,i,j))\n return output\n\ndef meanRMS(F):\n M = F.sum()/(F.size)\n rms = np.sqrt(( ( F - M )**2 ).sum()/F.size)\n return nar([M,rms])\n\n\n\n\ndef morestat(array,strin='',log=False):\n if log:\n mean = 10**(meanRMS(np.log10(array)))\n else:\n mean = meanRMS(array)\n print('[%0.4e,%0.4e \\pm %0.4e, %0.4e] %s %s'%(array.min(),mean[0],mean[1],array.max(),array.shape,strin))\n\ndef powerline(this_plt,x1,x2,y1,power,log=True,**kwargs):\n \"\"\"Plot a powerlaw on the current plot in matplot lib instance *plt*.\n Starts at *x1*, *y1* and runs to *x2*, whatever the power law dictates.\n *log* determines log or linear plot.\"\"\"\n if False:\n if True:\n x1 = 10**x1\n x2 = 10**x2\n x = [x1,x2]\n b = x1**(-power)*y1\n yf = x2**power*b\n y = [y1, yf]\n if True:\n x1 = np.log10(x1)\n x2 = np.log10(x2)\n if log:\n x = [x1,x2]\n yf = x2**power*x1**(-power)*y1\n y = [y1, yf]\n else:\n x = [x1,x2]\n yf = power*(x2-x1) + y1\n y = [y1,yf]\n this_plt.plot(x,y,**kwargs)\n\ndef read_csv(filename):\n file=open(filename,'r')\n lines=file.readlines()\n file.close()\n obs = [ L.split(',') for L in lines]\n values = {}\n for i,n in enumerate(obs[0]):\n values[n] = [ ooo[i] for ooo in obs[1:] ]\n try:\n values[n] = map(float,values[n])\n except:\n pass\n values[n]=nar(values[n])\n return values\n\ndef getdata(file_list):\n out = []\n for f in file_list:\n masses = read_csv(f)['Msun']\n out += map(float,masses) \n return nar(out)\n\ndef phist(array,width = 8, format = 'f', plot=plt,**kwargs):\n \"\"\"Accepts an array to histogram, and prints it in a way that doesn't suck.\n *width* is the width of the output field.\n *format* is the bin format ('f'loat or 'e'xponential)\"\"\"\n hist = plot.hist(array,**kwargs)\n val = hist[0]\n bin = hist[1]\n #These are meta-format strings.\n vbase = \"%s%dd \"%(\"%\",width)\n bbase = \"%s%d.2%s \"%(\"%\",width,format)\n halfformat = \"%s%d.2%s \"%(\"%\",width/2,format)\n vformat = \"\"\n bformat = halfformat\n for n in range(len(val)):\n vformat += vbase\n bformat += bbase\n print(vformat%tuple(val))\n print(bformat%tuple(bin))\n return hist\n\nclass ParameterException(Exception):\n def __init__(self, parameter,pf):\n self.value = 'Parameter file %s has no parameter %s'%(str(pf),parameter)\n def __str__(self):\n return repr(self.value)\n\ndef tabler(head,rows):\n \"\"\"Make a latex table.\"\"\"\n setup = '\\\\begin{table}[h]' + '\\n' + r'\\begin{center}' +'\\n' +'\\caption{}'\n setup += '\\\\begin{tabular}{ %s }'%('c '*len(head) )\n setup += '\\\\label{}'+'\\n'\n row_format = '%10s'+'& %10s'*(len(head)-1) \n head = row_format%tuple(head) + r'\\\\ \\hline \\hline' \n for this_row in rows:\n head += '\\n' + row_format%tuple(this_row) + r'\\\\'\n closing = \"\\\\hline\" + '\\n'\n closing += r'\\end{tabular} \\end{center} \\end{table}'\n return setup + head +closing\n","sub_path":"tools/davetools.py","file_name":"davetools.py","file_ext":"py","file_size_in_byte":17655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"279571634","text":"# coding=utf-8\n# Copyright 2018 KOGPT Authors\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\"\"\" PyTorch KOGPT model. \"\"\"\n\n####################################################\n# In this template, replace all the KOGPT (various casings) with your model name\n####################################################\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport collections\nimport json\nimport logging\nimport math\nimport os\nimport sys\nfrom io import open\n\nimport attr\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom torch.nn import CrossEntropyLoss\nimport torch.utils.checkpoint\nfrom torch.nn.parameter import Parameter\n\nfrom .modeling_utils import PreTrainedModel, prune_conv1d_layer, SequenceSummary\nfrom .modeling_utils import KO_Conv1D as Conv1D\nfrom .configuration_kogpt import KOGPTConfig\nfrom .file_utils import add_start_docstrings\n\n\n\n\n\nlogger = logging.getLogger(__name__)\n\n####################################################\n# This dict contrains shortcut names and associated url\n# for the pretrained weights provided with the models\n####################################################\nKOGPT_PRETRAINED_MODEL_ARCHIVE_MAP = {\n 'kogpt-base-uncased': \"https://s3.amazonaws.com/models.huggingface.co/bert/kogpt-base-uncased-pytorch_model.bin\"\n}\n\n####################################################\n# This is a conversion method from TF 1.0 to PyTorch\n# More details: https://medium.com/huggingface/from-tensorflow-to-pytorch-265f40ef2a28\n####################################################\ndef load_tf_weights_in_kogpt(model, config, tf_checkpoint_path):\n \"\"\" Load tf checkpoints in a pytorch model.\n \"\"\"\n try:\n import re\n import numpy as np\n import tensorflow as tf\n except ImportError:\n logger.error(\"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see \"\n \"https://www.tensorflow.org/install/ for installation instructions.\")\n raise\n tf_path = os.path.abspath(tf_checkpoint_path)\n logger.info(\"Converting TensorFlow checkpoint from {}\".format(tf_path))\n # Load weights from TF model\n init_vars = tf.train.list_variables(tf_path)\n names = []\n arrays = []\n for name, shape in init_vars:\n logger.info(\"Loading TF weight {} with shape {}\".format(name, shape))\n array = tf.train.load_variable(tf_path, name)\n names.append(name)\n arrays.append(array)\n\n for name, array in zip(names, arrays):\n name = name.split('/')\n # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v\n # which are not required for using pretrained model\n if any(n in [\"adam_v\", \"adam_m\", \"global_step\"] for n in name):\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\n continue\n pointer = model\n for m_name in name:\n if re.fullmatch(r'[A-Za-z]+_\\d+', m_name):\n l = re.split(r'_(\\d+)', m_name)\n else:\n l = [m_name]\n if l[0] == 'kernel' or l[0] == 'gamma':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'output_bias' or l[0] == 'beta':\n pointer = getattr(pointer, 'bias')\n elif l[0] == 'output_weights':\n pointer = getattr(pointer, 'weight')\n elif l[0] == 'squad':\n pointer = getattr(pointer, 'classifier')\n else:\n try:\n pointer = getattr(pointer, l[0])\n except AttributeError:\n logger.info(\"Skipping {}\".format(\"/\".join(name)))\n continue\n if len(l) >= 2:\n num = int(l[1])\n pointer = pointer[num]\n if m_name[-11:] == '_embeddings':\n pointer = getattr(pointer, 'weight')\n elif m_name == 'kernel':\n array = np.transpose(array)\n try:\n assert pointer.shape == array.shape\n except AssertionError as e:\n e.args += (pointer.shape, array.shape)\n raise\n logger.info(\"Initialize PyTorch weight {}\".format(name))\n pointer.data = torch.from_numpy(array)\n return model\n\n\n####################################################\n# PyTorch Models are constructed by sub-classing\n# - torch.nn.Module for the layers and\n# - PreTrainedModel for the models (itself a sub-class of torch.nn.Module)\n####################################################\n\n####################################################\n# Here is an example of typical layer in a PyTorch model of the library\n# The classes are usually identical to the TF 2.0 ones without the 'TF' prefix.\n#\n# See the conversion methods in modeling_tf_pytorch_utils.py for more details\n####################################################\n\n\n\n\n@attr.s(auto_attribs=True, frozen=True)\nclass HParams:\n n_vocab: int\n n_ctx: int\n n_embed: int\n n_hidden: int\n n_head: int\n n_layer: int\n gradient_checkpointing: bool\n\nclass Block(nn.Module):\n def __init__(self, hparams: HParams):\n super().__init__()\n self.ln_1 = Norm(hparams.n_hidden)\n self.ln_2 = Norm(hparams.n_hidden)\n self.mlp = MLP(hparams.n_hidden, hparams.n_hidden * 4)\n self.attn = Attention(hparams)\n\n def forward(self, x, past):\n a, present = self.attn(self.ln_1(x), past=past)\n x = x + a\n m = self.mlp(self.ln_2(x))\n x = x + m\n return x, present\n\n\nclass Norm(nn.Module):\n \"\"\" Normalize to mean = 0, std = 1, then do a diagonal affine transform.\n \"\"\"\n def __init__(self, n_features, *, dim=-1, epsilon=1e-5):\n super().__init__()\n self.n_features = n_features\n self.dim = dim\n self.epsilon = epsilon\n self.g = nn.Parameter(torch.ones(n_features))\n self.b = nn.Parameter(torch.zeros(n_features))\n\n def forward(self, x):\n assert x.shape[-1] == self.n_features\n u = torch.mean(x, dim=self.dim, keepdim=True)\n xmu = x - u\n s = torch.mean(xmu * xmu, dim=self.dim, keepdim=True)\n return xmu * torch.rsqrt(s + self.epsilon) * self.g + self.b\n\n\n\nclass MLP(nn.Module):\n def __init__(self, n_features, n_hidden):\n super().__init__()\n self.c_fc = Conv1D(n_features, n_hidden)\n self.c_proj = Conv1D(n_hidden, n_features)\n\n def forward(self, x):\n x = gelu(self.c_fc(x))\n x = self.c_proj(x)\n return x\n\n\nclass Attention(nn.Module):\n def __init__(self, hparams: HParams):\n super().__init__()\n assert hparams.n_hidden % hparams.n_head == 0\n self.hparams = hparams\n self.c_attn = Conv1D(hparams.n_hidden, hparams.n_hidden * 3)\n self.c_proj = Conv1D(hparams.n_hidden, hparams.n_hidden)\n\n def forward(self, x, past):\n assert len(x.shape) == 3 # [batch, sequence, features]\n assert x.shape[-1] == self.hparams.n_hidden\n if past is not None:\n # Should be [batch, 2, heads, sequence, features], where 2 is [k, v]\n assert len(past.shape) == 5\n assert past.shape[-1] == self.hparams.n_hidden\n c = self.c_attn(x)\n q, k, v = map(self.split_heads, torch.split(c, x.shape[-1], dim=2))\n present = torch.stack([k, v], dim=1)\n if past is not None:\n pk, pv = past[:, 0], past[:, 1]\n k = torch.cat([pk, k], dim=-2)\n v = torch.cat([pv, v], dim=-2)\n a = self.multihead_attn(q, k, v)\n a = self.merge_heads(a)\n a = self.c_proj(a)\n return a, present\n\n def split_heads(self, x):\n \"\"\" From [batch, sequence, features] to\n [batch, heads, sequence, features].\n \"\"\"\n return self.split_states(x, self.hparams.n_head).permute(0, 2, 1, 3)\n\n @staticmethod\n def split_states(x, n):\n \"\"\" Reshape the last dimension of x into [n, x.shape[-1]/n].\n \"\"\"\n *start, m = x.shape\n return x.reshape(start + [n, m // n])\n\n def merge_heads(self, x):\n \"\"\" Reverse of split_heads.\n \"\"\"\n return self.merge_states(x.permute(0, 2, 1, 3))\n\n @staticmethod\n def merge_states(x):\n \"\"\" Smash the last two dimensions of x into a single dimension.\n \"\"\"\n *start, a, b = x.shape\n return x.reshape(start + [a * b])\n\n def mask_attn_weights(self, w):\n # w has shape [batch, heads, dst_sequence, src_sequence],\n # where information flows from src to dst.\n _, _, nd, ns = w.shape\n b = self.attention_mask(nd, ns, dtype=w.dtype, device=w.device)\n b = b.reshape((1, 1, nd, ns))\n w = w * b - 1e10 * (1 - b)\n return w\n\n @staticmethod\n def attention_mask(nd, ns, *, dtype, device=None):\n \"\"\" 1's in the lower triangle, counting from the lower right corner.\n Same as tf.matrix_band_part(tf.ones([nd, ns]), -1, ns-nd),\n but doesn't produce garbage on TPUs.\n \"\"\"\n i = torch.arange(0, nd).unsqueeze(1)\n j = torch.arange(ns)\n return (i >= j - ns + nd).to(dtype=dtype, device=device)\n\n def multihead_attn(self, q, k, v):\n # q, k, v have shape [batch, heads, sequence, features]\n w = torch.matmul(q, k.permute(0, 1, 3, 2))\n w = w / math.sqrt(v.shape[-1])\n w = self.mask_attn_weights(w)\n w = F.softmax(w, dim=-1)\n a = torch.matmul(w, v)\n return a\n\n\ndef gelu(x, c=math.sqrt(2 / math.pi)):\n return 0.5 * x * (1 + torch.tanh(c * (x + 0.044715 * torch.pow(x, 3))))\n\n\ndef position_for(batch_size, n_steps, past_length, device=None):\n return (torch.arange(past_length, n_steps + past_length, device=device)\n .unsqueeze(0).repeat(batch_size, 1))\n\n\n\n####################################################\n# PreTrainedModel is a sub-class of torch.nn.Module\n# which take care of loading and saving pretrained weights\n# and various common utilities.\n#\n# Here you just need to specify a few (self-explanatory)\n# pointers for your model and the weights initialization\n# method if its not fully covered by PreTrainedModel's default method\n####################################################\nclass KOGPTPreTrainedModel(PreTrainedModel):\n \"\"\" An abstract class to handle weights initialization and\n a simple interface for dowloading and loading pretrained models.\n \"\"\"\n config_class = KOGPTConfig\n pretrained_model_archive_map = KOGPT_PRETRAINED_MODEL_ARCHIVE_MAP\n load_tf_weights = load_tf_weights_in_kogpt\n base_model_prefix = \"transformer\"\n\n def __init__(self, *inputs, **kwargs):\n super(KOGPTPreTrainedModel, self).__init__(*inputs, **kwargs)\n\n def _init_weights(self, module):\n \"\"\" Initialize the weights \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding, Conv1D)):\n # Slightly different from the original huggingfaces' gpt2\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n elif isinstance(module, Norm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n\nKOGPT_START_DOCSTRING = r\"\"\" OpenAI GPT-2 model was proposed in\n `Language Models are Unsupervised Multitask Learners`_\n by Alec Radford*, Jeffrey Wu*, Rewon Child, David Luan, Dario Amodei** and Ilya Sutskever**.\n It's a causal (unidirectional) transformer pre-trained using language modeling on a very large\n corpus of ~40 GB of text data.\n\n This model is a PyTorch `torch.nn.Module`_ sub-class. Use it as a regular PyTorch Module and\n refer to the PyTorch documentation for all matter related to general usage and behavior.\n\n .. _`Language Models are Unsupervised Multitask Learners`:\n https://openai.com/blog/better-language-models/\n\n .. _`torch.nn.Module`:\n https://pytorch.org/docs/stable/nn.html#module\n\n Parameters:\n config (:class:`~transformers.KOGPTConfig`): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the configuration.\n Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.\n\"\"\"\n\nKOGPT_INPUTS_DOCSTRING = r\"\"\" Inputs:\n **input_ids**: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Indices of input sequence tokens in the vocabulary.\n GPT-2 is a model with absolute position embeddings so it's usually advised to pad the inputs on\n the right rather than the left.\n Indices can be obtained using :class:`transformers.KOGPTTokenizer`.\n See :func:`transformers.PreTrainedTokenizer.encode` and\n :func:`transformers.PreTrainedTokenizer.convert_tokens_to_ids` for details.\n **past**:\n list of ``torch.FloatTensor`` (one for each layer):\n that contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model\n (see `past` output below). Can be used to speed up sequential decoding.\n **attention_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, sequence_length)``:\n Mask to avoid performing attention on padding token indices.\n Mask values selected in ``[0, 1]``:\n ``1`` for tokens that are NOT MASKED, ``0`` for MASKED tokens.\n **token_type_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n A parallel sequence of tokens (can be used to indicate various portions of the inputs).\n The embeddings from these tokens will be summed with the respective token embeddings.\n Indices are selected in the vocabulary (unlike BERT which has a specific vocabulary for segment indices).\n **position_ids**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Indices of positions of each input sequence tokens in the position embeddings.\n Selected in the range ``[0, config.max_position_embeddings - 1]``.\n **head_mask**: (`optional`) ``torch.FloatTensor`` of shape ``(num_heads,)`` or ``(num_layers, num_heads)``:\n Mask to nullify selected heads of the self-attention modules.\n Mask values selected in ``[0, 1]``:\n ``1`` indicates the head is **not masked**, ``0`` indicates the head is **masked**.\n **inputs_embeds**: (`optional`) ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, embedding_dim)``:\n Optionally, instead of passing ``input_ids`` you can choose to directly pass an embedded representation.\n This is useful if you want more control over how to convert `input_ids` indices into associated vectors\n than the model's internal embedding lookup matrix.\n\"\"\"\n\n@add_start_docstrings(\"The bare KOGPT Model transformer outputting raw hidden-states without any specific head on top.\",\n KOGPT_START_DOCSTRING, KOGPT_INPUTS_DOCSTRING)\nclass KOGPTModel(KOGPTPreTrainedModel):\n r\"\"\"\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)``\n Sequence of hidden-states at the last layer of the model.\n **past**:\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n that contains pre-computed hidden-states (key and values in the attention blocks).\n Can be used (see `past` input) to speed up sequential decoding.\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n tokenizer = KOGPTTokenizer.from_pretrained('kogpt')\n model = KOGPTModel.from_pretrained('kogpt')\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n outputs = model(input_ids)\n last_hidden_states = outputs[0] # The last hidden-state is the first element of the output tuple\n\n \"\"\"\n def __init__(self, hparams:KOGPTconfig.hparams):\n\n super().__init__()\n self.hparams = hparams\n self.wpe = nn.Embedding(hparams.n_ctx, hparams.n_embed)\n nn.init.normal_(self.wpe.weight, std=0.01)\n self.wte = nn.Embedding(hparams.n_vocab, hparams.n_embed)\n nn.init.normal_(self.wte.weight, std=0.02)\n self.blocks = nn.ModuleList(\n [Block(hparams) for _ in range(hparams.n_layer)])\n self.ln_f = Norm(self.hparams.n_hidden)\n if hparams.n_hidden != hparams.n_embed:\n self.in_proj = Conv1D(hparams.n_embed, hparams.n_hidden)\n self.out_proj = Conv1D(hparams.n_hidden, hparams.n_embed)\n else:\n self.in_proj = self.out_proj = None\n\n def forward(self, x, past=None):\n # Embedding\n past_length = 0 if past is None else past.shape[-2]\n batch_size, n_ctx = x.shape\n position = position_for(batch_size, n_ctx, past_length, x.device)\n h = self.wte(x) + self.wpe(position)\n assert h.shape == (batch_size, n_ctx, self.hparams.n_embed)\n if self.in_proj:\n h = self.in_proj(h)\n # Transformer\n presents = []\n for i, block in enumerate(self.blocks):\n if self.hparams.gradient_checkpointing:\n h, present = torch.utils.checkpoint.checkpoint(block, h, past[:, i] if past is not None else None)\n else:\n h, present = block(h, past=past[:, i] if past is not None else None)\n presents.append(present)\n h = self.ln_f(h)\n if self.out_proj:\n h = self.out_proj(h)\n # Output logits\n h_flat = h.reshape([batch_size * n_ctx, self.hparams.n_embed])\n logits = torch.matmul(h_flat, self.wte.weight.t())\n logits = logits.reshape([batch_size, n_ctx, self.hparams.n_vocab])\n return {\n 'presents': torch.stack(tuple(presents), dim=1),\n 'logits': logits,\n }\n\n\n\n@add_start_docstrings(\"\"\"The KOGPT Model transformer with a language modeling head on top\n(linear layer with weights tied to the input embeddings). \"\"\", KOGPT_START_DOCSTRING, KOGPT_INPUTS_DOCSTRING)\nclass KOGPTLMHeadModel(KOGPTPreTrainedModel):\n r\"\"\"\n **labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for language modeling.\n Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``\n Indices are selected in ``[-1, 0, ..., config.vocab_size]``\n All labels set to ``-1`` are ignored (masked), the loss is only\n computed for labels in ``[0, ..., config.vocab_size]``\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **loss**: (`optional`, returned when ``labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Language modeling loss.\n **prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, config.vocab_size)``\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n **past**:\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n that contains pre-computed hidden-states (key and values in the attention blocks).\n Can be used (see `past` input) to speed up sequential decoding.\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n import torch\n from transformers import KOGPTTokenizer, KOGPTLMHeadModel\n\n tokenizer = KOGPTTokenizer.from_pretrained('kogpt')\n model = KOGPTLMHeadModel.from_pretrained('kogpt')\n\n input_ids = torch.tensor(tokenizer.encode(\"Hello, my dog is cute\")).unsqueeze(0) # Batch size 1\n outputs = model(input_ids, labels=input_ids)\n loss, logits = outputs[:2]\n\n \"\"\"\n def __init__(self, config):\n super(KOGPTLMHeadModel, self).__init__(config)\n self.transformer = KOGPTModel(config)\n self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n\n self.init_weights()\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def forward(self, input_ids=None, past=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None,\n labels=None):\n transformer_outputs = self.transformer(input_ids,\n past=past,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds)\n hidden_states = transformer_outputs[0]\n\n lm_logits = self.lm_head(hidden_states)\n\n outputs = (lm_logits,) + transformer_outputs[1:]\n if labels is not None:\n # Shift so that tokens < n predict n\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = labels[..., 1:].contiguous()\n # Flatten the tokens\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)),\n shift_labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (loss), lm_logits, presents, (all hidden_states), (attentions)\n\n\n@add_start_docstrings(\"\"\"The KOGPT Model transformer with a language modeling and a multiple-choice classification\nhead on top e.g. for RocStories/SWAG tasks. The two heads are two linear layers.\nThe language modeling head has its weights tied to the input embeddings,\nthe classification head takes as input the input of a specified classification token index in the input sequence).\n\"\"\", KOGPT_START_DOCSTRING, KOGPT_INPUTS_DOCSTRING)\nclass KOGPTDoubleHeadsModel(KOGPTPreTrainedModel):\n r\"\"\"\n **mc_token_ids**: (`optional`, default to index of the last token of the input) ``torch.LongTensor`` of shape ``(batch_size, num_choices)``:\n Index of the classification token in each input sequence.\n Selected in the range ``[0, input_ids.size(-1) - 1[``.\n **lm_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size, sequence_length)``:\n Labels for language modeling.\n Note that the labels **are shifted** inside the model, i.e. you can set ``lm_labels = input_ids``\n Indices are selected in ``[-1, 0, ..., config.vocab_size]``\n All labels set to ``-1`` are ignored (masked), the loss is only\n computed for labels in ``[0, ..., config.vocab_size]``\n **mc_labels**: (`optional`) ``torch.LongTensor`` of shape ``(batch_size)``:\n Labels for computing the multiple choice classification loss.\n Indices should be in ``[0, ..., num_choices]`` where `num_choices` is the size of the second dimension\n of the input tensors. (see `input_ids` above)\n\n Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs:\n **lm_loss**: (`optional`, returned when ``lm_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Language modeling loss.\n **mc_loss**: (`optional`, returned when ``multiple_choice_labels`` is provided) ``torch.FloatTensor`` of shape ``(1,)``:\n Multiple choice classification loss.\n **lm_prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, num_choices, sequence_length, config.vocab_size)``\n Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).\n **mc_prediction_scores**: ``torch.FloatTensor`` of shape ``(batch_size, num_choices)``\n Prediction scores of the multiplechoice classification head (scores for each choice before SoftMax).\n **past**:\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n that contains pre-computed hidden-states (key and values in the attention blocks).\n Can be used (see `past` input) to speed up sequential decoding.\n **hidden_states**: (`optional`, returned when ``config.output_hidden_states=True``)\n list of ``torch.FloatTensor`` (one for the output of each layer + the output of the embeddings)\n of shape ``(batch_size, sequence_length, hidden_size)``:\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n **attentions**: (`optional`, returned when ``config.output_attentions=True``)\n list of ``torch.FloatTensor`` (one for each layer) of shape ``(batch_size, num_heads, sequence_length, sequence_length)``:\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.\n\n Examples::\n\n import torch\n from transformers import KOGPTTokenizer, KOGPTDoubleHeadsModel\n\n tokenizer = KOGPTTokenizer.from_pretrained('kogpt')\n model = KOGPTDoubleHeadsModel.from_pretrained('kogpt')\n\n # Add a [CLS] to the vocabulary (we should train it also!)\n tokenizer.add_special_tokens({'cls_token': '[CLS]'})\n model.resize_token_embeddings(len(tokenizer)) # Update the model embeddings with the new vocabulary size\n print(tokenizer.cls_token_id, len(tokenizer)) # The newly token the last token of the vocabulary\n\n choices = [\"Hello, my dog is cute [CLS]\", \"Hello, my cat is cute [CLS]\"]\n encoded_choices = [tokenizer.encode(s) for s in choices]\n cls_token_location = [tokens.index(tokenizer.cls_token_id) for tokens in encoded_choices]\n\n input_ids = torch.tensor(encoded_choices).unsqueeze(0) # Batch size: 1, number of choices: 2\n mc_token_ids = torch.tensor([cls_token_location]) # Batch size: 1\n\n outputs = model(input_ids, mc_token_ids=mc_token_ids)\n lm_prediction_scores, mc_prediction_scores = outputs[:2]\n\n \"\"\"\n\n def __init__(self, config):\n super(KOGPTDoubleHeadsModel, self).__init__(config)\n self.transformer = KOGPTModel(config)\n self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n self.multiple_choice_head = SequenceSummary(config)\n\n self.init_weights()\n\n def get_output_embeddings(self):\n return self.lm_head\n\n def forward(self, input_ids=None, past=None, attention_mask=None, token_type_ids=None, position_ids=None,\n head_mask=None, inputs_embeds=None,\n mc_token_ids=None, lm_labels=None, mc_labels=None):\n transformer_outputs = self.transformer(input_ids,\n past=past,\n attention_mask=attention_mask,\n token_type_ids=token_type_ids,\n position_ids=position_ids,\n head_mask=head_mask,\n inputs_embeds=inputs_embeds)\n\n hidden_states = transformer_outputs[0]\n\n lm_logits = self.lm_head(hidden_states)\n mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)\n\n outputs = (lm_logits, mc_logits) + transformer_outputs[1:]\n if mc_labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)),\n mc_labels.view(-1))\n outputs = (loss,) + outputs\n if lm_labels is not None:\n shift_logits = lm_logits[..., :-1, :].contiguous()\n shift_labels = lm_labels[..., 1:].contiguous()\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)),\n shift_labels.view(-1))\n outputs = (loss,) + outputs\n\n return outputs # (lm loss), (mc loss), lm logits, mc logits, presents, (all hidden_states), (attentions)","sub_path":"transformers/modeling_kogpt.py","file_name":"modeling_kogpt.py","file_ext":"py","file_size_in_byte":30411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"73000990","text":"#---------------------------------------------------------------------------\n# cateAnalysis_problem3.py\n# This function calculates the p-value given an input contingency table \n# using the chi-squared test of independence for an r row, c column \n# contingency table without using for or while loops.\n#\n# Designed by HsinYu (Katie) Chi\n# 05 March 2019\n#---------------------------------------------------------------------------\n\n#- Imports\nimport numpy as np\n\n#- Function\ndef chisquare(table):\n \"\"\"\n This function calculates the p-value given an input contingency table \n using the chi-squared test of independence for an r row, c column \n contingency table without using for or while loops.\n\n Arguments:\n table {list} -- [description]\n \"\"\"\n\n # I use the same idea of taking the table as an array, and calculate\n # the sum of each row and column, which Professor Johnny Lin shows\n # in the class.\n table_array = np.array(table)\n row0 = np.sum(table_array[0, :]) # 374 + 2629\n row1 = np.sum(table_array[1, :]) # 73 + 1219\n col0 = np.sum(table_array[:, 0]) # 374 + 73\n col1 = np.sum(table_array[:, 1]) # 2629 + 1219\n total = col0 + col1\n\n # Calculate the expected contingency\n newRow0 = (row0 * col0) / total\n newRow1 = (row0 * row1) / total\n newCol0 = (col0 * row0) / total\n newCol1 = (col0 * col1) / total\n\n # Calculate the chi squared t test\n chisquared = ((table_array[0] - newRow0)/newRow0) + \\\n ((table_array[1] - newRow1)/newRow1) + \\\n ((table_array[2] - newCol0)/newCol0) + \\\n ((table_array[3] - newCol1)/newCol1)\n\n print(chisquared)\n\n#===== end file =====\n","sub_path":"Python/330/cateAnalysis_problem3.py","file_name":"cateAnalysis_problem3.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"628333924","text":"from charmhelpers.core.templating import render\nfrom charms.reactive import remove_state\nfrom charms.reactive import set_state\nfrom charms.reactive import when\nfrom charms.reactive import when_not\n\nfrom charms.docker import DockerOpts\nfrom charms.docker import Compose\n\nfrom charmhelpers.core.hookenv import log\nfrom charmhelpers.core.hookenv import status_set\nfrom charmhelpers.core.hookenv import is_leader\nfrom charmhelpers.core.hookenv import leader_get\nfrom charmhelpers.core.hookenv import unit_get\nfrom charmhelpers.core.hookenv import open_port\nfrom charmhelpers.core.hookenv import unit_private_ip\nfrom charmhelpers.core import unitdata\nfrom charmhelpers.core.host import chdir\nfrom charmhelpers.core.host import service_restart\n\nfrom os import getenv\nfrom os import makedirs\nfrom os import path\nfrom os import rename\n\nimport subprocess\nfrom shlex import split\nfrom shutil import copyfile\n\nfrom tlslib import client_cert\nfrom tlslib import ca\n\n\n@when('etcd.available', 'docker.available')\n@when_not('swarm.available')\ndef swarm_etcd_cluster_setup(etcd):\n \"\"\"\n Expose the Docker TCP port, and begin swarm cluster configuration. Always\n leading with the agent, connecting to the discovery service, then follow\n up with the manager container on the leader node.\n \"\"\"\n con_string = etcd.connection_string().replace('http', 'etcd')\n bind_docker_daemon(con_string)\n start_swarm(con_string)\n status_set('active', 'Swarm configured. Happy swarming')\n\n\n@when('consul.available', 'docker.available')\n@when_not('swarm.available')\ndef swarm_consul_cluster_setup(consul):\n connection_string = \"consul://\"\n for unit in consul.list_unit_data():\n host_string = \"{}:{}\".format(unit['address'], unit['port'])\n connection_string = \"{}{},\".format(connection_string, host_string)\n bind_docker_daemon(connection_string.rstrip(','))\n start_swarm(connection_string.rstrip(','))\n\n\ndef start_swarm(cluster_string):\n ''' Render the compose configuration and start the swarm scheduler '''\n opts = {}\n opts['addr'] = unit_private_ip()\n opts['port'] = 2376\n opts['leader'] = is_leader()\n opts['connection_string'] = cluster_string\n render('docker-compose.yml', 'files/swarm/docker-compose.yml', opts)\n c = Compose('files/swarm')\n c.up()\n set_state('swarm.available')\n\n\n@when('swarm.available')\ndef swarm_messaging():\n if is_leader():\n status_set('active', 'Swarm leader running')\n else:\n status_set('active', 'Swarm follower')\n\n\n@when_not('etcd.connected', 'consul.connected')\ndef user_notice():\n \"\"\"\n Notify the user they need to relate the charm with ETCD or Consul to\n trigger the swarm cluster configuration.\n \"\"\"\n status_set('waiting', 'Waiting on Etcd or Consul relation')\n\n\n@when('swarm.available')\n@when_not('etcd.connected', 'consul.connected')\ndef swarm_relation_broken():\n \"\"\"\n Destroy the swarm agent, and optionally the manager.\n This state should only be entered if the Docker host relation with ETCD has\n been broken, thus leaving the cluster without a discovery service\n \"\"\"\n c = Compose('files/swarm')\n c.kill()\n c.rm()\n remove_state('swarm.available')\n status_set('waiting', 'Reconfiguring swarm')\n\n\n@when('easyrsa installed')\n@when_not('swarm.tls.opensslconfig.modified')\ndef inject_swarm_tls_template():\n \"\"\"\n layer-tls installs a default OpenSSL Configuration that is incompatibile\n with how swarm expects TLS keys to be generated. We will append what\n we need to the x509-type, and poke layer-tls to regenerate.\n \"\"\"\n if not is_leader():\n return\n else:\n status_set('maintenance', 'Reconfiguring SSL PKI configuration')\n\n log('Updating EasyRSA3 OpenSSL Config')\n openssl_config = 'easy-rsa/easyrsa3/x509-types/server'\n\n with open(openssl_config, 'r') as f:\n existing_template = f.readlines()\n\n # use list comprehension to enable clients,server usage for certificates\n # with the docker/swarm daemons.\n xtype = [w.replace('serverAuth', 'serverAuth, clientAuth') for w in existing_template] # noqa\n with open(openssl_config, 'w+') as f:\n f.writelines(xtype)\n\n set_state('swarm.tls.opensslconfig.modified')\n set_state('easyrsa configured')\n\n\n@when('tls.server.certificate available')\ndef enable_client_tls():\n '''\n Copy the TLS certificates in place and generate mount points for the swarm\n manager to mount the certs. This enables client-side TLS security on the\n TCP service.\n '''\n if not path.exists('/etc/docker'):\n makedirs('/etc/docker')\n\n kv = unitdata.kv()\n cert = kv.get('tls.server.certificate')\n with open('/etc/docker/server.pem', 'w+') as f:\n f.write(cert)\n with open('/etc/docker/ca.pem', 'w+') as f:\n f.write(leader_get('certificate_authority'))\n\n # schenanigans\n keypath = 'easy-rsa/easyrsa3/pki/private/{}.key'\n server = getenv('JUJU_UNIT_NAME').replace('/', '_')\n if path.exists(keypath.format(server)):\n copyfile(keypath.format(server), '/etc/docker/server-key.pem')\n else:\n copyfile(keypath.format(unit_get('public-address')),\n '/etc/docker/server-key.pem')\n\n opts = DockerOpts()\n config_dir = '/etc/docker'\n cert_path = '{}/server.pem'.format(config_dir)\n ca_path = '{}/ca.pem'.format(config_dir)\n key_path = '{}/server-key.pem'.format(config_dir)\n opts.add('tlscert', cert_path)\n opts.add('tlscacert', ca_path)\n opts.add('tlskey', key_path)\n opts.add('tlsverify', None)\n render('docker.defaults', '/etc/default/docker', {'opts': opts.to_s()})\n\n\n@when('swarm.available')\n@when_not('client.credentials.placed')\ndef prepare_end_user_package():\n \"\"\" Generate a downloadable package for clients to use to speak to the\n swarm cluster. \"\"\"\n if is_leader():\n client_cert('./swarm_credentials')\n ca('./swarm_credentials')\n\n # Prepare the workspace\n with chdir('./swarm_credentials'):\n rename('client.key', 'key.pem')\n rename('client.crt', 'cert.pem')\n rename('ca.crt', 'ca.pem')\n\n template_vars = {'public_address': unit_get('public-address')}\n\n render('enable.sh', './swarm_credentials/enable.sh', template_vars)\n\n cmd = 'tar cvf swarm_credentials.tar swarm_credentials'\n subprocess.check_call(split(cmd))\n copyfile('swarm_credentials.tar', '/home/ubuntu/swarm_credentials.tar')\n set_state('client.credentials.placed')\n\n\ndef bind_docker_daemon(connection_string):\n status_set('maintenance', 'Configuring Docker for TCP connections')\n opts = DockerOpts()\n private_address = unit_private_ip()\n opts.add('host', 'tcp://{}:2376'.format(private_address))\n opts.add('host', 'unix:///var/run/docker.sock')\n opts.add('cluster-advertise', '{}:2376'.format(private_address))\n opts.add('cluster-store', connection_string, strict=True)\n render('docker.defaults', '/etc/default/docker', {'opts': opts.to_s()})\n service_restart('docker')\n open_port(2376)\n if is_leader():\n open_port(3376)\n","sub_path":"reactive/swarm.py","file_name":"swarm.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"234864930","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\nimport os\nimport shlex\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport time\nfrom typing import Optional\n\nimport eden.thrift\nfrom fb303.ttypes import fb_status\nfrom .find_executables import EDEN_CLI, EDEN_DAEMON\n\n\nclass EdenFS(object):\n '''Manages an instance of the eden fuse server.'''\n\n def __init__(self, eden_dir=None, etc_eden_dir=None, home_dir=None,\n logging_settings=None):\n if eden_dir is None:\n eden_dir = tempfile.mkdtemp(prefix='eden_test.')\n self._eden_dir = eden_dir\n\n self._process = None\n self._etc_eden_dir = etc_eden_dir\n self._home_dir = home_dir\n self._logging_settings = logging_settings\n\n @property\n def eden_dir(self):\n return self._eden_dir\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, tb):\n self.cleanup()\n\n def cleanup(self):\n '''Stop the instance and clean up its temporary directories'''\n self.kill()\n self.cleanup_dirs()\n\n def cleanup_dirs(self):\n '''Remove any temporary dirs we have created.'''\n shutil.rmtree(self._eden_dir, ignore_errors=True)\n\n def kill(self):\n '''Stops and unmounts this instance.'''\n if self._process is None or self._process.returncode is not None:\n return\n self.shutdown()\n\n def _wait_for_healthy(\n self, timeout: float, exclude_pid: Optional[int]=None\n ):\n '''Wait for edenfs to start and report that it is healthy.\n\n Throws an error if it doesn't come up within the specified time.\n\n If exclude_pid, wait until edenfs reports a process ID different than\n the one specified by exclude_pid. This allows us to wait until the\n edenfs process changes when performing graceful restart.\n '''\n deadline = time.time() + timeout\n while time.time() < deadline:\n try:\n with self.get_thrift_client() as client:\n if client.getStatus() == fb_status.ALIVE:\n if exclude_pid is None:\n return\n # Also wait until the PID is different\n pid = client.getPid()\n if pid == exclude_pid:\n print('healthy, but wrong pid (%d)' % exclude_pid,\n file=sys.stderr)\n else:\n return\n except eden.thrift.EdenNotRunningError as ex:\n pass\n\n status = self._process.poll()\n if status is not None:\n if status < 0:\n msg = 'terminated with signal {}'.format(-status)\n else:\n msg = 'exit status {}'.format(status)\n raise Exception('edenfs exited before becoming healthy: ' +\n msg)\n\n time.sleep(0.1)\n raise Exception(\"edenfs didn't start within timeout of %s\" % timeout)\n\n def get_thrift_client(self):\n return eden.thrift.create_thrift_client(self._eden_dir)\n\n def run_cmd(self, command, *args, cwd=None):\n '''\n Run the specified eden command.\n\n Args: The eden command name and any arguments to pass to it.\n Usage example: run_cmd('mount', 'my_eden_client')\n Throws a subprocess.CalledProcessError if eden exits unsuccessfully.\n '''\n cmd = self._get_eden_args(command, *args)\n try:\n completed_process = subprocess.run(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n check=True, cwd=cwd)\n except subprocess.CalledProcessError as ex:\n # Re-raise our own exception type so we can include the error\n # output.\n raise EdenCommandError(ex)\n return completed_process.stdout.decode('utf-8')\n\n def run_unchecked(self, command, *args):\n '''\n Run the specified eden command.\n\n Args: The eden command name and any arguments to pass to it.\n Usage example: run_cmd('mount', 'my_eden_client')\n Returns the process return code.\n '''\n cmd = self._get_eden_args(command, *args)\n return subprocess.call(cmd)\n\n def _get_eden_args(self, command, *args):\n '''Combines the specified eden command args with the appropriate\n defaults.\n\n Args:\n command: the eden command\n *args: extra string arguments to the command\n Returns:\n A list of arguments to run Eden that can be used with\n subprocess.Popen() or subprocess.check_call().\n '''\n cmd = [EDEN_CLI, '--config-dir', self._eden_dir]\n if self._etc_eden_dir:\n cmd += ['--etc-eden-dir', self._etc_eden_dir]\n if self._home_dir:\n cmd += ['--home-dir', self._home_dir]\n cmd.append(command)\n cmd.extend(args)\n return cmd\n\n def start(\n self, timeout: float=30, takeover_from: Optional[int]=None\n ):\n '''\n Run \"eden daemon\" to start the eden daemon.\n '''\n use_gdb = False\n if os.environ.get('EDEN_GDB'):\n use_gdb = True\n # Starting up under GDB takes longer than normal.\n # Allow an extra 90 seconds (for some reason GDB can take a very\n # long time to load symbol information, particularly on dynamically\n # linked builds).\n timeout += 90\n\n takeover = (takeover_from is not None)\n self._spawn(gdb=use_gdb, takeover=takeover)\n\n self._wait_for_healthy(timeout, exclude_pid=takeover_from)\n\n def _spawn(self, gdb=False, takeover=False):\n if self._process is not None:\n raise Exception('cannot start an already-running eden client')\n\n args = self._get_eden_args(\n 'daemon',\n '--daemon-binary', EDEN_DAEMON,\n '--foreground',\n )\n if takeover:\n args.append('--takeover')\n\n # If the EDEN_GDB environment variable is set, run eden inside gdb\n # so a developer can debug crashes\n if os.environ.get('EDEN_GDB'):\n gdb_exit_handler = (\n 'python gdb.events.exited.connect('\n 'lambda event: '\n 'gdb.execute(\"quit\") if getattr(event, \"exit_code\", None) == 0 '\n 'else False'\n ')'\n )\n gdb_args = [\n # Register a handler to exit gdb if the program finishes\n # successfully.\n # Start the program immediately when gdb starts\n '-ex', gdb_exit_handler,\n # Start the program immediately when gdb starts\n '-ex', 'run'\n ]\n args.append('--gdb')\n for arg in gdb_args:\n args.append('--gdb-arg=' + arg)\n\n # Turn up the VLOG level for the fuse server so that errors are logged\n # with an explanation when they bubble up to RequestData::catchErrors\n if self._logging_settings:\n logging_arg = ','.join('%s=%s' % (module, level)\n for module, level in sorted(\n self._logging_settings.items()))\n args.extend(['--', '--logging=' + logging_arg])\n if 'EDEN_DAEMON_ARGS' in os.environ:\n args.extend(shlex.split(os.environ['EDEN_DAEMON_ARGS']))\n\n self._process = subprocess.Popen(args)\n\n def shutdown(self):\n '''\n Run \"eden shutdown\" to stop the eden daemon.\n '''\n self.run_cmd('shutdown')\n return_code = self._process.wait()\n self._process = None\n if return_code != 0:\n raise Exception('eden exited unsuccessfully with status {}'.format(\n return_code))\n\n def graceful_restart(self, timeout=30):\n # Get the process ID of the old edenfs process.\n # Note that this is not necessarily self._process.pid, since the eden\n # CLI may have spawned eden using sudo, and self._process may refer to\n # a sudo parent process.\n with self.get_thrift_client() as client:\n old_pid = client.getPid()\n\n old_process = self._process\n self._process = None\n\n self.start(timeout=timeout, takeover_from=old_pid)\n\n # Check the return code from the old edenfs process\n return_code = old_process.wait()\n if return_code != 0:\n raise Exception('eden exited unsuccessfully with status {}'.format(\n return_code))\n\n def add_repository(self, name, repo_path):\n '''\n Run \"eden repository\" to define a repository configuration\n '''\n self.run_cmd('repository', name, repo_path)\n\n def repository_cmd(self):\n '''\n Executes \"eden repository\" to list the repositories,\n and returns the output as a string.\n '''\n return self.run_cmd('repository')\n\n def list_cmd(self):\n '''\n Executes \"eden list\" to list the client directories,\n and returns the output as a string.\n '''\n return self.run_cmd('list')\n\n def clone(self, repo, path):\n '''\n Run \"eden clone\"\n '''\n # TODO: \"eden clone\" should handle creating the directory.\n if not os.path.isdir(path):\n os.mkdir(path)\n\n self.run_cmd('clone', repo, path)\n\n def unmount(self, path):\n '''\n Run \"eden unmount --destroy \"\n '''\n self.run_cmd('unmount', '--destroy', path)\n\n def in_proc_mounts(self, mount_path):\n '''Gets all eden mounts found in /proc/mounts, and returns\n true if this eden instance exists in list.\n '''\n with open('/proc/mounts', 'r') as f:\n mounts = [line.split(' ')[1] for line in f.readlines()\n if line.split(' ')[0] == 'edenfs']\n return mount_path in mounts\n\n def is_healthy(self):\n '''Executes `eden health` and returns True if it exited with code 0.'''\n return_code = self.run_unchecked('health')\n return return_code == 0\n\n\nclass EdenCommandError(subprocess.CalledProcessError):\n def __init__(self, ex):\n super().__init__(ex.returncode, ex.cmd, output=ex.output,\n stderr=ex.stderr)\n\n def __str__(self):\n return (\"eden command '%s' returned non-zero exit status %d\\n\"\n \"stderr=%s\" % (self.cmd, self.returncode, self.stderr))\n\n\ndef can_run_eden():\n '''\n Determine if we can run eden.\n\n This is used to determine if we should even attempt running the\n integration tests.\n '''\n global _can_run_eden\n if _can_run_eden is None:\n _can_run_eden = _compute_can_run_eden()\n\n return _can_run_eden\n\n\n_can_run_eden = None\n\n\ndef _compute_can_run_eden():\n # FUSE must be available\n if not os.path.exists('/dev/fuse'):\n return False\n\n # We must be able to start eden as root.\n # The daemon must either be setuid root, or we must have sudo priviliges.\n # Typically for the tests the daemon process is not setuid root,\n # so check if we have are able to run things under sudo.\n return _can_run_sudo()\n\n\ndef _can_run_sudo():\n cmd = ['/usr/bin/sudo', '-E', '/bin/true']\n with open('/dev/null', 'r') as dev_null:\n # Close stdout, stderr, and stdin, and call setsid() to make\n # sure we are detached from any controlling terminal. This makes\n # sure that sudo can't prompt for a password if it needs one.\n # sudo will only succeed if it can run with no user input.\n process = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, stdin=dev_null,\n preexec_fn=os.setsid)\n process.communicate()\n return process.returncode == 0\n","sub_path":"eden/integration/lib/edenclient.py","file_name":"edenclient.py","file_ext":"py","file_size_in_byte":12289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"621753145","text":"import os\nimport logging\nimport numpy as np\nfrom PIL import Image\nimport cv2\n\nclass GetCategoryBox:\n \"\"\"Gets the biggest box from given category\"\"\"\n\n def __init__(self, category, img_path):\n self.category = category\n self.img_path = img_path\n\n @staticmethod\n def get_main_box(boxes):\n \"\"\"Returns the biggest box\"\"\"\n if len(boxes) > 1:\n x1 = boxes[:, 0]\n x2 = boxes[:, 1]\n y1 = boxes[:, 2]\n y2 = boxes[:, 3]\n area = (x2 - x1) * (y2 - y1)\n main_box = boxes[np.argmax(area)]\n else:\n main_box = np.squeeze(boxes)\n\n return main_box\n\n def __call__(self, batch_boxes, batch_names):\n main_boxes = []\n images = []\n\n for boxes, name in zip(batch_boxes, batch_names):\n try:\n category_boxes = np.array(boxes[self.category]['boxes'])\n main_box = self.__class__.get_main_box(category_boxes)\n main_boxes.append(main_box)\n images.append(name)\n except KeyError:\n logger = logging.getLogger(__name__)\n logger.error(f\"{name}: {self.category} not found\")\n os.remove(os.path.join(self.img_path, name))\n\n return main_boxes, images\n\n\nclass CropBoxes:\n \"\"\"Saves the bounding box for image\"\"\"\n\n def __init__(self, img_path, cropped_path):\n self.img_path = img_path\n self.cropped_path = cropped_path\n\n def crop_box(self, box, image):\n \"\"\"Crops box from image\"\"\"\n img = Image.open(os.path.join(self.img_path, image))\n xmin, xmax, ymin, ymax = box\n cropped_box = img.crop((xmin, ymin, xmax, ymax))\n\n return cropped_box\n\n def __call__(self, boxes, images):\n for box, image in zip(boxes, images):\n cropped_box = self.crop_box(box, image)\n cropped_box.save(os.path.join(self.cropped_path, image))\n\n\nclass GetCategoryMask:\n \"\"\"Gets the biggest mask from given category\"\"\"\n\n def __init__(self, category, img_path):\n self.category = category\n self.img_path = img_path\n\n @staticmethod\n def get_main_segment(segments):\n \"\"\"Returns the biggest mask\"\"\"\n masks = segments['masks']\n boxes = np.array(segments['boxes'])\n\n if len(boxes) > 1:\n x1 = boxes[:, 0]\n x2 = boxes[:, 1]\n y1 = boxes[:, 2]\n y2 = boxes[:, 3]\n area = (x2 - x1) * (y2 - y1)\n main_mask = masks[np.argmax(area)]\n main_box = boxes[np.argmax(area)]\n else:\n main_mask = np.squeeze(masks)\n main_box = np.squeeze(boxes)\n\n return main_mask, main_box\n\n def __call__(self, batch_segments, batch_images, batch_names):\n main_masks = []\n main_boxes = []\n image_names = []\n\n for segments, image, name in zip(batch_segments, batch_images, batch_names):\n try:\n main_mask, main_box = self.__class__.get_main_segment(segments[self.category])\n main_mask = np.dstack([main_mask]*3)\n main_mask = np.multiply(image, main_mask)\n main_masks.append(main_mask)\n main_boxes.append(main_box)\n image_names.append(name)\n except KeyError:\n logger = logging.getLogger(__name__)\n logger.error(f\"{name}: {self.category} not found\")\n os.remove(os.path.join(self.img_path, name))\n\n return main_masks, main_boxes, image_names\n\n\nclass CropMasks:\n \"\"\"Saves the mask for image\"\"\"\n\n def __init__(self, cropped_path):\n self.cropped_path = cropped_path\n\n @staticmethod\n def crop_mask(mask, box):\n mask = cv2.cvtColor(mask.astype(np.uint8), cv2.COLOR_RGB2BGR)\n mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB)\n img = Image.fromarray(mask)\n xmin, xmax, ymin, ymax = box\n cropped_image = img.crop((xmin, ymin, xmax, ymax))\n\n return cropped_image\n\n def __call__(self, main_masks, main_boxes, image_names):\n for mask, box, image in zip(main_masks, main_boxes, image_names):\n cropped_mask = self.__class__.crop_mask(mask, box)\n cropped_mask.save(os.path.join(self.cropped_path, image))\n","sub_path":"master_thesis/transformations/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"559650334","text":"# Create your views here.\n# coding=utf-8\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.http import HttpResponseRedirect\nfrom django.template.response import TemplateResponse\nfrom portal.models import AfGlobalconf,AfIncidencia,AfEstadosIncidencia, \\\nAfNotasIncidencia,AfMailServer,AfUserNotify, AfTipoNotify, AfNotify_Tipo_instancia\nfrom django.http import JsonResponse\nfrom portal.Utils.decorators import *\nfrom portal.Utils.aux_meth import *\nfrom portal.Utils.logger import *\nfrom django.contrib import messages\nfrom portal.Incidencias.forms import IncidenciasForm,AfNotasIncidenciaForm\nfrom django.core.mail import BadHeaderError, send_mail\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import get_template\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom portal.Common.CustomMailBackEnd import CustomMailBackEnd\nimport datetime\n\nlogger=getLogger()\n\n\ndef getIncidenciasInfo(incidencias):\n\n list_it_estados=[]\n notas_asociadas = []\n for it in incidencias:\n\n notas_asociadas= AfNotasIncidencia.objects.filter(incidencia=it).order_by('fecha_creacion')\n estado= it.estado.estado if it.estado else 'No definido'\n \n list_it_estados.append({'incidencias' : it, 'estado_name' : estado,\n 'notas_asociadas' : notas_asociadas})\n notas_asociadas=[]\n\n return list_it_estados\n\n\n@login_required\ndef getItDetails(request, id, template_name='detalles_incidencia.html', notify_id=False):\n\n try:\n it= AfIncidencia.objects.get(id=id)\n incidencia_instance= [it]\n instancias_info= getIncidenciasInfo(incidencia_instance) # definido en aux_meth\n response=TemplateResponse(request, template_name, {'incidencias_info': instancias_info }).rendered_content\n\n data={'action': 'detalles_incidencia', 'html':response, 'available_info': len(instancias_info)}\n\n # flag que indica que la consulta viene hecha de la vista de notificaciones\n if notify_id:\n user_notify=AfUserNotify.objects.get(id=notify_id)\n if not user_notify.readed:\n user_notify.readed= True\n user_notify.save()\n \n except ObjectDoesNotExist as dne:\n\n messages.error(request, \"La incidencia sobre la que se solicita información no existe\")\n return HttpResponseRedirect('/administrar/proyectos')\n\n except Exception as e:\n #messages.success(request, 'Proyecto editado con éxito', extra_tags='Edición de proyecto')\n pass\n \n return JsonResponse({'data':data})\n\n\n\n@login_required\n@group_required('af_cloud_admin',)\ndef administrarIncidencias(request, template_name='incidenciasIndex.html', extra_context=None):\n try:\n\n af_user=AfUsuario.objects.get(user=request.user)\n if af_user.usu_administrador:\n incidencias = AfIncidencia.objects.all().order_by('fecha_apertura')\n else:\n incidencias = AfIncidencia.objects.filter(usu=af_user).order_by('fecha_apertura')\n\n except Exception as e:\n logger.info(\"Exception en administrarIncidencias: %s\" % format(e))\n\n list_it_estados = getIncidenciasInfo(incidencias)\n hasNotificationPending(request)\n paginator = Paginator(list_it_estados, 10)\n\n try:\n number = int(request.GET.get('page', '1'))\n except PageNotAnInteger:\n number = paginator.page(1)\n except EmptyPage:\n number = paginator.page(paginator.num_pages)\n c = paginator.page(number)\n context = {'p': c }\n return TemplateResponse(request, template_name, context)\n\n'''\n EmailMultiAlternatives (self, subject='', body='', from_email=None, to=None, bcc=None,\n connection=None, attachments=None, headers=None, alternatives=None,\n cc=None, reply_to=None):\n'''\ndef send_notify_mail(kwargs):\n\n asunto = kwargs.get ('asunto',\"default value\")\n cuerpo = kwargs.get ('cuerpo',\"default value\")\n estado = kwargs.get ('estado',\"Abierta\")\n from_mail = kwargs.get ('from_mail')\n to_email = kwargs.get ('to_email')\n\n cmbe= CustomMailBackEnd()\n conx= cmbe.get_connection()\n template =kwargs.get ('template',None)\n\n if template:\n htmly = get_template (template + \".html\")\n plaintext = get_template (template + \".txt\")\n else:\n htmly = get_template ('mail_incidencia.html')\n plaintext = get_template ('mail_incidencia.txt')\n\n d = { 'username': ('%s %s (%s)') % (from_mail.user.first_name,from_mail.user.first_name,from_mail.user.username) , \n 'contenido' :cuerpo, 'fecha': datetime.datetime.now(), 'estado': estado}\n\n text_content = plaintext.render(d)\n html_content = htmly.render(d)\n msg = EmailMultiAlternatives(asunto, text_content, from_mail.user.email, to_email, connection=conx)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n\n\ndef create_UserNotify(kwargs):\n\n to_user = kwargs.get ('to_user' , None)\n m_from = kwargs.get ('from_mail' , None)\n tipo_notify = kwargs.get ('tipo_notificacion' , None)\n incidencia = kwargs.get ('incidencia' , None)\n user_notify = kwargs.get ('user_notify' , None)\n\n if isinstance(to_user,list):\n for user in to_user:\n notify = AfUserNotify.objects.create(owner= user, to_user=user, from_user=m_from, fecha_creacion=datetime.datetime.now())\n n_tipo = AfTipoNotify.objects.get(short_desc=tipo_notify)\n n_t_i = AfNotify_Tipo_instancia.objects.create(notify=notify, tipo=n_tipo, incidencia=incidencia)\n \n \n@login_required\n@group_required('af_cloud_admin',)\ndef crearIncidencia(request, template_name='incidencias.html', extra_context=None):\n\n if request.method == \"POST\":\n\n form = IncidenciasForm(request.POST)\n\n if form.is_valid():\n\n try:\n\n asunto = form.cleaned_data['asunto']\n cuerpo = form.cleaned_data['cuerpo']\n af_user = AfUsuario.objects.get (user=request.user)\n gconf = AfGlobalconf.objects.first()\n to_email = gconf.email\n\n dict_mail={'asunto': asunto, 'cuerpo': cuerpo, 'from_mail': af_user, 'to_email':to_email,\n 'estado': 'Abierta', 'to_email' : [to_email], 'tipo_notificacion' : \"ITC\" }\n # configuracion de correo realizada ?\n mail_conf=AfMailServer.objects.count()\n if mail_conf:\n send_notify_mail (dict_mail)\n\n\n incidencia = AfIncidencia.objects.create(usu=af_user, asunto=asunto, cuerpo=cuerpo)\n estado = AfEstadosIncidencia.objects.get(estado='Abierta')\n incidencia.estado = estado\n incidencia.save()\n \n to_users=AfUsuario.objects.filter(usu_administrador=True)\n dict_mail.update({'to_user': list(to_users), 'incidencia': incidencia})\n \n create_UserNotify(dict_mail)\n \n except BadHeaderError:\n return HttpResponse('Invalid header found.')\n\n except Exception as e:\n print (\"exception sending mail : %s\" % format(e))\n\n messages.success(request, 'Incidencia registrada con éxito' , extra_tags='Creación de incidencia')\n return HttpResponseRedirect('/administrar/incidencias')\n else:\n return render(request, template_name, {'form': form})\n else:\n\n form = IncidenciasForm()\n return render(request, template_name, {'form': form})\n\n\ndef getToMail_NotifyTo (from_user,instance):\n \n lst_to_mail=[]\n notify_to= None\n \n if from_user.usu_administrador:\n notify_to= [instance.usu]\n lst_to_mail.append(instance.usu.user.email)\n else:\n msg_to= AfUsuario.objects.filter(usu_administrador=True)\n lst_to_mail= [u.user.email for u in msg_to]\n notify_to=list(msg_to)\n \n return notify_to, lst_to_mail\n \n@login_required\n@group_required(None)\ndef addNotaIncidencia(request, id, template_name='editarIncidencia.html'):\n \n try:\n instance = AfIncidencia.objects.get(id=id)\n from_user = AfUsuario.objects.get(user=request.user)\n estado_read_only = not from_user.usu_administrador\n \n if request.method == 'POST':\n\n form = AfNotasIncidenciaForm(request.POST or None, initial={'instance': instance, 'status_ro': estado_read_only})\n\n if form.is_valid():\n\n asunto = form.cleaned_data['asunto']\n cuerpo = form.cleaned_data['notas']\n estado = form.cleaned_data['estado'] if form.cleaned_data['estado'] else instance.estado\n instance.estado = estado\n nota = AfNotasIncidencia.objects.create (autor=from_user, incidencia=instance,notas=cuerpo, asunto=asunto)\n instance.fecha_updated=nota.fecha_creacion\n instance.save()\n # si el usuario q add la nota es el administrador, el receptor es el \"iniciador\" de la incidencia\n # notify_to , lista de afusuarios, lst_mail; lista de correos\n notify_to, lst_to_mail = getToMail_NotifyTo(from_user, instance) \n \n tipo_notificacion=AfTipoNotify.objects.get(short_desc='ITM')\n \n dict_notify={\n 'instance' : instance, \n 'from_user': from_user,\n 'notify_to': notify_to,\n 'tipo_notificacion': tipo_notificacion \n }\n deliverNotify(dict_notify)\n\n dict_mail={\n 'asunto' : asunto, 'cuerpo' : cuerpo, 'from_mail' : from_user,\n 'to_email' : lst_to_mail, 'estado' : estado.estado , 'template' : 'nota_incidencia',\n 'tipo_notificacion' :'ITM' , 'incidencia' : instance, 'to_users': notify_to\n }\n \n mail_conf=AfMailServer.objects.count()\n if mail_conf:\n send_notify_mail (dict_mail)\n\n messages.success(request, 'Nota añadida con éxito', extra_tags='Actuación en incidencia')\n return HttpResponseRedirect('/administrar/incidencias')\n\n form = AfNotasIncidenciaForm(initial={'instance': instance, 'status_ro': estado_read_only})\n return render(request, template_name, {'form': form, 'id': instance.id })\n\n except ObjectDoesNotExist as dne:\n messages.error(request, \"La incidencia solicitada no existe\")\n pass\n\n except Exception as ex:\n messages.error(request, \"Uhmmm... %s\" % (format(ex)))\n pass\n\n return HttpResponseRedirect('/administrar/incidencias')\n\ndef deliverNotify(kwargs):\n \n tipo_notificacion = kwargs.get ('tipo_notificacion' , None)\n instance = kwargs.get ('instance' , None)\n notify_to = kwargs.get ('notify_to' , None)\n from_user = kwargs.get ('from_user' , None)\n \n \n ids_notify_incidencia= list(AfNotify_Tipo_instancia.objects.filter(incidencia= instance).values_list('notify', flat=True))\n \n for u in notify_to:\n has_notify_asociada=AfUserNotify.objects.filter(owner=u, id__in=ids_notify_incidencia).count()\n if has_notify_asociada:\n \n notify = AfUserNotify.objects.get(owner=u, id__in=ids_notify_incidencia)\n notify.to_user = u\n notify.from_user = from_user\n notify.readed = False\n notify.fecha_creacion = instance.fecha_updated\n notify.save()\n \n noti_tipo_instancia = AfNotify_Tipo_instancia.objects.get(notify=notify, incidencia=instance)\n noti_tipo_instancia.tipo=tipo_notificacion\n noti_tipo_instancia.save()\n else:\n notify = AfUserNotify.objects.create(owner= u, to_user=u, from_user=from_user, fecha_creacion=datetime.datetime.now())\n n_t_i = AfNotify_Tipo_instancia.objects.create(notify=notify, tipo=tipo_notificacion, incidencia=instance)\n \n \n\n@login_required\n@group_required('af_cloud_admin',)\ndef eliminarIncidencia(request, id):\n \n try:\n \n incidencia= AfIncidencia.objects.filter(id=id)\n incidencia.delete()\n \n except ObjectDoesNotExist as dne:\n\n messages.error(request, \"La incidencia que solicita eliminar no existe\")\n return HttpResponseRedirect('/administrar/incidencias')\n\n except Exception as e:\n pass\n \n messages.success(request, 'Incidencia eliminada con éxito', extra_tags='Eliminación de incidencias')\n return HttpResponseRedirect('/administrar/incidencias')\n\n ","sub_path":"portal/Incidencias/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"196426910","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 26 10:28:54 2021\n\n@author: woojae-macbook13\n\"\"\"\n\nfrom pandas import*\nimport pandas as pd\nimport numpy as np\n\n\n# path = \".\\\\\"\nfilename = \"pr1.xlsx\"\n\n# dataset = pd.read_excel(path+filename)\ndataset = pd.read_excel(filename)\norder = \"고객\"\nitemcode = \"itemcode\"\nqty = \"quantity\"\n\norderSet = Series(dataset[order].drop_duplicates().sort_values().values)\nitemSet = Series(dataset[itemcode].drop_duplicates().sort_values().values)\n\nnOrders = len(orderSet)\nnItem = len(itemSet)\n\norderitemSetVector = {}\norderSetQtyVector = {}\n\n\n\n#주문(key) : [아이템벡터] (value)dictionary 생성 (루프)\nfor i in orderSet :\n \n # 각 주문에 대한 아이템 수 크기의 0벡터 생성: one-zero 벡터 용\n tempOZvector = np.zeros(len(itemSet))\n # 각 주문에 대한 아이템 수 크기의 0벡터 생성: 수량 벡터 용\n tempQtyVector = np.zeros(len(itemSet))\n # 고객 번호가 i 인 주문이 포함하는 아이템 목록\n tempItemList = dataset[dataset[order] == i][itemcode]\n # 고객 번호가 i 인 주문이 포함하는 아이템 목록\n tempQtyList = dataset[dataset[order] == i][qty]\n \n #각 고객이 포함한 아이템에 대하여 반복\n for j in range(len(tempItemList)) :\n # 고객 번호가 i 인 주문이 포함하는 아이템을 하나씩 가져옴. \n tempItem = tempItemList.iloc[j]\n # 현재 선택된 아이템의 위치(행번호)를 가져옴 \n tempItemIndex = itemSet[itemSet == tempItem].index[0]\n # 각 주문에 대한 ONE-ZERO 벡터를 생성: 아이템 수량 > 0 ==> 1, otherwise 0 \n # 해당 아이템을 가지므로 1을 assign 함 \n tempOZvector[tempItemIndex] = 1\n # item벡터와 같은위치에 1,0 대신 수량을 assign함\n # 각 주문에 대한 수량 벡터를 생성 \n tempQtyVector[tempItemIndex] = tempQtyList.iloc[j]\n \n orderitemSetVector[i] = tempOZvector\n orderSetQtyVector[i] = tempQtyVector\n \n# 결과 확인\ndfOrderItemVector = DataFrame(orderitemSetVector).T\ndfOrderQtyVector = DataFrame(orderSetQtyVector).T\n\n\n\n# 유사성 계산 함수 만들기\ndef calSimilarity(v1, v2) :\n inner_sum = 0\n size1 = 0.0\n size2 = 0.0\n \n for i in range(nItem) :\n size1 += v1[i]*v1[i]\n size2 += v2[i]*v2[i]\n inner_sum += v1[i]*v2[i]\n \n return inner_sum/(size1**(1/2)*size2**(1/2))\n\n\n\n# 작업 1 : 모든 사용자 조합간 유사성 지표 계산\nsetSimilarity = {}\n\nfor i in orderSet :\n tempSim = np.zeros(nOrders)\n \n k = 0\n for j in orderSet :\n if i != j :\n tempSim[k] = calSimilarity(dfOrderItemVector.T[i], dfOrderItemVector.T[j])\n \n k += 1\n \n setSimilarity[i] = tempSim\n \ndfSimilarity = DataFrame(setSimilarity)\n\n\n\n# 작업 2 : 각 사용자와 가장 유사한 사용자 선정\nsimilarone = np.zeros(nOrders)\n\nk = 0\nfor i in orderSet :\n idx = 0\n value = 0.0\n for j in range(nOrders) :\n if dfSimilarity[i][j] > value :\n idx = j\n value = dfSimilarity[i][j]\n \n similarone[k] = idx\n \n k += 1\n \n print(\"user %d -> idx : %d\" %(i, orderSet[idx]))\n \nprint()\n\n\n\n# 작업 3 : 유사한 사용자가 구매했으나 기준 사용는 구매하지 않은 아이템\n\nfor i in range(nOrders) :\n idx = similarone[i]\n for j in range(nItem) :\n if dfOrderItemVector.T[orderSet[i]][j] == 0 and dfOrderItemVector.T[orderSet[idx]][j] != 0 :\n print(\"We recommend this item %d for user %d\" %(j, i+1))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"13_week/pr12_1 .py","file_name":"pr12_1 .py","file_ext":"py","file_size_in_byte":3619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"444677247","text":"#!/bin/python3\n\nimport os\nimport sys\n\n\ndef getTotalX(a, b):\n results = 0\n for x in range(max(a), min(b) + 1):\n divideA = [x % j != 0 for j in a]\n divideB = [j % x != 0 for j in b]\n\n if sum(divideA) == 0 and sum(divideB) == 0:\n results += 1\n\n return results\n\n\nif __name__ == '__main__':\n f = open(os.environ['OUTPUT_PATH'], 'w')\n\n nm = input().split()\n\n n = int(nm[0])\n\n m = int(nm[1])\n\n a = list(map(int, input().rstrip().split()))\n\n b = list(map(int, input().rstrip().split()))\n\n total = getTotalX(a, b)\n\n f.write(str(total) + '\\n')\n\n f.close()\n","sub_path":"Algorithms/Implementation/between-two-sets.py","file_name":"between-two-sets.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"164684300","text":"# -*- coding:utf-8 -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\nSTOP_RENDERING = runtime.STOP_RENDERING\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1574208765.627848\n_enable_loop = True\n_template_filename = '/Users/dwim/Developer/AlejandroTurboGears/Python/myproject/myproject/templates/index.mak'\n_template_uri = '/Users/dwim/Developer/AlejandroTurboGears/Python/myproject/myproject/templates/index.mak'\n_source_encoding = 'utf-8'\nfrom markupsafe import escape_silent as escape\n_exports = ['title']\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n pass\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'local:templates.master', _template_uri)\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n h = context.get('h', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\n\\n')\n __M_writer('\\n
    \\n\\n
    \\n
    \\n

    Code your data model

    \\n

    Design your data model, Create the database, and Add some bootstrap data.

    \\n
    \\n\\n
    \\n

    Design your URL architecture

    \\n

    Decide your URLs, Program your controller methods, Design your\\n templates, and place some static files (CSS and/or Javascript).

    \\n
    \\n\\n
    \\n

    Distribute your app

    \\n

    Test your source, Generate project documents, Build a distribution.

    \\n
    \\n
    \\n\\n Thank you for choosing TurboGears.\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_title(context):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_writer = context.writer()\n __M_writer('\\n Welcome to TurboGears 2.4, standing on the shoulders of giants, since 2007\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"filename\": \"/Users/dwim/Developer/AlejandroTurboGears/Python/myproject/myproject/templates/index.mak\", \"uri\": \"/Users/dwim/Developer/AlejandroTurboGears/Python/myproject/myproject/templates/index.mak\", \"source_encoding\": \"utf-8\", \"line_map\": {\"28\": 0, \"34\": 1, \"35\": 5, \"36\": 14, \"37\": 14, \"38\": 20, \"39\": 20, \"40\": 22, \"41\": 22, \"42\": 24, \"43\": 24, \"44\": 26, \"45\": 26, \"46\": 28, \"47\": 28, \"53\": 3, \"57\": 3, \"63\": 57}}\n__M_END_METADATA\n\"\"\"\n","sub_path":"Python/myproject/data/templates/Users/dwim/Developer/AlejandroTurboGears/Python/myproject/myproject/templates/index.mak.py","file_name":"index.mak.py","file_ext":"py","file_size_in_byte":4680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"477213555","text":"__author__ = 'katherineford'\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n # ex: /flossy/\n url(r'^$', views.index, name='index'),\n # ex: flossy/getfloss/\n url(r'^getfloss/', views.get_floss, name='getfloss'),\n # ex: flossy/makepattern/\n url(r'^makepattern/', views.make_pattern, name='makepattern'),\n url(r'^dobusiness/', views.do_business, name='dobusiness'),\n]\n","sub_path":"bitstitch/flossy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"193519141","text":"#!/usr/bin/env python\n# coding = utf-8\n\nimport sys\nfrom PyQt4 import QtGui, QtCore\n\nclass CLineEdit(QtGui.QWidget):\n\t\"\"\"docstring for CLineEdit\"\"\"\n\tdef __init__(self):\n\t\tsuper(CLineEdit, self).__init__()\n\t\tself.initUI()\n\n\tdef initUI(self):\n\t\tself.lbl = QtGui.QLabel(self)\n\t\tqle = QtGui.QLineEdit(self)\n\n\t\tqle.move(60, 100)\n\t\tself.lbl.move(60, 40)\n\n\t\tqle.textChanged[str].connect(self.onChanged)\n\n\t\tself.setGeometry(300, 300, 300, 170)\n\t\tself.setWindowTitle('QtGui.QLineEdit')\n\t\tself.show()\n\n\tdef onChanged(self, text):\n\t\tself.lbl.setText(text)\n\t\tself.lbl.adjustSize()\n\ndef main():\n\tapp = QtGui.QApplication(sys.argv)\n\tex = CLineEdit()\n\tsys.exit(app.exec_())\n\t\n\nif __name__ == '__main__':\n\tmain()","sub_path":"GUI/test/lineEdit.py","file_name":"lineEdit.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"211848604","text":"import logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_all(isamAppliance, check_mode=False, force=False):\n \"\"\"\n Retrieving the complete list of SCIM configuration settings\n \"\"\"\n return isamAppliance.invoke_get(\"Retrieving the complete list of SCIM configuration settings\",\n \"/mga/scim/configuration\")\n\n\ndef get_user_profile(isamAppliance, check_mode=False, force=False):\n \"\"\"\n Retrieve configuration of SCIM user profile settings\n \"\"\"\n ret_obj = isamAppliance.invoke_get(\"Retrieve configuration of SCIM user profile settings\",\n \"/mga/scim/configuration/urn:ietf:params:scim:schemas:core:2.0:User\")\n return ret_obj['data']['urn:ietf:params:scim:schemas:core:2.0:User']\n\n\ndef get_isam_user(isamAppliance, check_mode=False, force=False):\n \"\"\"\n Retrieve configuration of SCIM ISAM user settings\n \"\"\"\n ret_obj = isamAppliance.invoke_get(\"Retrieve configuration of SCIM ISAM user settings\",\n \"/mga/scim/configuration/urn:ietf:params:scim:schemas:extension:isam:1.0:User\")\n return ret_obj['data']['urn:ietf:params:scim:schemas:extension:isam:1.0:User']\n\n\ndef update_user_profile(isamAppliance, ldap_connection, user_suffix, search_suffix, check_mode=False, force=False):\n \"\"\"\n Update SCIM user profile settings\n \"\"\"\n ret_obj = get_user_profile(isamAppliance)\n del ret_obj['ldap_connection']\n del ret_obj['user_suffix']\n del ret_obj['search_suffix']\n\n ret_obj['ldap_connection'] = ldap_connection\n ret_obj['user_suffix'] = user_suffix\n ret_obj['search_suffix'] = search_suffix\n return isamAppliance.invoke_put(\n \"Update SCIM user profile settings\",\n \"/mga/scim/configuration/urn:ietf:params:scim:schemas:core:2.0:User\",\n ret_obj)\n\n\ndef update_isam_user(isamAppliance, isam_domain, update_native_users, ldap_connection, check_mode=False, force=False):\n \"\"\"\n Update SCIM ISAM user settings\n \"\"\"\n ret_obj = get_isam_user(isamAppliance)\n del ret_obj['isam_domain']\n del ret_obj['update_native_users']\n del ret_obj['ldap_connection']\n\n ret_obj['isam_domain'] = isam_domain\n ret_obj['update_native_users'] = update_native_users\n ret_obj['ldap_connection'] = ldap_connection\n return isamAppliance.invoke_put(\n \"Update SCIM ISAM user settings\",\n \"/mga/scim/configuration/urn:ietf:params:scim:schemas:extension:isam:1.0:User\",\n ret_obj)\n","sub_path":"ibmsecurity/isam/aac/scim.py","file_name":"scim.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"314149544","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^add/$', views.add, name='add'),\n url(r'^display/$', views.display, name='display'),\n url(r'^edit/(?P\\d+)/$', views.edit, name='edit'),\n]\n","sub_path":"info/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"355663476","text":"from collections import defaultdict\nimport pandas as pd\n\nin_scanner = 'Scanner is in the cradle'\nout_scanner = 'Scanner is out of the cradle'\ndecode_check = 'usbt:send_decode'\n\ninput_file_name = 'lane5_LOG_20181020 (1).log'\noutput_file_name = 'output'\nencoding = 'ANSI'\nminimum_time = 1\nmaximum_time = 600\n\ncheck = 0\ntimestamp = defaultdict()\ndata = defaultdict(list)\n\nstart, stop = False, False\nwith open(input_file_name, encoding=encoding) as f:\n for line in f.readlines():\n line = line.strip()\n if in_scanner in line or out_scanner in line:\n print(line)\n t = line.split()[0]\n t = [i for i in t if i.isdigit()]\n t = ''.join(t)\n if len(t) == 16:\n t = t[1:]\n print(t)\n timestamp['Year'] = t[:2]\n timestamp['Month'] = t[2:4]\n timestamp['Day'] = t[4:6]\n timestamp['Hour'] = t[6:8]\n timestamp['Minute'] = t[8:10]\n timestamp['Second'] = t[10:12]\n timestamp['Millisecond'] = t[12:]\n print(timestamp)\n if in_scanner in line:\n if start:\n data['in'][-1] = t\n data['Number of Scans'][-1] = check\n else:\n data['in'].append(t)\n data['Number of Scans'].append(check)\n start, stop, check = True, False, 0\n elif start:\n start, stop = False, True\n data['out'].append(t)\n \n elif decode_check in line and stop:\n check += 1\n\ndata['Number of Scans'] = data['Number of Scans'][1:]\ndf = pd.DataFrame()\nfor k,v in data.items():\n df[k] = pd.Series(v)\nfor k in ['in', 'out']:\n df[k] = pd.to_datetime(df[k], format='%y%m%d%H%M%S%f')\n\ndf['Time In Cradle Timestamp'] = df['in']\ndf['Time In Cradle Duration'] = (df['out'] - df['in']).dt.total_seconds()\ndf['Time Out Cradle Duration'] = 0\nfor index in range(len(df)):\n try:\n del_time = df['in'].iloc[index + 1] - df['out'].iloc[index]\n df['Time Out Cradle Duration'].iloc[index] = del_time.total_seconds()\n except Exception as e:\n pass\ndf['Time Out Cradle Timestamp'] = df['out']\n\ndf = df.drop(['in', 'out'], axis=1)\ndf = df[['Time In Cradle Timestamp', 'Time In Cradle Duration', 'Time Out Cradle Timestamp', 'Time Out Cradle Duration', 'Number of Scans']]\n\n# df = df[df['Number of Scans'] != 0]\n# for k in ['Time In Cradle Duration', 'Time Out Cradle Duration']:\n# df = df[df[k] < maximum_time]\n# df = df[df[k] > minimum_time]\ndf.to_excel(output_file_name + '.xlsx', index=False)\n\n\n","sub_path":"log-to-excel-nofilter.py","file_name":"log-to-excel-nofilter.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"569107113","text":"from selenium.common.exceptions import StaleElementReferenceException\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nfrom ui.locators.b_locators import BasePageLocators\n\nRETRY_COUNT = 300\n\nclass BasePage(object):\n locators = BasePageLocators()\n\n def __init__(self, driver):\n self.driver = driver\n\n def wait(self, timeout=None):\n if timeout is None:\n timeout = 6\n return WebDriverWait(self.driver, timeout=timeout)\n\n def find(self, locator, timeout=None):\n return self.wait(timeout).until(\n EC.presence_of_element_located(locator)\n )\n\n def find_all(self, locator, timeout=None):\n return self.wait(timeout).until(\n EC.presence_of_all_elements_located(locator)\n )\n\n def click(self, locator, timeout=None):\n for i in range(RETRY_COUNT):\n try:\n self.find(locator)\n element = self.wait(timeout).until(\n EC.element_to_be_clickable(locator)\n )\n # self.scroll_to_element(element)\n element.click()\n return\n except StaleElementReferenceException:\n if i < RETRY_COUNT - 1:\n pass\n raise\n\n def scroll_to_element(self, element):\n self.driver.execute_script(\n 'arguments[0].scrollIntoView(true);',\n element\n )\n\n def move_to_element(self, locator):\n mv_to = self.find(locator)\n ActionChains(self.driver).move_to_element(mv_to).perform()\n","sub_path":"code/ui/pages/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":1676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"604700742","text":"import boto3\nimport json\n\ndef lambda_handler(event, context):\n db = boto3.resource('dynamodb')\n eventsTable = db.Table('potluck_events')\n \n eventItem = eventsTable.get_item(\n Key={\n \"id\":event['id']\n })\n if \"Item\" in eventItem:\n return eventItem['Item']\n else:\n return \"Event with this ID does not exist\"","sub_path":"lambdaFunctions/getEvent.py","file_name":"getEvent.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"167098372","text":"from zope import component\n\nfrom zope.event import notify\nfrom zope.lifecycleevent import ObjectModifiedEvent, Attributes\nfrom zope.app.container.contained import dispatchToSublocations\n\nfrom interfaces import IDispatcher\nfrom interfaces import IIndexable\n\ndef objectAdded(ev):\n obj = ev.object\n if not IIndexable.providedBy(obj):\n return\n \n indexer = component.getUtility(IDispatcher)\n indexer.index(obj)\n\ndef objectModified(ev):\n obj = ev.object\n if not IIndexable.providedBy(obj):\n return\n\n indexer = component.getUtility(IDispatcher)\n \n if ev.descriptions: # not used by archetypes/plone atm...\n # build the list of to be updated attributes\n attrs = []\n for desc in ev.descriptions:\n if isinstance(desc, Attributes):\n attrs.extend(desc.attributes)\n indexer.reindex(obj, attrs)\n if 'allow' in attrs: # dispatch to sublocations on security changes\n dispatchToSublocations(obj, ev)\n else:\n # with no descriptions (of changed attributes) just reindex all\n indexer.reindex(obj)\n\ndef objectCopied(ev):\n objectAdded(ev)\n\ndef objectRemoved(ev):\n obj = ev.object\n if not IIndexable.providedBy(obj):\n return\n\n indexer = component.getUtility(IDispatcher)\n indexer.unindex(obj)\n\ndef objectMoved(ev):\n obj = ev.object\n if not IIndexable.providedBy(obj):\n return\n\n if ev.newParent is None or ev.oldParent is None:\n # it's an IObjectRemovedEvent or IObjectAddedEvent\n return\n\n if ev.newParent is ev.oldParent:\n # it's a renaming operation\n dispatchToSublocations(obj, ev)\n \n indexer = component.getUtility(IDispatcher)\n indexer.reindex(obj)\n","sub_path":"z3c.indexing.dispatch/trunk/src/z3c/indexing/dispatch/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"218337000","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"滑动窗口最大值\"\"\"\n\nimport heapq\nimport collections\n\n\nclass Solution:\n # heap实现\n def maxSlidingWindow(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n cnt, heap, res = collections.Counter(), [], []\n for i, num in enumerate(nums):\n heapq.heappush(heap, -num)\n cnt[num] += 1\n while not cnt[-heap[0]]:\n heapq.heappop(heap)\n if i >= k - 1:\n res.append(-heap[0])\n cnt[nums[i - k + 1]] -= 1\n return res\n\n # deque实现\n def maxSlidingWindow_1(self, nums, k):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :rtype: List[int]\n \"\"\"\n if not nums:\n return []\n deque, res = collections.deque(), []\n for i, num in enumerate(nums):\n if i >= k and i-k >= deque[0]:\n deque.popleft()\n while deque and nums[deque[-1]] <= num:\n deque.pop()\n deque.append(i)\n if i >= k-1:\n res.append(nums[deque[0]])\n return res\n","sub_path":"leetcode/leetcode_239.py","file_name":"leetcode_239.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"75549046","text":"# -*- coding: utf-8 -*-\nimport datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Adding field 'Product.search_index'\n db.add_column(u'products_product', 'search_index',\n self.gf('djorm_pgfulltext.fields.VectorField')(default='', null=True, db_index=True),\n keep_default=False)\n\n\n def backwards(self, orm):\n # Deleting field 'Product.search_index'\n db.delete_column(u'products_product', 'search_index')\n\n\n models = {\n u'products.product': {\n 'Meta': {'object_name': 'Product'},\n 'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),\n 'height': ('django.db.models.fields.PositiveSmallIntegerField', [], {}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'latin_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),\n 'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),\n 'search_index': ('djorm_pgfulltext.fields.VectorField', [], {'default': \"''\", 'null': 'True', 'db_index': 'True'})\n }\n }\n\n complete_apps = ['products']","sub_path":"bakkerweb/products/migrations/0003_auto__add_field_product_search_index.py","file_name":"0003_auto__add_field_product_search_index.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"591144399","text":"# Problem 3\n\n# We need to find the largest prime factor of the number\n# n = 600851475143\n# Therefore a primality test is needed as well.\n# Let's be witty, a prime factor of a number n does not go beyond\n# the square root of n. So all prime factors of a given number n are\n# less than its square root.\n# We're going to use that to our advantage.\n# Since we now know the prime's factors threshold, we can start from\n# there down to a the number we're seeking. There's no need for us\n# to test all prime factors starting from 2.\n\n# Let's try and make an isPrime function. I'll try my best\n# to optimize its perfomance.\n\nfrom math import sqrt\nfrom time import perf_counter\nStart = perf_counter()\n\ndef isPrime(n):\n if n < 2: return False\n if n == 2: return True\n if n % 2 == 0: return False # Every even number except 2 is not prime\n divis = 3\n # We'll start from 3 to the threshold by a step of 2, to avoid even numbers\n # divis < sqrt(n) ::: divis² < n\n # This way we avoid using the sqrt function and the rounding process.\n while divis * divis < n:\n if n % divis == 0:\n return False\n divis += 2\n return True\n\nn = 600851475143\nthreshold = int(sqrt(n))\n\n# We'll start counting down from threshold, but it's more efficient to avoid even numbers\n# like we did in isPrime. If the calculated threshold is even, we add 1 then do our\n# tests while decrementing the threshold by a step of 2, otherwise we leave it as it is.\n\nif threshold % 2 == 0: threshold += 1\n\nwhile n % threshold != 0 and not isPrime(threshold):\n threshold -= 2\n\nEnd = perf_counter()\n\nprint(\"Result is equal to: \", threshold)\nprint(\"Time consumed: \", End-Start, \"seconds.\")\n","sub_path":"Problem3.py","file_name":"Problem3.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"522653937","text":"# -*- coding: utf-8 -*-\r\n\r\nimport re\r\nfrom abc import ABCMeta\r\nfrom scrapy.contrib.spiders import CrawlSpider, Rule\r\nfrom scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor\r\nfrom erobot.configs.ippondo_spider_config import IppondoActressSpiderConfig\r\nfrom erobot.contrib.ippondo.ippondo_actress_item_loader import IppondoJPActressItemLoader\r\n\r\nspider_config = IppondoActressSpiderConfig()\r\n\r\n \r\nclass IppondoActressSpider(CrawlSpider):\r\n __metaclass__ = ABCMeta\r\n \r\n allowed_domains = spider_config.allowed_domains\r\n rules = (Rule(SgmlLinkExtractor(allow=(re.compile(r'/50/act_list_[a-z]{1}\\.htm$'))),\r\n #rules = (Rule(SgmlLinkExtractor(allow=(re.compile(r'/50/act_list_k.htm'))),\r\n callback='parse_item',\r\n follow=True),)\r\n \r\n #def parse_start_url(self, response):\r\n # return self.parse_item(response)\r\n\r\n def parse_item(self, response):\r\n item_loader = self.actress_item_loader_cls(response)\r\n return item_loader.load_item()\r\n\r\n \r\nclass IppondoJPActressSpider(IppondoActressSpider):\r\n name = spider_config.name['jp']\r\n start_urls = spider_config.start_urls['jp']\r\n \r\n def __init__(self):\r\n super(IppondoJPActressSpider, self).__init__()\r\n self.actress_item_loader_cls = IppondoJPActressItemLoader\r\n","sub_path":"erovideo/erobot/spiders/ippondo_actress_spider.py","file_name":"ippondo_actress_spider.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"327150020","text":"import googleapiclient.discovery\nimport googleapiclient.errors\nfrom apiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n# from apiclient.errors import HttpError\n# from oauth2client.tools import argparser\nimport unidecode \n\nDEVELOPER_KEY = \"'AIzaSyBzWj8kvIXQJuQGXdiEVill9OUwK1vW-bg'\"\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\n\ndef youtube_search(q, max_results=50,order=\"relevance\", token=None, location=None, location_radius=None):\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)\n search_response = youtube.search().list(\n q=q,\n type=\"video\",\n pageToken=token,\n order = order,\n part=\"id,snippet\", # Part signifies the different types of data you want \n maxResults=max_results,\n location=location,\n locationRadius=location_radius).execute()\n\n title = []\n channelId = []\n channelTitle = []\n categoryId = []\n videoId = []\n viewCount = []\n likeCount = []\n dislikeCount = []\n commentCount = []\n favoriteCount = []\n category = []\n tags = []\n videos = []\n\n for search_result in search_response.get(\"items\", []):\n if search_result[\"id\"][\"kind\"] == \"youtube#video\":\n title.append(search_result['snippet']['title'])\n videoId.append(search_result['id']['videoId'])\n response = youtube.videos().list(part='statistics, snippet',id=search_result['id']['videoId']).execute()\n channelId.append(response['items'][0]['snippet']['channelId'])\n channelTitle.append(response['items'][0]['snippet']['channelTitle'])\n categoryId.append(response['items'][0]['snippet']['categoryId'])\n favoriteCount.append(response['items'][0]['statistics']['favoriteCount'])\n viewCount.append(response['items'][0]['statistics']['viewCount'])\n likeCount.append(response['items'][0]['statistics']['likeCount'])\n dislikeCount.append(response['items'][0]['statistics']['dislikeCount'])\n print(search_result)\n if 'commentCount' in response['items'][0]['statistics'].keys():\n commentCount.append(response['items'][0]['statistics']['commentCount'])\n else:\n commentCount.append([])\n if 'tags' in response['items'][0]['snippet'].keys():\n tags.append(response['items'][0]['snippet']['tags'])\n else:\n tags.append([])\n youtube_dict = {'tags':tags,'channelId': channelId,'channelTitle': channelTitle,'categoryId':categoryId,'title':title,'videoId':videoId,'viewCount':viewCount,'likeCount':likeCount,'dislikeCount':dislikeCount,'commentCount':commentCount,'favoriteCount':favoriteCount}\n # return youtube_dict\n print(youtube_dict) \n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"180289777","text":"NUL = 0x0 # NULL\nSP = 0x20 # space\nBEL = 0x07 # ^G) beeps;\nBS = 0x08 # ^H) backspaces one column (but not past the beginning of the line);\nHT = 0x09 # ^I) goes to the next tab stop or to the end of the line if there is no earlier tab stop;\nLF = 0x0A # ^J)\nVT = 0x0B # ^K) and FF (0x0C, ^L) all give a linefeed, and if LF/NL (new-line mode) is set also a carriage return;\nFF = 0x0C # see VT \nCR = 0x0D # ^M) gives a carriage return;\nSO = 0x0E # ^N) activates the G1 character set;\nSI = 0x0F # ^O) activates the G0 character set;\nCAN = 0x18 # ^X) and SUB (0x1A, ^Z) interrupt escape sequences;\nSUB = 0x1A # see CAN \nESC = 0x1B # ^[) starts an escape sequence;\nDEL = 0x7F # is ignored;\nCSI = 0x9B # is equivalent to ESC [. \n","sub_path":"terminal/ctrl.py","file_name":"ctrl.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"1956261","text":"#!/usr/bin/env python\nimport os\nimport sys\nimport getopt\nimport subprocess\nimport shutil\nfrom glob import glob\n\n# Packages to install:\n# libglib2.0-0\n# libxext6\n# libgl1-mesa-glx\n# libxi6\n# libsm6\n# libxrender1\n# libfontconfig1\n\n\ndef usage():\n print(\"Usage: %s [qmake_path]\" % os.path.basename(sys.argv[0]))\n\n\nclass QtDeployer():\n def __init__(self, fgap_exe_file, install_dir, data_dir, libraries_dir, qmake, debug_build):\n self.fgap_exe_file = os.path.normpath(fgap_exe_file)\n self.install_dir = os.path.normpath(install_dir)\n self.data_dir = os.path.normpath(data_dir)\n self.libraries_dir = os.path.normpath(libraries_dir)\n self.qmake = os.path.normpath(qmake)\n self.debug_build = False\n if debug_build == \"Debug\":\n self.debug_build = True\n\n p = subprocess.Popen([self.qmake, '-query', 'QT_INSTALL_LIBS'], stdout=subprocess.PIPE)\n self.qt_libs_dir, err = p.communicate()\n self.qt_libs_dir = os.path.normpath(self.qt_libs_dir.rstrip().decode('utf-8'))\n p = subprocess.Popen([self.qmake, '-query', 'QT_INSTALL_BINS'], stdout=subprocess.PIPE)\n self.qt_bin_dir, err = p.communicate()\n self.qt_bin_dir = os.path.normpath(self.qt_bin_dir.rstrip().decode('utf-8'))\n p = subprocess.Popen([self.qmake, '-query', 'QT_INSTALL_PLUGINS'], stdout=subprocess.PIPE)\n self.qt_plugins_dir, err = p.communicate()\n self.qt_plugins_dir = os.path.normpath(self.qt_plugins_dir.rstrip().decode('utf-8'))\n p = subprocess.Popen([self.qmake, '-query', 'QT_INSTALL_QML'], stdout=subprocess.PIPE)\n self.qt_qml_dir, err = p.communicate()\n self.qt_qml_dir = os.path.normpath(self.qt_qml_dir.rstrip().decode('utf-8'))\n\n if not sys.platform.startswith('win'):\n self.chrpath = 'patchelf'\n\n print('Qt deployer starting...')\n print('fgap_exe_file: ', self.fgap_exe_file)\n print('Install dir: ', self.install_dir)\n print('Data dir: ', self.data_dir)\n print('Libraries dir: ', self.libraries_dir)\n print('qmake: ', self.qmake)\n print('Debug build: ', self.debug_build)\n print('Qt libs dir: ', self.qt_libs_dir)\n print('Qt bin dir: ', self.qt_bin_dir)\n print('Qt plugins dir:', self.qt_plugins_dir)\n print('Qt qml dir: ', self.qt_qml_dir)\n\n def change_rpath(self, filename, new_rpath):\n rpath = '$ORIGIN/' + new_rpath\n if new_rpath == '.':\n rpath = '$ORIGIN'\n command = [self.chrpath, '--set-rpath', rpath, filename]\n try:\n subprocess.check_call(command)\n except:\n print('Failed to change rpath')\n\n def get_dependencies(self, file_name, dependencies):\n try:\n p = subprocess.Popen([file_name], stdout=subprocess.PIPE,\n env=dict(os.environ.copy(), LD_TRACE_LOADED_OBJECTS='1'))\n deps, err = p.communicate()\n except OSError:\n return\n\n for lib in deps.split('\\n'):\n lib_name = ''\n lib_dir = ''\n lib_name_and_dir = lib.split('=>')\n if len(lib_name_and_dir) > 1:\n lib_name = lib_name_and_dir[0].strip()\n lib_dir = lib_name_and_dir[1].strip()\n lib_dir = lib_dir[0:lib_dir.find('(')].strip()\n if lib_name and lib_dir:\n self.get_dependencies(lib_dir, dependencies)\n dependencies[lib_name] = lib_dir\n\n def copy_libs(self):\n print(\"copying Qt libraries...\")\n\n lib_ext = '*.so.*'\n dest = self.libraries_dir\n if sys.platform.startswith('win'):\n lib_ext = '*.dll'\n dest = os.path.normpath(os.path.join(self.data_dir, '..'))\n self.qt_libs_dir = self.qt_bin_dir\n\n for needed_lib in self.needed_libraries:\n for lib in glob(os.path.join(self.qt_libs_dir, needed_lib + lib_ext)):\n if sys.platform.startswith('win') and os.path.basename(lib).startswith('Qt'):\n debug_lib = os.path.basename(lib).split('.')[0].endswith('d')\n if self.debug_build:\n if not debug_lib:\n continue\n else:\n if debug_lib:\n continue\n\n # print('Copy: ', lib, '->', dest)\n if os.path.islink(lib):\n linkto = os.readlink(lib)\n try:\n os.symlink(linkto, os.path.join(dest, os.path.basename(lib)))\n except:\n # print('Link exists')\n pass\n else:\n if not os.path.exists(dest):\n os.makedirs(dest)\n shutil.copy2(lib, os.path.join(dest, os.path.basename(lib)))\n if not sys.platform.startswith('win'):\n self.change_rpath(os.path.join(dest, os.path.basename(lib)),\n os.path.relpath(dest, self.libraries_dir))\n\n print('Copying plugins:', self.plugins)\n for plugin in self.plugins:\n target = os.path.join(self.data_dir, 'plugins', plugin)\n if os.path.exists(target):\n shutil.rmtree(target)\n pluginPath = os.path.join(self.qt_plugins_dir, plugin)\n if os.path.exists(pluginPath):\n self.copytree(pluginPath, target, symlinks=True)\n\n if os.path.exists(self.qt_qml_dir):\n print('Copying qt quick 2 imports')\n target = os.path.join(self.data_dir, 'qml')\n\n for lib in filter(lambda x: os.path.basename(x) in self.needed_qml, glob(self.qt_qml_dir+'/*')):\n self.copytree(lib,os.path.join(target, os.path.basename(lib)), symlinks=True)\n\n def copy_libclang(self, data_dir, llvm_install_dir):\n libsource = os.path.join(llvm_install_dir, 'lib', 'libclang.so')\n libtarget = os.path.join(self.libraries_dir)\n if sys.platform.startswith(\"win\"):\n libsource = os.path.join(llvm_install_dir, '..', 'libclang.dll')\n libtarget = os.path.join(data_dir, '..')\n resourcesource = os.path.join(llvm_install_dir, 'lib', 'clang')\n resourcetarget = os.path.join(data_dir, 'share', 'cplusplus', 'clang')\n print(\"copying libclang...\")\n shutil.copy(libsource, libtarget)\n if not sys.platform.startswith('win') and os.access(d, os.X_OK):\n self.change_rpath(libtarget)\n if os.path.exists(resourcetarget):\n shutil.rmtree(resourcetarget)\n self.copytree(resourcesource, resourcetarget, symlinks=True)\n\n def deploy(self):\n if not sys.platform.startswith('win'):\n self.change_rpath(self.fgap_exe_file,\n os.path.relpath(self.libraries_dir, os.path.dirname(self.fgap_exe_file)))\n\n self.plugins = ['iconengines', 'imageformats', 'platformthemes',\n 'platforminputcontexts', 'platforms', 'xcbglintegrations']\n\n self.needed_libraries = [\n 'Qt5Core', 'Qt5Widgets', 'Qt5Gui', 'Qt5Qml', 'Qt5Quick', 'Qt5Network',\n 'Qt5DBus', 'Qt5Svg', 'icudata', 'icui18n', 'icuuc'\n ]\n\n self.needed_qml = [\"Qt\", \"QtQuick\", \"QtQuick.2\", \"QtGraphicalEffects\"]\n\n if sys.platform.startswith('win'):\n self.needed_libraries.extend(['libgcc_s_dw2-1', 'libwinpthread-1', 'libstdc++-6', 'icuin53', 'icuuc53', 'icudt53'])\n self.copy_libs()\n else:\n self.needed_libraries = map(lambda lib: 'lib' + lib, self.needed_libraries)\n self.copy_libs()\n\n if 'LLVM_INSTALL_DIR' in os.environ:\n self.copy_libclang(self.data_dir, os.environ[\"LLVM_INSTALL_DIR\"])\n\n def copytree(self, src, dst, symlinks=False, ignore=None):\n if not os.path.exists(dst):\n os.makedirs(dst)\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s):\n self.copytree(s, d, symlinks, ignore)\n else:\n shutil.copy2(s, d)\n# print('Copy:', s, '->', d)\n if not sys.platform.startswith('win') and os.access(d, os.X_OK):\n self.change_rpath(d, os.path.relpath(self.libraries_dir, os.path.dirname(d)))\n\n\nif __name__ == \"__main__\":\n if sys.platform == 'darwin':\n print(\"Use macqtdeploy!\")\n sys.exit(2)\n else:\n try:\n opts, args = getopt.gnu_getopt(sys.argv[1:], 'hi', ['help', 'ignore-errors'])\n except:\n usage()\n sys.exit(2)\n # fgap_exe_name, install_dir, data_dir, libraries_dir, qmake, debug_build\n deployer = QtDeployer(os.path.normpath(args[0]), args[1], args[2], args[3], args[4], args[5])\n deployer.deploy()\n","sub_path":"scripts/deployqt.py","file_name":"deployqt.py","file_ext":"py","file_size_in_byte":9032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"248006382","text":"import asyncio\nfrom http import HTTPStatus\nfrom typing import List, Optional\n\nfrom fastapi import Depends, Query, Request, status\nfrom fastapi.exceptions import HTTPException\nfrom fastapi.responses import FileResponse, RedirectResponse\nfrom fastapi.routing import APIRouter\nfrom loguru import logger\nfrom pydantic.types import UUID4\nfrom starlette.responses import HTMLResponse, JSONResponse\n\nfrom lnbits.core import db\nfrom lnbits.core.helpers import to_valid_user_id\nfrom lnbits.core.models import User\nfrom lnbits.decorators import check_admin, check_user_exists\nfrom lnbits.helpers import template_renderer, url_for\nfrom lnbits.settings import get_wallet_class, settings\n\nfrom ...extension_manager import InstallableExtension, get_valid_extensions\nfrom ..crud import (\n create_account,\n create_wallet,\n delete_wallet,\n get_balance_check,\n get_inactive_extensions,\n get_installed_extensions,\n get_user,\n save_balance_notify,\n update_installed_extension_state,\n update_user_extension,\n)\nfrom ..services import pay_invoice, redeem_lnurl_withdraw\n\ncore_html_routes: APIRouter = APIRouter(tags=[\"Core NON-API Website Routes\"])\n\n\n@core_html_routes.get(\"/favicon.ico\", response_class=FileResponse)\nasync def favicon():\n return FileResponse(\"lnbits/core/static/favicon.ico\")\n\n\n@core_html_routes.get(\"/\", response_class=HTMLResponse)\nasync def home(request: Request, lightning: str = \"\"):\n return template_renderer().TemplateResponse(\n \"core/index.html\", {\"request\": request, \"lnurl\": lightning}\n )\n\n\n@core_html_routes.get(\"/robots.txt\", response_class=HTMLResponse)\nasync def robots():\n data = \"\"\"\n User-agent: *\n Disallow: /\n \"\"\"\n return HTMLResponse(content=data, media_type=\"text/plain\")\n\n\n@core_html_routes.get(\n \"/extensions\", name=\"core.extensions\", response_class=HTMLResponse\n)\nasync def extensions(\n request: Request,\n user: User = Depends(check_user_exists),\n enable: str = Query(None),\n disable: str = Query(None),\n):\n await toggle_extension(enable, disable, user.id)\n\n # Update user as his extensions have been updated\n if enable or disable:\n updated_user = await get_user(user.id)\n assert updated_user, \"User does not exist.\"\n user = updated_user\n\n return template_renderer().TemplateResponse(\n \"core/extensions.html\", {\"request\": request, \"user\": user.dict()}\n )\n\n\n@core_html_routes.get(\n \"/install\", name=\"install.extensions\", response_class=HTMLResponse\n)\nasync def extensions_install(\n request: Request,\n user: User = Depends(check_user_exists),\n activate: str = Query(None),\n deactivate: str = Query(None),\n):\n try:\n installed_exts: List[\"InstallableExtension\"] = await get_installed_extensions()\n installed_exts_ids = [e.id for e in installed_exts]\n\n installable_exts: List[\n InstallableExtension\n ] = await InstallableExtension.get_installable_extensions()\n installable_exts += [\n e for e in installed_exts if e.id not in installed_exts_ids\n ]\n\n for e in installable_exts:\n installed_ext = next((ie for ie in installed_exts if e.id == ie.id), None)\n if installed_ext:\n e.installed_release = installed_ext.installed_release\n # use the installed extension values\n e.name = installed_ext.name\n e.short_description = installed_ext.short_description\n e.icon = installed_ext.icon\n\n except Exception as ex:\n logger.warning(ex)\n installable_exts = []\n\n try:\n ext_id = activate or deactivate\n if ext_id and user.admin:\n if deactivate and deactivate not in settings.lnbits_deactivated_extensions:\n settings.lnbits_deactivated_extensions += [deactivate]\n elif activate:\n settings.lnbits_deactivated_extensions = list(\n filter(\n lambda e: e != activate, settings.lnbits_deactivated_extensions\n )\n )\n await update_installed_extension_state(\n ext_id=ext_id, active=activate is not None\n )\n\n all_extensions = list(map(lambda e: e.code, get_valid_extensions()))\n inactive_extensions = await get_inactive_extensions()\n extensions = list(\n map(\n lambda ext: {\n \"id\": ext.id,\n \"name\": ext.name,\n \"icon\": ext.icon,\n \"shortDescription\": ext.short_description,\n \"stars\": ext.stars,\n \"isFeatured\": ext.featured,\n \"dependencies\": ext.dependencies,\n \"isInstalled\": ext.id in installed_exts_ids,\n \"isAvailable\": ext.id in all_extensions,\n \"isActive\": ext.id not in inactive_extensions,\n \"latestRelease\": dict(ext.latest_release)\n if ext.latest_release\n else None,\n \"installedRelease\": dict(ext.installed_release)\n if ext.installed_release\n else None,\n },\n installable_exts,\n )\n )\n\n return template_renderer().TemplateResponse(\n \"core/install.html\",\n {\n \"request\": request,\n \"user\": user.dict(),\n \"extensions\": extensions,\n },\n )\n except Exception as e:\n logger.warning(e)\n raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))\n\n\n@core_html_routes.get(\n \"/wallet\",\n response_class=HTMLResponse,\n description=\"\"\"\nArgs:\n\njust **wallet_name**: create a new user, then create a new wallet for user with wallet_name
    \njust **user_id**: return the first user wallet or create one if none found (with default wallet_name)
    \n**user_id** and **wallet_name**: create a new wallet for user with wallet_name
    \n**user_id** and **wallet_id**: return that wallet if user is the owner
    \nnothing: create everything
    \n\"\"\",\n)\nasync def wallet(\n request: Request = Query(None),\n nme: Optional[str] = Query(None),\n usr: Optional[UUID4] = Query(None),\n wal: Optional[UUID4] = Query(None),\n):\n user_id = usr.hex if usr else None\n wallet_id = wal.hex if wal else None\n wallet_name = nme\n\n if not user_id:\n new_user = await create_account()\n user = await get_user(new_user.id)\n assert user, \"Newly created user has to exist.\"\n logger.info(f\"Create user {user.id}\")\n else:\n user = await get_user(user_id)\n if not user:\n return template_renderer().TemplateResponse(\n \"error.html\", {\"request\": request, \"err\": \"User does not exist.\"}\n )\n if (\n len(settings.lnbits_allowed_users) > 0\n and user_id not in settings.lnbits_allowed_users\n and user_id not in settings.lnbits_admin_users\n and user_id != settings.super_user\n ):\n return template_renderer().TemplateResponse(\n \"error.html\", {\"request\": request, \"err\": \"User not authorized.\"}\n )\n if user_id == settings.super_user or user_id in settings.lnbits_admin_users:\n user.admin = True\n if user_id == settings.super_user:\n user.super_user = True\n\n if not wallet_id:\n if user.wallets and not wallet_name:\n wallet = user.wallets[0]\n else:\n wallet = await create_wallet(user_id=user.id, wallet_name=wallet_name)\n logger.info(\n f\"Created new wallet {wallet_name if wallet_name else '(no name)'} for user {user.id}\"\n )\n\n return RedirectResponse(\n f\"/wallet?usr={user.id}&wal={wallet.id}\",\n status_code=status.HTTP_307_TEMPORARY_REDIRECT,\n )\n\n logger.debug(\n f\"Access {'user '+ user.id + ' ' if user else ''} {'wallet ' + wallet_name if wallet_name else ''}\"\n )\n userwallet = user.get_wallet(wallet_id)\n if not userwallet:\n return template_renderer().TemplateResponse(\n \"error.html\", {\"request\": request, \"err\": \"Wallet not found\"}\n )\n\n return template_renderer().TemplateResponse(\n \"core/wallet.html\",\n {\n \"request\": request,\n \"user\": user.dict(),\n \"wallet\": userwallet.dict(),\n \"service_fee\": settings.lnbits_service_fee,\n \"web_manifest\": f\"/manifest/{user.id}.webmanifest\",\n },\n )\n\n\n@core_html_routes.get(\"/withdraw\", response_class=JSONResponse)\nasync def lnurl_full_withdraw(request: Request):\n user = await get_user(request.query_params.get(\"usr\"))\n if not user:\n return {\"status\": \"ERROR\", \"reason\": \"User does not exist.\"}\n\n wallet = user.get_wallet(request.query_params.get(\"wal\"))\n if not wallet:\n return {\"status\": \"ERROR\", \"reason\": \"Wallet does not exist.\"}\n\n return {\n \"tag\": \"withdrawRequest\",\n \"callback\": url_for(\"/withdraw/cb\", external=True, usr=user.id, wal=wallet.id),\n \"k1\": \"0\",\n \"minWithdrawable\": 1000 if wallet.withdrawable_balance else 0,\n \"maxWithdrawable\": wallet.withdrawable_balance,\n \"defaultDescription\": f\"{settings.lnbits_site_title} balance withdraw from {wallet.id[0:5]}\",\n \"balanceCheck\": url_for(\"/withdraw\", external=True, usr=user.id, wal=wallet.id),\n }\n\n\n@core_html_routes.get(\"/withdraw/cb\", response_class=JSONResponse)\nasync def lnurl_full_withdraw_callback(request: Request):\n user = await get_user(request.query_params.get(\"usr\"))\n if not user:\n return {\"status\": \"ERROR\", \"reason\": \"User does not exist.\"}\n\n wallet = user.get_wallet(request.query_params.get(\"wal\"))\n if not wallet:\n return {\"status\": \"ERROR\", \"reason\": \"Wallet does not exist.\"}\n\n pr = request.query_params.get(\"pr\")\n\n async def pay():\n try:\n await pay_invoice(wallet_id=wallet.id, payment_request=pr)\n except:\n pass\n\n asyncio.create_task(pay())\n\n balance_notify = request.query_params.get(\"balanceNotify\")\n if balance_notify:\n await save_balance_notify(wallet.id, balance_notify)\n\n return {\"status\": \"OK\"}\n\n\n@core_html_routes.get(\"/deletewallet\", response_class=RedirectResponse)\nasync def deletewallet(wal: str = Query(...), usr: str = Query(...)):\n user = await get_user(usr)\n if not user:\n raise HTTPException(HTTPStatus.FORBIDDEN, \"User not found.\")\n\n user_wallet_ids = [u.id for u in user.wallets]\n\n if wal not in user_wallet_ids:\n raise HTTPException(HTTPStatus.FORBIDDEN, \"Not your wallet.\")\n else:\n await delete_wallet(user_id=user.id, wallet_id=wal)\n user_wallet_ids.remove(wal)\n logger.debug(\"Deleted wallet {wal} of user {user.id}\")\n\n if user_wallet_ids:\n return RedirectResponse(\n url_for(\"/wallet\", usr=user.id, wal=user_wallet_ids[0]),\n status_code=status.HTTP_307_TEMPORARY_REDIRECT,\n )\n\n return RedirectResponse(\n url_for(\"/\"), status_code=status.HTTP_307_TEMPORARY_REDIRECT\n )\n\n\n@core_html_routes.get(\"/withdraw/notify/{service}\")\nasync def lnurl_balance_notify(request: Request, service: str):\n bc = await get_balance_check(request.query_params.get(\"wal\"), service)\n if bc:\n await redeem_lnurl_withdraw(bc.wallet, bc.url)\n\n\n@core_html_routes.get(\n \"/lnurlwallet\", response_class=RedirectResponse, name=\"core.lnurlwallet\"\n)\nasync def lnurlwallet(request: Request):\n async with db.connect() as conn:\n account = await create_account(conn=conn)\n user = await get_user(account.id, conn=conn)\n assert user, \"Newly created user not found.\"\n wallet = await create_wallet(user_id=user.id, conn=conn)\n\n asyncio.create_task(\n redeem_lnurl_withdraw(\n wallet.id,\n request.query_params.get(\"lightning\"),\n \"LNbits initial funding: voucher redeem.\",\n {\"tag\": \"lnurlwallet\"},\n 5, # wait 5 seconds before sending the invoice to the service\n )\n )\n\n return RedirectResponse(\n f\"/wallet?usr={user.id}&wal={wallet.id}\",\n status_code=status.HTTP_307_TEMPORARY_REDIRECT,\n )\n\n\n@core_html_routes.get(\"/service-worker.js\", response_class=FileResponse)\nasync def service_worker():\n return FileResponse(\"lnbits/core/static/js/service-worker.js\")\n\n\n@core_html_routes.get(\"/manifest/{usr}.webmanifest\")\nasync def manifest(usr: str):\n user = await get_user(usr)\n if not user:\n raise HTTPException(status_code=HTTPStatus.NOT_FOUND)\n\n return {\n \"short_name\": settings.lnbits_site_title,\n \"name\": settings.lnbits_site_title + \" Wallet\",\n \"icons\": [\n {\n \"src\": settings.lnbits_custom_logo\n if settings.lnbits_custom_logo\n else \"https://cdn.jsdelivr.net/gh/lnbits/lnbits@0.3.0/docs/logos/lnbits.png\",\n \"type\": \"image/png\",\n \"sizes\": \"900x900\",\n }\n ],\n \"start_url\": f\"/wallet?usr={usr}&wal={user.wallets[0].id}\",\n \"background_color\": \"#1F2234\",\n \"description\": \"Bitcoin Lightning Wallet\",\n \"display\": \"standalone\",\n \"scope\": \"/\",\n \"theme_color\": \"#1F2234\",\n \"shortcuts\": [\n {\n \"name\": wallet.name,\n \"short_name\": wallet.name,\n \"description\": wallet.name,\n \"url\": f\"/wallet?usr={usr}&wal={wallet.id}\",\n }\n for wallet in user.wallets\n ],\n }\n\n\n@core_html_routes.get(\"/admin\", response_class=HTMLResponse)\nasync def index(request: Request, user: User = Depends(check_admin)):\n if not settings.lnbits_admin_ui:\n raise HTTPException(status_code=HTTPStatus.NOT_FOUND)\n\n WALLET = get_wallet_class()\n _, balance = await WALLET.status()\n\n return template_renderer().TemplateResponse(\n \"admin/index.html\",\n {\n \"request\": request,\n \"user\": user.dict(),\n \"settings\": settings.dict(),\n \"balance\": balance,\n },\n )\n\n\n@core_html_routes.get(\"/uuidv4/{hex_value}\")\nasync def hex_to_uuid4(hex_value: str):\n try:\n user_id = to_valid_user_id(hex_value).hex\n return RedirectResponse(url=f\"/wallet?usr={user_id}\")\n except Exception as e:\n raise HTTPException(status_code=HTTPStatus.BAD_REQUEST, detail=str(e))\n\n\nasync def toggle_extension(extension_to_enable, extension_to_disable, user_id):\n if extension_to_enable and extension_to_disable:\n raise HTTPException(\n HTTPStatus.BAD_REQUEST, \"You can either `enable` or `disable` an extension.\"\n )\n\n # check if extension exists\n if extension_to_enable or extension_to_disable:\n ext = extension_to_enable or extension_to_disable\n if ext not in [e.code for e in get_valid_extensions()]:\n raise HTTPException(\n HTTPStatus.BAD_REQUEST, f\"Extension '{ext}' doesn't exist.\"\n )\n\n if extension_to_enable:\n logger.info(f\"Enabling extension: {extension_to_enable} for user {user_id}\")\n await update_user_extension(\n user_id=user_id, extension=extension_to_enable, active=True\n )\n elif extension_to_disable:\n logger.info(f\"Disabling extension: {extension_to_disable} for user {user_id}\")\n await update_user_extension(\n user_id=user_id, extension=extension_to_disable, active=False\n )\n","sub_path":"lnbits/core/views/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":15606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"167499543","text":"#!/usr/bin/env python\n#File: make_all.py\n#\n# Script intended to read all data from hospitalizations in a given Brazilian State.\n# Later you can manipulate this data using \"datasus\" module.\n#\n# Example of usage in a linux terminal:\n#\n# >>> directory=\"/media/alex/ALEXDATA/data_sets/HEALTH/HOSPITALIZATION/MT/\"\n# >>> output=\"/media/alex/ALEXDATA/data_sets/HEALTH/HOSPITALIZATION/MT/DATASUS_MT.csv\"\n# >>> python make_all.py $directory $output \n\n# Load system package.\nimport sys\n\ndirectory = sys.argv[1] # Where is the data?\noutput = sys.argv[2] # Output file path with csv extension.\n\n# My repository.\nrepository = \"/home/alex/Dropbox/repositories/doctoral_thesis/libraries/\"\n\n# Include once my repository in the path for searching libraries.\nif repository not in sys.path:\n sys.path.append(repository)\n \n# Import my libraries.\nimport datasus.tools as sus\n\n# Read all data. All diseases for all locations in the selected state.\nSUS = sus.data_frame(directory)\n\n# Export to a csv file.\nSUS.to_csv(output)\n","sub_path":"scripts/datasus/make_all.py","file_name":"make_all.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"532588954","text":"import csv\nimport re\nnim = []\nnama = []\nwith open('DaftarNama.csv') as csv_file:\n csv_reader = csv.reader(csv_file,delimiter=';')\n line_count = 0\n for row in csv_reader:\n nim.append(row[0])\n nama.append(row[1])\n\nwhile True:\n print ('=========================')\n pilihan = input('Pilih Menu:\\n1.Cari Mahasiswa\\n2.Tambah Mahasiswa\\n3.Tampilkan Daftar Mahasiswa\\n4.Selesai\\nPilihan: ')\n if (pilihan=='1'):\n while True:\n search = input('Masukkan Nama atau Nim: ')\n try:\n if '0'<=search[0]<='9':\n #print('1')\n index = nim.index(search)\n else:\n #print('2')\n index = nama.index(' '+search)\n print('Nama:',nama[index])\n print('NIM:',nim[index])\n break\n except ValueError:\n print('Sorry not found, please try again')\n elif (pilihan=='2'):\n with open('DaftarNama.csv') as csv_file:\n raw_nim = input('Masukkan Nim: ')\n nim.append(raw_nim)\n raw_nama = input('Masukkan Nama: ')\n nama.append(' '+raw_nama)\n new_line = '\\n'+raw_nim+';'+' '+raw_nama\n for p in csv_file:\n csv_file.write(new_line)\n ##print (new_line)\n ##csv_file.write(new_line)\n elif(pilihan=='3'):\n with open('DaftarNama.csv') as csv_file:\n csv_reader = csv.reader(csv_file,delimiter=';')\n for o in csv_reader:\n print (o)\n csv_file.close()\n \n \n \n elif (pilihan=='4'):\n print('Program Selesai')\n break\n else:\n print('Input Salah, Coba lagi')\n \n \n''' \n elif (pilihan=='2'):\n writer = open('DaftarNama.csv','a')\n raw_nim = input('Masukkan Nim: ')\n nim.append(raw_nim)\n raw_nama = input('Masukkan Nama: ')\n nama.append(' '+raw_nama)\n new_line = '\\n'+raw_nim+';'+' '+raw_nama\n print (new_line)\n writer.write(new_line)\n writer.close()\n'''\n\n","sub_path":"SP VIKA/SP VIKA.py","file_name":"SP VIKA.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"79648532","text":"import shutil\nimport datetime\nimport meteva\nimport os\nimport numpy as np\n#from meteva.base.io import DataBlock_pb2\n#from meteva.base.io.GDS_data_service import GDSDataService\nfrom multiprocessing import Process,cpu_count\n\npara_example= {\n \"cup_count\":1,\n \"ip_port_file\":r\"H:\\test_data\\input\\input\\meb\\ip_port.txt\",\n \"local_binary_dir\": r\"O:\\data\\mdfs\",\n \"local_sta_dir\": r\"O:\\data\\sta\",\n \"local_grid_dir\":r\"O:\\data\\grid\",\n \"max_save_day\": 14,\n \"sta_origin_dirs\": [\n [\"mdfs:///SURFACE/QC_BY_FSOL/RAIN01_ALL_STATION/\", [[0, 2359]]],\n [\"mdfs:///SURFACE/QC_BY_FSOL/WIND_AVERAGE_2MIN_ALL_STATION/\", [[0, 2359]]],\n [\"mdfs:///SURFACE/QC_BY_FSOL/TMP_ALL_STATION/\", [[0, 2359]]],\n ],\n \"grid_origin_dirs\": {\n \"NWFD_SCMOC\": [\n [\"NWFD_SCMOC/RAIN03\", [[1100, 1200],[2100,2300]]],\n [\"NWFD_SCMOC/TMP/2M_ABOVE_GROUND\", [[1100, 1200],[2100,2359]]],\n [\"NWFD_SCMOC/WIND/10M_ABOVE_GROUND\", [[1100, 1200],[2100,2359]]],\n ],\n \"EWMWF\": [\n [\"ECMWF_HR/TMP_2M/\", [[1100, 1200],[2200,2359]]],\n [\"ECMWF_HR/APCP/\", [[1100, 1200],[2200,2359]]],\n [\"mdfs:///ECMWF_HR/WIND_10M/\", [[1100, 1200],[2200,2359]]],\n ],\n \"GRAPES_GFS\": [\n [\"mdfs:///GRAPES_GFS/WIND/10M_ABOVE_GROUND/\", [[1100, 1200],[2200,2359]]],\n [\"GRAPES_GFS/TMP/2M_ABOVE_GROUND\", [[1100, 1200],[2200,2359]]],\n [\"GRAPES_GFS/APCP\", [[1100, 1200],[2200,2359]]],\n ],\n }\n}\n\n\n\n\n\ndef download_one_cup(k,ip,port,local_binary_dir,local_sta_dir,local_grid_dir,file_sta_list,file_grid_list):\n service = meteva.base.io.GDSDataService(ip, port)\n for filepath in file_sta_list:\n dir,file = os.path.split(filepath)\n save_path = local_binary_dir + \"/\" + dir + \"/\" + file\n dati_str = meteva.product.application.get_dati_str_of_path(save_path)\n try:\n status, response = service.getData(dir, file)\n ByteArrayResult = meteva.base.io.DataBlock_pb2.ByteArrayResult()\n if status == 200:\n ByteArrayResult.ParseFromString(response)\n if ByteArrayResult is not None:\n byteArray = ByteArrayResult.byteArray\n save_path_sta = local_sta_dir + \"/\" + dir + \"/\" + dati_str + \"/\" + file\n meteva.base.tool.path_tools.creat_path(save_path_sta)\n br = open(save_path_sta, 'wb')\n br.write(byteArray)\n br.close()\n print(save_path_sta)\n print(k)\n except Exception as e:\n print(e)\n\n for filepath in file_grid_list:\n dir,file = os.path.split(filepath)\n save_path = local_binary_dir + \"/\" + dir + \"/\" + file\n dati_str = meteva.product.application.get_dati_str_of_path(save_path)\n try:\n status, response = service.getData(dir, file)\n ByteArrayResult = meteva.base.io.DataBlock_pb2.ByteArrayResult()\n if status == 200:\n ByteArrayResult.ParseFromString(response)\n if ByteArrayResult is not None:\n byteArray = ByteArrayResult.byteArray\n meteva.base.tool.path_tools.creat_path(save_path)\n br = open(save_path, 'wb')\n br.write(byteArray)\n br.close()\n if dir.upper().find(\"WIND\") >= 0:\n if (dir.upper().find(\"GUST\")) >= 0:\n grd = meteva.base.io.byteArray_to_griddata(byteArray)\n else:\n grd = meteva.base.io.byteArray_to_gridwind(byteArray)\n else:\n grd = meteva.base.io.byteArray_to_griddata(byteArray)\n save_path_nc = local_grid_dir + \"/\" + dir + \"/\" + dati_str + \"/\" + file + \".nc\"\n meteva.base.write_griddata_to_nc(grd, save_path_nc, creat_dir=True,show=True)\n print(k)\n except Exception as e:\n print(e)\n\ndef download_mp(ip,port,local_binary_dir,local_sta_dir,local_grid_dir,download_sta_list,download_grid_list,multi_pro_num):\n max_pro_num = cpu_count() - 2\n if multi_pro_num > max_pro_num:\n multi_pro_num = max_pro_num\n\n file_sta_dict_list = {}\n file_grid_dict_list = {}\n for i in range(multi_pro_num):\n file_sta_dict_list[i] = []\n file_grid_dict_list[i] = []\n\n for i in range(len(download_sta_list)):\n k = i % multi_pro_num\n file_sta_dict_list[k].append(download_sta_list[i])\n for i in range(len(download_grid_list)):\n k = i % multi_pro_num\n file_grid_dict_list[k].append(download_grid_list[i])\n\n PP = []\n for k in range(multi_pro_num):\n tmpp = Process(target=download_one_cup, args=(k,ip,port,local_binary_dir,local_sta_dir,local_grid_dir,file_sta_dict_list[k],file_grid_dict_list[k]))\n PP.append(tmpp)\n print('Waiting for all subprocesses done...')\n for pc in PP:\n pc.start()\n\n for pp in PP:\n pp.join()\n print('All subprocesses done.')\n\n\ndef in_op_time(hm,op_list_list):\n in_op = False\n for down_set in op_list_list:\n if hm >= down_set[0] and hm <= down_set[1]:\n in_op = True\n return in_op\n\ndef download_from_gds(para):\n #遍历下载\n now = datetime.datetime.now()\n print(\"于\"+str(now)+\"开始下载\")\n weekago = now - datetime.timedelta(days=7)\n hm = now.hour * 100 + now.minute\n ip,port = meteva.base.io.read_gds_ip_port(para[\"ip_port_file\"])\n service = meteva.base.io.GDSDataService(ip, port)\n if (service is None):\n print(\"service is None\")\n return\n download_sta_list = []\n for down_set in para[\"sta_origin_dirs\"]:\n if in_op_time(hm,down_set[1]):\n dir_list = []\n meteva.base.tool.path_tools.get_gds_all_dir(ip,port,down_set[0],dir_list)\n for dir in dir_list:\n file_list = meteva.base.tool.path_tools.get_gds_file_list_in_one_dir(ip,port,dir)\n file_list.sort(reverse = True)\n for file in file_list:\n dati = meteva.product.application.get_dati_of_path(file)\n if dati < weekago:break\n dati_str = meteva.product.application.get_dati_str_of_path(file)\n save_path_sta = para[\"local_sta_dir\"] + \"/\" + dir + \"/\" + dati_str + \"/\" + file\n if not os.path.exists(save_path_sta):\n download_sta_list.append(dir + \"/\" +file)\n\n download_grid_list = []\n for key in para[\"grid_origin_dirs\"].keys():\n down_set_group = para[\"grid_origin_dirs\"][key]\n for down_set in down_set_group:\n if in_op_time(hm, down_set[1]):\n dir_list = []\n meteva.base.tool.path_tools.get_gds_all_dir(ip,port,down_set[0],dir_list)\n for dir in dir_list:\n file_list = meteva.base.tool.path_tools.get_gds_file_list_in_one_dir(ip,port,dir)\n file_list.sort(reverse=True)\n for file in file_list:\n dati = meteva.product.application.get_dati_of_path(file)\n if dati < weekago: break\n save_path = para[\"local_binary_dir\"] + \"/\" +dir+\"/\" +file\n if not os.path.exists(save_path):\n download_grid_list.append(dir + \"/\" + file)\n else:\n try:\n dati_str = meteva.product.application.get_dati_str_of_path(save_path)\n save_path_nc = para[\"local_grid_dir\"] + \"/\" + dir + \"/\" + dati_str + \"/\" + file+\".nc\"\n if not os.path.exists(save_path_nc):\n if dir.upper().find(\"WIND\")>=0:\n if (dir.upper().find(\"GUST\"))>=0:\n grd = meteva.base.read_griddata_from_gds_file(save_path)\n else:\n grd = meteva.base.read_gridwind_from_gds_file(save_path)\n else:\n grd = meteva.base.read_griddata_from_gds_file(save_path)\n if grd is not None:\n meteva.base.write_griddata_to_nc(grd, save_path_nc, creat_dir=True)\n else:\n print(save_path + \"文件格式错误\")\n except Exception as e:\n print(e)\n\n download_mp(ip, port, para[\"local_binary_dir\"], para[\"local_sta_dir\"], para[\"local_grid_dir\"], download_sta_list, download_grid_list,\n para[\"cup_count\"])\n\n\ndef remove(dir,save_day):\n file_list = meteva.base.tool.path_tools.get_path_list_in_dir(dir)\n now = datetime.datetime.now()\n for file in file_list:\n dati = meteva.product.application.get_dati_of_path(file)\n dday = (now - dati).total_seconds()/(3600*24)\n if dday > save_day:\n os.remove(file)\n print(dir +\"目录下\"+str(save_day)+\"天之前的数据已删除\")\n\n\npara_list = [\n {\n \"input\":r\"O:\\data\\grid\\GRAPES_GFS\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\":r\"L:\\luoqi\\GRAPES_GFS\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\":datetime.datetime(2020,3,1,8,0),\n \"end\":datetime.datetime(2020,6,1,8,0),\n \"hour_range\":[8,21,12],\n \"dh_range\":[3,241,3],\n \"recover\":False\n },\n\n {\n \"input\": r\"O:\\data\\grid\\ECMWF_HR\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\": r\"L:\\luoqi\\ECMWF_HR\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\": datetime.datetime(2020, 3, 1, 8, 0),\n \"end\": datetime.datetime(2020, 6, 1, 8, 0),\n \"hour_range\": [8, 21, 12],\n \"dh_range\": [3, 241, 3],\n \"recover\": False\n },\n\n {\n \"input\": r\"O:\\data\\grid\\NCEP_GFS_HR\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\": r\"L:\\luoqi\\NCEP_GFS_HR\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\": datetime.datetime(2020, 3, 1, 8, 0),\n \"end\": datetime.datetime(2020, 6, 1, 8, 0),\n \"hour_range\": [8, 21, 12],\n \"dh_range\": [3, 241, 3],\n \"recover\": False\n },\n\n {\n \"input\": r\"O:\\data\\grid\\SHANGHAI_HR\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\": r\"L:\\luoqi\\SHANGHAI_HR\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\": datetime.datetime(2020, 3, 1, 8, 0),\n \"end\": datetime.datetime(2020, 6, 1, 8, 0),\n \"hour_range\": [0, 24, 1],\n \"dh_range\": [0, 25, 1],\n \"recover\": False\n },\n\n {\n \"input\": r\"O:\\data\\grid\\GRAPES_MESO_HR\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\": r\"L:\\luoqi\\GRAPES_MESO_HR\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\": datetime.datetime(2020, 3, 1, 8, 0),\n \"end\": datetime.datetime(2020, 6, 1, 8, 0),\n \"hour_range\": [2, 24, 3],\n \"dh_range\": [0, 85, 1],\n \"recover\": False\n },\n\n {\n \"input\": r\"O:\\data\\grid\\GRAPES_3KM\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\": r\"L:\\luoqi\\GRAPES_3KM\\APCP\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\": datetime.datetime(2020, 3, 1, 8, 0),\n \"end\": datetime.datetime(2020, 6, 1, 8, 0),\n \"hour_range\": [2, 24, 3],\n \"dh_range\": [0, 37, 1],\n \"recover\": False\n },\n\n]\n\n\npara_list1 = [\n {\n \"input\":r\"O:\\data\\grid\\NWFD_SCMOC\\RAIN03\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\":r\"\\\\10.28.27.93\\SCMOC\\RAIN03\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\":datetime.datetime(2020,5,20,8,0),\n \"end\":datetime.datetime(2020,6,1,8,0),\n \"hour_range\":[8,21,12],\n \"dh_range\":[3,241,3],\n \"recover\":False\n },\n {\n \"input\": r\"O:\\data\\grid\\NWFD_SCMOC\\TMP\\2M_ABOVE_GROUND\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\": r\"\\\\10.28.27.93\\SCMOC\\TMP\\2M_ABOVE_GROUND\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\": datetime.datetime(2020, 5, 20, 8, 0),\n \"end\": datetime.datetime(2020, 6, 1, 8, 0),\n \"hour_range\": [8, 21, 12],\n \"dh_range\": [3, 241, 3],\n \"recover\": False\n },\n {\n \"input\": r\"O:\\data\\grid\\NWFD_SCMOC\\WIND\\10M_ABOVE_GROUND\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"output\": r\"\\\\10.28.27.93\\SCMOC\\WIND\\10M_ABOVE_GROUND\\YYYYMMDD\\YYMMDDHH.TTT.nc\",\n \"start\": datetime.datetime(2020, 5, 20, 8, 0),\n \"end\": datetime.datetime(2020, 6, 1, 8, 0),\n \"hour_range\": [8, 21, 12],\n \"dh_range\": [3, 241, 3],\n \"recover\": False\n },\n]\n\n\ndef copy_data_file(para_list):\n for para in para_list:\n time0 = para[\"start\"]\n time1 = datetime.datetime(time0.year,time0.month,time0.day,0,0)\n hour_list = np.arange(para[\"hour_range\"][0],para[\"hour_range\"][1],para[\"hour_range\"][2]).tolist()\n dh_list = np.arange(para[\"dh_range\"][0], para[\"dh_range\"][1], para[\"dh_range\"][2]).tolist()\n recover = para[\"recover\"]\n while time1 <= para[\"end\"]:\n for hour in hour_list:\n time2 = time1 +datetime.timedelta(hours=hour)\n for dh in dh_list:\n path_out = meteva.base.get_path(para[\"output\"],time2,dh)\n if recover or not os.path.exists(path_out):\n path_in = meteva.base.get_path(para[\"input\"],time2,dh)\n if os.path.exists(path_in):\n meteva.base.creat_path(path_out)\n shutil.copyfile(path_in,path_out)\n time1 = time1 + datetime.timedelta(hours=24)\n\n\n\nif __name__ == '__main__':\n #download_from_gds(para_example)\n copy_data_file(para_list1)\n\n\n\n","sub_path":"meteva/product/application/data_collection.py","file_name":"data_collection.py","file_ext":"py","file_size_in_byte":13756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"188101879","text":"# Create your views here.\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom homepage.models import *\n\n\ndef home(request):\n vars = {\n 'title': 'Proyecto DB - UBB',\n 'centralNuclear': getProductores(\"nuclear\"),\n 'centralSolar': getProductores(\"solar\"),\n 'centralHidroElectrica': getProductores(\"hidroElectrica\"),\n 'centralElectrica': getProductores(\"termicoElectrica\"),\n }\n contexto = RequestContext(request)\n return render_to_response('homepage.html', vars, contexto)\n","sub_path":"homepage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"240855250","text":"'''\nCreated on 22 Aug 2013\n\n@author: sjefferies\n'''\n\nimport time\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nfrom helper import SeleniumInstanceHelper\n\nclass MenuHelperFunctions:\n \n def __init__(self):\n self._selenium_instance = None \n \n #EWB Menu Actions\n\n def select_from_EWB_menu(self, menu_option_text, *args):\n \"\"\"\n Selects an option from an E-WorkBook Web menu.\n \n Can be used on any menu following the standard menu format used within EWB Web.\n \n NOTE: Simulates events using native events. Currently no fallback for browsers where native \n events are not supported in WebDriver (i.e. Safari).\n \n *Arguments*\n - _menu_option_text_ - the top level menu option to click on (if no *args are specified) \n or hover over (if *args are specified)\n - _*args_ - optional additional sub menu item text\n \n *Example*\n | Open Insert Menu |\n | Select From Menu | Insert File | Other |\n \"\"\"\n self._selenium_instance = SeleniumInstanceHelper()._get_selenium_instance()\n prev_menu = menu_option_text\n self._selenium_instance.wait_until_page_contains_element('ewb-popup-menu')\n self._menu_select('ewb-popup-menu', menu_option_text)\n for arg in args:\n ActionChains(self._selenium_instance._current_browser()).send_keys(Keys.ARROW_RIGHT).perform()\n self._selenium_instance.wait_until_page_contains_element('xpath=//div[contains(@class, \"x-menu-item-active\")]/a[text()=\"{0}\"]'.format(prev_menu))\n #self._ensure_menu_selected(prev_menu)\n prev_menu = arg\n menu_id = self._selenium_instance.get_element_attribute('xpath=//a[text()=\"{0}\"]/../../..@id'.format(arg))\n self._sub_menu_select(menu_id, arg)\n self._selenium_instance.wait_until_page_contains_element('xpath=//div[contains(@class, \"x-menu-item-active\")]/a[text()=\"{0}\"]'.format(prev_menu))\n ActionChains(self._selenium_instance._current_browser()).send_keys(Keys.RETURN).perform()\n\n def _ensure_menu_selected(self, menu_text, timeout=30):\n #checks a menu item is selected - private\n self._selenium_instance = SeleniumInstanceHelper()._get_selenium_instance()\n base_time = time.time()\n menu_selected = False\n while not menu_selected and (((time.time()-base_time) < timeout)):\n try:\n self._selenium_instance.wait_until_page_contains_element('xpath=//a[text()=\"{0}\"]/..[contains(@class, \"x-menu-item-active\")]'.format(menu_text))\n menu_selected = True\n except:\n self._selenium_instance._info(\"RETRYING ELEMENT LOCATION\")\n if not menu_selected:\n raise AssertionError('Menu item \"{0}\" not selected'.format(menu_text))\n\n def select_new_entity_type(self, creation_type_text, entity_type):\n \"\"\"\n Selects a new entity type from the E-WorkBook Web popup menu\n \n | Open Tile Header Tool Menu | Administrators |\n | Select New Entity Type | Create New | Project |\n \"\"\"\n self._selenium_instance = SeleniumInstanceHelper()._get_selenium_instance()\n self._menu_select('ewb-popup-menu', creation_type_text)\n ActionChains(self._selenium_instance._current_browser()).send_keys(Keys.ARROW_RIGHT).perform()\n if creation_type_text=='Use Record to Create':\n self._sub_menu_select('ewb-popup-menu-submenu-ewb-entity-menu-template', entity_type)\n else:\n self._sub_menu_select('ewb-popup-menu-submenu-ewb-entity-menu-new', entity_type)\n ActionChains(self._selenium_instance._current_browser()).send_keys(Keys.RETURN).perform()\n\n def _menu_select(self, menu_id, menu_option_text, load_timeout=30):\n \"\"\"\n Selects a menu option\n \"\"\"\n self._selenium_instance = SeleniumInstanceHelper()._get_selenium_instance()\n row_number = 0\n number_of_rows = 0\n base_time = time.time()\n while ((number_of_rows == 0) and ((time.time()-base_time) < load_timeout)):\n number_of_rows = self._selenium_instance.get_matching_xpath_count('//*[@id=\"{0}\"]/div/div'.format(menu_id))\n time.sleep(1)\n self._selenium_instance._info(\"Number of menu elements = '%s'\" % number_of_rows)\n for index in range(1, int(number_of_rows)+1):\n try:\n if self._selenium_instance.get_text('xpath=//*[@id=\"{0}\"]/div/div[{1}]/a'.format(menu_id, index)) == menu_option_text:\n row_number= index\n self._selenium_instance._info(\"Row number = '%s'\" % row_number)\n except ValueError:\n pass\n self._selenium_instance._info(\"Row number = '%s'\" % row_number)\n for i in range(int(row_number)):\n ActionChains(self._selenium_instance._current_browser()).send_keys(Keys.ARROW_DOWN).perform()\n \n def _sub_menu_select(self, menu_id, menu_option_text, load_timeout=30):\n \"\"\"\n Selects a sub-menu option\n \n SJ - Is this really needed? A sub-menu is just another menu...\n \"\"\"\n self._selenium_instance = SeleniumInstanceHelper()._get_selenium_instance()\n row_number = 0\n number_of_rows = 0\n number_of_unselectable_rows = 0\n base_time = time.time()\n while ((number_of_rows == 0) and ((time.time()-base_time) < load_timeout)):\n self._selenium_instance._info(\"Counting number of menu elements\")\n number_of_rows = int(self._selenium_instance.get_matching_xpath_count('//*[@id=\"{0}\"]/div/div'.format(menu_id)))\n number_of_selectable_rows = self._selenium_instance.get_matching_xpath_count('//*[@id=\"{0}\"]/div/div/a'.format(menu_id))\n number_of_unselectable_rows = int(number_of_rows) - int(number_of_selectable_rows)\n time.sleep(1)\n self._selenium_instance._info(\"Number of menu elements = '%s'\" % number_of_rows)\n for index in range(1, int(number_of_rows)+1):\n try:\n if self._selenium_instance.get_text('xpath=//*[@id=\"{0}\"]/div/div[{1}]'.format(menu_id, index)) == menu_option_text:\n row_number= index\n self._selenium_instance._info(\"Row number = '%s'\" % row_number)\n except ValueError:\n pass\n row_number = row_number - number_of_unselectable_rows\n self._selenium_instance._info(\"Row number = '%s'\" % row_number)\n for i in range(int(row_number)-1):\n ActionChains(self._selenium_instance._current_browser()).send_keys(Keys.ARROW_DOWN).perform() \n \n def menu_click(self, menu_locator, menu_option):\n self._selenium_instance = SeleniumInstanceHelper()._get_selenium_instance()\n menu_elem = self._selenium_instance._element_find(menu_locator, True, True)\n self._selenium_instance._info(\"Opening Menu '%s'\" % menu_locator)\n ActionChains(self._selenium_instance._current_browser()).move_to_element(menu_elem).perform()\n self._selenium_instance._info(\"Selecting Menu Option '%s'\" % menu_option)\n ActionChains(self._selenium_instance._current_browser()).click(self._selenium_instance._element_find(menu_option, True, True)).perform()","sub_path":"Resources/ElnCore/Keywords/Selenium/WebHelperFunctions/menu_helper_functions.py","file_name":"menu_helper_functions.py","file_ext":"py","file_size_in_byte":7360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"438192512","text":"#Producto Cruz - Zuriel Ernesto Morales Casas\nimport sys\n\nclass Relation:\n def __init__(self, source):\n self.schema = []\n self.records = []\n header_flag = True\n with open(source, \"rt\") as f:\n linenum = 1\n for line in f:\n if header_flag == True:\n header_flag = False\n for token in line.replace(\"\\n\", \"\").split(\",\"):\n if(token[0] != \"r\" and token[0] != \"e\" and token[0] != \"c\"):\n raise ValueError(\"Tipo de dato no reconocido.\")\n if not self.schemaHasField(token):\n self.schema.append(token)\n else:\n print(\"La relacion '%s' contiene nombres de campo ambiguos (%s).\"%(source, token))\n quit()\n self.schema_len = len(self.schema)\n else:\n linenum += 1\n data_row = line.replace(\"\\n\", \"\").split(\",\")\n if(len(data_row) != self.schema_len):\n print(\"Error en linea %i del archivo: Se esperaban %i campos pero la fila tiene %i.\"%(linenum, self.schema_len, len(data_row)))\n quit()\n else:\n new_record = []\n for i in range(len(data_row)):\n if(self.schema[i][0] == \"c\"):\n new_record.append(tokenToString(data_row[i]))\n elif(self.schema[i][0] == \"r\"):\n new_record.append(float(data_row[i]))\n elif(self.schema[i][0] == \"e\"):\n new_record.append(int(data_row[i]))\n else:\n raise ValueError(\"Tipo de dato no reconocido.\")\n self.records.append(tuple(new_record))\n del new_record\n\n def schemaHasField(self, field_name):\n return field_name in self.schema\n\n def getFieldType(self, field_name):\n for f in self.schema:\n if f == field_name:\n return f[1]\n return None\n\n def getFieldIndex(self, field_name):\n return self.schema.index(field_name) if field_name in self.schema else -1\n\n\ndef schCompat(a, b):\n if(type(a) != Relation or type(b) != Relation):\n raise ValueError(\"Function expects two 'Relation' objects.\")\n if len(a.schema) != len(b.schema):\n return False\n for i in range(len(a.schema)):\n if a.schema[i][0] != b.schema[i][0]:\n return False\n return True\n\n\ndef tokenToString(token):\n if(token[0] != '\"' or token[-1:] != '\"'):\n raise ValueError(\"Token {} no es una cadena valida.\".format(token))\n output = token[1:-1]\n if '\"' in output:\n raise ValueError(\"Token {} no es una cadena valida.\".format(token))\n return output\n\nif len(sys.argv) != 3:\n print(\"Se necesitan dos relaciones.\")\n quit()\n\nrel_a = Relation(sys.argv[1])\nrel_b = Relation(sys.argv[2])\n\n#check ambiguity between schemas\nfor field in rel_a.schema:\n if rel_b.schemaHasField(field):\n print(\"Nombres de campo duplicados entre relaciones ({}).\".format(field))\n quit()\n\n#print header\nflag = True\nfor field in rel_a.schema:\n sys.stdout.write(\"{}{}\".format(\",\" if not flag else \"\", field))\n flag = False\nfor field in rel_b.schema:\n sys.stdout.write(\",{}\".format(field))\nsys.stdout.write(\"\\n\")\n\n#build output tuples list\noutput_tuples = []\nfor a in rel_a.records:\n for b in rel_b.records:\n new_tuple = a + b\n if not new_tuple in output_tuples:\n output_tuples.append(new_tuple)\n\n#print out records\nfor t in output_tuples:\n flag = True\n for x in t:\n sys.stdout.write(\"{}{}\".format(\",\" if not flag else \"\", x if type(x) != str else '\"' + x + '\"'))\n flag = False\n sys.stdout.write(\"\\n\")\nsys.stdout.flush()\n","sub_path":"FBDD/Tarea2/cruz.py","file_name":"cruz.py","file_ext":"py","file_size_in_byte":4015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"646703161","text":"import requests\nimport re\nfrom data.url import Url\n\n\nclass Seed(object):\n def __init__(self, params):\n self.urlList = []\n self.params = {\n \"q\": params\n }\n\n def __repr__(self):\n return \"\".format(self.urlList)\n\n @classmethod\n def get_seed(cls, params):\n return cls(params)\n\n def generate_url_seeds_from_google(self):\n google_url = \"http://www.google.com/search\"\n response = requests.get(google_url, params=self.params)\n htmls = re.findall(r'.*?', response.text)\n\n for html in htmls:\n targetUrl = re.findall(r'https://.*?&', html)\n if len(targetUrl) == 0:\n print(\"Couldn't generate query seed from google, please try other query words. Or try again later\")\n else:\n self.urlList.append(targetUrl[0][:-1])\n\n self.urlList.pop(-1)\n\n def generate_url_seeds_from_bing(self):\n bing_url = \"https://www.bing.com/search\"\n response = requests.get(bing_url, params=self.params)\n htmls = re.findall(r'.*?', response.text)\n\n for html in htmls:\n self.urlList.append(html)\n\n def get_url_seed_list(self):\n return self.urlList\n\n\n\n","sub_path":"seed/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"342937666","text":"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('anime.urls')),\n path('accounts/', include('django.contrib.auth.urls')),\n path('accounts/', include('registration.urls')),\n path('contact/', include('contact.urls')),\n path('accounts/', include('allauth.urls')),\n path('oauth/', include('social_django.urls', namespace='social'))\n\n]\n\nurlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\nif settings.DEBUG:\n from django.conf.urls.static import static\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n\n\nadmin.site.site_header = \"Kyanime\"\nadmin.site.index_title = \"Panel de Administrador\"\nadmin.site.site_title = \"Kyanime, tu página\"\n","sub_path":"Kyanime/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"227742367","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2019 CERN.\n#\n# invenio-app-ils is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Related records API.\"\"\"\n\nfrom flask import current_app\nfrom invenio_records_rest.utils import obj_or_import_string\n\nfrom invenio_app_ils.errors import RelatedRecordError\n\n\ndef record_to_relation_dump(record, relation):\n \"\"\"Convert a record to a relation dump.\"\"\"\n return dict(\n pid=record[record.pid_field],\n pid_type=record._pid_type,\n relation_type=relation.name\n )\n\n\ndef get_node(record, relation):\n \"\"\"Get node for a record with a relation.\"\"\"\n PIDNodeClass = obj_or_import_string(relation.api)\n return PIDNodeClass(pid=record.pid, relation_type=relation)\n\n\nclass RelatedRecords(object):\n \"\"\"Manage related records.\"\"\"\n\n def __init__(self, parent):\n \"\"\"Initialize related records proxy.\n\n :param parent: Parent record\n \"\"\"\n self.parent = parent\n self.changed_related_records = []\n\n @property\n def editions(self):\n \"\"\"Get related editions.\"\"\"\n return self.get_related(RelatedRecords.edition_relation())\n\n @property\n def languages(self):\n \"\"\"Get related languages.\"\"\"\n return self.get_related(RelatedRecords.language_relation())\n\n def add_edition(self, record):\n \"\"\"Add a new related edition.\"\"\"\n self.add(record, RelatedRecords.edition_relation())\n\n def add_language(self, record):\n \"\"\"Add a new related language.\"\"\"\n self.add(record, RelatedRecords.language_relation())\n\n def add(self, record, relation):\n \"\"\"Add a new related record.\"\"\"\n self._add_record(\n record,\n relation,\n parent_node=self._parent_node(relation)\n )\n\n def _add_record(self, record, relation, parent_node=None):\n \"\"\"Add related record.\"\"\"\n if record == self.parent:\n raise RelatedRecordError(\n \"Cannot add itself ({} #{}) as a related {}.\".format(\n record.__class__.__name__,\n record[record.pid_field],\n relation.name\n )\n )\n record_node = get_node(record, relation)\n if record_node.is_parent or record_node.is_child:\n raise RelatedRecordError(\n (\"Failed to add {} #{} as a related {} to {} #{} because it \"\n \"already has relations.\").format(\n record.__class__.__name__,\n record[record.pid_field],\n relation.name,\n self.parent.__class__.__name__,\n self.parent[self.parent.pid_field]\n )\n )\n if parent_node is None:\n parent_node = get_node(self.parent, relation)\n self.dump_add(self.parent, record, relation, update_related=True)\n parent_node.insert_child(record.pid)\n\n def remove_edition(self, record):\n \"\"\"Remove related edition.\"\"\"\n self.remove(record, RelatedRecords.edition_relation())\n\n def remove_language(self, record):\n \"\"\"Remove related language.\"\"\"\n self.remove(record, RelatedRecords.language_relation())\n\n def remove(self, record, relation):\n \"\"\"Remove existing related record.\"\"\"\n self._remove_record(\n record,\n relation,\n parent_node=self._parent_node(relation)\n )\n\n def _remove_record(self, child, relation, parent_node=None):\n \"\"\"Remove related record with a relation.\"\"\"\n if parent_node is None:\n parent_node = get_node(self.parent, relation)\n parent_pid = parent_node.pid\n parent = self.parent\n is_parent_equal = parent_pid.pid_value == child[child.pid_field] and \\\n parent_pid.pid_type == child._pid_type\n if is_parent_equal:\n # Trying to remove parent\n # TODO: remove old relations and copy over relations to self.parent\n raise RelatedRecordError(\n (\"Cannot remove the {} relation from {} {}. Please remove this\"\n \" relation by editing {} {}.\").format(\n relation.name,\n self.parent.__class__.__name__,\n self.parent[self.parent.pid_field],\n child.__class__.__name__,\n child[child.pid_field]\n )\n )\n parent_node.remove_child(child.pid)\n self.dump_remove(parent, child, relation, update_related=True)\n\n def _parent_node(self, relation_type):\n \"\"\"Get the parent node with the given relation_type.\"\"\"\n node = get_node(self.parent, relation_type)\n parents = list(node.parents)\n is_child = len(parents) > 0\n if is_child:\n PIDNodeClass = obj_or_import_string(relation_type.api)\n return PIDNodeClass(pid=parents[0], relation_type=relation_type)\n return get_node(self.parent, relation_type)\n\n def get_related(self, relation_type):\n \"\"\"Get all related records from the related records dump.\"\"\"\n return [\n self.parent.get_record_by_pid(obj[\"pid\"], pid_type=obj[\"pid_type\"])\n for obj in self.parent[\"related_records\"]\n if obj[\"relation_type\"] == relation_type.name\n ]\n\n def _get_related_db(self, relation_type):\n \"\"\"Get all related records from the DB.\"\"\"\n node = self._parent_node(relation_type)\n children = [node.pid] + list(node.children)\n return [\n self.parent.get_record_by_pid(\n child.pid_value,\n pid_type=child.pid_type\n )\n for child in children\n if child.pid_value != self.parent[self.parent.pid_field]\n ]\n\n def dump_add(self, parent, record, relation, update_related=False):\n \"\"\"Add record to related records dump.\"\"\"\n obj = record_to_relation_dump(record, relation)\n related_records = parent[\"related_records\"]\n if obj not in related_records:\n related_records.append(obj)\n self.dump_add(record, parent, relation)\n self.changed_related_records.append(record)\n\n if update_related:\n for related in self._get_related_db(relation):\n self.changed_related_records.append(related)\n self.dump_add(related, record, relation)\n\n def dump_remove(self, parent, record, relation, update_related=False):\n \"\"\"Remove record to related records dump.\"\"\"\n obj = record_to_relation_dump(record, relation)\n related_records = parent[\"related_records\"]\n if obj in related_records:\n related_records.remove(obj)\n self.dump_remove(record, parent, relation)\n self.changed_related_records.append(record)\n\n if update_related:\n for related in self._get_related_db(relation):\n self.changed_related_records.append(related)\n self.dump_remove(related, record, relation)\n\n @staticmethod\n def edition_relation():\n \"\"\"Get edition relation type.\"\"\"\n return current_app.config[\"EDITION_RELATION\"]\n\n @staticmethod\n def language_relation():\n \"\"\"Get language relation type.\"\"\"\n return current_app.config[\"LANGUAGE_RELATION\"]\n\n @staticmethod\n def get_relation_by_name(name):\n \"\"\"Get the relation_type by name.\"\"\"\n for relation in current_app.config[\"PIDRELATIONS_RELATION_TYPES\"]:\n if relation.name == name:\n return relation\n raise RelatedRecordError(\n \"No relation type with name: {}\".format(name)\n )\n","sub_path":"invenio_app_ils/records/related/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":7767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"651578609","text":"import sys\n\nimport copy\nimport numpy as np\nfrom libact.labelers import IdealLabeler\nfrom libact.query_strategies import RandomSampling\nfrom libact.query_strategies import UncertaintySampling\nfrom sklearn.datasets import load_files\nfrom sklearn.model_selection import train_test_split\nfrom libact.base.dataset import Dataset\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom model.naive_bayes import NaiveBayes\nimport matplotlib.pyplot as plt\n\n\ndef run(trn_ds, tst_ds, lbr, model, qs, quota):\n error_trained_data, error_test_data = [], []\n\n for _ in range(quota):\n # Standard usage of libact objects\n ask_id = qs.make_query()\n X, _ = zip(*trn_ds.data)\n lb = lbr.label(X[ask_id])\n trn_ds.update(ask_id, lb)\n\n model.train(trn_ds)\n error_trained_data = np.append(error_trained_data, 1 - model.score(trn_ds))\n error_test_data = np.append(error_test_data, 1 - model.score(tst_ds))\n\n return error_trained_data, error_test_data\n\nsys.argv[0]= '/home/salman/thesis/corpuses/movie_reviews'\n\nmovie_reviews_data_folder = sys.argv[0]\nmovie_reviews_dataset = load_files(movie_reviews_data_folder, shuffle=False)\nprint(\"n_samples: %d\" % len(movie_reviews_dataset.data))\n\nreviews, sentiments= Dataset(movie_reviews_dataset.data, movie_reviews_dataset.target).format_sklearn()\nreviews_train, reviews_test, sentiments_train, sentiments_test = train_test_split(\n reviews, sentiments, test_size=0.25)\n\n# S = set(X) # collect unique label names\n# D = dict( zip(S, range(len(S))) ) # assign each string an integer, and put it in a dict\n# Y = [D[y2_] for y2_ in X]\n\ncount_vectorizer = CountVectorizer()\nreviews_train_counts = count_vectorizer.fit_transform(reviews_train)\nprint(reviews_train_counts.shape)\n\ntfidf_transformer = TfidfTransformer()\nreviews_train_tfidf = tfidf_transformer.fit_transform(reviews_train_counts)\nprint(reviews_train_tfidf.shape)\n\ntrain_ds = Dataset(reviews_train_tfidf.toarray(), np.concatenate(\n [sentiments_train[:10], [None] * (len(sentiments_train) - 10)]))\n# classifier = NaiveBayes.fit(reviews_train_tfidf, sentiments_train)\n\n\nreviews_test_counts= count_vectorizer.transform(reviews_test)\nreviews_test_tfidf= tfidf_transformer.transform(reviews_test_counts)\nprint(reviews_test_tfidf.shape)\ntest_ds = Dataset(reviews_test_tfidf.toarray(), sentiments_test)\n\ntrain_ds_copy = copy.deepcopy(train_ds)\nfully_labeled_trn_ds = Dataset(reviews_train_tfidf.toarray(), sentiments_train)\nlbr = IdealLabeler(fully_labeled_trn_ds)\nquota = len(sentiments_train) - 10\nqs = UncertaintySampling(train_ds, method='sm', model= NaiveBayes())\nmodel = NaiveBayes()\nclassifier = model.train(train_ds)\n#\nerror_uncertainty_train, error_uncertainty_test = run(train_ds, test_ds, lbr, model, qs, quota)\n\n# qs2 = RandomSampling(train_ds_copy)\n# model = NaiveBayes()\n#\n# error_sample_train, error_sample_test = run(train_ds_copy, test_ds, lbr, model, qs2, quota)\n\n# # Plot the learning curve of UncertaintySampling to RandomSampling\n# # The x-axis is the number of queries, and the y-axis is the corresponding\n# # error rate.\nquery_num = np.arange(1, quota + 1)\nplt.plot(query_num, error_uncertainty_train, 'b', label='Uncertainty Training')\n# plt.plot(query_num, error_sample_train, 'r', label='Random Train')\nplt.plot(query_num, error_uncertainty_test, 'g', label='Uncertainty Test')\n# plt.plot(query_num, error_sample_test, 'k', label='Random Test')\nplt.xlabel('Number of Queries')\nplt.ylabel('Error')\nplt.title('Experiment Result')\nplt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),\n fancybox=True, shadow=True, ncol=5)\nplt.show()\n\n# def calculateTFIDF(review_data):\n# reviews_counts = count_vectorizer.transform(review_data)\n# reviews_tfidf = tfidf_transformer.transform(reviews_counts)\n# return reviews_tfidf\n#\n# def predictReviews(review):\n# predicted = classifier.predict(calculateTFIDF(review))\n# return predicted\n#\n# revi= ['its a great movie','not a bad movie']\n# predicts= predictReviews(revi)\n#\n# for doc, category in zip(revi, predicts):\n# print('%r => %s' % (doc, movie_reviews_dataset.target_names[category]))\n\n","sub_path":"model/read_reviews.py","file_name":"read_reviews.py","file_ext":"py","file_size_in_byte":4258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"490399518","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# Author : Guillermo Herrera Banda: guillermo.herrera@bitconsultores-ec.com\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv\nfrom openerp.osv import expression\n\n\nclass tariff_item(osv.osv):\n _name = 'tariff.item'\n\n def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=80):\n if args is None:\n args = []\n if operator in expression.NEGATIVE_TERM_OPERATORS:\n domain = [('code', operator, name), ('name', operator, name)]\n else:\n domain = ['|', ('code', operator, name), ('name', operator, name)]\n ids = self.search(cr, user, expression.AND([domain, args]), limit=limit, context=context)\n return self.name_get(cr, user, ids, context=context)\n\n def name_get(self, cr, uid, ids, context=None):\n if not ids:\n return []\n if isinstance(ids, (int, long)):\n ids = [ids]\n reads = self.read(cr, uid, ids, ['name', 'code'], context=context)\n res = []\n for record in reads:\n name = record['name']\n if record['code']:\n name = '[' + record['code'] + ']' + ' ' + name\n res.append((record['id'], name))\n return res\n\n _columns = {\n 'code': fields.char('Codigo'),\n 'name': fields.char('Nombre'),\n 'apply': fields.boolean('aplica credito?')\n\n }\n\n\n","sub_path":"o2s_purchase_importation/tariff_item.py","file_name":"tariff_item.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"526186520","text":"import pika\nimport sys\nimport logging\nimport ssl\n\nlogging.basicConfig(level=logging.INFO)\n\ncp=pika.ConnectionParameters(\nssl=True,\nssl_options = dict(\nssl_version=ssl.PROTOCOL_TLSv1,\nca_certs=\"/home/diane/tls-gen/basic/result/ca_certificate.pem\",\nkeyfile=\"/home/diane/tls-gen/basic/result/client_key.pem\",\ncertfile=\"/home/diane/tls-gen/basic/result/client_certificate.pem\",\ncert_reqs=ssl.CERT_REQUIRED))\n\n\nconnection = pika.BlockingConnection(cp)\nchannel = connection.channel()\n\nchannel.queue_declare(queue='hello')\nmessage =\"Hello World\"\n\nchannel.publish(exchange='', routing_key='hello', body=message)\nprint(\" [x] Sent %r\" % message)\nconnection.close()\n","sub_path":"Implementation/Examples/AMQP/Receipt_Sending_TLS/send_TLS.py","file_name":"send_TLS.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"6012261","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.mixture import GaussianMixture\nfrom sklearn.svm import LinearSVC, SVC\nfrom sklearn.datasets import make_regression\nfrom sklearn.linear_model import LinearRegression\n\n# K = 8\nN = 3 # number of classes\nM = 100 # number of data for each class\nmean = [[1, 1], [7, 7], [15, 1]] # means of classification data\ncov = [[[12, 0], [0, 1]], [[8, 3], [3, 2]], [[2, 0], [0, 2]]] # covariance of classification data\n\nclass ClassData:\n def __init__(self, data=np.empty(shape=(0, 2)), labels=np.empty(shape=(0, 1)), pair=np.empty(shape=(0, 3)), gridx=None, gridy=None):\n self.data = data\n self.labels = labels\n self.pair = pair\n self.gridx = gridx\n self.gridy = gridy\n self.boundary = None\n\ncls_algorithms = [\"Naive Bayes\", \"KNN\", \"EM\", \"Logistic Regression\", \"SVM\"]\n\norigin = ClassData()\ntrain = ClassData()\ntest = ClassData()\n\nclass RegData:\n def __init__(self, x=np.empty(shape=(0, 1)), y=np.empty(shape=(0, 1)), predict=np.empty(shape=(0, 1))):\n self.x = x\n self.y = y\n self.predict = predict\n\nreg_origin = RegData()\nreg_train = RegData()\nreg_test = RegData()\n\nfig = plt.figure()\n\ndef generate_classification_data():\n global origin, train, test\n\n for i in range(N):\n origin.data = np.append(origin.data, np.random.multivariate_normal(mean[i], cov[i], M), axis=0)\n origin.labels = np.append(origin.labels, np.array([i] * M))\n origin.pair = np.append(origin.data, origin.labels.reshape((len(origin.labels), 1)), axis = 1)\n train.pair, test.pair = np.split(np.random.permutation(origin.pair), [int(N*M*0.7)])\n train.data, train.labels = np.split(train.pair, [2], axis=1)\n test.data, test.labels = np.split(test.pair, [2], axis=1)\n x_min, x_max = origin.data[:, 0].min() - 1, origin.data[:, 0].max() + 1\n y_min, y_max = origin.data[:, 1].min() - 1, origin.data[:, 1].max() + 1\n origin.gridx, origin.gridy = train.gridx, train.gridy = test.gridx, test.gridy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))\n\ndef generate_regression_data():\n global reg_origin, reg_train, reg_test\n x, y = make_regression(n_samples=M, n_features=1, noise=40.0, shuffle=False, bias=10.0)\n data = np.append(x, y.reshape(len(y), 1), axis=1)\n data = data[data[:,0].argsort(axis=0)]\n reg_origin.x, reg_origin.y = data.T\n reg_origin.x = reg_origin.x.reshape(len(reg_origin.x), 1)\n reg_origin.y = reg_origin.y.reshape(len(reg_origin.y), 1)\n reg_train.x, reg_test.x = np.split(reg_origin.x, [int(M*0.7)])\n reg_train.y, reg_test.y = np.split(reg_origin.y, [int(M*0.7)])\n\ndef fit(algorithm):\n global train\n\n if algorithm == \"Naive Bayes\":\n model = GaussianNB()\n elif algorithm == \"KNN\":\n model = KNeighborsClassifier(3)\n elif algorithm == \"EM\":\n model = GaussianMixture(3)\n elif algorithm == \"Logistic Regression\":\n model = LogisticRegression(multi_class='auto', solver='lbfgs')\n elif algorithm == \"SVM\":\n model = SVC(kernel=\"linear\")\n else:\n raise ValueError(\"Wrong algorithm type\")\n\n res = ClassData(data=train.data, labels=train.labels, gridx=train.gridx, gridy=train.gridy)\n model.fit(train.data, train.labels.ravel())\n model.algorithm = algorithm\n res.boundary = model.predict(np.c_[res.gridx.ravel(), res.gridy.ravel()]).reshape(res.gridx.shape)\n\n return (res, model)\n\ndef classification(model):\n global train, test\n\n res = ClassData(data=test.data, gridx=test.gridx, gridy=test.gridy)\n res.labels = model.predict(test.data)\n res.boundary = model.predict(np.c_[res.gridx.ravel(), res.gridy.ravel()]).reshape(res.gridx.shape)\n\n return res\n\ndef regression(model):\n global reg_train\n\n res = RegData(x=reg_test.x, y=reg_test.y)\n model.fit(reg_train.x, reg_train.y)\n res.predict = model.predict(res.x)\n\n return (res, model)\n\ndef plot_class(data, pos, title=None, model=None, boundary=False):\n global fig\n\n color = ('ro', 'go', 'bo') # colors of each clpass\n ax = fig.add_subplot(6, 3, pos)\n # ax.set_title(title)\n ax.text(0, 0, title, horizontalalignment='left', verticalalignment='bottom', fontsize='large', fontweight='bold', transform=ax.transAxes)\n # ax.axis('equal')\n ax.set_xlim(data.gridx[0][0], data.gridx[0][-1])\n ax.set_ylim(data.gridy[0][0], data.gridy[-1][0])\n for i in range(len(data.data)):\n x, y = data.data[i].T\n ax.plot(x, y, color[int(data.labels[i])])\n if model is not None and model.algorithm=='SVM':\n boundary = False\n for i in range(len(model.intercept_)):\n ax.plot(data.gridx[0], -data.gridx[0]*(model.coef_[i][0]/model.coef_[i][1])-model.intercept_[i]/model.coef_[i][1], 'xkcd:black')\n if len(data.data) > N*M*0.3:\n for sv in model.support_vectors_:\n x, y = sv\n ax.plot(x, y, 'ko')\n if boundary:\n if data.boundary is None:\n raise ValueError(\"you must calculate boundary before plot\")\n ax.contourf(data.gridx, data.gridy, data.boundary, alpha=0.2)\n\ndef plot_reg(data, pos, title, model=None):\n global reg_origin, reg_train\n\n ax = fig.add_subplot(6, 3, pos)\n ax.text(0, 0, title, horizontalalignment='left', verticalalignment='bottom', fontsize='large', fontweight='bold', transform=ax.transAxes)\n if model is not None:\n ax.scatter(reg_train.x, reg_train.y, c='g')\n ax.scatter(data.x, data.y, c='r')\n ax.plot(reg_origin.x, model.predict(reg_origin.x), c='k')\n else:\n ax.scatter(data.x, data.y, c='b')\n\ndef main():\n global cls_algorithms, fig, test, reg_train\n \n generate_regression_data()\n plot_reg(reg_origin, 1, 'original regression data')\n res, model = regression(LinearRegression())\n plot_reg(res, 2, 'Linear regression', model=model)\n\n generate_classification_data()\n plot_class(origin, 3, 'original classification data')\n for idx in range(5):\n sv = ds = None\n train_res, model = fit(cls_algorithms[idx])\n test_predict = classification(model)\n test_res = test\n test_res.boundary = test_predict.boundary\n plot_class(train_res, (idx+1)*3+1, cls_algorithms[idx]+' training data', model, boundary=True)\n plot_class(test_res, (idx+1)*3+2, cls_algorithms[idx]+' test data', model, boundary=True)\n plot_class(test_predict, (idx+1)*3+3, cls_algorithms[idx]+' prediction results', model, boundary=False)\n plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)\n plt.show()\n \n\nif __name__=='__main__':\n main()\n","sub_path":"HW2/hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":6777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"244293671","text":"import matplotlib.pyplot as plt\nfrom pyfem2 import *\n\nEl = PlaneStrainQuad4Reduced\n\nE = 100\nNu = 0\nV = FiniteElementModel('Test')\nV.Mesh(p=[[-1,-1],[1,-1],[1,1],[-1,1]], t=[[0,1,2,3]])\nV.ElementBlock('All', ALL)\nV.Material('Material-1')\nV.materials['Material-1'].Elastic(E=E, Nu=Nu)\nV.AssignProperties('All', El, 'Material-1', t=1, hourglass_control=True)\n\nV.PrescribedBC((0,3), X)\nV.PrescribedBC((0,), Y)\n\nstep = V.StaticStep()#solver=NEWTON)\nstep.ConcentratedLoad(1, X, 5.)\nstep.ConcentratedLoad(2, X, 5.)\nstep.run()\n\nV.Plot2D(deformed=True)\n#print(V.dofs.reshape(-1,2))\n#print(V.steps.last.frames[-1].field_outputs['S'].data[0,:,0])\nplt.show()\n","sub_path":"data/it1.py","file_name":"it1.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"433839031","text":"from twisted.internet.protocol import Protocol, ClientFactory as CF\nfrom twisted.internet import defer, reactor\n\nimport logging\nimport json\n\nclass ClientProtocol(Protocol):\n\n def __init__(self, config):\n self.logger = logging.getLogger(self.__class__.__name__)\n self.config = config\n self._connection_defer = defer.Deferred()\n\n def onCallback(func):\n def _tmp(self, *args, **kwargs):\n returnDefer = defer.Deferred()\n\n def callAndSet():\n self._current_defer = defer.Deferred()\n returnValue = func(self, *args, **kwargs)\n self._current_defer.addCallback(\n lambda r: returnDefer.callback(returnValue)\n )\n return self._current_defer\n\n ad = lambda d: callAndSet() if d is None else d.addCallback(ad)\n self._connection_defer.addCallback(ad)\n\n return returnDefer\n\n return _tmp\n\n def dataReceived(self, data):\n self._logPeer('Received data from')\n self.logger.info('Data: %s', data)\n self._current_defer.callback(None)\n\n def connectionMade(self):\n self._logPeer('Connection ready to')\n self._connection_defer.callback(None)\n\n def connectionLost(self, reason):\n self._logPeer('Connection lost to')\n self.logger.info('Reason: %s', reason)\n\n @onCallback\n def sendStart(self):\n self._logPeer('Sending start command to')\n jsonString = json.dumps({ 'command': 'start' })\n self.transport.write(jsonString.encode())\n return self\n\n @onCallback\n def sendConfig(self):\n self._logPeer('Sending configuration to')\n jsonString = json.dumps(self.config)\n self.transport.write(jsonString.encode())\n return self\n\n @onCallback\n def sendStop(self):\n self._logPeer('Sending stop command to')\n jsonString = json.dumps({ 'command': 'stop' })\n self.transport.write(jsonString.encode())\n return self\n\n @onCallback\n def getLogs(self):\n self._logPeer('Sending stop command to')\n jsonString = json.dumps({ 'command': 'status' })\n self.transport.write(jsonString.encode())\n return self\n\n def _logPeer(self, message):\n dst = self.transport.getPeer()\n self.logger.info('%s %s:%s', message, dst.host, dst.port)\n\n\nclass ClientFactory(CF):\n\n def __init__(self, configs, isStopping = False, isLogging = False, port = 38388):\n self.logger = logging.getLogger(self.__class__.__name__)\n self.protocols = {}\n for host,config in configs:\n self.logger.info('Creating connection to %s:%s', host, port)\n self.protocols[host] = ClientProtocol(config)\n reactor.connectTCP(host, port, self)\n\n if isStopping:\n d = defer.gatherResults(\n [p.sendStop() for p in self.protocols.values()]\n )\n d.addCallback(lambda r: reactor.stop())\n elif isLogging:\n d = defer.gatherResults(\n [p.getLogs() for p in self.protocols.values()]\n )\n d.addCallback(lambda r: reactor.stop())\n else:\n d = defer.gatherResults(\n [p.sendConfig() for p in self.protocols.values()]\n )\n d.addCallback(lambda r: [p.sendStart() for p in r])\n d.addCallback(lambda ds: defer.gatherResults(ds).addCallback(\n lambda r: reactor.stop()\n ))\n\n def buildProtocol(self, addr):\n self.logger.info('Building protocol for %s:%s', addr.host, addr.port)\n return self.protocols[addr.host]\n\n def startedConnecting(self, connector):\n dst = connector.getDestination()\n self.logger.info('Starting to connect to %s:%s', dst.host, dst.port)\n\n def clientConnectionLost(self, connector, reason):\n dst = connector.getDestination()\n self.logger.info('Lost connection to %s:%s', dst.host, dst.port)\n self.protocols[dst.host] = None\n\n def clientConnectionFailed(self, connector, reason):\n dst = connector.getDestination()\n self.logger.info('Connection failed to %s:%s', dst.host, dst.port)\n self.logger.info('Reason: %s', reason)\n self.protocols[dst.host] = None\n","sub_path":"scripts/src/son/client/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"27812457","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\n# Hand coded one hot encoding for \"hello\"\nh = [1, 0, 0, 0]\ne = [0, 1, 0, 0]\nl = [0, 0, 1, 0]\no = [0, 0, 0, 1]\n\n# One cell RNN input_dim = 4, output_dim=2, sequence -> 5\ncell = nn.RNN(input_size=4, hidden_size=2, batch_first=True)\n\n# provide random prev hidden-state (batch_size, sequence_size, feature)\nhidden = Variable(torch.randn(1, 1, 2))\n\n# Propagate through RNN\ninputs = Variable(torch.tensor([h, e, l, l, o]).type(torch.FloatTensor))\nfor one in inputs:\n one = one.view(1, 1, -1)\n out, hidden = cell(one, hidden)\n print(\"One input size :\", one.size(), \"\\tOut size: \", out.size())\n\n# Adjustment - 1: We can do the whole at once through seq_len\ninputs = inputs.view(1, 5, -1)\nout, hidden = cell(inputs, hidden)\nprint(\"Squence input size : \", inputs.size(),\"\\tHidden size: \",hidden.size(), \"\\tOut size : \", out.size())\n\n# Adjustment - 2: Now we want to feed batch of data\ninputs = Variable(torch.Tensor([[h, e, l, l, o],\n [e, o, l, l, l],\n [l, l, e, e, l]]).type(torch.FloatTensor))\n# update initial hidden size accrodingly\nhidden = Variable(torch.randn(1, 3, 2))\n\nout, hidden = cell(inputs, hidden)\nprint(\"Squence input size : \", inputs.size(),\"\\tHidden size: \",hidden.size(), \"\\tOut size : \", out.size())\n","sub_path":"RNNs/1_basic_rnn.py","file_name":"1_basic_rnn.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"527560974","text":"from setuptools import setup\n\nREQUIRED=[\n 'scikit-learn>=0.23.2',\n 'tensorflow>=2.3.1',\n 'keras>=2.4.3',\n 'pillow>=8.0.0',\n 'matplotlib>=3.3.2',\n 'pydot>=1.4.1',\n 'pyclickhouse>=0.6.4',\n 'lru-dict>=1.1.6',\n 'pytest>=6.1.1',\n 'dill>=0.3.2',\n 'pytz>=2020.1',\n 'tqdm>=4.50.2',\n 'ujson>=4.0.1',\n 'scandir>=1.10.0',\n 'pymongo>=3.11.0',\n 'numpy>=1.19.2',\n 'lru-dict>=1.1.6'\n]\n\nsetup(name='iwlearn3',\n version='0.1.4',\n description='Immowelt Machine Learning Framework (Python 3)',\n url='https://github.com/mfridental/iwlearn',\n download_url = 'https://github.com/mfridental/iwlearn/archive/0.1.4.tar.gz',\n keywords = ['Scikit-Learn', 'Tensorflow', 'Keras', 'Machine Learning'],\n classifiers=[\n \"Programming Language :: Python :: 3\"\n ],\n author='Maxim Fridental (Maintainer)',\n author_email='maxim@fridental.de',\n license='Apache2',\n packages=['iwlearn', 'iwlearn.models', 'iwlearn.training', 'iwlearn.storage'],\n install_requires=REQUIRED,\n test_suite='tests',\n zip_safe=False)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"122462034","text":"import os\nfrom PyQt5.QtCore import QVariant\n\nlyr = iface.activeLayer()\nif lyr is None:\n raise Exception('select layer in TOC')\n\nskip_cnt = 0\nnull_cnt = 0\nqgis_invalid_cnt = 0\noverall_vertex_cnt = 0\nfeat_cnt = 0\nfeats = lyr.selectedFeatures() if lyr.selectedFeatureCount() > 0 else lyr.getFeatures()\nmultipart_cnt = 0\ngeos_invalid_cnt = 0\nfor in_feat in feats:\n feat_cnt+=1\n in_geom = in_feat.geometry()\n if in_geom is None:\n print(in_feat.id(), 'NULL geometry, skipped')\n skip_cnt += 1\n null_cnt += 1\n continue\n if in_geom.isMultipart():\n multipart_cnt +=1\n polygons = in_geom.asMultiPolygon()\n else:\n polygons = [in_geom.asPolygon()]\n part_idx = 0\n for polygon in polygons:\n if len(polygon) > 100:\n print('fid:', in_feat.id(), 'rings:', len(polygon))\n ring_idx = 0\n for ring in polygon:\n vertex_cnt = len(ring)\n overall_vertex_cnt += vertex_cnt\n if vertex_cnt > 3000:\n print('fid:', in_feat.id(), ' part:', part_idx, ' ring:', ring_idx, ' vertices:', vertex_cnt)\n# for vertex in ring:\n# if vertex[0] <= -180 or vertex[0] >= 180 or vertex[1] <= -90 or vertex[1] >= 90:\n# print('fid:', in_feat.id(), 'out of bounds:', vertex)\n ring_idx += 1\n part_idx += 1\n if not in_geom.isGeosValid ():\n print('fid:', in_feat.id(), 'NOT geos valid')\n geos_invalid_cnt += 1\n continue\n geom_errors = in_geom.validateGeometry()\n if len(geom_errors) > 0:\n print('fid:', in_feat.id(), 'geometry NOT valid:')\n for geom_error in geom_errors:\n print(geom_error.what())\n print('fid:', in_feat.id(), 'skipped')\n skip_cnt += 1\n qgis_invalid_cnt += 1\n\nprint('-------')\nprint('layer feature count', lyr.featureCount())\nprint('dataprovider feature count', lyr.dataProvider().featureCount())\nprint('analyzed features', feat_cnt)\nprint('multipart features', multipart_cnt)\nprint('skipped:', skip_cnt)\nprint('null geometries', null_cnt)\nprint('qgis invalid:', qgis_invalid_cnt)\nprint('geos invalid', geos_invalid_cnt)\nprint('overall_vertex_cnt', overall_vertex_cnt)\nprint('finished')","sub_path":"QGIS/check-geometry-validity.py","file_name":"check-geometry-validity.py","file_ext":"py","file_size_in_byte":2239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"464725471","text":"'''\n7. String segmentation\nYou are given a dictionary of words and a large input string. You have to find out whether the input string can be completely segmented into the words of a given dictionary. The following two examples elaborate on the problem further.\n\nGiven a dictionary of words.\n\napple\napple\npear\npie\n\nInput string of “applepie” can be segmented into dictionary words.\n\napple\npie\nInput string “applepeer” cannot be segmented into dictionary words.\n\napple\npeer\n\n'''\n\ndef can_segment_string(s, dictionary):\n n = len(s)\n for i in range (1, n + 1):\n firstWord = s[0:i]\n if firstWord in dictionary:\n secondWord = s[i:]\n if secondWord in dictionary or can_segment_string(secondWord, dictionary):\n return True\n return False\n\n#tested in browser","sub_path":"Python/strSegmenter.py","file_name":"strSegmenter.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"275783650","text":"def tri_from_file(path):\n### Reads file and saves the string in the file as a variable ###\n file = open(path)\n sides = file.read()\n l1, l2, l3 = [int(i) for i in sides.split()]\n### Process Content ###\n #Checks to see if its a triangle\n if (l1 + l2 ) > l3 and (l1 + l3) > l2 and (l2 + l3) > l1:\n #Three equal sides\n if(l1==l2==l3):\n #Returning string\n return(\"Equilátero\")\n #Two equl sides\n if(l1==l2 or l1==l3 or l2==l3):\n #Returning string\n return(\"Isóceles\")\n #No equal sides\n if(l1 != l2 != l3):\n #Returning string\n return(\"Escaleno\")\n #Not a triangle at all\n else:\n #Returning string\n return(\"No triángulo\")\n # close the damn file!\n file.close()\n### Main Function ###\nif __name__ == '__main__':\n print (tri_from_file(\"equi1.txt\"))","sub_path":"ago-dic-2020/ErickEscarcega/primer parcial/primer_parcial.py","file_name":"primer_parcial.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"241428837","text":"import pybullet as p\nimport pybullet_data\nimport time\n\n# 连接引擎\n_ = p.connect(p.GUI)\n\n# 添加资源路径\np.setAdditionalSearchPath(pybullet_data.getDataPath())\np.setPhysicsEngineParameter(numSolverIterations=10)\n\n# 载入地面模型,useMaximalCoordinates加大坐标刻度可以加快加载\np.loadURDF(\"plane100.urdf\", useMaximalCoordinates=True)\n\n# 创建过程中不渲染\np.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 0)\n# 不展示GUI的套件\np.configureDebugVisualizer(p.COV_ENABLE_GUI, 0)\n# 禁用 tinyrenderer\np.configureDebugVisualizer(p.COV_ENABLE_TINY_RENDERER, 0)\n\np.setGravity(0, 0, -10)\np.setRealTimeSimulation(1)\n\nshift = [0, -0.02, 0]\nscale = [1, 1, 1]\n\n# 创建视觉形状和碰撞箱形状\nvisual_shape_id = p.createVisualShape(\n shapeType=p.GEOM_MESH,\n fileName=\"duck.obj\",\n rgbaColor=[1, 1, 1, 1],\n specularColor=[0.4, 0.4, 0],\n visualFramePosition=shift,\n meshScale=scale\n)\n\ncollision_shape_id = p.createCollisionShape(\n shapeType=p.GEOM_MESH,\n fileName=\"duck_vhacd.obj\",\n collisionFramePosition=shift,\n meshScale=scale\n)\n\n# 使用创建的视觉形状和碰撞箱形状使用createMultiBody将两者结合在一起\n# p.createMultiBody(\n# baseMass=1,\n# baseCollisionShapeIndex=collision_shape_id,\n# baseVisualShapeIndex=visual_shape_id,\n# basePosition=[0, 0, 2],\n# useMaximalCoordinates=True\n# )\nfor i in range(3):\n p.createMultiBody(\n baseMass=1,\n baseCollisionShapeIndex=collision_shape_id,\n baseVisualShapeIndex=visual_shape_id,\n basePosition=[0, 0, 2 * i],\n useMaximalCoordinates=True\n )\n\n# 创建结束,重新开启渲染\np.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 1)\n\nwhile (1):\n time.sleep(1./240.)\n","sub_path":"self_learning/test/demo04.py","file_name":"demo04.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"603414583","text":"from collections import OrderedDict\nfrom scipy.spatial.transform import Rotation as R\nimport numpy as np\nimport json\n\n\ndef pretty_print(ob):\n print(json.dumps(ob, indent=4))\n\n\ndef euler_to_rot(angles):\n # Euler ZYX to Rot\n # Note that towr has (x, y, z) order\n x = angles[0]\n y = angles[1]\n z = angles[2]\n ret = np.array([\n np.cos(y) * np.cos(z),\n np.cos(z) * np.sin(x) * np.sin(y) - np.cos(x) * np.sin(z),\n np.sin(x) * np.sin(z) + np.cos(x) * np.cos(z) * np.sin(y),\n np.cos(y) * np.sin(z),\n np.cos(x) * np.cos(z) + np.sin(x) * np.sin(y) * np.sin(z),\n np.cos(x) * np.sin(y) * np.sin(z) - np.cos(z) * np.sin(x), -np.sin(y),\n np.cos(y) * np.sin(x),\n np.cos(x) * np.cos(y)\n ]).reshape(3, 3)\n return ret\n\n\ndef quat_to_rot(quat):\n \"\"\"\n Parameters\n ----------\n quat (np.array): scalar last quaternion\n\n Returns\n -------\n ret (np.array): SO3\n\n \"\"\"\n return (R.from_quat(quat)).as_matrix()\n\n\ndef rot_to_quat(rot):\n \"\"\"\n Parameters\n ----------\n rot (np.array): SO3\n\n Returns\n -------\n quat (np.array): scalar last quaternion\n\n \"\"\"\n return R.from_matrix(rot).as_quat()\n\n\ndef smooth_changing(ini, end, dur, curr_time):\n ret = ini + (end - ini) * 0.5 * (1 - np.cos(curr_time / dur * np.pi))\n if curr_time > dur:\n ret = end\n\n return ret\n\n\ndef smooth_changing_vel(ini, end, dur, curr_time):\n ret = (end - ini) * 0.5 * (np.pi / dur) * np.sin(curr_time / dur * np.pi)\n if curr_time > dur:\n ret = 0.\n\n return ret\n\n\ndef smooth_changing_acc(ini, end, dur, curr_time):\n ret = (end - ini) * 0.5 * (np.pi / dur) * (np.pi / dur) * np.cos(\n curr_time / dur * np.pi)\n if curr_time > dur:\n ret = 0.\n\n return ret\n\n\ndef quat_to_exp(quat):\n img_vec = np.array([quat[0], quat[1], quat[2]])\n w = quat[3]\n theta = 2.0 * np.arcsin(\n np.sqrt(img_vec[0] * img_vec[0] + img_vec[1] * img_vec[1] +\n img_vec[2] * img_vec[2]))\n\n if np.abs(theta) < 1e-4:\n return np.zeros(3)\n ret = img_vec / np.sin(theta / 2.0)\n\n return ret * theta\n\n\ndef exp_to_quat(exp):\n theta = np.square(exp[0] * exp[0] + exp[1] * exp[1] + exp[2] * exp[2])\n ret = np.zeros(4)\n if theta > 1e-4:\n ret[0] = sin(theta / 2.0) * exp[0] / theta\n ret[1] = sin(theta / 2.0) * exp[1] / theta\n ret[2] = sin(theta / 2.0) * exp[2] / theta\n ret[3] = cos(theta / 2.0)\n else:\n ret[0] = 0.5 * exp[0]\n ret[1] = 0.5 * exp[1]\n ret[2] = 0.5 * exp[2]\n ret[3] = 1.0\n return ret\n\n\ndef get_alpha_from_frequency(hz, dt):\n omega = 2 * np.pi * hz\n alpha = (omega * dt) / (1. + (omega * dt))\n\n return np.clip(alpha, 0., 1.)\n\n\ndef adjoint(T):\n R, p = T[0:3, 0:3], T[0:3, 3]\n so3 = [[0, -p[2], p[1]], [p[2], 0, -p[0]], [-p[1], p[0], 0]]\n return np.r_[np.c_[R, np.zeros((3, 3))], np.c_[np.dot(so3, R), R]]\n\n\ndef iso_inv(T):\n R, p = T[0:3, 0:3], T[0:3, 3]\n Rt = np.array(R).T\n return np.r_[np.c_[Rt, -np.dot(Rt, p)], [[0, 0, 0, 1]]]\n\n\ndef print_attrs(ob):\n attr = vars(ob)\n print(\", \\n\".join(\"%s: %s\" % item for item in attr.items()))\n\n\nclass HermiteCurve(object):\n def __init__(self, start_pos, start_vel, end_pos, end_vel):\n self._p1 = start_pos\n self._v1 = start_vel\n self._p2 = end_pos\n self._v2 = end_vel\n\n def evaluate(self, s_in):\n s = np.clip(s_in, 0., 1.)\n return self._p1 * (2 * s**3 - 3 * s**2 + 1) + self._p2 * (\n -2 * s**3 + 3 * s**2) + self._v1 * (s**3 - 2 * s**2 +\n s) + self._v2 * (s**3 - s**2)\n\n def evaluate_first_derivative(self, s_in):\n s = np.clip(s_in, 0., 1.)\n\n return self._p1 * (6 * s**2 - 6 * s) + self._p2 * (\n -6 * s**2 + 6 * s) + self._v1 * (3 * s**2 - 4 * s +\n 1) + self._v2 * (3 * s**2 - 2 * s)\n\n def evaluate_second_derivative(self, s_in):\n s = np.clip(s_in, 0., 1.)\n\n return self._p1 * (12 * s - 6) + self._p2 * (\n -12 * s + 6) + self._v1 * (6 * s - 4) + self._v2 * (6 * s - 2)\n\n\nclass HermiteCurveVec(object):\n def __init__(self, start_pos, start_vel, end_pos, end_vel):\n self._p1 = np.copy(start_pos)\n self._v1 = np.copy(start_vel)\n self._p2 = np.copy(end_pos)\n self._v2 = np.copy(end_vel)\n self._dim = start_pos.shape[0]\n\n self._curves = []\n for i in range(self._dim):\n self._curves.append(\n HermiteCurve(start_pos[i], start_vel[i], end_pos[i],\n end_vel[i]))\n\n def evaluate(self, s_in):\n return np.array([c.evaluate(s_in) for c in self._curves])\n\n def evaluate_first_derivative(self, s_in):\n return np.array(\n [c.evaluate_first_derivative(s_in) for c in self._curves])\n\n def evaluate_second_derivative(self, s_in):\n return np.array(\n [c.evaluate_second_derivative(s_in) for c in self._curves])\n\n\nclass HermiteCurveQuat(object):\n def __init__(self, quat_start, ang_vel_start, quat_end, ang_vel_end):\n self._qa = R.from_quat(quat_start)\n self._omega_a = np.copy(ang_vel_start)\n self._qb = R.from_quat(quat_end)\n self._omega_b = np.copy(ang_vel_end)\n\n # Initialize Data Structures\n self._q0 = R.from_quat(quat_start)\n\n if np.linalg.norm(ang_vel_start) < 1e-6:\n self._q1 = R.from_quat(quat_start) * R.from_quat([0., 0., 0., 1.])\n else:\n self._q1 = R.from_quat(quat_start) * R.from_rotvec(\n (np.linalg.norm(ang_vel_start) / 3.0) *\n (ang_vel_start / np.linalg.norm(ang_vel_start)))\n\n if np.linalg.norm(ang_vel_end) < 1e-6:\n self._q2 = R.from_quat(quat_end) * R.from_quat([0., 0., 0., 1.])\n else:\n self._q2 = R.from_quat(quat_end) * R.from_rotvec(\n (np.linalg.norm(ang_vel_end) / 3.0) *\n (ang_vel_end / np.linalg.norm(ang_vel_end)))\n\n self._q3 = R.from_quat(quat_end)\n\n self._omega_1aa = self._q1 * self._q0.inv()\n self._omega_2aa = self._q2 * self._q1.inv()\n self._omega_3aa = self._q3 * self._q2.inv()\n\n self._omega_1 = self._omega_1aa.as_rotvec()\n self._omega_2 = self._omega_2aa.as_rotvec()\n self._omega_3 = self._omega_3aa.as_rotvec()\n\n def _compute_basis(self, s_in):\n s = np.clip(s_in, 0., 1.)\n\n self._b1 = 1 - (1 - s)**3\n self._b2 = 3 * s**2 - 2 * s**3\n self._b3 = s**3\n self._bdot1 = 3 * (1 - s)**2\n self._bdot2 = 6 * s - 6 * s**2\n self._bdot3 = 3 * s**2\n self._bddot1 = -6 * (1 - s)\n self._bddot2 = 6 - 12 * s\n self._bddot3 = 6 * s\n\n def evaluate(self, s_in):\n s = np.clip(s_in, 0., 1.)\n self._compute_basis(s)\n\n if np.linalg.norm(self._omega_1) > 1e-5:\n qtmp1 = R.from_rotvec(\n (np.linalg.norm(self._omega_1) * self._b1) *\n (self._omega_1 / np.linalg.norm(self._omega_1)))\n else:\n qtmp1 = R.from_quat([0., 0., 0., 1.])\n if np.linalg.norm(self._omega_2) > 1e-5:\n qtmp2 = R.from_rotvec(\n (np.linalg.norm(self._omega_2) * self._b2) *\n (self._omega_2 / np.linalg.norm(self._omega_2)))\n else:\n qtmp2 = R.from_quat([0., 0., 0., 1.])\n if np.linalg.norm(self._omega_3) > 1e-5:\n qtmp3 = R.from_rotvec(\n (np.linalg.norm(self._omega_3) * self._b3) *\n (self._omega_3 / np.linalg.norm(self._omega_3)))\n else:\n qtmp3 = R.from_quat([0., 0., 0., 1.])\n\n return (qtmp3 * qtmp2 * qtmp1 * self._q0).as_quat()\n\n def evaluate_ang_vel(self, s_in):\n s = np.clip(s_in, 0., 1.)\n self._compute_basis(s)\n\n return self._omega_1 * self._bdot1 + self._omega_2 * self._bdot2 + self._omega_3 * self._bdot3\n\n def evaluate_ang_acc(self, s_in):\n s = np.clip(s_in, 0., 1.)\n self._compute_basis(s)\n\n return self._omega_1 * self._bddot1 + self._omega_2 * self._bddot2 + self._omega_3 * self._bddot3\n","sub_path":"util/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":8173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"649683028","text":"#____________________________________________________________________________|\n# Thanks to Frankie Hobbins, Joel Daniels, Julien Duroure,\n# Hjalti Hjalmarsson, Bassam Kurdali, Luciano Munoz, Cristian Hasbun,\n# and anyone that I left out!\n#\n# Latest update: 2.78 Keyframe Type support!\n# \"support\": \"TESTING\",\n\nbl_info = {\n \"name\": \"Animator's Toolbox\",\n \"description\": \"A set of tools specifically for animators.\",\n \"author\": \"Brandon Ayers (thedaemon)\",\n \"version\": (0, 4),\n \"blender\": (2, 77, 0),\n \"location\": \"View3D > Toolbar > Animation > Animator's Toolbox\",\n \"warning\": \"\", # used for warning icon and text in addons panel\n \"wiki_url\": \"https://github.com/thedaemon/Blender-Scripts\",\n \"tracker_url\": \"https://github.com/thedaemon/Blender-Scripts/issues\",\n \"category\": \"Animation\"\n }\n\nimport os.path\nimport bpy\nfrom bpy.props import *\nfrom bpy.types import Operator\n\nKEYMAPS = list()\n\n# FEATURE: Jump forward/backward every N frames. Currently hardcoded variable.\nclass AnimatorsToolboxFrameJump(bpy.types.Operator):\n\n \"\"\"Jump a number of frames forward/backwards\"\"\"\n bl_idname = \"screen.animatorstools_frame_jump\"\n bl_label = \"Jump Frames\"\n\n forward = bpy.props.BoolProperty(default=True)\n\n def execute(self, context):\n scene = context.scene\n framedelta = 4\n if self.forward:\n scene.frame_current = scene.frame_current + framedelta\n else:\n scene.frame_current = scene.frame_current - framedelta\n\n return {\"FINISHED\"}\n\n# FEATURE: A toggle to keep the animator from selecting something other\n# than the Armature.\nclass ToggleSelectability(bpy.types.Operator):\n \"\"\"Turns off selection for all objects\n leaving only Armatures selectable\"\"\"\n bl_idname = \"bone.toggleselectability\"\n bl_label = \"Armature Selection Only\"\n\n def execute(self, context):\n do_i_hide_select = not bpy.context.active_object.hide_select\n if bpy.context.selected_objects == []:\n if bpy.context.object.type == \"ARMATURE\":\n for ob in bpy.context.scene.objects:\n ob.hide_select = True\n else:\n for ob in bpy.context.scene.objects:\n if ob.type != \"ARMATURE\":\n ob.hide_select = do_i_hide_select\n else:\n if bpy.context.object.type == \"ARMATURE\":\n for ob in bpy.context.scene.objects:\n if ob.type != \"ARMATURE\":\n do_i_hide_select2 = not ob.hide_select\n for ob in bpy.context.scene.objects:\n ob.hide_select = do_i_hide_select2\n break\n bpy.context.object.hide_select = False\n else:\n for ob in bpy.context.selected_objects:\n ob.hide_select = not ob.hide_select\n return{'FINISHED'}\n\n# Useless because blender already has this freaking command but I programmed\n# it anyways. I may use it for specific axis template.\nclass ClearAllTransforms(bpy.types.Operator):\n \"\"\"Clears all transforms on the bone I hope\"\"\"\n bl_idname = \"pose.clearall\"\n bl_label = \"Clear Transforms\"\n\n def execute(self,context):\n for obj in bpy.data.objects:\n if obj.type == 'ARMATURE':\n bpy.ops.pose.rot_clear()\n bpy.ops.pose.loc_clear()\n bpy.ops.pose.scale_clear()\n return{'FINISHED'}\n\n# FEATURE: A toggle for OpenSubdiv on all objects in scene with a Subdivision\n# Surface Modifier.\nclass ToggleOpensubdiv(bpy.types.Operator):\n \"\"\"Toggles OpenSubdiv for all Objects for\n improved animation playback speed\"\"\"\n bl_idname = \"mesh.opensubdiv\"\n bl_label = \"Mesh OpenSubdiv\"\n # Does nothing, testing.\n my_bool = bpy.props.BoolProperty(name=\"Toggle Option\")\n\n def execute(self,context):\n for mm in (m for o in bpy.context.scene.objects\n for m in o.modifiers if m.type=='SUBSURF'):\n if mm.use_opensubdiv == True:\n mm.use_opensubdiv = False\n else:\n if mm.use_opensubdiv == False:\n mm.use_opensubdiv = True\n return{'FINISHED'}\n\n# Feature: Turns OpenSubdiv on for all meshes with Subdivision Surface\n# Modifiers for improved viewport performance.\nclass OpensubdivOn(bpy.types.Operator):\n bl_idname = \"opensubdiv.on\"\n bl_label = \"OpenSubdiv On\"\n\n def execute(self,context):\n for mm in (m for o in bpy.context.scene.objects\n for m in o.modifiers if m.type=='SUBSURF'):\n mm.use_opensubdiv = True\n return{'FINISHED'}\n\n# Feature: Turns OpenSubdiv on for all meshes with Subdivision Surface\n# Modifiers for improved viewport performance.\nclass OpensubdivOff(bpy.types.Operator):\n bl_idname = \"opensubdiv.off\"\n bl_label = \"OpenSubdiv Off\"\n\n def execute(self,context):\n for mm in (m for o in bpy.context.scene.objects\n for m in o.modifiers if m.type=='SUBSURF'):\n mm.use_opensubdiv = False\n return{'FINISHED'}\n\n# FEATURE: Simple X-Ray toggle for Armature\nclass ToggleXray(bpy.types.Operator):\n \"\"\"Toggles X-Ray mode for bones\"\"\"\n bl_idname = \"bone.togglexray\"\n bl_label = \"Armature X-Ray\"\n\n def execute(self, context):\n for obj in bpy.data.objects:\n if obj.type == 'ARMATURE':\n obj.show_x_ray = not obj.show_x_ray\n return{'FINISHED'}\n# FEATURE: Simple Auto-IK toggle for Armature\n#context.active_object.data, \"use_auto_ik\", text=\"Auto IK\")\nclass ToggleAutoIK(bpy.types.Operator):\n \"\"\"Toggles Auto IK mode for bones\"\"\"\n bl_idname = \"bone.toggleautoik\"\n bl_label = \"Armature Auto IK\"\n\n\n def execute(self, context):\n for obj in bpy.data.active_object:\n if obj.type == 'ARMATURE':\n bpy.context.object.data.use_auto_ik = True\n return{'FINISHED'}\n\n# FEATURE: Advanced Boomsmash version 011 classes\nclass BoomProps(bpy.types.PropertyGroup):\n\n global_toggle = BoolProperty(\n name = 'Global',\n description = 'Same boomsmash settings for all scenes in file.',\n default = False)\n\n #twm.image_settings = bpy.types.ImageFormatSettings(\n # bpy.context.scene.render.image_settings)\n\n #scene_cam = BoolProperty(\n # name = 'Active Camera',\n # description = 'Always renders from the active camera\n # that's set in the Scene properties')\n\n incremental = BoolProperty(\n name = 'Incremental',\n description = 'Save incremental boomsmashes.',\n default = False)\n\n use_stamp = BoolProperty(\n name = 'Stamp',\n description = 'Turn on stamp .',\n default = False)\n\n transparent = BoolProperty(\n name = 'Transparent',\n description = 'Make background transparent .',\n default = False)\n\n autoplay = BoolProperty(\n name = 'Autoplay',\n description = 'Automatically play boomsmash after making it.',\n default = False)\n\n unsimplify = BoolProperty(\n name = 'Unsimplify',\n description = \"subdivision surface levels at it's render settings.\",\n default = False)\n\n onlyrender = BoolProperty(\n name = 'Only Render',\n description = 'Only have renderable objects visible during.',\n default = False)\n\n frame_skip = IntProperty(\n name = 'Skip Frames',\n description = 'Number of frames to skip',\n default = 0,\n min = 0)\n\n resolution_percentage = IntProperty(\n name = 'Resolution Percentage',\n description = ' a percentage of the Render Resolution.',\n default = 50,\n min = 0,\n max = 100)\n\n #DEBUG\n #pu.db\n\n dirname = StringProperty(\n name = '',\n description = 'Folder where your boomsmash will be stored',\n default = bpy.app.tempdir,\n subtype = 'DIR_PATH')\n\n filename = StringProperty(\n name = '',\n description = 'Filename where your boomsmash will be stored',\n default = 'Boomsmash',\n subtype = 'FILE_NAME')\n# BOOMSMASH\nclass setDirname(bpy.types.Operator):\n bl_idname = 'bs.setdirname'\n bl_label = 'BoomsmashDirname'\n bl_description = 'boomsmash use blendfile directory'\n bl_options = {'REGISTER', 'INTERNAL'}\n\n def execute(self, context):\n cs = context.scene\n cs.boom_props.dirname = os.path.dirname(bpy.data.filepath)\n return {'FINISHED'}\n# BOOMSMASH\nclass setFilename(bpy.types.Operator):\n bl_idname = 'bs.setfilename'\n bl_label = 'BoomsmashFilename'\n bl_description = 'boomsmash use blendfile name _ scene name'\n bl_options = {'REGISTER', 'INTERNAL'}\n\n def execute(self, context):\n cs = context.scene\n blend_name = os.path.basename(\n os.path.splitext(bpy.data.filepath)[0])\n cs.boom_props.filename = blend_name + '_' + bpy.context.scene.name\n return {'FINISHED'}\n# BOOMSMASH\nclass DoBoom(bpy.types.Operator):\n bl_idname = 'bs.doboom'\n bl_label = 'Boomsmash'\n bl_description = 'Start boomsmash, use, enjoy, think about donate ;)'\n bl_options = {'REGISTER'}\n\n def execute(self, context):\n cs = context.scene\n wm = context.window_manager\n rd = context.scene.render\n sd = context.space_data\n\n if wm.boom_props.global_toggle:\n boom_props = wm.boom_props\n else:\n boom_props = cs.boom_props\n\n #pu.db\n #guardo settings\n old_use_stamp = rd.use_stamp\n old_onlyrender = sd.show_only_render\n old_simplify = rd.use_simplify\n old_filepath = rd.filepath\n old_alpha_mode = rd.alpha_mode\n #old_image_settings = rd.image_settings\n old_resolution_percentage = rd.resolution_percentage\n old_frame_step = cs.frame_step\n #afecto settings originales\n rd.use_stamp = boom_props.use_stamp\n sd.show_only_render = boom_props.onlyrender\n if boom_props.unsimplify:\n rd.use_simplify = False\n rd.filepath = cs.boom_props.dirname + cs.boom_props.filename\n rd.alpha_mode = 'TRANSPARENT' if boom_props.transparent else 'SKY'\n #rd.image_settings = boom_props.image_settings\n rd.resolution_percentage = boom_props.resolution_percentage\n cs.frame_step = boom_props.frame_skip + 1\n #view_pers = context.area.spaces[0].region_3d.view_perspective\n #if boom_props.scene_cam and view_pers is not 'CAMERA':\n # bpy.ops.view3d.viewnumpad(type = 'CAMERA')\n #ejecuto\n bpy.ops.render.opengl(animation = True)\n if boom_props.autoplay:\n bpy.ops.render.play_rendered_anim()\n #devuelvo settings\n rd.use_stamp = old_use_stamp\n sd.show_only_render = old_onlyrender\n rd.use_simplify = old_simplify\n rd.filepath = old_filepath\n rd.alpha_mode = old_alpha_mode\n #rd.image_settings = old_image_settings\n rd.resolution_percentage = old_resolution_percentage\n context.scene.frame_step = old_frame_step\n #if boom_props.scene_cam and view_pers is not 'CAMERA':\n # bpy.ops.view3d.viewnumpad(type = 'CAMERA')\n return {'FINISHED'}\n\n\n## UI ##\nfrom bpy.types import PropertyGroup, Panel\nfrom bpy.props import *\n\nclass animatorstoolboxData(PropertyGroup):\n bl_idname = 'animatorstoolboxDataUI'\n \"\"\"\n UI property group for the add-on WORK IN PROGRESS\n\n Options to adjust how the panel is displayed.\n\n bpy > types > WindowManager > animatorstoolboxDataUI\n bpy > context > window_manager > animatorstoolboxDataUI\n \"\"\"\n displayMode = BoolProperty(name='Display Mode', description=\"Use\"\n \"this to hide many of the options below that\"\n \"are generally needed while rigging.\"\n \"(Useful for animating.)\",\n default=False)\n boomsmashOptions = BoolProperty(name='Deform Options', description=\"Disp\"\n \"lay the deform options for this bone.\",\n default=False)\n\n\ndef draw_optimization_panel(context, layout):\n scene = context.scene\n rd = scene.render\n\n col = layout.column(align=True)\n #col.label(text=\"Optimizations:\")\n #col.layout.column(align=True)\n #col.label(text=\"OpenSubdiv\")\n row = layout.row(align=True)\n row.label(text=\"OpenSubdiv\")\n row.operator(\"opensubdiv.on\", text=\"On\")\n row.operator(\"opensubdiv.off\", text=\"Off\")\n\n#--Simplify\n #col = layout.column(align=True)\n #col.label(text=\"Simplify:\")\n row = layout.row(align=True)\n row.prop(rd, \"use_simplify\", text=\"Use Simplify\")\n row.prop(rd, \"simplify_subdivision\", text=\"Subdivision\")\n #layout.active = rd.use_simplify\n #split = layout.split()\n #col = split.column()\n #col.label(text=\"Viewport:\")\n #col.prop(rd, \"simplify_subdivision\", text=\"Subdivision\")\n #col.prop(rd, \"simplify_child_particles\", text=\"Child Particles\")\n #col = split.column()\n #col.label(text=\"Render:\")\n #col.prop(rd, \"simplify_subdivision_render\", text=\"Subdivision\")\n #col.prop(rd, \"simplify_child_particles_render\", text=\"Child Particles\")\n #col = split.column()\n #col.prop(cscene, \"use_camera_cull\")\n #subsub = col.column()\n #subsub.active = cscene.use_camera_cull\n #subsub.prop(cscene, \"camera_cull_margin\")\n\n# Animator's Toolbox Main Panel\ndef draw_animatorstoolbox_panel(context, layout):\n#--Defining shortcuts for commands\n obj = context.object\n userpref = context.user_preferences\n obj = context.object\n edit = userpref.edit\n toolsettings = context.tool_settings\n scene = context.scene\n screen = context.screen\n rd = scene.render\n cscene = scene.cycles\n\n#--Selection\n col = layout.column(align=True)\n #col.label(text=\"Selection:\")\n row = layout.row(align=True)\n row.operator(\"bone.toggleselectability\", text=\"Select Armature Only\")\n row.prop(obj, \"show_x_ray\", text=\"X Ray\")\n #--Auto IK\n if obj and obj.type == 'ARMATURE' and obj.mode in {'POSE'}:\n col = layout.column(align=True)\n row = col.row()\n row.prop(context.active_object.data, \"use_auto_ik\", text=\"Auto IK\")\n # row.prop(obj, \"bone.toggleautoik\", text=\"Auto IK\")\n\n#--Reset Transforms\n col = layout.column(align=True)\n #col.label(text=\"Reset Transforms: Axis Not working yet!\")\n row = col.row()\n row.operator(\"pose.transforms_clear\", text=\"Reset All\")\n row = col.row(align=True)\n row.operator(\"pose.loc_clear\", text=\"Location\")\n row.operator(\"pose.rot_clear\", text=\"Rotation\")\n row.operator(\"pose.scale_clear\", text=\"Scale\")\n #row = layout.row(align=True)\n #row.operator(\"pose.loc_clear\", text=\"X\")\n #row.operator(\"pose.loc_clear\", text=\"Y\")\n #row.operator(\"pose.loc_clear\", text=\"Z\")\n #row = col.row(align=True)\n #row.operator(\"pose.rot_clear\", text=\"X\")\n #row.operator(\"pose.rot_clear\", text=\"Y\")\n #row.operator(\"pose.rot_clear\", text=\"Z\")\n #row = col.row(align=True)\n #row.operator(\"pose.scale_clear\", text=\"X\")\n #row.operator(\"pose.scale_clear\", text=\"Y\")\n #row.operator(\"pose.scale_clear\", text=\"Z\")\n #col = layout.column(align=True)\n\n\n#--Pose Tools\n col = layout.column(align=True)\n col.label(text=\"Pose:\")\n #row = col.row(align=True)\n #row.operator(\"pose.copy\", text=\"Copy\")\n #row.operator(\"pose.paste\", text=\"Paste\")\n #row.operator(\"pose.paste\", text=\"Flipped\").flipped = True\n # This will seperate the rows\n #col = layout.column(align=True)\n row = col.row(align=True)\n row.operator(\"pose.breakdown\", text=\"Breakdowner\")\n row.operator(\"pose.push\", text=\"Push\")\n row.operator(\"pose.relax\", text=\"Relax\")\n\n\n#-- X- Ray\n #row.prop(obj, \"show_x_ray\", text=\"X Ray\")\n\n#--Keying\n col = layout.column(align=True)\n col.label(text=\"Keyframes:\")\n row = layout.row(align=True)\n row.prop(toolsettings, \"use_keyframe_insert_auto\", text=\"\", toggle=True)\n if toolsettings.use_keyframe_insert_auto:\n row.prop(toolsettings, \"use_keyframe_insert_keyingset\",\n text=\"\", toggle=True)\n if screen.is_animation_playing:\n subsub = row.row()\n subsub.prop(toolsettings, \"use_record_with_nla\", toggle=True)\n row.prop_search(scene.keying_sets_all, \"active\",\n scene, \"keying_sets_all\", text=\"\")\n row.operator(\"screen.animation_play\", text=\"\", icon='PLAY')\n row.operator(\"screen.keyframe_jump\", text=\"\",\n icon='PREV_KEYFRAME').next = False\n row.operator(\"screen.keyframe_jump\", text=\"\",\n icon='NEXT_KEYFRAME').next = True\n#--New Key Type\n col = layout.column(align=True)\n col.label(text=\"New Key Type:\")\n row = layout.row(align=True)\n row.prop(edit, \"keyframe_new_interpolation_type\", text=\"\", icon_only=False)\n row.prop(edit, \"keyframe_new_handle_type\", text=\"\", icon_only=False)\n row.prop(toolsettings, \"keyframe_type\", text=\"\", icon_only=False)\n\n#--Motion Path\n pchan = context.active_pose_bone\n mpath = pchan.motion_path if pchan else None\n col = layout.column(align=True)\n col.label(text=\"Motion Paths:\")\n if mpath:\n row = col.row(align=True)\n row.operator(\"pose.paths_update\", text=\"Update\")\n row.operator(\"pose.paths_clear\", text=\"\", icon='X')\n else:\n col.operator(\"pose.paths_calculate\", text=\"Calculate\")\n\n\n# Animator's ToolBox Draw Calls\nclass AnimatorsToolBox(bpy.types.Panel):\n \"\"\"Creates a custom Animator Panel in the 3D View\"\"\"\n bl_label = \"Animator's Toolbox\"\n bl_idname = \"ANIM_TOOLBOX\"\n bl_space_type = 'VIEW_3D'\n bl_region_type = 'TOOLS'\n bl_category = \"Animation\"\n#--Header\n def draw_header(self, context):\n layout = self.layout\n#animatorstoolboxDataUIProps = context.window_manager.animatorstoolboxDataUI\n #layout.prop('animatorstoolboxDataUI', \"displayMode\", text=\"\")\n DoBTN = self.layout\n DoBTN.operator('bs.doboom', text = '', icon = 'RENDER_ANIMATION')\n#--Draw Toolboxes\n def draw(self, context):\n layout = self.layout\n draw_animatorstoolbox_panel(context, layout)\n\n\n layout = self.layout\n draw_optimization_panel(context, layout)\n\n\n layout = self.layout\n draw_boomsmash_panel(context, layout)\n\n#animatorstoolboxData = context.window_manager.animatorstoolboxDataUI\n#scene = context.scene\n#preferences = context.user_preferences.addons[\"animatorstoolbox\"].preferences\n#if preferences.use_boomsmash:\n# draw_animatorstoolbox_panel(context, layout)\n# draw_boomsmash_panel(context, layout)\n#else:\n# draw_animatorstoolbox_panel(context, layout)\n\n# BOOMSMASH\ndef draw_boomsmash_panel(context, layout):\n #layout.row().prop(self, \"boomsmash_panel\", expand=True)\n col = layout.column(align = True)\n cs = context.scene\n wm = context.window_manager\n rd = context.scene.render\n if wm.boom_props.global_toggle:\n boom_props = wm.boom_props\n else:\n boom_props = cs.boom_props\n#-File Name\n col.label(text = 'boomsmash filename:')\n row = col.row()\n row.prop(cs.boom_props, 'filename')\n row.operator('bs.setfilename', text = '', icon = 'FILE_BLEND')\n#-Folder\n col.label(text = 'boomsmash folder:')\n row = col.row()\n row.prop(cs.boom_props, 'dirname')\n row.operator('bs.setdirname', text = '', icon = 'FILE_FOLDER')\n col.separator()\n\n col.label(text = 'Use preview range:')\n sub = col.split()\n subrow = sub.row(align = True)\n subrow.prop(context.scene, 'use_preview_range', text = '')\n subrow.prop(context.scene, 'frame_preview_start', text = 'Start')\n subrow.prop(boom_props, 'frame_skip', text = 'Skip')\n subrow.prop(context.scene, 'frame_preview_end', text = 'End')\n col.separator()\n final_res_x = (rd.resolution_x * boom_props.resolution_percentage) / 100\n final_res_y = (rd.resolution_y * boom_props.resolution_percentage) / 100\n col.label(text = 'Final Resolution: {} x {}'.format(str(final_res_x)[:-2],\n str(final_res_y)[:-2]))\n col.prop(boom_props, 'resolution_percentage', slider = True )\n col.separator()\n #col.label(text=\"BoomSmash:\")\n #col.operator('bs.doboom', text = 'BoomSmash', icon = 'RENDER_ANIMATION')\n split = col.split()\n subcol = split.column()\n #subcol.prop(boom_props, 'incremental')\n subcol.prop(boom_props, 'use_stamp')\n subcol.prop(boom_props, 'onlyrender')\n #subcol.prop(boom_props, 'scene_cam')\n subcol = split.column()\n subcol.prop(boom_props, 'transparent')\n subcol.prop(boom_props, 'autoplay')\n subcol.prop(boom_props, 'unsimplify')\n col.separator()\n #col.label(text = 'Output Format:')\n #col.template_image_settings(wm.image_settings, color_management = False)\n\n\n\n\ndef register():\n bpy.utils.register_module(__name__)\n#---Boomsmash\n bpy.types.Scene.boom_props = PointerProperty(\n type = BoomProps, name = 'BoomSmash Properties', description = '')\n\n bpy.types.WindowManager.boom_props = PointerProperty(\n type = BoomProps,\n name = 'BoomSmash Global Properties',\n description = '')\n#---KeyMaps\n wm = bpy.context.window_manager\n kc = wm.keyconfigs.addon\n km = kc.keymaps.new(name=\"Frames\")\n kmi = km.keymap_items.new(\n \"screen.animatorstools_frame_jump\",\n \"RIGHT_ARROW\", \"PRESS\", shift=True)\n kmi.properties.forward = True\n KEYMAPS.append((km, kmi))\n kmi = km.keymap_items.new(\n \"screen.animatorstools_frame_jump\",\n \"LEFT_ARROW\", \"PRESS\", shift=True)\n kmi.properties.forward = False\n KEYMAPS.append((km, kmi))\n\ndef unregister():\n bpy.utils.unregister_module(__name__)\n#---Boomsmash\n del bpy.types.Scene.boom_props\n del bpy.types.WindowManager.boom_props\n#---KeyMaps\n for km, kmi in KEYMAPS:\n km.keymap_items.remove(kmi)\n KEYMAPS.clear()\n\n# The End\nif __name__ == \"__main__\":\n register()","sub_path":"scripts/addons_extern/Animators_Toolbox.py","file_name":"Animators_Toolbox.py","file_ext":"py","file_size_in_byte":22045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"392169826","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\n\n# UserManager as _UserManager 这样指定才会正确继承,按照django源码命\n# 定义用户模型完成后,须去settings,指定AUTH_USER_MODEL = 'users.Users' ('app.类名'),否则django不会辨识\nfrom Enterprise.models import Chain, Provinces\n\nfrom oauth.models import CustomerInformation\n\n\nclass EnterpriseCertificationInfo(models.Model):\n \"\"\"企业认证\"\"\"\n \"\"\"认证审核\"\"\"\n REVIEWER_LOGO = {\n \"STAY\": 1,\n \"PASS\": 2,\n \"DEFEAT\": 3,\n\n }\n REVIEWER_STATE = (\n (1, \"待审核\"),\n (2, \"审核通过\"),\n (3, \"不通过\"),\n )\n company_id = models.CharField(max_length=100, primary_key=True, verbose_name=\"企业id\")\n name = models.CharField(max_length=50, verbose_name=\"企业名字\")\n code = models.CharField(max_length=50, verbose_name=\"信用代码\")\n avatar = models.CharField(max_length=200, verbose_name=\"营业执照\")\n contacts = models.CharField(max_length=20, verbose_name=\"联系人\")\n phone = models.CharField(max_length=50, verbose_name=\"电话号码\")\n identity_status = models.SmallIntegerField(choices=REVIEWER_STATE, default=1, verbose_name=\"审核状态\")\n industryid = models.CharField(null=True,max_length=5,verbose_name=\"行业id\")\n create_time = models.DateTimeField(auto_now_add=True,null=True)\n administrator_status = models.CharField(verbose_name='管理员状态', max_length=10, null=True)\n user = models.ForeignKey(CustomerInformation, on_delete=models.CASCADE, verbose_name=\"关联用户\")\n reviewer_time = models.DateField(verbose_name=\"审核通过时间\", null=True)\n reviewer_name = models.CharField(max_length=50, verbose_name=\"审核人\", null=True)\n opinion = models.CharField(max_length=100,verbose_name = \"审核意见\",null=True)\n province = models.CharField(max_length=20,verbose_name=\"省份\",null=True)\n industry = models.CharField(max_length=100,verbose_name=\"行业\",null=True)\n username = models.CharField(max_length=100,verbose_name=\"用户名\",null=True)\n demand_config = models.CharField(max_length=120, verbose_name=\"配置需求\", default='1')\n recommended = models.IntegerField(default=0, verbose_name=\"推荐数\", null=True)\n access = models.IntegerField(default=0, verbose_name=\"访问数\", null=True)\n kind = models.TextField(verbose_name=\"主营&企业标签\", null=True)\n lndividual_labels = models.TextField(verbose_name=\"个人标签\", null=True)\n\n\n class Meta:\n db_table = 'db_EnterpriseCertificationInfo'\n\n\nclass Top_up_Payment(models.Model):\n \"\"\"支付充值表\"\"\"\n balance = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=\"总金额\",default=0)\n userid = models.ForeignKey(EnterpriseCertificationInfo, on_delete=models.CASCADE)\n\n class Meta:\n db_table = \"db_Top_up_Payment\"\n verbose_name = \"充值表\"\n\n # def __str__(self):\n # return self.balance\n\n\nclass Record(models.Model):\n \"\"\"记录表\"\"\"\n mobile_count = models.IntegerField(verbose_name=\"手机号的总数\")\n send_count = models.IntegerField(verbose_name=\"发送短信的总数\")\n user = models.ForeignKey(EnterpriseCertificationInfo, on_delete=models.CASCADE)\n\n class Meta:\n db_table = \"db_Record\"\n verbose_name = \"记录表\"\n\n\nclass ManualMessagePost(models.Model):\n \"\"\"手动营销\"\"\"\n customer_id = models.IntegerField(db_column='Customer_id', blank=True, null=True) # Field name made lowercase.\n industry = models.CharField(db_column='Industry', max_length=255, blank=True,\n null=True) # Field name made lowercase.\n province = models.CharField(db_column='Province', max_length=255, blank=True,\n null=True) # Field name made lowercase.\n business_scope = models.CharField(db_column='Business_scope', max_length=255, blank=True,\n null=True) # Field name made lowercase.\n filter = models.CharField(db_column='Filter', max_length=255, blank=True, null=True) # Field name made lowercase.\n content = models.CharField(max_length=255, blank=True, null=True)\n task_id = models.CharField(db_column='Task_id', max_length=255, blank=True, null=True) # Field name made lowercase.\n\n class Meta:\n db_table = 'Manual_message_post'\n\n\nclass ManualMessageStatus(models.Model):\n \"\"\"手动营销\"\"\"\n customer_id = models.IntegerField(db_column='Customer_id', blank=True, null=True) # Field name made lowercase.\n amount = models.CharField(db_column='Amount', max_length=255, blank=True,\n null=True) # Field name made lowercase.\n task_id = models.CharField(db_column='Task_id', max_length=255, blank=True,\n null=True) # Field name made lowercase.\n success = models.CharField(db_column='Success', max_length=255, blank=True,\n null=True) # Field name made lowercase.\n unknow = models.CharField(db_column='Unknow', max_length=255, blank=True,\n null=True) # Field name made lowercase.\n failed = models.CharField(db_column='Failed', max_length=255, blank=True,\n null=True) # Field name made lowercase.\n\n class Meta:\n db_table = 'Manual_message_status'\n\n\nclass Template(models.Model):\n \"\"\"模板模型\"\"\"\n REVIEWER_LOGO = {\n \"STAY\": 1,\n \"PASS\": 2,\n \"DEFEAT\": 3,\n\n }\n REVIEWER_STATE = (\n (1, \"待审核\"),\n (2, \"审核通过\"),\n (3, \"不通过\"),\n )\n template_name = models.CharField(max_length=50,verbose_name=\"模板名称\")\n sms_type = models.CharField(max_length=50,verbose_name=\"发送类型\")\n data_time = models.DateField(verbose_name=\"日期\",auto_now_add=True)\n user = models.CharField(max_length=50,verbose_name=\"操作用户\")\n content = models.CharField(max_length=500,verbose_name=\"发送内容\")\n reviewer_time = models.DateField(verbose_name=\"审核通过时间\", null=True)\n reviewer_name = models.CharField(max_length=50, verbose_name=\"审核人\", null=True)\n state = models.SmallIntegerField(choices=REVIEWER_STATE, default=1, verbose_name=\"审核状态\")\n\n class Meta:\n db_table = \"db_Template\"\n\nclass Order(models.Model):\n \"\"\"短信订单表\"\"\"\n creat_time = models.DateTimeField(auto_now_add=True, verbose_name=\"创建时间\")\n company_id = models.CharField(max_length=100,verbose_name=\"企业id\")\n order_id = models.CharField(max_length=64, primary_key=True, verbose_name=\"订单号\")\n total_count = models.IntegerField(default=1, verbose_name=\"号码总数\")\n total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=\"单批总金额\")\n sms_type = models.CharField(max_length=50, verbose_name=\"发送类型\")\n username = models.CharField(max_length=50, verbose_name=\"用户\")\n mobile = models.CharField(max_length=2000, verbose_name=\"手机号\")\n price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=\"单价\")\n\n class Meta:\n db_table = \"db_Order\"\n\n\nclass ConsumptionRecord(models.Model):\n \"\"\"短信消费记录表\"\"\"\n creat_time = models.DateTimeField(auto_now_add=True, verbose_name=\"创建时间\")\n enterprise = models.ForeignKey(EnterpriseCertificationInfo, on_delete=models.PROTECT, verbose_name=\"消费企业\")\n order_id = models.ForeignKey(Order, on_delete=models.PROTECT, verbose_name=\"订单号\")\n total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=\"单批总金额\")\n balance = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=\"余额\")\n\n class Meta:\n db_table = \"db_ConsumptionRecord\"\n\nclass PayCertificationInfo(models.Model):\n \"\"\"认证记录表\"\"\"\n order_id = models.CharField(max_length=100,verbose_name=\"订单id\",primary_key=True)\n user_id = models.CharField(max_length=15,verbose_name=\"用户\")\n openid = models.CharField(max_length=80,verbose_name=\"打开id\")\n money = models.DecimalField(max_digits=10, decimal_places=2, verbose_name=\"单价\")\n company_name = models.CharField(max_length=100,verbose_name=\"企业名称\")\n mobile = models.CharField(max_length=20,verbose_name=\"联系人电话\")\n name = models.CharField(max_length=20,verbose_name=\"联系人\")\n # create_time = models.DateTimeField(auto_now_add=True,verbose_name=\"生成时间\")\n\n class Meta:\n db_table = \"PayCertificationInfo\"\n","sub_path":"up_down_chain/up_down_chain/app/Users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"229249340","text":"import torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nfrom parapred.cnn import Masked1dConvolution\nfrom parapred.hslstm import LSTMHardSigmoid\n\n# accepts CDRs up to length 28 + 2 residues either side\nPARAPRED_MAX_LEN = 40\n\n# 21 amino acids + 7 meiler features\nPARAPRED_N_FEATURES = 28\n\n# kernel size as per Parapred\nPARAPRED_KERNEL_SIZE = 3\n\n\nclass Parapred(nn.Module):\n \"\"\"\n Main Parapred model\n\n Details of model architecture in Liberis et al., 2018\n https://academic.oup.com/bioinformatics/article/34/17/2944/4972995\n\n \"\"\"\n def __init__(self,\n input_dim: int = PARAPRED_MAX_LEN,\n output_dim: int = PARAPRED_MAX_LEN,\n n_channels: int = PARAPRED_N_FEATURES,\n kernel_size: int = PARAPRED_KERNEL_SIZE,\n n_hidden_cells: int = 256,\n lstm_activation: str = \"hard_sigmoid\"):\n \"\"\"\n\n :param input_dim:\n :param output_dim:\n :param n_channels:\n :param kernel_size:\n :param n_hidden_cells:\n :param lstm_activation:\n \"\"\"\n\n super().__init__()\n self.mconv = Masked1dConvolution(\n input_dim,\n in_channels=n_channels,\n output_dim=output_dim,\n out_channels=n_channels,\n kernel_size=kernel_size\n )\n self.elu = nn.ELU()\n\n # Keeping batch first as that's how it comes from the CNN\n # We offer two activation options; the hard sigmoid which\n # was the Keras default at the time of Parapred's publication,\n # or the regular sigmoid function which is now the standard\n # for both PyTorch and Keras/TF.\n if lstm_activation == 'sigmoid':\n self.lstm = nn.LSTM(\n input_size=n_channels,\n hidden_size=n_hidden_cells,\n batch_first=True,\n bidirectional=True,\n )\n elif lstm_activation == 'hard_sigmoid':\n self.lstm = LSTMHardSigmoid(\n input_size=n_channels,\n hidden_size=n_hidden_cells,\n batch_first=True,\n bidirectional=True,\n )\n\n # need to multiply by 2 as it's a bidirectional LSTM.\n self.fc = nn.Linear(n_hidden_cells*2, 1)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, input_tensor: torch.Tensor, mask: torch.BoolTensor, lengths: torch.LongTensor) -> torch.Tensor:\n \"\"\"\n Forward pass of Parapred given the input, mask, and sequence lengths\n\n :param input_tensor: an input tensor of (bsz x features x seqlen)\n :param mask: a boolean tensor of (bsz x 1 x seqlen)\n :param lengths: a LongTensor of (seqlen); must be equal to bsz\n :return:\n \"\"\"\n # residual connection following ELU\n o = input_tensor + self.elu(self.mconv(input_tensor, mask))\n\n # Packing sequences to remove padding\n packed_seq = pack_padded_sequence(o.permute(0, 2, 1), lengths, batch_first=True, enforce_sorted=True)\n o_packed, (h, c) = self.lstm(packed_seq)\n\n # Re-pad sequences before prediction of probabilities\n o, lengths = pad_packed_sequence(o_packed, batch_first=True, total_length=PARAPRED_MAX_LEN)\n\n # Predict probabilities\n o = self.sigmoid(self.fc(o))\n\n return o\n\n\ndef clean_output(output_tensor: torch.Tensor, sequence_length: int) -> torch.Tensor:\n \"\"\"\n Clean the output tensor of probabilities to remove the predictions for padded positions\n\n :param output_tensor: output from the Parapred model; shape: (max_length x 1)\n :param sequence_length: length of sequence\n\n :return:\n \"\"\"\n return output_tensor[:sequence_length].view(-1)\n","sub_path":"parapred/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"107964914","text":"import operator\n\n\ndef readStudentDetails():\n\n numberOfStudents = int(input(\"Enter the total number of students: \"))\n # {\"Ramesh\": 560, \"Amit\": 925, \"Harshal\": 698, \"Uday\": 980, \"lokesh\": 792,\n # \"Bhavin\": 258, \"Hansika\":988, \"Anuradha\": 842}\n\n studentsRecord = {}\n\n for students in range(1, numberOfStudents+1):\n print(\"Enter the name\", students, \"th\", \"of the student: \")\n name = input()\n print(\"Enter the marks of the {}: \".format(name))\n marks = int(input())\n studentsRecord[name] = marks\n # numberOfStudents -= numberOfStudents\n\n return studentsRecord\n\n\ndef rank_students(studentsRecord):\n\n sortedstudentsrecord = sorted(studentsRecord.items(), key=operator.itemgetter(1), reverse=True)\n print(sortedstudentsrecord)\n print(\"{} has secured first rank, scoring {} marks\".format(sortedstudentsrecord[0][0], sortedstudentsrecord[0][1]))\n print(\"{} has secured second rank, scoring {} marks\".format(sortedstudentsrecord[1][0], sortedstudentsrecord[1][1]))\n print(\"{} has secured third rank, scoring {} marks\".format(sortedstudentsrecord[2][0], sortedstudentsrecord[2][1]))\n return sortedstudentsrecord\n\n\ndef reward_student(sortedstudentsrecord, reward):\n print(\"{} has received a cash reward of ${}\".format(sortedstudentsrecord[0][0], reward[0]))\n print(\"{} has received a cash reward of ${}\".format(sortedstudentsrecord[1][0], reward[1]))\n print(\"{} has received a cash reward of ${}\".format(sortedstudentsrecord[2][0], reward[2]))\n\n\ndef appricate_student(sortedstudentsrecord):\n for record in sortedstudentsrecord:\n if record[1] >= 950:\n print(\"Congratulation scoring {} marks, {}\".format(record[1], record[0]))\n else:\n break\n\n\nstudentsRecord = readStudentDetails()\nsortedstudentsrecord = rank_students(studentsRecord)\n\nreward = (500, 300, 100)\nreward_student(sortedstudentsrecord, reward)\nappricate_student(sortedstudentsrecord)\n","sub_path":"__Python/__Data structure/__dictionary/__ordered dict/rank_students.py","file_name":"rank_students.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"442225088","text":"class Client:\n \n def __init__(self, qrCode, address, amount, iban, acc, bic, vs):\n self.qrCode = qrCode\n self.address = address\n self.amount = amount\n self.iban = iban\n self.acc = acc\n self.bic = bic\n self.vs = vs\n\n def __str__(self):\n return f'QRcode: {self.qrCode}\\nAdresa: {self.address}\\nIBAN: {self.iban}\\nUcet: {self.acc}\\nBIC: {self.bic}\\nVS: {self.vs}\\nSuma: {self.amount}'","sub_path":"pdfBillExtract/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"591561638","text":"# coding=utf-8\n# 导入flask\nfrom flask import Flask\n\n# 创建flask应用程序\n# 第一个参数指代Flask所对应的模板, 其可以决定静态文件从哪个文职开始找\napp = Flask(__name__,\n static_url_path='/static', # 表示静态文件访问的路径\n static_folder='static', # 表示静态文件所存放的目录 默认值是static\n template_folder='templates' # 表示模板文件存放的目录\n )\n\n\n# =====从对象中加载配置=====#\n# class Config(object):\n# DEBUG = True\n# app.config.from_object(Config)\n\n# =====从文件中加载配置=====#\n# app.config.from_pyfile('config.ini')\n\n# =====从环境变量中加载配置=====#\n# app.config.from_envvar('ENVCONFIG')\n\n# 一些常用的配置 可以直接通过app.的形式设置\napp.debug = True\napp.config['DEBUG'] = True\n# 使用装饰器路由与视图函数关联\n@app.route('/')\ndef index():\n return 'Hello World!'\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"day_1/demo1_helloworld.py","file_name":"demo1_helloworld.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"540073861","text":"import csv\nimport os\n\npath = \"D:/Ridwan/Tutorials/Real Python/Python Basic Books/code/chapter11\"\n\nwith open(os.path.join(path, \"wonka2.csv\"), \"r\") as my_file:\n reader = csv.reader(my_file, delimiter=\"\\t\")\n next(reader)\n for row in reader:\n print(row)\n","sub_path":"chapter11/my_csv2.py","file_name":"my_csv2.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"239005889","text":"import torch\nfrom nltk.tokenize import wordpunct_tokenize\n\nimport json\n# import plotly.express as px\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom nltk.tokenize import wordpunct_tokenize\nfrom tqdm.auto import tqdm\nimport numpy as np\nimport random\nimport pandas as pd\n\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import train_test_split\n\nfrom torch.utils.data import Dataset, DataLoader\nimport torch\n\nfrom sklearn import metrics\n\n# WORD2VEC_PATH = '/Users/nbabakov/input/cc.ru.300.vec'\nWORD2VEC_PATH = '//home/nikbabakov/input/cc.ru.300.vec'\n\nclass WordData(torch.utils.data.Dataset):\n def __init__(self, initial_sentences_list, target_class, word2index):\n assert len(initial_sentences_list) == len(target_class)\n self.device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n self.initial_sentences_list = []\n self.target_class = target_class\n self.word2index = word2index\n self.init_len = 30\n\n self.pad_index = 0\n\n self.load(initial_sentences_list)\n\n def __len__(self):\n return len(self.initial_sentences_list)\n\n def process_text(self, text):\n\n words = wordpunct_tokenize(text.lower())\n\n return words\n\n def indexing(self, tokenized_text):\n indexes = []\n for word in tokenized_text:\n if word in self.word2index:\n indexes.append(self.word2index[word])\n return indexes\n\n def load(self, initial_sentences_list):\n\n data_iterator = tqdm(initial_sentences_list, desc='Loading data')\n\n for text in data_iterator:\n init_tokens = self.process_text(text[0])\n indexed_words_init = self.indexing(init_tokens)\n self.initial_sentences_list.append(indexed_words_init)\n\n\n def __getitem__(self, index):\n\n init_sent = self.initial_sentences_list[index][:self.init_len]\n init_pads = [self.pad_index] * (self.init_len - len(init_sent))\n init_sent = torch.tensor(init_sent + init_pads).long()\n\n target = self.target_class[index]\n\n return init_sent.to(self.device), target\n\n\ndef get_our_approach_metrics():\n\n dd = pd.read_csv('support.csv', sep=';', header=None)\n\n df = pd.DataFrame()\n df['text'] = dd[1]\n df['text_cat'] = dd[0]\n with open(\"cat_mapper.json\") as f:\n cat_mapper = json.load(f)\n df['category_id'] = df.text_cat.map(cat_mapper)\n\n # word2freq = {}\n # # lengths = []\n #\n # for text in tqdm(list(df['text'])):\n #\n # words = wordpunct_tokenize(text.lower())\n #\n # # lengths.append(len(words))\n #\n # for word in words:\n #\n # if word in word2freq:\n # word2freq[word] += 1\n # else:\n # word2freq[word] = 1\n\n word2index = {'PAD': 0}\n vectors = []\n\n #READ W2V\n word2vec_file = open(WORD2VEC_PATH)\n\n n_words, embedding_dim = word2vec_file.readline().split()\n n_words, embedding_dim = int(n_words), int(embedding_dim)\n # Zero vector for PAD\n vectors.append(np.zeros((1, embedding_dim)))\n\n progress_bar = tqdm(desc='Read word2vec', total=n_words)\n\n while True:\n\n line = word2vec_file.readline().strip()\n\n if not line:\n break\n\n current_parts = line.split()\n\n current_word = ' '.join(current_parts[:-embedding_dim])\n\n # if current_word in word2freq:\n word2index[current_word] = len(word2index)\n\n current_vectors = current_parts[-embedding_dim:]\n current_vectors = np.array(list(map(float, current_vectors)))\n current_vectors = np.expand_dims(current_vectors, 0)\n\n vectors.append(current_vectors)\n\n progress_bar.update(1)\n # break#!!!!!!!!!!!!!!!!!!!!!!\n\n progress_bar.close()\n\n word2vec_file.close()\n\n VECTORS = np.concatenate(vectors)\n\n class SentenceEncoder(torch.nn.Module):\n\n def __init__(self):\n super().__init__()\n\n self.embedding = torch.nn.Embedding.from_pretrained(torch.FloatTensor(VECTORS), padding_idx=0)\n self.conv_init = torch.nn.Conv1d(300, 128, kernel_size=3)\n self.pool_init = torch.nn.MaxPool1d(28)\n\n def forward(self, x):\n x_emb = self.embedding(x)\n x_cnn = self.conv_init(x_emb.transpose(1, 2))\n x_pool = self.pool_init(x_cnn).squeeze()\n\n return x_pool\n\n\n dataset = WordData(df['text'],df['category_id'], word2index)\n data_loader = DataLoader(dataset, batch_size=1)\n\n X = []\n y = []\n\n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n question_encoder = SentenceEncoder()\n question_encoder.load_state_dict(torch.load(\"question_encoder\"))\n question_encoder.to(device)\n\n for intial_sent, target in data_loader:\n with torch.no_grad():\n encoded_sent = question_encoder(intial_sent)\n # print(type(encoded_sent), encoded_sent.shape)\n encoded_sent = encoded_sent.cpu().numpy()\n X.append(encoded_sent)\n y.append(target)\n\n # print(X[0].shape, X[0])\n X_train, X_test, y_train, y_test = train_test_split (X, y ,test_size=0.33, random_state=0)\n\n model = LinearSVC()\n model.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n\n print(\"OUR APPROACH\")\n print(metrics.classification_report(y_test, y_pred, ))\n","sub_path":"comparative_pipeline_draft/sent_embed.py","file_name":"sent_embed.py","file_ext":"py","file_size_in_byte":5369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"208768371","text":"import numpy as np\nimport pickle\n\n\ndef accuracy(predictions, labels):\n \"\"\"Compute the accuracy, given predictions and labels\"\"\"\n assert predictions.shape == labels.shape\n p, l = predictions.astype(np.int32), labels.astype(np.int32)\n return np.where(p == l, 1., 0.).mean() * 100\n\n\ndef load_prime_mnist():\n \"\"\"\n Loads and processes MNIST dataset. First pixel values are normalized and then labels are\n created prime numbers have label = 1 and others have label = 0.\n The validation set is a held out set that could be used for validating the performance of the\n model.\n \"\"\"\n with open(\"assignment4-mnist.pkl\", 'rb') as f:\n mnist = pickle.load(f)\n\n (train_data, train_label) = (mnist[\"train\"], mnist[\"train_labels\"])\n (val, val_label) = (mnist[\"val\"], mnist[\"val_labels\"])\n\n # Normalize the pixel values to [0. 1.] interval\n train_data = train_data.reshape((-1, 28*28)) / 255.\n val = val.reshape((-1, 28*28)) / 255.\n\n # Set label of prime numbers to 1 and rest to 0\n label = np.isin(train_label, [2, 3, 5, 7])\n val_label = np.isin(val_label, [2, 3, 5, 7])\n\n return (train_data, label), (val, val_label)\n\n\ndef show(image):\n \"\"\"\n Render a given numpy.uint8 2D array of pixel data.\n \"\"\"\n from matplotlib import pyplot\n import matplotlib as mpl\n fig = pyplot.figure()\n ax = fig.add_subplot(1, 1, 1)\n imgplot = ax.imshow(image, cmap=mpl.cm.Greys)\n imgplot.set_interpolation('nearest')\n ax.xaxis.set_ticks_position('top')\n ax.yaxis.set_ticks_position('left')\n pyplot.show()\n\n","sub_path":"cmpt-310/fall_2019/A4/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"631878637","text":"import pandas as pd\nimport quandl, math, datetime\nimport numpy as np\nfrom sklearn import preprocessing, cross_validation, svm\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport pickle\n\nstyle.use('ggplot')\n\n#Get all the columns of Google's stock\n#Basics:\n#features: input, labels: output\ndf = quandl.get('WIKI/GOOGL')\n\n#Get only the necessary columns\ndf = df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]\n\n#Generate a 'high (minus) low percentage' column\ndf['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close'] * 100\n\n#Generate a 'percentage change' column\ndf['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100\n\n#Further filter the columns\ndf = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]\n\n#The column name which is to be forecasted\nforecast_col = 'Adj. Close'\n\n#Fill the NA(Not Available) columns with -99999\ndf.fillna(-99999, inplace=True)\n\n# 1 percent of the data\n# ^\nforecast_out = int(math.ceil(0.01*len(df)))\n\nprint('Predict what will happen in ' + str(forecast_out) + ' days.')\n\ndf['label'] = df[forecast_col].shift(-forecast_out)\n\n#X is a feature: input, all the columns except 'label'\nX = np.array(df.drop(['label'], 1))\n\n#Scale the features to a smaller range of values\nX = preprocessing.scale(X)\n\n#X till now:\n#We have the Xs below, we need y and c for y = mX + c\nX_lately = X[-forecast_out:]\n\n#To predict future, we need past, and past only\nX = X[:-forecast_out]\n\n#Delete NaN(Not a number) fields\n#This will discard all the features which fall into the future\ndf.dropna(inplace=True)\n\n#y is a label: output, a column named 'label'\ny = np.array(df['label'])\n\n#Shuffles up data and returns random elements from the\n#given data to X_train, X_test, y_train, y_test respectively\nX_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2)\n\n#Create a classifier (in this case, a LinearRegression classifier\n#is used\n#n_jobs is the number of concurrent jobs that the system should do\n#-1 indicates the maximum number of jobs as possible\nclf = LinearRegression(n_jobs=-1)\n\n#Find what would the m and c be in the following equation:\n#y = mx + c\n#which is an equation of a straight line: a LINEAR fit\nclf.fit(X_train, y_train)\n\n#Save the classifier,\nwith open('linearregression.pickle', 'wb') as f:\n pickle.dump(clf, f)\n\n#To read\npickle_in = open('linearregression.pickle', 'rb')\nclf = pickle.load(pickle_in)\n\n#Find the score/accuracy against some testing data: X_test, y_test\naccuracy = clf.score(X_test, y_test)\n\n#Forecast future (i. e. y) for X_lately\nforecast_set = clf.predict(X_lately)\n\nprint(forecast_set, forecast_out)\n\n#To plot a graph\ndf['Forecast'] = np.nan\n\nlast_date = df.iloc[-1].name\nlast_unix = last_date.timestamp()\none_day = 86400\nnext_unix = last_unix + one_day\n\nfor i in forecast_set:\n next_date = datetime.datetime.fromtimestamp(next_unix)\n next_unix += one_day\n df.loc[next_date] = [np.nan for _ in range(len(df.columns) - 1)] + [i]\n\ndf['Adj. Close'].plot()\ndf['Forecast'].plot()\nplt.legend(loc=4)\nplt.xlabel('Date')\nplt.ylabel('Price')\nplt.show()\n#Graph plotted!","sub_path":"4_regression_pickling_scaling.py","file_name":"4_regression_pickling_scaling.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"117880906","text":"import sqlite3\n\ndef find_ip(ip):\n conn = sqlite3.connect('firstspotted.db')\n c = conn.cursor()\n with conn:\n c.execute('SELECT hostname FROM fir WHERE ip = :ip',{'ip':ip})\n data = c.fetchall()\n conn.close()\n if len(data) == 0:\n q3 = input('ip does not exist, try again? No or [ip]')\n if q3 == 'No':\n return \n else:\n find_ip(q3)\n else:\n for i in data:\n print(i)\n q4 = input('choose your user: [User] or No')\n if q4 =='No':\n return \n else:\n q6 = input('which scope? (successful,Invalid, FAILED')\n if q6 != 'successful' and q6 != 'Invalid' and q6 != 'FAILED':\n print('No messing around, see ya')\n return \n else:\n resume(ip,q4,q6)\n\n\n\ndef resume(ip,q4,q6):\n conn = sqlite3.connect('firstspotted.db')\n c = conn.cursor()\n with conn:\n c.execute(\"SELECT ip,hostname,time,state FROM fir WHERE ip = :ip AND hostname = :host AND state = :state\",{'ip':ip,'host':q4,'state':q6})\n data = c.fetchall()\n conn.close()\n if len(data) == 0:\n print('does not exist, bye')\n return \n else:\n print('first-time spotted: ')\n for i in data:\n print(i)\n s = q6\n if s == 'successful':\n conn = sqlite3.connect('rsuc.db')\n c = conn.cursor()\n with conn:\n c.execute(\"SELECT ip,hostname,datetime,geolocation,method FROM success_logins WHERE ip = :ip AND hostname = :user\",{'ip':ip,'user':q4})\n data = c.fetchall()\n conn.close()\n if len(data) == 0:\n print('does not exist bye')\n return \n else:\n print('most recent spotted:(success) ')\n for i in data:\n print(i)\n return \n elif s == 'Invalid':\n conn = sqlite3.connect('rinva.db')\n c = conn.cursor()\n with conn:\n c.execute(\"SELECT hostname, ip, geolocation, datatime FROM invalid_logins WHERE ip = :ip AND hostname = :user\",{'ip':ip,'user':q4})\n data = c.fetchall()\n conn.close()\n if len(data) == 0:\n print(' does not exist, bye')\n return\n else:\n print('most recent spotted:(invalid) ')\n for i in data:\n print(i)\n return\n elif s =='FAILED':\n conn = sqlite3.connect('rf.db')\n c = conn.cursor()\n with conn:\n c.execute(\"SELECT ip, hostname,geoloctaion,method,datatime FROM failed_logins WHERE ip = :ip AND hostname = :user\",{'ip':ip,'user':q4})\n data = c.fetchall()\n conn.close()\n if len(data) == 0:\n print('does not exist')\n return\n else:\n print('most recent spotted:(failed) ')\n for i in data:\n print(i)\n return\n","sub_path":"version 4 /actions_v4.py","file_name":"actions_v4.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"102014994","text":"import argparse\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Output average box')\n parser.add_argument('-i', '--input', type=str, help='path of output file from verification algorithm', required=True)\n return parser.parse_args()\n\ndef main(args):\n with open(args.input, \"r\") as f:\n lines = f.readlines()\n start = len(lines) - 1\n while \"display average box:\" not in lines[start]:\n start -= 1\n end = start + 1\n while \"}\" not in lines[end]:\n end += 1\n box = lines[start + 1:end]\n box = sorted(box, key=lambda x: int(x.strip(\" {\\n\").split(\":\")[0]))\n \n print('{')\n for line in box:\n print(line.replace(\"\\n\", \"\").replace(\"{\", \" \"))\n print('}')\n\nif __name__=='__main__':\n args = parse_args()\n main(args)\n","sub_path":"result/clean_box_output.py","file_name":"clean_box_output.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"72652141","text":"import Constructor\nimport Packet\nimport Constants\nimport Presenter\nimport Tools\n\n\nimport socket\n\n''' This method takes demanded domain name, type of question\n fields and question class. Also it takes server ip where\n this question will be resolved.\n'''\n\n\ndef resolve(d_name, q_type, q_class, server_ip):\n # this is packet we will send to client\n demanded_packet = None\n\n # Create a UDP socket\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n for i in range(Constants.DNS_RECURSION_MAX_DEPTH):\n random_id = Tools.random_int()\n data = Constructor.construct_header(random_id, 0x0100, 0x1, 0, 0, 0)\n data += Constructor.construct_question(d_name, q_type, q_class)\n\n server_address = (server_ip, Constants.DNS_PORT_NUMBER)\n\n sock.sendto(data, server_address)\n\n response_data, server = sock.recvfrom(4096)\n\n packet = Packet.Packet(response_data)\n\n Presenter.print_packet(packet)\n\n # check if its authoritative answer\n if packet.header.authoritative_answer:\n demanded_packet = packet\n break\n else:\n if len(packet.additionals) == 0:\n print(\"No additionals found\")\n break\n for additional in packet.additionals:\n if additional.a_type == 0x0001:\n server_ip = additional.data\n break\n\n sock.close()\n\n return demanded_packet\n","sub_path":"DNS Server/Resolver.py","file_name":"Resolver.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"350812959","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport pandas as pd\nimport datetime\n#matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom dateutil import parser\n\ndf_ferrara = pd.read_csv('ferrara_270615.csv')\ndf_milano = pd.read_csv('milano_270615.csv')\ndf_mantova = pd.read_csv('mantova_270615.csv')\ndf_ravenna = pd.read_csv('ravenna_270615.csv')\ndf_torino = pd.read_csv('torino_270615.csv')\ndf_asti = pd.read_csv('asti_270615.csv')\ndf_bologna = pd.read_csv('bologna_270615.csv')\ndf_piacenza = pd.read_csv('piacenza_270615.csv')\ndf_cesena = pd.read_csv('cesena_270615.csv')\ndf_faenza = pd.read_csv('faenza_270615.csv')\n\n# 取出我们要分析的温度和日期数据\ny1 = df_milano['temp']\nx1 = df_milano['day']\n\n#把日期数据转换成 datetime 的格式\nday_milano = [parser.parse(x) for x in x1]\n\n# 调用 subplot 函数\nfig, ax = plt.subplots()\nplt.xticks(rotation=70)\nhours = mdates.DateFormatter('%H:%M')\nax.xaxis.set_major_formatter(hours)\nax.plot(day_milano ,y1, 'r')","sub_path":"601-607/Pic9-8.py","file_name":"Pic9-8.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"395611972","text":"'''\n网友实现:http://bookshadow.com/weblog/2017/03/26/leetcode-complex-number-multiplication/\nLeetCode537:Complex Number Multiplication\nGiven two strings representing two complex numbers.\n\nYou need to return a string representing their multiplication. Note i2 = -1 according to the definition.\n\nExample 1:\nInput: \"1+1i\", \"1+1i\"\nOutput: \"0+2i\"\nExplanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.\nExample 2:\nInput: \"1+-1i\", \"1+-1i\"\nOutput: \"0+-2i\"\nExplanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.\n'''\n\nclass Solution(object):\n def complexNumberMultiply(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n extract = lambda s: map(int, s[:-1].split(\"+\"))\n m, n = extract(a)\n p, q = extract(b)\n return '%d+%di' % (m * p - n * q, m * q + n * p)\n\n","sub_path":"LeetCode-Python2/2017.5/LeetCode537-Complex Number Multiplication.py","file_name":"LeetCode537-Complex Number Multiplication.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"107017224","text":"from django.core import serializers\nfrom django.contrib import admin\nfrom django.http import HttpResponse\nfrom django.contrib.admin.options import csrf_protect_m\nfrom django.contrib.admin.utils import unquote\nfrom functools import update_wrapper\n\n\nclass AdminPreviewMix(admin.ModelAdmin):\n \"\"\"\n Admin view for generate preview\n \"\"\"\n\n @csrf_protect_m\n def preview_view(self, request, object_id=None, form_url='', extra_context=None):\n model = self.model\n opts = model._meta\n add = object_id is None\n if add:\n return HttpResponse('No preview for new objects')\n obj = self.get_object(request, unquote(object_id))\n\n ModelForm = self.get_form(request, obj)\n if request.method == 'POST':\n form = ModelForm(request.POST, request.FILES, instance=obj)\n if form.is_valid():\n form_validated = True\n new_object = self.save_form(request, form, change=not add)\n data = serializers.serialize('json', [new_object])\n request.session['preview_data_json_%s_%s' % (obj.__class__.__name__.lower(), obj.id)] = data\n return HttpResponse('success')\n else:\n return HttpResponse(form.errors)\n\n def get_urls(self):\n from django.conf.urls import patterns, url\n\n def wrap(view):\n def wrapper(*args, **kwargs):\n return self.admin_site.admin_view(view)(*args, **kwargs)\n return update_wrapper(wrapper, view)\n info = self.model._meta.app_label, self.model._meta.model_name\n urlpatterns = super(AdminPreviewMix, self).get_urls()\n urlpatterns += patterns('',\n url(r'^(.+)/preview$', wrap(self.preview_view), name='%s_%s_preview' % info),\n )\n return urlpatterns\n","sub_path":"rs_contents/preview/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"591918562","text":"# Created byMartin.cz\n# Copyright (c) Martin Strohalm. All rights reserved.\n\nimport pero\n\n\nclass DrawTest(pero.Graphics):\n \"\"\"Test case for angled text drawing.\"\"\"\n \n \n def draw(self, canvas, *args, **kwargs):\n \"\"\"Draws the test.\"\"\"\n \n # clear canvas\n canvas.fill(pero.colors.White)\n \n # init glyphs\n origin = pero.Plus(\n line_width = 1,\n line_color = pero.colors.Red,\n size = 10)\n \n label = pero.Text(\n font_size = 14,\n text_align = pero.TEXT_ALIGN_CENTER,\n text_base = pero.TEXT_BASE_MIDDLE,\n text_bgr_color = \"lightgrey\",\n angle_units = pero.DEG)\n \n # init coords\n x = 70\n y = 70\n \n # test angles\n for angle in range(-360, 360, 45):\n \n if x+80 > 400:\n x = 70\n y += 100\n \n title = \"ANGLE%d\" % angle\n label.draw(canvas, x=x, y=y, text=title, angle=angle)\n origin.draw(canvas, x=x, y=y)\n \n x += 80\n\n\n# run test\nif __name__ == '__main__':\n pero.debug(DrawTest(), 'show', \"Text Angle\", 400, 450)\n","sub_path":"examples/drawing/draw_text_angle.py","file_name":"draw_text_angle.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"624323645","text":"\"\"\"\n1. 对比哈希表和Trie树\n哈希表虽然能在O(1)时间内寻找键值, 但却不能做:\n a. 找到具有同一前缀的全部键值\n b. 按词典序枚举字符串的数据集\nTrie 可以做到上面两个,\n此外:随着哈希表大小增大,会出现大量的冲突,时间复杂度可能增加到O(n)(哈希链表)\nTrie树存储多个具有相同前缀的键时可以使用较少的空间此时Trie树只需要O(m)的时间复杂度,m是键长。\n在平衡树中查找键值需要O(mlogn)时间复杂度\n\n应用:1. 自动补全(前缀查询) 2.拼写检查 3.IP路由(最长前缀匹配) 4. 单词游戏 5.T9打字预��\n\nTrie结构:\n a. 最多有R个指向子节点的链接,其中每个链接对应数据集中的一个字母\n b. 布尔字段,指定节点是对应键的结尾还是键的前缀\n\n操作:insert 和 search\ninsert:\n a. 链接存在:沿着链接移动到树的下一个子层,for循环继续搜索下个字符\n b. 链接不存在:创建一个新的节点,并将它与父节点的链接相连\n时间空间复杂度都为O(m)\nsearch:\n a. 存在链接,移动到该链接后面路径中的下个节点,继续搜索下个键字符\n b. 没有链接,若已无键字符,且当前节点标记为isEnd,返回true。否则返回False\n时间复杂度O(m),空间复杂度O(1)\n\n查找Trie树中的前缀\n 和搜索键相似,区别,到达键前缀的末尾时,总返回true,不用考虑isEnd标记。\n\"\"\"\nclass Trie:\n\n def __init__(self):\n self.root = {}\n self.end_of_word = \"#\"\n\n def insert(self, word):\n node = self.root\n for char in word:\n node = node.setdefault(char, {})\n node[self.end_of_word] = self.end_of_word\n\n def search(self, word):\n node = self.root\n for char in word:\n if char not in node:\n return False\n node = node[char]\n return self.end_of_word in node\n\n def startsWith(self, prefix):\n node = self.root\n for char in prefix:\n if char not in node:\n return False\n node = node[char]\n return True\n\n","sub_path":"Week7/Trie.py","file_name":"Trie.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"340098660","text":"\nimport asyncio\nfrom time import sleep\nimport libscrc\n\nimport global_vars\nfrom db_utils import Transport, TransportData, CustomUser\n\n\nclass MyException(Exception):\n pass\n\n\nclass TCPserverCustom(asyncio.Protocol):\n\n def __init__(self, **kwargs):\n\n # global_vars.main_logger.info(\"test server init.\")\n\n self.server_host = kwargs.get('server_host')\n self.server_port = kwargs.get('server_port')\n self.max_block_size = kwargs.get('max_block_size')\n self.db_transport = Transport()\n self.db_transport_data = TransportDataCustom()\n self.db_custom_user = CustomUser()\n self.timeout = 5 * 60\n\n def _timeout(self):\n # print(\"=================== timeout =================\")\n self.timeout_handle = self.loop.call_later(\n self.timeout, self._timeout,\n )\n # raise MyException(\"e\")\n\n def run_server(self):\n self.loop = asyncio.get_event_loop()\n self.timeout_handle = self.loop.call_later(\n self.timeout, self._timeout,\n )\n self.loop.create_task(asyncio.start_server(self.handle_client, self.server_host, self.server_port))\n self.loop.run_forever()\n\n def processRequest(self, req_msg, logged_user):\n msgs = req_msg.split(';')\n\n print(\"processRequest: \", msgs)\n\n if msgs[0] == \">000L\":\n # print(\"------------ check_login ----------\")\n user_id, err_msg = self.db_custom_user.check_login(msgs[1], msgs[2])\n if user_id:\n print('user_id = ', user_id)\n reply = \"000L;OK;0\"\n crc16 = format(libscrc.modbus(reply.encode()), '04x')\n return user_id, \"<\" + reply + \";\" + crc16 + '\\n', err_msg\n else:\n # print('------ bad login or password --------')\n reply = \"000L;Err;2\"\n crc16 = format(libscrc.modbus(reply.encode()), '04x')\n return None, \"<\" + reply + \";\" + crc16 + '\\n', err_msg\n\n elif msgs[0] == \">00SD\":\n # print(\"----------->>> transport_data ----> logged_user = \", logged_user)\n if logged_user:\n dt = msgs[1]\n tm = msgs[2]\n lat = msgs[3]\n lon = msgs[4]\n course = msgs[5]\n speed = msgs[6]\n altitude = msgs[7]\n sats = msgs[8]\n flags1 = msgs[9]\n crc16 = msgs[10]\n result, err_msg = self.db_transport_data.save_data(logged_user, dt, tm, lat, lon, course, speed, altitude, sats, flags1)\n if result:\n # print('---- data saved ----')\n reply = \"00SD;OK;0\"\n crc16 = format(libscrc.modbus(reply.encode()), '04x')\n return logged_user, \"<\" + reply + '\\n', err_msg\n else:\n # print('---- data nit saved - error ----')\n reply = \"00SD;Err;1\"\n crc16 = format(libscrc.modbus(reply.encode()), '04x')\n return logged_user, \"<\" + reply + '\\n', err_msg\n else:\n # print('--- user not logged ----')\n reply = \"00SD;Err;3\"\n crc16 = format(libscrc.modbus(reply.encode()), '04x')\n global_vars.main_logger.error(\"Error: not logged.\")\n return logged_user, \"<\" + reply + '\\n', None\n else:\n reply = \"00SD;Err;4\"\n crc16 = format(libscrc.modbus(reply.encode()), '04x')\n return logged_user, \"<\" + reply + '\\n', None\n\n async def handle_client(self, reader, writer):\n request = None\n\n logged_user = None\n\n while True:\n try:\n request = (await reader.read(self.max_block_size)).decode('utf8')\n except Exception as e:\n print(\"============= Exception (1) ==========\")\n global_vars.main_logger.error(\"exception: \" + str(e))\n continue\n\n if request:\n request = str(request)\n global_vars.main_logger.info(str(request))\n request = request.rstrip()\n try:\n logged_user, reply, err_msg = self.processRequest(request, logged_user)\n except MyException as e:\n print(\"============= raise MyException (2) ==========\")\n break\n except Exception as e:\n print(\"============= Exception (2) ==========\")\n break\n if err_msg:\n global_vars.main_logger.error(str(err_msg))\n if not logged_user:\n # print(\"--------------------- >>> Not logged user ---- >>> exit ---------\")\n break\n # print(\"handle_client --------------------->: reply = \", reply)\n try:\n writer.write(reply.encode('utf8'))\n global_vars.main_logger.info(\"OUTPUT: \" + str(reply))\n except Exception as e:\n global_vars.main_logger.error(\"exception (0): \" + str(e))\n # global_vars.main_logger.info(\"data =\" + str(request) + \"|\")\n # break\n else:\n sleep(0.3)\n break\n\n try:\n await writer.drain()\n except ConnectionResetError as e:\n global_vars.main_logger.error(\"exception (1): \" + str(e))\n sleep(0.5)\n break\n except BrokenPipeError as e:\n global_vars.main_logger.error(\"exception (2): \" + str(e))\n sleep(0.5)\n break\n\n # print('------------- waiting ------------')\n # sleep(1)\n\n writer.close()\n\n return False\n","sub_path":"tcp_server/TCPserverCustom.py","file_name":"TCPserverCustom.py","file_ext":"py","file_size_in_byte":5860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"274531385","text":"\"\"\"Houses all the different models for simulation.\"\"\"\n\nimport math\nimport numpy as np\n\n\ndef IDM(p, state):\n \"\"\"Intelligent Driver Model (IDM), second order ODE.\n\n Note that if the headway is negative, model will begin accelerating; If velocity is negative, \n model will begin decelerating. Therefore you must take care to avoid any collisions or negative speeds\n in the simulation.\n\n Args:\n p: parameters - [max speed, comfortable time headway, jam spacing, comfortable acceleration,\n comfortable deceleration]\n state: list of [headway, self velocity, leader velocity]\n\n Returns:\n acceleration\n \"\"\"\n return p[3]*(1-(state[1]/p[0])**4-((p[2]+state[1]*p[1]+(state[1]*(state[1]-state[2]))\n / (2*(p[3]*p[4])**(1/2)))/(state[0]))**2)\n\n\ndef IDM_free(p, state):\n \"\"\"Free flow model for IDM, state = self velocity, p = parameters. Returns acceleration.\"\"\"\n return p[3]*(1-(state/p[0])**4)\n\n\ndef IDM_eql(p, v):\n \"\"\"Equilibrium solution for IDM, v = velocity, p = parameters. Returns headway corresponding to eql.\"\"\"\n s = ((p[2]+p[1]*v)**2/(1 - (v/p[0])**4))**.5\n return s\n\n\ndef OVM(p, state):\n \"\"\"Optimal Velocity Model (OVM), second order ODE.\n\n Different forms of the optimal velocity function are possible - this implements the original\n formulation which uses tanh, with 4 parameters for the optimal velocity function.\n\n Args:\n p: parameters - p[0],p[1],p[2],p[4] are shape parameters for the optimal velocity function.\n The maximum speed is p[0]*(1 - tanh(-p[2])), jam spacing is p[4]. p[1] controls the\n slope of the velocity/headway equilibrium curve. p[3] is a sensitivity parameter\n which controls the strength of acceleration.\n state: list of [headway, self velocity, leader velocity] (leader velocity unused)\n\n Returns:\n acceleration\n \"\"\"\n\n return p[3]*(p[0]*(math.tanh(p[1]*state[0]-p[2]-p[4])-math.tanh(-p[2]))-state[1])\n\n\ndef OVM_free(p, state):\n \"\"\"Free flow model for OVM\"\"\"\n return p[3]*(p[0]*(1-math.tanh(-p[2])) - state[1])\n\n\ndef OVM_eql(p, s):\n \"\"\"Equilibrium Solution for OVM, s = headway, p = parameters. Note that eql_type = 's'.\"\"\"\n return p[0]*(math.tanh(p[1]*s-p[2]-p[4])-math.tanh(-p[2]))\n\n\ndef IDM_shift_eql(p, v, shift_parameters, state):\n \"\"\"Calculates an acceleration which shifts the equilibrium solution for IDM.\n\n The model works by solving for an acceleration which modifies the equilibrium solution by some\n fixed amount. Any model which has an equilibrium solution which can be solved analytically,\n it should be possible to define a model in this way. For IDM, the result that comes out lets\n you modify the equilibrium by a multiple.\n E.g. if the shift parameter = .5, and the equilibrium headway is usually 20 at the provided speed,\n we return an acceleration which makes the equilibrium headway 10. If we request 'decel', the parameter\n must be > 1 so that the acceleration is negative. Otherwise the parameter must be < 1.\n\n Args:\n p: parameters for IDM\n v: velocity of vehicle to be shifted\n shift_parameters: list of two parameters, 0 index is 'decel' which is > 1, 1 index is 'accel' which\n is < 1. Equilibrium goes to n*s, where s is the old equilibrium, and n is the parameter.\n E.g. shift_parameters = [2, .4], if state = 'decel' we return an acceleration which makes\n the equilibrium goes to 2 times its normal distance.\n state: one of 'decel' if we want equilibrium headway to increase, 'accel' if we want it to decrease.\n\n Returns:\n acceleration which shifts the equilibrium\n \"\"\"\n # TODO constant acceleration formulation based on shifting eql is not good because it takes\n # too long to reach new equilibrium. See shifteql.nb/notes on this for a new formulation\n # or just continue using generic_shift which seems to work fine\n\n # In Treiber/Kesting JS code they have another way of doing cooperation where vehicles will use their\n # new deceleration if its greater than -2b\n if state == 'decel':\n temp = shift_parameters[0]**2\n else:\n temp = shift_parameters[1]**2\n\n return (1 - temp)/temp*p[3]*(1 - (v/p[0])**4)\n\n\ndef generic_shift(unused, unused2, shift_parameters, state):\n \"\"\"Acceleration shift for any model, shift_parameters give constant deceleration/acceleration.\"\"\"\n if state == 'decel':\n return shift_parameters[0]\n else:\n return shift_parameters[1]\n\n\ndef mobil(veh, lc_actions, lside, rside, newlfolhd, newlhd, newrfolhd, newrhd, newfolhd, timeind, dt,\n userelax_cur=True, userelax_new=False, use_coop=True, use_tact=True):\n \"\"\"Minimizing total braking during lane change (MOBIL) lane changing decision model.\n\n parameters:\n 0 - safety criteria (maximum deceleration allowed after LC, more negative = less strict),\n 1 - safety criteria for maximum deceleration allowed, when velocity is 0\n 2 - incentive criteria (>0, larger = more strict. smaller = discretionary changes more likely),\n 3 - politeness (taking other vehicles into account, 0 = ignore other vehicles, ~.1-.2 = realistic),\n 4 - bias on left side (can add a bias to make vehicles default to a certain side of the road),\n 5 - bias on right side,\n 6 - probability of checking LC while in discretionary state (not in original model. set to\n 1/dt to always check discretionary. probability of checking per 1 second)\n naming convention - l/r = left/right respectively, current lane if no l/r\n new indicates that it would be the configuration after potential change\n\n Args:\n veh: ego vehicle\n lc_actions: dictionary where lane changing actions are stored, keys = vehicles, values = 'l' or 'r'\n lside: bool whether model evaluates a left lane change\n rside: bool whether model evaluates a right lane change\n newlfolhd: new left follower headway\n newlhd: new vehicle headway for left change\n newrfolhd: new right follower headway\n newrhd: new vehicle headway for right change\n newfolhd: new follower headway\n timeind: time index\n dt: time step\n userelax_cur: If True, we include relaxation in the evaluation of current acceleration, so that the\n cf model is not reevaluated if vehicle is in relaxation. True is recommended\n userelax_new: If True, we include relaxation in the evaluation of the new acceleration. False is\n recommended.\n use_coop: Controls whether cooperative model is applied (see coop_tact_model)\n use_tact: Controls whether tactical model is applied (see coop_tact_model)\n\n Returns:\n None. (modifies lc_actions in place)\n \"\"\"\n p = veh.lc_parameters\n lincentive = rincentive = -math.inf\n\n # calculate cura, fola, newfola\n if not userelax_cur and veh.in_relax:\n cura = veh.get_cf(veh.hd, veh.speed, veh.lead, veh.lane, timeind, dt, False)\n else:\n cura = veh.acc # more generally could use a method to return acceleration\n # cura = veh.acc_bounds(cura)\n fola, newfola = mobil_helper(veh.fol, veh, veh.lead, newfolhd, timeind, dt, userelax_cur, userelax_new)\n\n # to compute left side: need to compute lfola, newlfola, newla\n if lside:\n lfol = veh.lfol\n llead = lfol.lead\n lfola, newlfola = mobil_helper(lfol, llead, veh, newlfolhd, timeind, dt, userelax_cur, userelax_new)\n\n userelax = userelax_new and veh.in_relax\n newla = veh.get_cf(newlhd, veh.speed, llead, veh.llane, timeind, dt, userelax)\n # newla = veh.acc_bounds(newla)\n\n lincentive = newla - cura + p[3]*(newlfola - lfola + newfola - fola) + p[4]\n\n # same for right side\n if rside:\n rfol = veh.rfol\n rlead = rfol.lead\n rfola, newrfola = mobil_helper(rfol, rlead, veh, newrfolhd, timeind, dt, userelax_cur, userelax_new)\n\n userelax = userelax_new and veh.in_relax\n newra = veh.get_cf(newrhd, veh.speed, rlead, veh.rlane, timeind, dt, userelax)\n # newra = veh.acc_bounds(newra)\n\n rincentive = newra - cura + p[3]*(newrfola - rfola + newfola - fola) + p[5]\n\n # determine which side we want to potentially intiate LC for\n if rincentive > lincentive:\n side = 'r'\n lctype = veh.r_lc\n incentive = rincentive\n\n newhd = newrhd\n newlcsidefolhd = newrfolhd\n selfsafe = newra\n lcsidefolsafe = newrfola\n else:\n side = 'l'\n lctype = veh.l_lc\n incentive = lincentive\n\n newhd = newlhd\n newlcsidefolhd = newlfolhd\n selfsafe = newla\n lcsidefolsafe = newlfola\n\n # safety criteria formulations\n # default value of safety -\n # safe = p[0] (or use the maximum safety, p[1])\n \n # safety changes with relative velocity (implemented in treiber, kesting' traffic-simulation.de) -\n safe = veh.speed/veh.maxspeed\n safe = safe*p[0] + (1-safe)*p[1]\n \n # if lctype == 'discretionary': # different safeties for discretionary/mandatory\n # safe = p[0]\n # else:\n # safe = p[1] # or use the relative velocity safety\n\n # safeguards for negative headway (necessary for IDM)\n if newhd is not None and newhd < 0:\n selfsafe = safe - 5\n if newlcsidefolhd is not None and newlcsidefolhd < 0:\n lcsidefolsafe = safe - 5\n\n # determine if LC can be completed, and if not, determine if we want to enter cooperative or\n # tactical states\n if lctype == 'discretionary':\n if incentive > p[2]:\n if selfsafe > safe and lcsidefolsafe > safe:\n lc_actions[veh] = side\n else:\n coop_tact_model(veh, newlcsidefolhd, lcsidefolsafe, selfsafe, safe, side, lctype,\n use_coop=use_coop, use_tact=use_tact)\n else: # mandatory state\n if selfsafe > safe and lcsidefolsafe > safe:\n lc_actions[veh] = side\n else:\n coop_tact_model(veh, newlcsidefolhd, lcsidefolsafe, selfsafe, safe, side, lctype,\n use_coop=use_coop, use_tact=use_tact)\n return\n\n\ndef mobil_helper(fol, curlead, newlead, newhd, timeind, dt, userelax_cur, userelax_new):\n \"\"\"Helper function for MOBIL computes new accelerations for fol after a potential lane change.\n\n Args:\n fol: follower is assumed to follow curlead in the current configuration in new potential\n configuration it would follow newlead\n curlead: current leader for fol\n newlead: new leader for fol\n newhd: new headway for fol\n timeind: time index\n dt: time step\n userelax_cur: If True, apply relaxation in current acceleration. True recommended.\n userelax_new: If True, apply relaxation in new acceleration. False recommended.\n\n Returns:\n fola: The current acceleration for fol\n newfola: new acceleration for fol after the lane change\n \"\"\"\n if fol.cf_parameters is None:\n fola = 0\n newfola = 0\n else:\n if not userelax_cur and fol.in_relax:\n fola = fol.get_cf(fol.hd, fol.speed, curlead, fol.lane, timeind, dt, False)\n else:\n fola = fol.acc\n\n userelax = userelax_new and fol.in_relax\n newfola = fol.get_cf(newhd, fol.speed, newlead, fol.lane, timeind, dt, userelax)\n # fola = fol.acc_bounds(fola)\n # newfola = fol.acc_bounds(newfola)\n\n return fola, newfola\n\n\ndef coop_tact_model(veh, newlcsidefolhd, lcsidefolsafe, selfsafe, safe, side, lctype, use_coop=True,\n use_tact=True, jam_spacing = 2):\n \"\"\"Cooperative and tactical model for a lane changing decision model.\n\n Explanation of model -\n first we assume that we can give vehicles one of two commands - accelerate or decelerate. These commands\n cause a vehicle to give more space, or less space, respectively. See any shift_eql function.\n There are three possible options - cooperation and tactical, or only cooperation, or only tactical\n\n In the tactical model, first we check the safety conditions to see what is preventing us from\n changing (either lcside fol or lcside lead). if both are violating safety, and the lcside leader is\n faster than vehicle, then the vehicle gets deceleration to try to change behind them. If vehicle is\n faster than lcside leader, then the vehicle gets acceleration to try to overtake. if only one is\n violating safety, the vehicle moves in a way to prevent that violation. Meaning -\n if only the follower's safety is violated, the vehicle accelerates\n if the vehicle's own safety is violated; the vehicle decelerates\n the tactical model only modifies the acceleration of veh.\n\n in the cooperative model, we try to identify a cooperating vehicle. A cooperating vehicle always gets a\n deceleration added so that it will give extra space to let the ego vehicle successfully change lanes.\n If the cooperation is applied without tactical, then the cooperating vehicle must be the lcside follower,\n and the newlcsidefolhd must be > jam spacing. We cannot allow cooperation between veh and coop veh\n when the headway is < jam spacing, because otherwise it is possible for the coop veh to have 0 speed,\n and veh still cannot change lanes, leading to a gridlock situation where neither vehicle can move.\n Jam spacing refers to the jam spacing of the vehicle which the condition is used for.\n if cooperation is applied with tactical, then in addition to the above, it's also possible the\n cooperating vehicle is the lcside follower's follower, where additionally the newlcsidefolhd is\n < jam spacing, but the headway between the lcside follower's follower and veh is > jam spacing.\n In this case, the lcside follower cannot cooperate, so we allow its follower to cooperate instead.\n In the first case where the cooperating vehicle is the lcside follower, the tactical model is applied\n as normal.\n In the second case, since the issue is the the lcside follower is directly blocking the vehicle,\n the vehicle accelerates if the lcside follower has a slower speed than vehicle, and decelerates otherwise.\n The cooperative model only modifies the acceleration of the cooperating vehicle.\n\n when a vehicle requests cooperation, it has to additionally fulfill a condition which simulates\n the choice of the cooperating vehicle. All vehicles have a innate probability (coop_parameters attribute)\n of cooperating, and for a discretionary LC, this innate probability controls whether or not the\n cooperation is accepted.\n For a mandatory LC, vehicle can add to this probability, which simulates forcing the cooperation.\n vehicles have a lc_urgency attribute which is updated upon initiating a mandatory change. lc_urgency is a\n tuple of two positions, at the first position, only the follower's innate cooperation probability\n is used. at the second position, the follower is always forced to cooperate, even if it has 0\n innate cooperation probability, and the additional cooperation probability is interpolated linearally\n between these two positions.\n\n Implementation details -\n when a vehicle has cooperation or tactical components applied, it has a lc_side attribute which is\n set to either 'l' or 'r' instead of None. This marks the vehicle as having the coop/tact added, and\n will make it so the vehicle attempts to complete the LC at every timestep even if its only a discretionary\n change. vehicles also have a coop_veh attribute which stores the cooperating vehicle. A cooperating\n vehicle does not have any attribute marking it as such.\n the lc_urgency attribute needs to be set whenever a mandatory route event begins. the lc_side, coop_veh,\n and lc_urgency attributes need to be reset to None whenever the change is completed.\n in the road event where a lane ends on the side == lc_side, then lc_side and coop_veh need to be reset.\n\n Args:\n veh: vehicle which wants to change lanes\n newlcsidefolhd: new lcside follower headway\n lcsidefolsafe: safety value for lcside follower; viable if > safe\n selfsafe: safety value for vehicle; viable if > safe\n safe: safe value for change\n side: either 'l' or 'r', side vehicle wants to change\n lctype:either 'discretionary' or 'mandatory'\n use_coop: bool, whether to apply cooperation model. if use_coop and use_tact are both False,\n this function does nothing.\n use_tact: bool, whether to apply tactical model\n jam_spacing: float, headway such that (jam_spacing, 0) is equilibrium solution for coop_veh\n\n Returns:\n None (modifies veh, veh.coop_veh)\n \"\"\"\n # clearly it would be possible to modify different things, such as how the acceleration modifications\n # are obtained, and changing the conditions for entering/exiting the cooperative/tactical conditions\n # in particular we might want to add extra conditions for entering cooperative state\n tact = use_tact\n if side == 'l':\n lcsidefol = veh.lfol\n else:\n lcsidefol = veh.rfol\n\n if use_coop and use_tact:\n coop_veh = veh.coop_veh\n if coop_veh is not None: # first, check cooperation is valid, and apply cooperation if so\n if coop_veh is lcsidefol and newlcsidefolhd > jam_spacing: # coop_veh = lcsidefol\n coop_veh.acc += coop_veh.shift_eql('decel')\n\n elif coop_veh is lcsidefol.fol and newlcsidefolhd < jam_spacing and \\\n coop_veh.hd + newlcsidefolhd + lcsidefol.len > jam_spacing: # coop_veh = lcsidefol.fol\n coop_veh.acc += coop_veh.shift_eql('decel')\n if lcsidefol.speed > veh.speed:\n tactstate = 'decel'\n else:\n tactstate = 'accel'\n veh.acc += veh.shift_eql(tactstate)\n tact = False\n else: # cooperation is not valid -> reset\n veh.lc_side = None\n veh.coop_veh = None\n\n # if there is no coop_veh, then see if we can get vehicle to cooperate\n elif newlcsidefolhd is not None: # newlcsidefolhd is None only if lcsidefol is an anchor vehicle\n if newlcsidefolhd > jam_spacing:\n coop_veh = lcsidefol\n elif lcsidefol.fol.cf_parameters is not None and \\\n lcsidefol.fol.hd+lcsidefol.len + newlcsidefolhd > jam_spacing:\n coop_veh = lcsidefol.fol\n\n temp = coop_veh.coop_parameters\n if lctype == 'mandatory':\n start, end = veh.lc_urgency[:]\n temp += (veh.pos - start)/(end - start+1e-6)\n\n if temp >= 1 or np.random.rand() < temp:\n veh.coop_veh = coop_veh\n veh.lc_side = side\n # apply cooperation\n coop_veh.acc += coop_veh.shift_eql('decel')\n # apply tactical in case coop_veh = lcsidefol.fol (otherwise we go to normal tactical model)\n if coop_veh is not lcsidefol:\n tact = False\n if lcsidefol.speed > veh.speed:\n tactstate = 'decel'\n else:\n tactstate = 'accel'\n veh.acc += veh.shift_eql(tactstate)\n\n elif use_coop and not use_tact:\n coop_veh = veh.coop_veh\n if coop_veh is not None:\n if coop_veh is lcsidefol and newlcsidefolhd > jam_spacing: # conditions for cooperation when there is no tactical\n coop_veh.acc += coop_veh.shift_eql('decel')\n else: # cooperating vehicle not valid -> reset\n veh.lc_side = None\n veh.coop_veh = None\n elif newlcsidefolhd is not None and newlcsidefolhd > jam_spacing: # vehicle is valid\n # check cooperation condition\n temp = lcsidefol.coop_parameters\n if lctype == 'mandatory':\n start, end = veh.lc_urgency[:]\n temp += (veh.pos - start)/(end - start + 1e-6)\n\n if temp >= 1 or np.random.rand() < temp: # cooperation agreed/forced -> add cooperation\n veh.coop_veh = lcsidefol\n veh.lc_side = side\n # apply cooperation\n lcsidefol.acc += lcsidefol.shift_eql('decel')\n\n if tact: # apply tactical model\n # mark side if not already\n if veh.lc_side != side:\n veh.lc_side = side\n # find vehicle which is preventing change - if both lcsidefol and lcsidelead are prventing,\n # default to looking at the lcsidelead speed\n if lcsidefolsafe < safe:\n if selfsafe < safe: # both unsafe\n if lcsidefol.lead.speed > veh.speed: # edge case where lcsidefol.lead is None?\n tactstate = 'decel'\n else:\n tactstate = 'accel'\n else: # only follower unsafe\n tactstate = 'accel'\n else: # only leader unsafe\n tactstate = 'decel'\n\n veh.acc += veh.shift_eql(tactstate)\n\n\ndef IDM_parameters(*args):\n \"\"\"Suggested parameters for the IDM/MOBIL.\"\"\"\n # time headway parameter = 1 -> always unstable in congested regime. \n # time headway = 1.5 -> restabilizes at high density\n cf_parameters = [33.3, 1., 2, 1.1, 1.5] # note speed is supposed to be in m/s\n lc_parameters = [-4, -10, .4, .1, 0, .2, .5]\n\n return cf_parameters, lc_parameters\n","sub_path":"havsim/simulation/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":21651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"392990938","text":"\"\"\"\nThis file defines Petra function call expressions and statements.\n\"\"\"\n\nimport re\n\nfrom llvmlite import ir\nfrom typing import List, Optional, Tuple, Union\n\nfrom .codegen import CodegenContext\nfrom .expr import Expr\nfrom .statement import Statement\nfrom .validate import ValidateError\nfrom .type import Type\nfrom .typecheck import TypeContext, TypeCheckError\n\n\nclass Call(Expr):\n \"\"\"\n A function call expression.\n \"\"\"\n\n def __init__(self, name: str, args: List[Expr]):\n self.name = name\n self.args = args\n self.t: Union[Tuple[()], Optional[Type]] = None\n self.validate()\n\n def get_type(self) -> Type:\n if isinstance(self.t, Type):\n return self.t\n if self.t == ():\n raise TypeCheckError(\"Attempted to use Call statement as expression\")\n raise Exception(\"Expected type to exist - was typecheck called?\")\n\n def validate(self) -> None:\n if not re.match(r\"^[a-z][a-zA-Z0-9_]*$\", self.name):\n raise ValidateError(\n \"Function call to '%s' does not match regex \"\n \"^[a-z][a-zA-Z0-9_]*$\" % self.name\n )\n\n def typecheck(self, ctx: TypeContext) -> None:\n # check existence of name\n if self.name not in ctx.functypes:\n raise TypeCheckError(\"Undeclared function '%s'\" % self.name)\n (t_in, t_out) = ctx.functypes[self.name]\n # check argument types\n if len(self.args) != len(t_in):\n raise TypeCheckError(\n \"Function call to '%s' expects %s arguments, not %s\"\n % (self.name, len(t_in), len(self.args))\n )\n for i, arg in enumerate(self.args):\n arg.typecheck(ctx)\n if arg.get_type() != t_in[i]:\n raise TypeCheckError(\n \"Argument %s of call to '%s' should be of type\"\n \"%s, not %s\" % (i, self.name, str(t_in[i]), str(arg.get_type()))\n )\n self.t = t_out\n\n def codegen(self, builder: ir.IRBuilder, ctx: CodegenContext) -> ir.Value:\n def codegen_arg(arg: Expr) -> ir.Value:\n return arg.codegen(builder, ctx)\n\n args = tuple(map(codegen_arg, self.args))\n func = ctx.funcs[self.name]\n return builder.call(func, args)\n","sub_path":"petra/call.py","file_name":"call.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"603711341","text":"def solution(p, s):\n answer = []\n\n while len(p)!=0:\n count=0\n for i in range(len(p)):\n p[i]=p[i]+s[i]\n\n while True:\n if(len(p)==0):break\n\n if(p[0]>=100):\n p.pop(0)\n s.pop(0)\n count=count+1\n else:break\n if (count != 0): answer.append(count)\n\n return answer\n\n\nif __name__ == \"__main__\":\n progresses = [93, 30, 55]\n speeds = [1, 30, 5]\n print(solution(progresses, speeds))","sub_path":"Programmers/Stack,Queue/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"577273825","text":"#!/usr/bin/env python3\nimport os\nimport re\nfrom subprocess import getstatusoutput, getoutput\n\nprg = \"things.py\"\n\n# --------------------------------------------------\ndef test_exists():\n \"\"\"Checks if program exists\"\"\"\n\n assert os.path.isfile(prg)\n\n# --------------------------------------------------\ndef test_first_line():\n \"\"\"Checks if output is correct for input_file.txt\"\"\"\n\n out = getoutput(f'{prg} ..\\\\input_file.txt')\n expected = \"2\"\n\n assert out.split('\\n')[0][-1] == expected\n\n# ------------------------------------------------------\ndef test_sort():\n \"\"\"Checks that the order of printing is from highest frequency to lowest\"\"\"\n\n out = getoutput(f'{prg} ..\\\\input_file.txt')\n out.split('\\n')\n\n basis = 'live - 2'\n to_find = 'africa - 1'\n\n assert to_find in out[out.index(basis) + 1:]\n","sub_path":"11_things/things_test.py","file_name":"things_test.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"191636797","text":"import pandas as pd\n\ndf = pd.read_csv(\"concat.csv\")\n\nstuff = set()\ncnt = 0\nfor idx, row in enumerate(df.iterrows()):\n row = row[1]\n stuff.add(row.EVENT_ID)\n if(row.osm == -1):\n cnt += 1\n\nprint(len(stuff))\nprint(cnt, \"-1s\")","sub_path":"modeling/street/unique.py","file_name":"unique.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"328484845","text":"# -*- coding: utf-8 -*-\nimport json\nimport os.path\nfrom robot.api import logger\nfrom robot.api.deco import keyword\nfrom jsonpath_rw import Index, Fields\nfrom jsonpath_rw_ext import parse\nfrom .version import VERSION\n\n__author__ = 'Traitanit Huangsri'\n__email__ = 'traitanit.hua@gmail.com'\n__version__ = VERSION\n\n\nclass JSONLibraryKeywords(object):\n ROBOT_EXIT_ON_FAILURE = True\n\n @keyword('Load JSON From File')\n def load_json_from_file(self, file_name):\n \"\"\"Load JSON from file.\n\n Return json as a dictionary object.\n\n Arguments:\n - file_name: absolute json file name\n\n Return json object (list or dictionary)\n\n Examples:\n | ${result}= | Load Json From File | /path/to/file.json |\n \"\"\"\n logger.debug(\"Check if file exists\")\n if os.path.isfile(file_name) is False:\n logger.error(\"JSON file: \" + file_name + \" not found\")\n raise IOError\n with open(file_name) as json_file:\n data = json.load(json_file)\n return data\n\n @keyword('Add Object To Json')\n def add_object_to_json(self, json_object, json_path, object_to_add):\n \"\"\"Add an dictionary or list object to json object using json_path\n\n Arguments:\n - json_object: json as a dictionary object.\n - json_path: jsonpath expression\n - object_to_add: dictionary or list object to add to json_object which is matched by json_path\n\n Return new json object.\n\n Examples:\n | ${dict}= | Create Dictionary | latitude=13.1234 | longitude=130.1234 |\n | ${json}= | Add Object To Json | ${json} | $..address | ${dict} |\n \"\"\"\n json_path_expr = parse(json_path)\n for match in json_path_expr.find(json_object):\n if type(match.value) is dict:\n match.value.update(object_to_add)\n if type(match.value) is list:\n match.value.append(object_to_add)\n\n return json_object\n\n @keyword('Get Value From Json')\n def get_value_from_json(self, json_object, json_path):\n \"\"\"Get Value From JSON using JSONPath\n\n Arguments:\n - json_object: json as a dictionary object.\n - json_path: jsonpath expression\n\n Return array of values\n\n Examples:\n | ${values}= | Get Value From Json | ${json} | $..phone_number |\n \"\"\"\n json_path_expr = parse(json_path)\n return [match.value for match in json_path_expr.find(json_object)]\n\n @keyword('Update Value To Json')\n def update_value_to_json(self, json_object, json_path, new_value):\n \"\"\"Update value to JSON using JSONPath\n\n Arguments:\n - json_object: json as a dictionary object.\n - json_path: jsonpath expression\n - new_value: value to update\n\n Return new json_object\n\n Examples:\n | ${json_object}= | Update Value To Json | ${json} | $..address.streetAddress | Ratchadapisek Road |\n \"\"\"\n json_path_expr = parse(json_path)\n for match in json_path_expr.find(json_object):\n path = match.path\n if isinstance(path, Index):\n match.context.value[match.path.index] = new_value\n elif isinstance(path, Fields):\n match.context.value[match.path.fields[0]] = new_value\n return json_object\n\n @keyword('Delete Object From Json')\n def delete_object_from_json(self, json_object, json_path):\n \"\"\"Delete Object From JSON using json_path\n\n Arguments:\n - json_object: json as a dictionary object.\n - json_path: jsonpath expression\n\n Return new json_object\n\n Examples:\n | ${json_object}= | Delete Object From Json | ${json} | $..address.streetAddress |\n \"\"\"\n json_path_expr = parse(json_path)\n for match in json_path_expr.find(json_object):\n path = match.path\n if isinstance(path, Index):\n del(match.context.value[match.path.index])\n elif isinstance(path, Fields):\n del(match.context.value[match.path.fields[0]])\n return json_object\n\n @keyword('Convert JSON To String')\n def convert_json_to_string(self, json_object):\n \"\"\"Convert JSON object to string\n\n Arguments:\n - json_object: json as a dictionary object.\n\n Return new json_string\n\n Examples:\n | ${json_str}= | Convert JSON To String | ${json_obj} |\n \"\"\"\n return json.dumps(json_object)\n\n @keyword('Convert String to JSON')\n def convert_string_to_json(self, json_string):\n \"\"\"Convert String to JSON object\n\n Arguments:\n - json_string: JSON string\n\n Return new json_object\n\n Examples:\n | ${json_object}= | Convert String to JSON | ${json_string} |\n \"\"\"\n return json.loads(json_string)\n\n","sub_path":"venv/Lib/site-packages/JSONLibrary/JSONLibraryKeywords.py","file_name":"JSONLibraryKeywords.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"206519709","text":"from graphic import draw_grid\nfrom pygame import display, image\nfrom buttons import ButtonReady\nfrom const import *\n\n\nclass BattleField(object):\n def __init__(self, screen, player_1, player_2):\n \"\"\"\n Данный класс отвечает отрисовку игрового поля во время игры\n \"\"\"\n self.screen = screen\n self.background_img = image.load(\"img/water-texture_(23).jpg\")\n self.player = player_1\n self.enemy_player = player_2\n self.ready_button = ButtonReady(screen)\n\n def update(self):\n \"\"\"\n Данная функция рисует игровое поле если идет игра игрок против игрока\n \"\"\"\n self.screen.blit(self.background_img, (0, 0))\n draw_grid(self.screen, 0)\n draw_grid(self.screen, 1)\n for ship in self.player.ships:\n ship.draw(self.screen)\n for part in self.player.parts_enemy_ship:\n self.screen.blit(part.image, (part.rect.x, part.rect.y))\n for part in self.enemy_player.parts_enemy_ship:\n self.screen.blit(part.image, (part.rect.x-MEDIUM, part.rect.y))\n display.flip()\n\n def update2(self):\n \"\"\"\n Данная функция рисует игровое поле если идет игра игрок против компьютера\n \"\"\"\n self.screen.blit(self.background_img, (0, 0))\n draw_grid(self.screen, 0)\n draw_grid(self.screen, 1)\n for ship in self.enemy_player.ships:\n ship.draw(self.screen)\n for part in self.enemy_player.parts_enemy_ship:\n self.screen.blit(part.image, (part.rect.x, part.rect.y))\n for part in self.player.parts_enemy_ship:\n self.screen.blit(part.image, (part.rect.x-MEDIUM, part.rect.y))\n display.flip()\n\n def swap(self):\n \"\"\"\n Данная функция меняет местами игроков в классе BattleShip\n \"\"\"\n self.player, self.enemy_player = self.enemy_player, self.player\n\n def draw_preparation_field(self):\n \"\"\"\n Данная функция рисует поле проверки готовности\n \"\"\"\n self.screen.blit(self.background_img, (0, 0))\n draw_grid(self.screen, 0)\n draw_grid(self.screen, 1)\n self.ready_button.draw_button()\n display.flip()","sub_path":"PycharmProjects/BattleShip2.0/battlefield.py","file_name":"battlefield.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"438465373","text":"#!/usr/bin/env python3\n\nimport sys\nimport json\nimport os\n\nfrom urllib.request import urlopen\n\nimport hashlib\n\nfrom datetime import datetime\n\n\nDEBUG = 0\n\nSCRIPTPATH = \"/mnt/mirror-snapshot/utils\"\n\n\ndef log_print(output):\n if DEBUG:\n print(output)\n\n\ndef gen_md5(str):\n md5str = hashlib.md5(str.encode(encoding='utf-8'))\n return md5str.hexdigest()\n\nif __name__ == '__main__':\n # usage:\n # newpra.py xxx.json ppa-baseurl [rpaname]\n # newrpa.py result.json http://pools.corp.deepin.com/ppa/debian0311/\n # [e21b073b0d7d63d4b53c65b235309f37]\n\n if len(sys.argv) > 1:\n # get file list to download\n resultjson = sys.argv[1]\n baseurl = sys.argv[2]\n\n with open(resultjson, 'r') as f:\n data = json.load(f)\n\n modifytime = data['time']\n\n # example:\n # {'repo': 'debian', 'filelist':\n # ['pool/non-free/e/ebook-dev-alp/ebook-dev-alp_200407-2.dsc',\n # 'pool/non-free/e/ebook-dev-alp/ebook-dev-alp_200407.orig.tar.gz',\n # 'pool/non-free/e/ebook-dev-alp/ebook-dev-alp_200407-2.diff.gz'],\n # 'name': 'ebook-dev-alp', 'newversion': '200407-1', 'type': 'update',\n # 'arch': 'source', 'oldversion': '200407-2'}\n jsondetails = data['details']\n\n # sometimes not any packages updated\n if not jsondetails:\n print(\"There is no packages updated in this checkupdate, exit.\")\n os._exit(1)\n\n # download all files\n if len(sys.argv) == 4:\n rpaname = sys.argv[3]\n else:\n rpaname = gen_md5(\n baseurl + datetime.now().strftime(\"%Y-%m-%d~%H%M%S\"))\n\n rpapath = \"/tmp/\" + rpaname\n TMPDIR = \"/tmp/rpa-\" + rpaname\n\n log_print(TMPDIR)\n\n os.mkdir(TMPDIR)\n os.chdir(TMPDIR)\n os.mkdir(\"src\")\n os.mkdir(\"deb\")\n\n for fileitem in jsondetails:\n if fileitem['arch'] == 'source':\n for x in fileitem['filelist']:\n fileurl = baseurl + \"/\" + x\n log_print(fileurl)\n g = urlopen(fileurl)\n with open(\"src/\" + os.path.basename(x), 'b+w') as f:\n f.write(g.read())\n else:\n for x in fileitem['filelist']:\n fileurl = baseurl + \"/\" + x\n log_print(fileurl)\n g = urlopen(fileurl)\n with open(\"deb/\" + os.path.basename(x), 'b+w') as f:\n f.write(g.read())\n\n # make a new rpa from template\n os.system(\"cp -r \" + SCRIPTPATH + \"/rpabase \" + rpapath)\n # os.system(\"cp -r /tmp/rpabase \" + rpapath)\n os.chdir(rpapath)\n # includedsc only one .dsc file each time\n dsccmd = 'find ' + TMPDIR + '/src/ -name \"*.dsc\" -exec reprepro -b ' + \\\n rpapath + ' includedsc unstable {} \\; >/dev/null 2>&1'\n os.system(dsccmd)\n os.system(\"reprepro -b . includedeb unstable \" +\n TMPDIR + \"/deb/*.deb >/dev/null 2>&1\")\n\n # to rpa\n basedir = \"/srv/pool/base/rpa/\" + rpaname\n wwwdir = \"/srv/pool/www/rpa/\" + rpaname\n # basedir = \"/tmp/base/rpa/\" + rpaname\n # wwwdir = \"/tmp/www/rpa/\" + rpaname\n\n if len(sys.argv) == 4:\n # update rpa has dirs, remove\n os.system(\"rm -rf \" + basedir)\n os.system(\"rm -rf \" + wwwdir)\n\n os.mkdir(basedir)\n os.mkdir(wwwdir)\n\n os.system(\"cp -rf \" + rpapath + \"/db \" + basedir + \"/\")\n os.system(\"cp -rf \" + rpapath + \"/conf \" + basedir + \"/\")\n\n os.system(\"cp -rf \" + rpapath + \"/dists \" + wwwdir + \"/\")\n os.system(\"cp -rf \" + rpapath + \"/pool \" + wwwdir + \"/\")\n os.system(\"cp -rf \" + rpapath + \"/checkupdate \" + wwwdir + \"/\")\n\n # get the rpa size\n sizecmd = \"du -sh \" + rpapath + \"/pool 2>/dev/null | awk '{print $1;}'\"\n rpasize = os.popen(sizecmd).read().strip()\n if rpasize:\n data['size'] = rpasize\n\n # output the result json\n with open(wwwdir + '/checkupdate/result.json', 'w') as f:\n json.dump(data, f)\n\n # clean\n os.system(\"rm -rf \" + TMPDIR)\n os.system(\"rm -rf \" + rpapath)\n\n # end, print the rpaname\n print(rpaname)\n","sub_path":"newrpa.py","file_name":"newrpa.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"169496590","text":"\"\"\"PATH COMPRESSION: _______________________________________________________\n\nPath compression tries to find traces of single character transitions inside a\nstate machine. A sequence of single character transitions is called a 'path'.\nInstead of implementing each state individually the states of a path are \nimplemented in one MegaState, i.e. a 'PathWalkerState'.\n\n \n path ['p', 'r', 'i', 'n', 't', PTC]\n |\n path_iterator ---->---' \n\n .-------------------------.\n | path_iterator = path[0] |\n '-------------------------'\n |\n |<-----------------------------------.\n | |\n .-----------'''--------------. true .-----------------.\n / *input_p == *path_iterator ? \\----------| ++path_iterator |\n \\______________________________/ | ++input_p |\n | '-----------------'\n |\n .------------------------.\n | |----- [a-h] ----> state 21\n | |----- [j] ----> state 185\n | transition_map(*input) |----- 'o' ----> state 312\n | |----- [p-z] ----> state 21\n | |----- [a-h] ----> state 21\n '------------------------'\n\nAs shown in the above figure, a PathWalkerState implements the states on the\npath by 'path walking'. That is, it compares the current input with the\ncurrent character on the path. If it fits, it continues on the path. If it\ndoes not, then it enters the PathWalkerState's transition map. The transition \nmap of all FSM_State-s absorbed by a PathWalkerState must be the same.\n\nEXPLANATION: __________________________________________________________________\n\nFor path compression, traits of single character transitions are identified\nwhile the remaining transitions of the involved states are the same (or covered\nby what is triggered by the current path element). This type of compression is\nuseful in languages that contain keywords. Consider for example a state\nmachine, containing the key-word 'for':\n\n\n( 0 )-- 'f' --->( 1 )-- 'o' --->( 2 )-- 'r' -------->(( 3 ))--( [a-z] )-.\n \\ \\ \\ |\n \\ \\ \\ |\n `--([a-eg-z])---`--([a-np-z])---`--([a-qs-z])-->(( 4 ))<-----------'\n\n\nThe states 0, 1, and 2 can be implemented by a PathWalkerState. It consists of\na common transition map which is preceded by a single character check. The\nsingle character check changes along a fixed path: the sequence of characters\n'f', 'o', 'r'. This is shown in the following pseudo-code:\n\n /* Character sequence of path is stored in array. */\n character array[4] = { 'f', 'o', 'r', PTC, };\n\n 0: p = &array[0]; goto PATH_WALKER_1;\n 1: p = &array[1]; goto PATH_WALKER_1;\n 2: p = &array[2]; goto PATH_WALKER_1;\n\n PATH_WALKER_1:\n /* Single Character Check */\n if input == *p: ++p; goto PATH_WALKER_1;\n elif input == PTC: goto StateAfterPath;\n elif *p == 0: goto STATE_3;\n\n /* Common Transition Map: The 'skeleton transition map' */\n if x < 'a': drop out\n elif x > 'z': drop out\n else: goto STATE_4\n\nThe array with the character sequence ends with a path terminating character\nPTC. It acts similar to the 'terminating zero' in classical C Strings. This\nway it can be detected when to trigger to the terminal state, i.e. the first\nstate after the path. For a state to be part of the path, it must hold that \n\n 'state.transition_map - transition character' \n matches 'path.transition_map'\n\nwhere 'transition character' is the character on which it transits to its\nsubsequent state. The 'transition character' is a 'wildcard', because it \nis handled in the pathwalker's head and not as part of the path walker's\nbody (if state_key = this state).\n\nEach state which is part of a path, can be identified by the identifier of the\nPathWalkerState + the position on the path (+ the id of the path, if a\nPathWalkerState walks more than one path), i.e.\n\n state on path <--> (PathWalkerState.index, path iterator position)\n\nAssume that in the above example the path is the 'PATH_WALKER_1' and the\ncharacter sequence is given by an array:\n\n path_1_sequence = { 'f', 'o', 'r', PTC };\n \nthen the three states 0, 1, 2 are identified as follows\n\n STATE_0 <--> (PATH_WALKER_1, path_1_sequence)\n STATE_1 <--> (PATH_WALKER_1, path_1_sequence + 1)\n STATE_2 <--> (PATH_WALKER_1, path_1_sequence + 2)\n\nIn the MegaState terminology, the path iterator position acts as a 'state_key'\nwhich identifies the state the pathwalker current represents. The\nPathWalkerState implements dedicated entry doors for each state on a path,\nwhere the path iterator (~ state key) is set to the appropriate position.\n\n(C) 2009-2013 Frank-Rene Schaefer\n\"\"\"\nimport quex.engine.analyzer.mega_state.path_walker.find as find\nfrom quex.engine.analyzer.mega_state.path_walker.state import PathWalkerState\nfrom quex.constants import E_Compression\n\nfrom copy import copy\n\ndef do(TheAnalyzer, CompressionType, AvailableStateIndexSet):\n \"\"\"________________________________________________________________________\n RETURNS: \n \n list( PathWalkerState )\n\n NOTE: _____________________________________________________________________\n\n Inheritance:\n\n FSM_State <----- MegaState <------- PathWalkerState\n\n A MegaState contains the '.implemented_state_index_set' which tells about\n what states have actually been implemented by the PathWalkerState.\n \"\"\"\n assert CompressionType in [E_Compression.PATH, E_Compression.PATH_UNIFORM]\n assert isinstance(AvailableStateIndexSet, set)\n\n # (*) Find all single character transitions (paths) inside TheAnalyzer's \n # state machine.\n path_list = find.do(TheAnalyzer, CompressionType, AvailableStateIndexSet)\n\n # (*) Select paths, so that a maximum of states is implemented by path walkers.\n path_list = select(path_list)\n path_list_assert_consistency(path_list, TheAnalyzer, AvailableStateIndexSet, CompressionType)\n\n # (*) Group paths\n # \n # Different paths may have the same common transition map. If this is\n # the case, they can be implemented by the same PathWalkerState.\n return group(path_list, TheAnalyzer, CompressionType)\n\ndef select(path_list):\n \"\"\"The CharacterPath-s which have been found may intersect. However, a \n state can only appear in one distinct path. If a set of paths intersect\n the longest of them is chosen. \n\n RETURNS: list( CharacterPath ) \n\n where the 'best' possible configuration of character paths is chosen.\n \"\"\"\n class BelongDB(dict):\n \"\"\"belong_db: \n \n state_index --> paths of which state_index is part. \n \"\"\"\n def __init__(self, PathList):\n self.path_list = [path for path in PathList] # clone.\n\n for i, path in enumerate(self.path_list):\n for state_index in path.implemented_state_index_set():\n entry = self.get(state_index)\n if entry is not None: entry.add(i)\n else: self[state_index] = set([i])\n return\n\n def iterpaths(self):\n for i, path in enumerate(self.path_list):\n yield i, path\n\n def compute_value(self, path_i):\n \"\"\"What happens if 'path' is chosen?\n\n -- Gain: Multiple states are implemented by a single PathWalkerState.\n \n gain = len(implemented states by path)\n\n -- Cost: If one of the states of the path intersects with another\n path, then the other path cannot be implemented.\n\n cost = number of states present in intersecting paths if those\n states have no other paths which implements them.\n ___________________________________________________________________\n RETURNS: \n \n (gain - cost, extra_key, extra_key)\n\n where 'gain - cost' gives the value of the path. The other two\n extra keys do not relate to the value. They identify the path\n itself and are provided as a means to make the selection process\n deterministic.\n \"\"\"\n # -- The states implemented by path\n path = self.path_list[path_i]\n implemented_set = path.implemented_state_index_set()\n\n # -- Forbidden are those paths which have a state in common with 'path'\n # -- Those states implemented in forbidden paths become endangered.\n # I.e. they might not to be implemented by a PathWalkerState.\n lost_path_list = []\n remaining_path_list = []\n remaining_implementation_set = set()\n for other_path_i, other_path in self.iterpaths():\n if path_i == other_path_i: continue\n\n # Terminal may be present in another path (exclude it from consideration)\n if implemented_set.isdisjoint(other_path.implemented_state_index_set()):\n remaining_path_list.append(other_path)\n remaining_implementation_set.update(path.implemented_state_index_set())\n else:\n lost_path_list.append(other_path)\n\n lost_implementation_set = set()\n for lost_path in lost_path_list:\n # A state of a lost path is not implemented by path walking, if\n # it is not implemented by the 'path' itself or by one of the \n # non-intersecting paths of 'path'.\n lost_implementation_set.update(\n lost_path.implemented_state_index_set() \\\n - implemented_set \\\n - remaining_implementation_set \\\n )\n\n cost = - len(lost_implementation_set)\n gain = len(implemented_set)\n\n # EXTRA COMPARISON KEYS, so that sorting becomes DETERMINISTIC in \n # in case that two paths provide the SAME GAIN. Clearly, these keys\n # are no functional necessity.\n #\n # -- The 'negative' triggers, so that lower triggers sort higher.\n extra_key_0 = tuple(- x.trigger for x in path.step_list[:-1])\n # -- The number of the first state on the path.\n extra_key_1 = - path.step_list[0].state_index\n return (gain - cost, extra_key_0, extra_key_1)\n\n def get_best_path(AvailablePathList):\n \"\"\"The best path is the path that brings the most gain. The 'gain'\n of a path is a function of the number of states it implements minus\n the states that may not be implemented because other intersecting\n paths cannot be chosen anymore.\n\n RETURN: [0] winning path\n [1] list of indices of paths which would be no longer \n available, because the winning path intersects.\n \"\"\"\n belong_db = BelongDB(AvailablePathList)\n\n max_value = None\n max_length = None\n winner_i = None\n for i, path in belong_db.iterpaths():\n # INPORTANT: Consider 'length == length' so that other criteria\n # can trigger which support deterministic solutions.\n if max_value is not None and len(path.step_list) < max_length: \n continue # No chance\n\n value = belong_db.compute_value(i)\n\n if max_value is None or max_value < value:\n max_value = value\n winner_i = i\n max_length = len(belong_db.path_list[i].step_list)\n\n return winner_i\n\n\n result = []\n work_list = copy(path_list)\n while len(work_list):\n work_list.sort(key=lambda p: - p.state_index_set_size())\n\n elect_i = get_best_path(work_list)\n\n # Copy path from 'work_list' to 'result', \n # BEFORE list content is changed.\n elect = work_list[elect_i]\n del work_list[elect_i]\n result.append(elect)\n\n dropped_list = []\n implemented_set = elect.implemented_state_index_set()\n for i, path in enumerate(work_list):\n if implemented_set.isdisjoint(path.implemented_state_index_set()): continue\n dropped_list.append(i)\n\n # Delete all paths which are impossible, if 'elect_i' is chosen.\n # Reverse sort of list indices (greater first) \n # => simply 'del work_list[i]' \n for i in sorted(dropped_list, reverse=True):\n del work_list[i]\n\n # None of the remaining paths shall have states in common with the elect.\n for path in work_list:\n assert elect.implemented_state_index_set().isdisjoint(path.implemented_state_index_set())\n\n return result\n\ndef group(CharacterPathList, TheAnalyzer, CompressionType):\n \"\"\"Different character paths may be walked down by the same path walker.\n This function groups the given list of CharacterPath-s and assigns them to\n PathWalkerState-s. \n \"\"\"\n path_walker_list = []\n # (*) Collect path walkers into groups of similar ones\n for path in CharacterPathList:\n for path_walker in path_walker_list:\n # Set-up the walk in an existing PathWalkerState\n if path_walker.accept(path, TheAnalyzer, CompressionType): \n break\n else:\n # Create a new PathWalkerState\n path_walker = PathWalkerState(path, TheAnalyzer)\n path_walker_list.append(path_walker)\n\n return path_walker_list\n\ndef path_list_assert_consistency(path_list, TheAnalyzer, AvailableStateIndexList, CompressionType):\n # None of the paths shall contain a state which is not available for compression.\n # No state shall be implemented by more than one path.\n remainder = set(AvailableStateIndexList)\n for path in path_list:\n assert path.implemented_state_index_set().issubset(remainder)\n remainder.difference_update(path.implemented_state_index_set())\n\n # A state shall not be implemented on two paths. It was the task of \n # 'select()' to make an optimal choice.\n appeared_state_index_set = set()\n for path in path_list:\n delta = len(path.step_list) - 1\n size_before = len(appeared_state_index_set)\n appeared_state_index_set.update(path.implemented_state_index_set())\n size_after = len(appeared_state_index_set)\n assert size_after - size_before == delta\n\n # Each path must be consistent in itself\n for path in path_list:\n path.assert_consistency(TheAnalyzer, CompressionType)\n","sub_path":"quex/engine/analyzer/mega_state/path_walker/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":15147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"366259393","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#Author: Mathias Hauser\n#Date: \n# ds = xray.Dataset(coords={'longitude': np.arange(-125, -65, 0.5),\n# 'latitude': np.arange(50, 25, -0.5)})\n\n\nimport copy\nimport numpy as np\nimport six\n\nfrom shapely.geometry import Polygon, MultiPolygon\n\n\nfrom .mask import _mask\nfrom .plot import _plot\n\n\nclass Regions_cls(object):\n \"\"\"\n class for plotting regions and creating region masks\n\n Attributes\n ----------\n name : string\n Name of the collection of regions.\n numbers : list of int\n List of numerical indces for every region.\n names : list of string\n Long name of each region.\n abbrevs : list of string\n List of abbreviations of each region.\n outlines : List of Nx2 float array of vertices, Polygon, MultiPolygon\n List of coordinates/ outline of the region as shapely \n Polygon/ MultiPolygon or list. Must be accessible as \n outlines[number].\n centroids : list of 1x2 array.\n Center of mass of this region.\n \"\"\"\n\n def __init__(self, name, numbers, names, abbrevs, outlines, centroids=None, \n source=''):\n\n \"\"\"\n Parameters\n ----------\n name : string\n Name of the collection of regions.\n numbers : list of int\n List of numerical indces for every region.\n names : dict of string\n Long name of each region. Must be accessible as names[number].\n abbrevs : dict of string\n List of abbreviations of each region. Must be accessible as \n abbrevs[number].\n outlines : List of Nx2 float array of vertices, Polygon, MultiPolygon\n List of coordinates/ outline of the region as shapely \n Polygon/ MultiPolygon or list. Must be accessible as \n outlines[number].\n centroids : list of 1x2 iterable, optional.\n Center of mass of this region. If not provided is calculated\n as (Multi)Polygon.centroid\n source : string, optional\n Source of the region definitions. Default: ''.\n\n Example\n -------\n name = 'Example'\n numbers = [0, 1]\n names = ['Unit Square1', 'Unit Square2']\n abbrevs = ['uSq1', 'uSq2']\n\n outl1 = ((0, 0), (0, 1), (1, 1.), (1, 0))\n outl2 = ((0, 1), (0, 2), (1, 2.), (1, 1))\n outlines = [outl1, outl2]\n \n r = Regions_cls(name, numbers, names, abbrevs, outlines)\n \n from shapely.geometry import Polygon\n \n numbers = [1, 2]\n names = {1:'Unit Square1', 2: 'Unit Square2'}\n abbrevs = {1:'uSq1', 2:'uSq2'}\n poly = {1: Polygon(outl1), 2: Polygon(outl2)}\n\n r = Regions_cls(name, numbers, names, abbrevs, poly) \n \"\"\"\n\n super(Regions_cls, self).__init__()\n \n regions = dict()\n region_ids = dict() \n\n if centroids is None:\n centroids = {i : None for i in numbers}\n\n for n in numbers:\n r = Region_cls(n, names[n], abbrevs[n], outlines[n], centroids[n])\n \n regions[n] = r\n\n self.regions = regions \n self.name = name\n self.source = source\n\n def __getitem__(self, key):\n \"\"\"\n subset of Regions or Region\n\n Parameters\n ----------\n key : (list of) int or string\n Key can be a mixed (list of) number, abbrev or name of the \n defined regions. If a list is given returns a subset of all \n regions, if a single element is given returns this region.\n\n Returns\n -------\n selection : Regions_cls or Region_cls\n If a list is given returns a subset of all \n regions, if a single element is given returns this region.\n\n \"\"\"\n \n key = self.map_keys(key)\n if isinstance(key, (int, np.integer)):\n return self.regions[key]\n else:\n # subsample the regions\n regions = {k : self.regions[k] for k in key}\n new_self = copy.copy(self) # shallow copy\n new_self.regions = regions\n return new_self\n\n def __len__(self):\n return len(self.numbers)\n\n def map_keys(self, key):\n \"\"\"\n map from names and abbrevs of the regions to numbers\n\n Parameters\n ----------\n key : (list of) string\n key can be a single or a list of abbreviation/ name of \n existing regions.\n\n Returns\n -------\n mapped_key : int or list of int\n\n Raises a KeyError if the key does not exist.\n\n \"\"\"\n\n # a single key\n if isinstance(key, (int, np.integer, six.string_types)):\n key = self.region_ids[key]\n # a list of keys\n else:\n key = [self.region_ids[k] for k in key]\n # make sure they are unique\n key = np.unique(key).tolist()\n\n return key\n\n def __repr__(self):\n abbrevs = \" \".join(self.abbrevs)\n msg = \"{} '{}' Regions ({})\\n{}\"\n msg = msg.format(len(self.numbers), self.name, self.source, \n abbrevs)\n return msg\n\n\n self.name\n\n def __iter__(self):\n for i in self.numbers:\n yield self[i]\n\n def combiner(self, prop):\n return [getattr(r, prop) for r in self.regions.values()]\n\n @property\n def region_ids(self):\n \"\"\"dict mapping all names and abbrevs to the region number\"\"\"\n\n # collect data\n abbrevs = self.abbrevs\n names = self.names\n numbers = self.numbers\n # combine data and make a mapping\n all_comb = zip(numbers + abbrevs + names, (numbers * 3))\n region_ids = {key : value for key, value in all_comb}\n return region_ids\n \n @property\n def abbrevs(self):\n \"\"\"list of abbreviations\"\"\"\n return self.combiner('abbrev')\n\n @property\n def names(self):\n \"\"\"list of long names\"\"\"\n return self.combiner('name')\n\n @property\n def numbers(self):\n \"\"\"list of the numbers of the regions\"\"\"\n return self.combiner('number')\n \n @property\n def coords(self):\n \"\"\"list of coordinates of the region vertices as numpy array\"\"\"\n return self.combiner('coords')\n\n @property\n def polygons(self):\n \"\"\"list of shapely Polygon/ MultiPolygon of the regions\"\"\"\n return self.combiner('polygon')\n\n @property\n def centroids(self):\n \"\"\"list of the center of mass of the regions\"\"\"\n return self.combiner('centroid')\n\n @property\n def _is_polygon(self):\n \"\"\"is there at least one region that was a Polygon/ MultiPolygon\n\n .\"\"\"\n return np.any(np.array(self.combiner('_is_polygon')))\n\n\n# add the plotting method\nRegions_cls.plot = _plot\n# add the mask method\nRegions_cls.mask = _mask\n\n# =============================================================================\n\nclass Region_cls(object):\n \"\"\"a single Region, used as member of 'Regions_cls'\n\n\n Attributes\n ----------\n number : int\n Number of this region.\n name : string\n Long name of this region.\n abbrev : string\n Abbreviation of this region.\n polygon : Polygon or MultiPolygon\n Coordinates/ outline of the region as shapely Polygon/\n MultiPolygon.\n coords : numpy array\n Coordinates/ outline of the region as 2D numpy array.\n centroid : 1x2 ndarray\n Center of mass of this region.\n\n \"\"\"\n def __init__(self, number, name, abbrev, outline, centroid=None):\n \"\"\"\n\n Parameters\n ----------\n number : int\n Number of this region.\n name : string\n Long name of this region.\n abbrev : string\n Abbreviation of this region.\n outline : Nx2 float array of vertices, Polygon or MultiPolygon\n Coordinates/ outline of the region as shapely Polygon/\n MultiPolygon or list.\n centroid : 1x2 iterable, optional.\n Center of mass of this region. If not provided is calculated\n by as (Multi)Polygon.centroid\n\n Example\n -------\n outl = ((0, 0), (0, 1), (1, 1.), (1, 0))\n r = Region_cls(1, 'Unit Square', 'USq', outl)\n \n from shapely.geometry import Polygon\n \n poly = Polygon(outl)\n r = Region_cls(1, 'Unit Square', 'USq', outl, [0.5, 0.75])\n \"\"\"\n\n\n super(Region_cls, self).__init__()\n \n self.number = number\n self.name = name\n self.abbrev = abbrev\n\n self._is_polygon = isinstance(outline, (Polygon, MultiPolygon))\n\n if self._is_polygon:\n self._polygon = outline\n self._coords = None\n else:\n self._polygon = None\n self._coords = np.array(outline)\n\n assert self.coords.ndim == 2\n assert self.coords.shape[1] == 2\n \n # the Polygon Centroid is much stabler\n if centroid is None:\n centroid = np.array(self.polygon.centroid.coords)[0]\n \n self.centroid = centroid\n\n\n def __repr__(self):\n msg = \"Region: {} ({} / {})\\ncenter: {}\"\n return msg.format(self.name, self.abbrev, self. number, self.centroid)\n \n @property\n def polygon(self):\n \"\"\"shapely Polygon or MultiPolygon of the region\"\"\"\n\n if self._polygon is None:\n self._polygon = Polygon(self.coords)\n return self._polygon\n\n @property\n def coords(self):\n \"\"\"numpy array of the region\"\"\"\n\n if self._coords is None:\n\n # make an array of polygons\n if isinstance(self._polygon, Polygon):\n polys = [self._polygon]\n else:\n polys = list(self._polygon)\n \n # separate the single polygons with NaNs\n nan = np.ones(shape=(1, 2)) * np.nan\n l = list()\n for poly in polys:\n l.append(np.vstack((np.array(poly.exterior.coords), nan)))\n\n # remove the very last NaN\n self._coords = np.vstack(l)[:-1, :]\n \n return self._coords","sub_path":"regionmask/core/regions.py","file_name":"regions.py","file_ext":"py","file_size_in_byte":10210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"549499552","text":"import os\nfrom random import randint\nfrom string import ascii_letters\nfrom abc import ABCMeta\nfrom functools import partial\n\nfrom ._exceptions import DeleteError, PermissionError, out_of_space\nfrom ._abstract import AbstractVlermv\nfrom ._exceptions import OpenError\n\ndef _rmdirs(base, leaf):\n for fn in _reversed_directories(base, leaf):\n if os.listdir(fn) == []:\n os.rmdir(fn)\n else:\n break\n\ndef _get_fn(fn, mode, load):\n '''\n Load a contents, checking that the file was not modified during the read.\n '''\n try:\n mtime_before = os.path.getmtime(fn)\n except OSError:\n mtime_before = None\n\n try:\n with open(fn, mode) as fp:\n item = load(fp)\n except OpenError:\n raise\n else:\n mtime_after = os.path.getmtime(fn)\n if mtime_before in {None, mtime_after}:\n return item\n else:\n raise EnvironmentError('File was edited during read: %s' % fn)\n\n\ndef _random_file_name():\n n = len(ascii_letters) - 1\n return ''.join(ascii_letters[randint(0, n)] for _ in range(10))\n\ndef _mkdirp(x):\n try:\n os.makedirs(x, exist_ok=True)\n except TypeError:\n # Python 2\n if not os.path.isdir(x):\n os.makedirs(x)\n\ndef _mktemp(tempdir, filename=_random_file_name):\n _mkdirp(tempdir)\n return os.path.join(tempdir, filename())\n\ndef _reversed_directories(outer, inner):\n while outer != inner:\n yield inner\n inner = os.path.dirname(inner)\n\nclass Vlermv(AbstractVlermv):\n '''\n A :py:class:`dict` API to a filesystem\n '''\n class LinkWrapper(metaclass=ABCMeta):\n '''\n This is a Wrapper for hard and symbolic links. Assign a key to an instance of\n Symlink to create a symlink from the key to the file referenced by the SymLink.\n\n :param key: Vlermv key to link to\n :returns: Object to be assigned as the value of different key in the\n same Vlermv\n '''\n def __init__(self, key):\n self.key = key\n class Link(LinkWrapper):\n func = os.link\n class Symlink(LinkWrapper):\n func = os.symlink\n\n def __init__(self, *directory, indexfile='.index', tempdir='.tmp', **kwargs):\n '''\n :param str directory: Top-level directory of the vlermv\n :param serializer: A thing with dump and load functions for\n serializing and deserializing Python objects,\n like :py:mod:`json`, :py:mod:`yaml`, or\n anything in :py:mod:`vlermv.serializers`\n :type serializer: :py:mod:`serializer `\n :param transformer: A thing with to_path and from_path functions\n for transforming keys to file paths and back.\n Several are available in :py:mod:`vlermvtransformers`.\n :type transformer: :py:mod:`transformer `\n :param bool mutable: Whether values can be updated and deleted\n :param str tempdir: Subdirectory inside of base_directory to use for temporary files\n :param str indexfile: Unless this value is None, vlermv will allow you\n to to access your filesystem as if a file at any particular path can\n both reference files (like a directory) and contain data (like a\n regular file). When a file needs to be both a directory and a\n regular file, vlermv will create the directory and save the file\n contents in a file with this name (default is \".index\") as a child\n of the directory.\n\n These are mostly relevant for initialization via :py:func:`Vlermv.memoize`.\n\n :param bool appendable: Whether new values can be added to the Vlermv\n (Set this to False to ensure that the decorated function is never\n run and that the all results are cached; this is useful for reviewing\n old data in a read-only mode.)\n :param bool cache_exceptions: If the decorated function raises\n an exception, should the failure and exception be cached?\n The exception is raised either way.\n :raises TypeError: If cache_exceptions is True but the serializer\n can't cache exceptions\n '''\n\n # For copying\n self._args = directory\n self._kwargs = dict(kwargs)\n self._kwargs['indexfile'] = indexfile\n self._kwargs['tempdir'] = tempdir\n\n super(Vlermv, self).__init__(**kwargs)\n if not directory:\n raise TypeError('Specify a directory for a vlermv.')\n self.base_directory = _base_directory(*directory)\n self.tempdir = tempdir\n self.indexfile = indexfile\n\n @property\n def allow_empty(self):\n return self.indexfile not in {'', None}\n\n def __repr__(self):\n return '%s(%s)' % (self.__class__.__name__, repr(self.base_directory))\n\n def filename(self, key):\n self._check_path(key)\n return super(Vlermv, self).filename(key)\n\n def from_filename(self, filename):\n try:\n key = super(Vlermv, self).from_filename(filename)\n self._check_path(key)\n except KeyError:\n pass\n else:\n return key\n\n def _check_path(self, key):\n path = self.transformer.to_path(key)\n if self.tempdir in path:\n raise KeyError('Reserved for temporary files: %s' % repr(key))\n elif self.indexfile in path:\n raise KeyError('Reserved for index files: %s' % repr(key))\n return path\n \n def _make_index(self, fn):\n this = fn\n while True:\n init, last = os.path.split(this)\n if init == self.base_directory:\n break\n elif os.path.isfile(this):\n fn = os.path.join(this, self.indexfile)\n\n tmp = _mktemp(os.path.join(init, self.tempdir))\n os.rename(this, tmp)\n _mkdirp(this)\n os.rename(tmp, fn)\n return fn\n else:\n this = init\n\n def __setitem__(self, index, obj):\n super(Vlermv, self).__setitem__(index, obj)\n fn = self.filename(index)\n if os.path.isdir(fn):\n self._make_index(fn)\n fn = os.path.join(fn, self.indexfile)\n exists = os.path.exists(fn)\n\n if (not self.mutable) and exists:\n raise PermissionError('This vlermv is immutable, and %s already exists.' % fn)\n elif (not self.appendable) and (not exists):\n raise PermissionError('This vlermv not appendable, and %s does not exist.' % fn)\n elif isinstance(obj, self.LinkWrapper):\n src = self.filename(obj.key)\n dst = self.filename(index)\n os.makedirs(os.path.dirname(dst), exist_ok = True)\n obj.func(src, dst)\n else:\n self._make_index(fn)\n try:\n tmp = _mktemp(os.path.join(os.path.dirname(fn), self.tempdir))\n except NotADirectoryError:\n raise NotImplementedError('The path probably includes an ancestor file that needs to be converted to a directory with indexfile. This conversion is not yet performed automatically.')\n with open(tmp, 'w+' + self._b()) as fp:\n try:\n self.serializer.dump(obj, fp)\n except Exception as e:\n if out_of_space(e):\n fp.close()\n os.remove(tmp)\n raise BufferError('Out of space')\n else:\n raise\n os.rename(tmp, fn)\n\n def __getitem__(self, index):\n fn = self.filename(index)\n if os.path.isdir(fn):\n fn = os.path.join(fn, self.indexfile)\n\n try:\n return _get_fn(fn, 'r+' + self._b(), self.serializer.load)\n except OpenError:\n raise KeyError(index)\n\n def __delitem__(self, index):\n super(Vlermv, self).__delitem__(index)\n fn = self.filename(index)\n try:\n os.remove(fn)\n except DeleteError as e:\n raise KeyError(*e.args)\n else:\n _rmdirs(self.base_directory, os.path.dirname(fn))\n\n def __len__(self):\n length = 0\n for dirpath, _, filenames in os.walk(self.base_directory):\n for filename in filenames:\n length += 1\n return length\n\n def keys(self):\n for filename in self.files():\n key = self.from_filename(filename)\n if key != None:\n yield key\n\n def ignored(self):\n for filename in self.files():\n if self.from_filename(filename) == None:\n yield filename\n\n def files(self):\n xs = os.walk(self.base_directory, topdown=True, followlinks=True)\n for dirpath, dirnames, filenames in xs:\n if os.path.basename(dirpath) in {self.tempdir, self.indexfile}:\n dirnames[:] = []\n else:\n for filename in filenames:\n if filename == self.indexfile:\n path = dirpath\n else:\n path = os.path.join(dirpath, filename)\n yield path\n\n def rename(self, old, new):\n '''\n Rename a key/file atomically with :py:func:`os.rename`.\n\n :param old: Old key\n :param new: New key\n '''\n oldfn, newfn = self.filename(old), self.filename(new)\n if os.path.isdir(newfn):\n newfn = os.path.join(newfn, self.indexfile)\n _mkdirp(os.path.dirname(newfn))\n os.rename(oldfn, newfn)\n _rmdirs(self.base_directory, os.path.dirname(newfn))\n\ndef _base_directory(*directory):\n return os.path.expanduser(os.path.join(*directory))\n","sub_path":"env/lib/python3.9/site-packages/vlermv/_fs.py","file_name":"_fs.py","file_ext":"py","file_size_in_byte":9781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"128232670","text":"#!/usr/bin/python\n# -*- encoding: utf-8 -*-\n\nimport csv\nimport optparse\nimport psycopg2\nimport sys\n\nparser = optparse.OptionParser(usage=\"%prog [options] dataset csv division region-column value-column\")\nparser.add_option(\"\", \"--db-host\",\n action=\"store\",\n default=\"localhost\",\n help=\"database hostname (default %default)\")\nparser.add_option(\"\", \"--db-name\",\n action=\"store\",\n help=\"database name\")\nparser.add_option(\"\", \"--db-user\",\n action=\"store\",\n help=\"database username\")\n\nparser.add_option(\"\", \"--print-loaded-rows-to\",\n help=\"print loaded rows to this file\")\n\n(options, args) = parser.parse_args()\nif len(args) != 5:\n parser.error(\"Wrong number of arguments\")\ndataset_name, csv_filename, division_name, region_col, value_col = args\n\ndb_connection_data = []\nif options.db_host:\n db_connection_data.append(\"host=\" + options.db_host)\nif options.db_name:\n db_connection_data.append(\" dbname=\" + options.db_name)\nif options.db_user:\n db_connection_data.append(\" user=\" + options.db_user)\ndb = psycopg2.connect(\" \".join(db_connection_data))\n\n\ndef each(filename):\n global current_row, w\n \n f = open(filename, 'r')\n r = csv.reader(f)\n \n if options.print_loaded_rows_to:\n g = open(options.print_loaded_rows_to, 'w')\n w = csv.writer(g)\n else:\n w = None\n \n header = r.next()\n if w: w.writerow(header)\n for row in r:\n current_row = row\n yield dict(zip(header, [x.decode(\"utf-8\") for x in row]))\n \n f.close()\n\nclass Col(str):\n \"\"\"A column name, as opposed to a constant string.\n \"\"\"\ndef as_seq(gen, *cols):\n for d in gen:\n yield tuple((\n d[col] if isinstance(col, Col) else col for col in cols\n ))\n\nc = db.cursor()\nc.execute(\"\"\"\n insert into dataset (name, division_id) (select %s, division.id from division where name = %s)\n\"\"\", (dataset_name, division_name))\nc.close()\n\nc = db.cursor()\nc.execute(\"\"\"\n select currval('dataset_id_seq'::regclass)\n\"\"\")\ndataset_id = c.fetchone()[0]\nc.close()\n\nfor t in as_seq(each(csv_filename), dataset_id, Col(value_col), division_name, Col(region_col)):\n c = db.cursor()\n if not t[1]:\n print >>sys.stderr, \"Skipping '%s', because the value is blank\" % (t[3],)\n continue\n \n try:\n float(t[1])\n except ValueError:\n print >>sys.stderr, \"Skipping '%s', because the value is bad: %s\" % (t[3], t[1])\n continue\n \n try:\n c.execute(\"\"\"\n insert into data_value (\n dataset_id,\n division_id,\n region_id,\n value\n ) (\n select %s, division.id, region.id, GREATEST(0, %s::numeric)\n from region\n join division on region.division_id = division.id\n where division.name = %s and region.name = %s\n )\n \"\"\", t\n )\n if c.rowcount == 0:\n print >>sys.stderr, \"Region '{division_name}/{region_name}' not found in database\".format(division_name=t[2], region_name=t[3])\n elif w:\n w.writerow(current_row)\n finally:\n c.close()\ndb.commit()\n","sub_path":"bin/load-data.py","file_name":"load-data.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"640293353","text":"import unittest\nimport time\nfrom getpass import getpass\nimport logging\nimport foursquare\nimport os\n\nimport urlparse\n\nTEST_OAUTH = False\n\nMY_COORDS = [34.09075, -118.27516]\n\n\nclass TestFoursquare(unittest.TestCase):\n maxDiff = None\n \n def setUp(self):\n self.assertIsNotNone(FOURSQUARE_CONSUMER_KEY)\n self.assertTrue(len(FOURSQUARE_CONSUMER_KEY)>0)\n\n self.assertIsNotNone(FOURSQUARE_CONSUMER_SECRET)\n self.assertTrue(len(FOURSQUARE_CONSUMER_SECRET)>0)\n\n self.assertIsNotNone(FOURSQUARE_OAUTH_CALLBACK)\n self.assertTrue(len(FOURSQUARE_OAUTH_CALLBACK)>0)\n\n global FOURSQUARE_ACCESS_TOKEN\n if not FOURSQUARE_ACCESS_TOKEN:\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET,\n callback_uri=FOURSQUARE_OAUTH_CALLBACK)\n auth_url = fs.authenticate(response_type='token')\n access_token = raw_input('\\nPlease go the following URL and authorize your app:\\n\\n%s\\n\\nEnter the access_token in the url it redirects you to and press enter: ' % (auth_url,))\n FOURSQUARE_ACCESS_TOKEN = access_token\n\n self.assertIsNotNone(FOURSQUARE_ACCESS_TOKEN)\n self.assertTrue(len(FOURSQUARE_ACCESS_TOKEN)>0)\n\n\n def test_unauthenticated(self):\n \"Testing unauthenticated methods.\"\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n\n venues = fs.venues_search(str(MY_COORDS[0])+','+str(MY_COORDS[1]))\n self.failUnless('venues' in venues['response'])\n local_cafe = find_if(venues['response']['venues'], lambda o: o['id'] == '49d7d4b2f964a5206a5d1fe3')\n self.failUnless(local_cafe)\n\n self.assertRaises(foursquare.FoursquareException, lambda: fs.users_friends(id='self'))\n \n def test_oauth_authenticate_url(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET,\n callback_uri=FOURSQUARE_OAUTH_CALLBACK)\n #test token\n auth_url = fs.authenticate()\n parse_result = urlparse.urlparse(auth_url)\n self.assertEqual('foursquare.com', parse_result.netloc)\n self.assertEqual('https', parse_result.scheme)\n self.assertEqual('/oauth2/authenticate', parse_result.path)\n qs_parse_result = urlparse.parse_qs(parse_result.query)\n self.assertEqual(\n {'client_secret':[FOURSQUARE_CONSUMER_SECRET],'client_id':[FOURSQUARE_CONSUMER_KEY],\n 'redirect_uri':[FOURSQUARE_OAUTH_CALLBACK], 'v':['20110808'], 'response_type':['token']},\n qs_parse_result)\n\n #test code, overriding default args\n auth_url = fs.authenticate(redirect_uri=FOURSQUARE_OAUTH_CALLBACK, response_type='code')\n parse_result = urlparse.urlparse(auth_url)\n self.assertEqual('foursquare.com', parse_result.netloc)\n self.assertEqual('https', parse_result.scheme)\n self.assertEqual('/oauth2/authenticate', parse_result.path)\n qs_parse_result = urlparse.parse_qs(parse_result.query)\n self.assertEqual(\n {'client_secret':[FOURSQUARE_CONSUMER_SECRET],'client_id':[FOURSQUARE_CONSUMER_KEY],\n 'redirect_uri':[FOURSQUARE_OAUTH_CALLBACK], 'v':['20110808'], 'response_type':['code']},\n qs_parse_result)\n\n def test_oauth_code(self):\n if not TEST_OAUTH:\n return\n\n # Authorization dance.\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET,\n callback_uri=FOURSQUARE_OAUTH_CALLBACK)\n auth_url = fs.authenticate(response_type='code')\n if not FOURSQUARE_AUTH_CODE:\n FOURSQUARE_AUTH_CODE = os.environ.get('FOURSQUARE_AUTH_CODE')\n if not FOURSQUARE_AUTH_CODE:\n FOURSQUARE_AUTH_CODE = raw_input('\\nPlease go the following URL and authorize your app:\\n\\n%s\\n\\nEnter the code in the querystring it redirects you to and press enter: ' % (auth_url,))\n \n access_token = fs.access_token(FOURSQUARE_AUTH_CODE)\n fs.set_access_token(access_token)\n\n # Now we can test some methods.\n user = fs.users_requests()\n self.failUnless('user' in user['response'])\n\n def test_oauth_token(self):\n if not TEST_OAUTH:\n return\n\n # Authorization dance.\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET,\n callback_uri=FOURSQUARE_OAUTH_CALLBACK)\n auth_url = fs.authenticate(response_type='token')\n access_token = raw_input('\\nPlease go the following URL and authorize your app:\\n\\n%s\\n\\nEnter the access_token in the url it redirects you to and press enter: ' % (auth_url,))\n fs.set_access_token(access_token)\n\n # Now we can test some methods.\n user = fs.users(id='self')\n self.failUnless('user' in user['response'])\n\n def test_arg_handling(self):\n \"\"\"Testing handling of API method arguments.\"\"\"\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n # Missing required args.\n self.assertRaises(foursquare.FoursquareException, lambda: fs.venues())\n # Extra args\n self.assertRaises(foursquare.FoursquareException,\n lambda: fs.venues(MY_COORDS[0], MY_COORDS[1],\n unknown_arg='BLUH'))\n #correct required kw args\n venues = fs.venues_search(ll=str(MY_COORDS[0])+','+str(MY_COORDS[1]))\n self.failUnless('venues' in venues['response'])\n self.assertTrue(len(venues['response']['venues']) > 0)\n\n #correct required plus optional kw args\n venues = fs.venues_search(ll=str(MY_COORDS[0])+','+str(MY_COORDS[1]), limit=4)\n self.failUnless('venues' in venues['response'])\n self.assertTrue(len(venues['response']['venues']) == 4)\n\n #correct required args plus optional kw args\n venues = fs.venues_search(str(MY_COORDS[0])+','+str(MY_COORDS[1]), limit=4)\n self.failUnless('venues' in venues['response'])\n self.assertTrue(len(venues['response']['venues']) == 4)\n\n def test_id_parameter(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n checkins=fs.users(id='self')\n self.assertTrue(len(checkins['response']['user']) > 0)\n\n def test_aspect_parameter(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n checkins=fs.users_checkins(id='self')\n self.assertTrue(len(checkins['response']['checkins']) > 0)\n\n def test_aspect(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n checkins=fs.users_venuehistory(id='self')\n self.assertTrue(checkins['response'].get('venues'))\n\n def test_actions(self):\n #TODO: how can we do a post request non-destructively?\n return\n \n def test_friends(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n friends = fs.users_friends(id='self')\n self.assertTrue(len(friends['response']['friends']) >= 0)\n \n def test_venues_categories(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n categories = fs.venues_categories()\n self.assertTrue(len(categories['response']['categories']) >= 0)\n\n def test_checkin_history(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n checkins = fs.users_checkins(id='self')\n self.assertIn('checkins', checkins['response'])\n self.assertIn('items', checkins['response']['checkins'])\n self.assertIn('count', checkins['response']['checkins'])\n self.assertGreaterEqual(len(checkins['response']['checkins']['items']), 0)\n self.assertGreaterEqual(checkins['response']['checkins']['count'],\n len(checkins['response']['checkins']['items']))\n\n def test_checkin_all_history(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n checkins = fs.users_checkins(id='self')\n self.assertIn('checkins', checkins['response'])\n self.assertIn('count', checkins['response']['checkins'])\n checkin_count = checkins['response']['checkins']['count']\n \n checkin_history = foursquare.all_history(fs, batchsize=250)\n\n self.assertEqual(len(checkin_history), checkin_count)\n\n def test_checkin_all_history_after_timestamp(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n checkins = fs.users_checkins(id='self')\n self.assertIn('checkins', checkins['response'])\n self.assertIn('count', checkins['response']['checkins'])\n checkin_count = checkins['response']['checkins']['count']\n\n if checkin_count==0:\n return\n\n afterTimestamp = checkins['response']['checkins']['items'][0]['createdAt']\n \n checkin_history = foursquare.all_history(fs, batchsize=250, afterTimestamp=afterTimestamp)\n\n self.assertEqual(len(checkin_history), 1)\n\n def test_all_friends(self):\n fs = foursquare.Foursquare(consumer_key=FOURSQUARE_CONSUMER_KEY,\n consumer_secret=FOURSQUARE_CONSUMER_SECRET)\n fs.set_access_token(FOURSQUARE_ACCESS_TOKEN)\n friends = fs.users_friends(id='self')\n self.assertIn('friends', friends['response'])\n self.assertIn('count', friends['response']['friends'])\n friend_count = friends['response']['friends']['count']\n\n all_friends = foursquare.all_friends(fs)\n\n self.assertEqual(len(all_friends), friend_count)\n\ndef find_if(objs, pred):\n for o in objs:\n if pred(o):\n return o\n return None\n\n\nFOURSQUARE_CONSUMER_KEY=os.environ.get('FOURSQUARE_CONSUMER_KEY')\nFOURSQUARE_CONSUMER_SECRET=os.environ.get('FOURSQUARE_CONSUMER_SECRET')\nFOURSQUARE_OAUTH_CALLBACK=os.environ.get('FOURSQUARE_OAUTH_CALLBACK')\nFOURSQUARE_AUTH_CODE=os.environ.get('FOURSQUARE_AUTH_CODE')\nFOURSQUARE_ACCESS_TOKEN=os.environ.get('FOURSQUARE_ACCESS_TOKEN')\n\nif __name__ == '__main__':\n if not FOURSQUARE_CONSUMER_KEY:\n FOURSQUARE_CONSUMER_KEY = raw_input('Enter your foursquare consumer key: ')\n if not FOURSQUARE_CONSUMER_SECRET:\n FOURSQUARE_CONSUMER_SECRET = raw_input('Enter your foursquare consumer secret: ')\n if not FOURSQUARE_OAUTH_CALLBACK:\n FOURSQUARE_OAUTH_CALLBACK = raw_input('Enter your foursquare oauth callback uri: ')\n \n unittest.main()\n","sub_path":"tests/test_foursquare.py","file_name":"test_foursquare.py","file_ext":"py","file_size_in_byte":11996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"455582477","text":"\"\"\"\nProject: pubsne\nAuthors:\n\tkceades\n\"\"\"\n\n# importing from files I wrote\nimport snmc\nimport tools\nimport snetools\n\n# imports from standard packages\nimport os\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom mfa import FactorAnalysis\nimport pickle\nfrom multiprocessing import Process\nfrom threading import Thread\nimport time\n\n\n\nclass Parameters(snmc.Parameters):\n\t\"\"\"\n\tStoring parameters for the data creation\n\n\tnote: this extends the snmc.Parameters class, so as a base it has all of\n\t\t its parameters (after the call to it's init)\n\t\"\"\"\n\tdef __init__(self):\n\t\t\"\"\" constructor \"\"\"\n\t\t# getting all the fields from snmc.Parameters\n\t\tsnmc.Parameters.__init__(self)\n\t\t# the number of components used in the analysis objects\n\t\tself.num_components = 25\n\t\t# the modes of analysis\n\t\tself.model_modes = ['PCA','emFA']\n\t\t# the types of signals we can look at\n\t\tself.signal_modes = ['flux','filter_flux','dust_flux'\\\n\t\t\t,'filter_dust_flux','mag','filter_mag','dust_mag','filter_dust_mag']\n\t\t# reduced sources list (to only include factory and public)\n\t\tself.main_sources = ['Factory','Public']\n\t\t# whether or not to reject outliers based on statistical significance\n\t\t# (i.e. x-sigma outliers) when creating an analysis object\n\t\tself.reject_outliers = True\n\t\t# the number of sigma to do a rejection at\n\t\tself.reject_sigma = 4.0\n\t\t# the directory where all the pickled data files will be stored\n\t\tself.base_dir = os.getcwd() + '/pickleddata'\n\t\tif not os.path.isdir(self.base_dir):\n\t\t\tos.makedirs(self.base_dir)\n\n\n\nclass DataGenerator(object):\n\t\"\"\"\n\tClass to generate data to be used in analyses: it generates based on the\n\tsignal type you want to give it, the source and the model mode.\n\t\"\"\"\n\tdef __init__(self,snmc_pars=None):\n\t\t\"\"\" Constuctor \"\"\"\n\t\tself.pars = Parameters()\n\t\tself.snset = None\n\t\tself.snset_generator = None\n\t\tself.a_dict = None\n\t\tself.coeff_dict = None\n\t\tself.snmc_pars = None\n\t\tif snmc_pars:\n\t\t\tself.snmc_pars = snmc_pars\n\n\tdef run_everything(self,print_progress=True):\n\t\t\"\"\"\n\t\tGoes through all possible source types and creates the various pickled\n\t\tdictionaries from them to store for future use.\n\n\t\t:print_progress: (bool) (optional) whether to print progress through the\n\t\t\t\t\t\t\tfor loop\n\t\t\"\"\"\n\t\tfor source in self.pars.sources:\n\t\t\tif print_progress:\n\t\t\t\tprint(source)\n\t\t\tself.run_everything_individual(source)\n\n\tdef run_everything_individual(self,source):\n\t\t\"\"\"\n\t\tCreates the pickled dictionaries with supernovae and analysis objects\n\t\tfor use later.\n\n\t\t:source: (str) choose from snmc.Parameters.sources\n\t\t\"\"\"\n\t\tself.create_novas(source)\n\t\tself.create_phase_novas(source)\n\t\tself.run_full_analysis(source,'dust_flux')\n\t\t# self.run_full_analysis(source,'filter_dust_flux')\n\n\tdef create_phase_novas(self,source_type='Public'):\n\t\t\"\"\"\n\t\tcreates a pickled file of supernovas by phase\n\t\t\n\t\t:source_type: (str) choose from snmc.Parameters.sources\n\t\t\"\"\"\n\t\tif self.snset_generator!=source_type:\n\t\t\tself.snset = snmc.SnSet(source_type,True,True,self.snmc_pars)\n\t\t\tself.snset_generator = source_type\n\t\tfilename = os.path.join(self.pars.base_dir,source_type+'_Novas_Phase.p')\n\t\tsavefile = open(filename,'wb')\n\t\tpickle.dump(self.snset.phase_novas,savefile)\n\t\tsavefile.close()\n\n\tdef create_novas(self,source_type='Public'):\n\t\t\"\"\"\n\t\tcreates a pickled nova file with all the supernova objects\n\n\t\t:source_type: (str) choose from snmc.Parameters.sources\n\t\t\"\"\"\n\t\tif self.snset_generator!=source_type:\n\t\t\tself.snset = snmc.SnSet(source_type,True,True,self.snmc_pars)\n\t\t\tself.snset_generator = source_type\n\t\tfilename = os.path.join(self.pars.base_dir,source_type+'_Novas.p')\n\t\tsavefile = open(filename,'wb')\n\t\tpickle.dump(self.snset.data,savefile)\n\t\tsavefile.close()\n\n\tdef run_full_analysis(self,source_type='Public',signal_mode='dust_flux'):\n\t\t\"\"\"\n\t\tcreates a pickled dictionary of analysis objects\n\n\t\t:source_type: (str) choose from snmc.Parameters.sources\n\t\t:signal_mode: (str) choose from Parameters.signal_modes\n\t\t\"\"\"\n\t\tif self.snset_generator!=source_type:\n\t\t\tself.create_phase_novas(source_type)\n\n\t\tself.a_dict = {mode:{phase:None for phase \\\n\t\t\tin self.pars.phases} for mode in self.pars.model_modes}\n\t\tself.coeff_dict = {mode:{phase:None for phase \\\n\t\t\tin self.pars.phases} for mode in self.pars.model_modes}\n\n\t\tfor mode in self.pars.model_modes:\n\t\t\tfor phase in self.pars.phases:\n\t\t\t\tself.single_run(mode,self.pars.num_components,phase,signal_mode)\n\t\t\n\t\tfilename = ''\n\t\tif signal_mode[:6]=='filter':\n\t\t\tfilename = os.path.join(self.pars.base_dir,source_type\\\n\t\t\t\t+'_Objects_Filter.p')\n\t\telse:\n\t\t\tfilename = os.path.join(self.pars.base_dir,source_type+'_Objects.p')\n\t\tsavefile = open(filename,'wb')\n\t\tpickle.dump(self.a_dict,savefile)\n\t\tsavefile.close()\n\n\t\tcoeffname = ''\n\t\tif signal_mode[:6]=='filter':\n\t\t\tcoeffname = os.path.join(self.pars.base_dir,source_type\\\n\t\t\t\t+'_Coeffs_Filter.p')\n\t\telse:\n\t\t\tcoeffname = os.path.join(self.pars.base_dir,source_type+'_Coeffs.p')\n\t\tcoefffile = open(coeffname,'wb')\n\t\tpickle.dump(self.coeff_dict,coefffile)\n\t\tcoefffile.close()\n\n\tdef single_run(self,mode='emFA',num=25,phase=0,signal_mode='dust_flux'):\n\t\t\"\"\"\n\t\tCreates the analysis object to populate self.a_dict.\n\n\t\t:mode: (str) choose from Parameters.model_modes\n\t\t:num: (int) usually called with Parameters.num_components as the input\n\t\t:phase: (int) choose from snmc.Parameters.phases\n\t\t:signal_mode: (str) choose from Parameters.signal_modes\n\t\t\"\"\"\n\t\tspectra = self.snset.phase_novas[phase]\n\t\tsigma = self.pars.reject_sigma\n\t\tif self.pars.reject_outliers is False:\n\t\t\tsigma = 1000\n\t\ta_object,coeffs = snetools.create_model(spectra,signal_mode,mode\\\n\t\t\t,num,sigma)\n\t\tself.a_dict[mode][phase] = a_object\n\t\tself.coeff_dict[mode][phase] = coeffs\n\n\n\ndef source_create_everything(source):\n\t\"\"\"\n\tCreates a DataGenerator object for the specified source and runs through\n\tall the data and analysis object creation for that object.\n\n\t:source: (str) choose from Parameters.sources\n\t\"\"\"\n\td = DataGenerator()\n\td.run_everything_individual(source)\n\n\n\ndef processed_run(print_progress=True):\n\t\"\"\"\n\tSpeeds up creating the data for all the sources by doing them individually\n\tin different processes.\n\n\t:print_progress: (bool) (optional) whether or not to print the source while\n\t\t\t\t\t\trunning through it\n\t\"\"\"\n\tpars = Parameters()\n\tprocesses = []\n\tfor source in pars.sources:\n\t\tprocess = Process(target=source_create_everything,args=(source,))\n\t\tprocesses.append(process)\n\t\tprocess.start()\n\t\tif print_progress:\n\t\t\tprint('Process started for {} source'.format(source))\n\tfor process in processes:\n\t\tprocess.join()\n\tif print_progress:\n\t\tprint('All processes finished.')\n\n\n\ndef threaded_run(print_progress=True):\n\t\"\"\"\n\tSpeeds up creating the data for all the sources by doing them individually\n\tin different threads.\n\n\t:print_progress: (bool) (optional) whether or not to print the source while\n\t\t\t\t\t\trunning through it\n\t\"\"\"\n\tpars = Parameters()\n\tthreads = []\n\tfor source in pars.sources:\n\t\tthread = Thread(target=source_create_everything,args=(source,))\n\t\tthreads.append(thread)\n\t\tthread.start()\n\t\tif print_progress:\n\t\t\tprint('Thread started for {} source'.format(source))\n\tfor thread in threads:\n\t\tthread.join()\n\tif print_progress:\n\t\tprint('All threads finished.')\n\n\n#########################################\n# Example of how to run this code\n#########################################\n# if __name__ == '__main__':\n# \t# based on my trials, it looks like processed_run runs significantly faster\n# \t# than threaded_run, and both are faster than creating a DataGenerator\n# \t# object and calling the run_everything method.\n# \tprocessed_run()","sub_path":"creator.py","file_name":"creator.py","file_ext":"py","file_size_in_byte":7519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"412880873","text":"import csv\n\n#JRの駅と路線読み込み\ncsv_file1 = open(\"../Cytoscape Out/JR-tohoku-edge.csv\", \"r\", encoding = \"utf-8\", errors = \"\", newline = \"\")\nfp1 = csv.reader(csv_file1, delimiter = \",\", doublequote = True, lineterminator = \"\\r\\n\", quotechar = '\"', skipinitialspace = True)\nfp2 = open('../frontier/edge/JR-tohoku-frontier-edge.txt', 'w')\nfp3 = open('../frontier/edge/JR-tohoku-frontier-weight.txt', 'w')\nstation_frontier_dict = {}\nexsit_flag = 0\nstation_count = 1\n\n\"\"\"\nfor row in fp1:\n edge = '%d %d\\n' % (int(row[0]),int(row[1]))\n weight = '%f\\n' % (float(row[2]))\n fp2.write(edge)\n fp3.write(weight)\n\"\"\"\n\nfor row in fp1:\n for station_cd in station_frontier_dict:\n if row[0] == station_cd:\n exsit_flag = 1\n break\n if exsit_flag == 0:\n station_frontier_dict[row[0]] = station_count\n station_count += 1\n\n exsit_flag = 0\n\n for station_cd in station_frontier_dict:\n if row[1] == station_cd:\n exsit_flag = 1\n break\n if exsit_flag == 0:\n station_frontier_dict[row[1]] = station_count\n station_count += 1\n\n exsit_flag = 0\n edge = '%d %d\\n' % (station_frontier_dict[row[0]],station_frontier_dict[row[1]])\n weight = '%f\\n' % (float(row[2]))\n fp2.write(edge)\n fp3.write(weight)\n","sub_path":"Code_py/frontier-make-edge.py","file_name":"frontier-make-edge.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"269613826","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = \"orchester\"\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^(?P\\d+)/$', views.DetailView.as_view(), name='detail'),\n url(r'^(?P\\d+)/register/$', views.register, name='register'),\n url(r'^(?P\\d+)/unregister/$', views.unregister, name='unregister'),\n]\n","sub_path":"orchester_cms_integration/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"344902684","text":"import time\nimport scrapy\nimport datetime\nfrom selenium import webdriver\nfrom ..config.web_elements import *\nfrom ..items import NsdlSecurityItem\nfrom dateutil.relativedelta import relativedelta\nfrom selenium.webdriver.support.ui import Select\nfrom ..config.urls import allowed_domains, start_url\nfrom selenium.webdriver.chrome.options import Options\nfrom ..config.selenium_chrome import HEADLESS_OPTIONS, CHROME_DRIVER_PATH\n\n\nclass NsdlIssuanceSecurity(scrapy.Spider):\n name = 'issuance_security_crawler'\n allowed_domains = [allowed_domains[0]]\n start_urls = [start_url[0]]\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n\n def parse(self, response, **kwargs):\n \"\"\"\n This function will parse through all the dates in the current month and extracts the Security ISIN and\n Security name from the NSDL website.\n\n Extracted data will go through a condition, if ISIN already present in MAS_SECURITIES table, it will drop off\n that particular data and if it doesn't exist in MAS_SECURITIES then it will push the data into the table.\n (This process is taken care by the Pipelines.py)\n\n :param response: Response from the URL\n :param kwargs: Keyword arguments\n \"\"\"\n\n calendar_rows = [1, 2, 3, 4, 5, 6]\n calendar_cols = [1, 2, 3, 4, 5, 6, 7]\n for row in calendar_rows:\n for col in calendar_cols:\n options = Options()\n options.add_argument(HEADLESS_OPTIONS['headless'])\n options.add_argument(HEADLESS_OPTIONS['window_size'])\n options.add_argument(HEADLESS_OPTIONS['sandbox'])\n options.add_argument(HEADLESS_OPTIONS['dev_shm_usage'])\n options.add_argument(HEADLESS_OPTIONS['disable_gpu'])\n options.add_argument(HEADLESS_OPTIONS['network_service'])\n options.add_argument(HEADLESS_OPTIONS['display_compositor'])\n driver = webdriver.Chrome(executable_path=CHROME_DRIVER_PATH, options=options)\n\n driver.get(self.start_urls[0])\n criteria = Select(driver.find_element_by_xpath(criteria_path[0]))\n criteria.select_by_value(criteria_value[0])\n\n market = Select(driver.find_element_by_xpath(market_path[0]))\n market.select_by_value(market_value[0])\n\n current_date = datetime.datetime.today().date() - relativedelta(months=1)\n month_in_words = datetime.date(current_date.year, current_date.month, current_date.day).strftime('%B')\n\n date_picker = driver.find_element_by_id(date_picker_path[0])\n date_picker.click()\n time.sleep(1)\n\n month_year_title = driver.find_element_by_class_name(date_picker_mon_yr[0])\n month_year_title.click()\n time.sleep(1)\n\n year = driver.find_element_by_xpath(date_picker_year[0])\n year.clear()\n year.send_keys(current_date.year)\n time.sleep(1)\n\n month_rows = [1, 2, 3, 4]\n month_cols = [1, 2, 3]\n for mrows in month_rows:\n for mcols in month_cols:\n month = driver.find_element_by_xpath(mas_securities_month[0].format(mrows, mcols))\n if month.text == month_in_words[0:3]:\n month.click()\n time.sleep(1)\n\n day = driver.find_element_by_xpath(date_locator_path[0].format(row, col))\n day.click()\n time.sleep(1)\n\n go_button = driver.find_element_by_xpath(go_button_path[0])\n go_button.click()\n time.sleep(3)\n\n try:\n issuance_table = driver.find_element_by_xpath(issuance_table_path[0])\n time.sleep(1)\n for i_index, i_row in enumerate(issuance_table.find_elements_by_xpath(issuance_table_row[0])):\n td_issuance_data = []\n if i_index > 2:\n for t_cell in i_row.find_elements_by_xpath(issuance_table_cell[0]):\n td_issuance_data.append(t_cell.text)\n time.sleep(1)\n\n if len(td_issuance_data) > 3:\n security_items = NsdlSecurityItem()\n security_items['security_isin'] = td_issuance_data[0]\n security_items['security_name'] = td_issuance_data[1]\n security_items['exchange_code'] = None\n security_items['security_type'] = 'CORPBOND'\n security_items['security_code'] = None\n security_items['bse_security_symbol'] = None\n security_items['nse_security_symbol'] = None\n security_items['mse_security_symbol'] = None\n security_items['industry'] = None\n yield security_items\n except Exception as error:\n print('Exception raised :', error)\n driver.close()\n","sub_path":"FundRatingNSDL/nsdl_extraction/nsdl_extraction/spiders/mas_securities_issuance.py","file_name":"mas_securities_issuance.py","file_ext":"py","file_size_in_byte":5288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"545028463","text":"import os\n\nyear_list = ['2005-2019', '2005-2011', '2011-2019']\nmonth_list = ['06-08']\n\nfor year in year_list:\n for month in month_list:\n\n cmd = 'python main_plot_GC_NO2_trends_US.py ' + \\\n '--time_range=' + year + '_' + month\n\n os.system(cmd)\n","sub_path":"MERRA2_plot/plot/plot_overpass_GC_NO2_trend/code/main_call_plot_GC_NO2_trends_US.py","file_name":"main_call_plot_GC_NO2_trends_US.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"511308102","text":"import cx_Freeze\nimport sys\nimport os \nbase = None\n\nif sys.platform == 'win32':\n base = \"Win32GUI\"\n\nos.environ['TCL_LIBRARY'] = r\"C:\\Users\\rajan\\AppData\\Local\\Programs\\Python\\Python37-32\\tcl\\tcl8.6\"\nos.environ['TK_LIBRARY'] = r\"C:\\Users\\rajan\\AppData\\Local\\Programs\\Python\\Python37-32\\tcl\\tk8.6\"\n\nexecutables = [cx_Freeze.Executable(\"File_Management.py\", base=base, icon=\"file.ico\")]\n\n\ncx_Freeze.setup(\n name = \"File Management\",\n options = {\"build_exe\": {\"packages\":[\"tkinter\",\"os\"], \"include_files\":[\"file.ico\",'tcl86t.dll','tk86t.dll']}},\n version = \"2.0\",\n description = \"Tkinter Application\",\n executables = executables\n )","sub_path":"only_code/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"397586622","text":"'''\nSee following paper for quick description of GAP:\nhttp://aclweb.org/anthology//P/P10/P10-1097.pdf\n'''\n\nfrom operator import itemgetter\nfrom random import shuffle\nimport copy\n\nclass GeneralizedAveragePrecision(object):\n\n @staticmethod\n def accumulate_score(gold_vector):\n accumulated_vector = []\n accumulated_score = 0\n for (key, score) in gold_vector:\n accumulated_score += float(score)\n accumulated_vector.append([key, accumulated_score])\n return accumulated_vector\n\n\n\n '''\n gold_vector: a vector of pairs (key, score) representing all valid results\n evaluated_vector: a vector of pairs (key, score) representing the results retrieved by the evaluated method\n gold_vector and evaluated vector don't need to include the same keys or be in the same length\n '''\n\n @staticmethod\n def calc(gold_vector, evaluated_vector, random=False):\n gold_map = {}\n for [key, value] in gold_vector:\n gold_map[key]=value\n sorted_gold_vector = sorted(gold_vector, key=itemgetter(1), reverse=True)\n gold_vector_accumulated = GeneralizedAveragePrecision.accumulate_score(sorted_gold_vector)\n\n\n ''' first we use the eval score to sort the eval vector accordingly '''\n if random is False:\n sorted_evaluated_vector = sorted(evaluated_vector, key=itemgetter(1), reverse=True)\n else:\n sorted_evaluated_vector = copy.copy(evaluated_vector)\n shuffle(sorted_evaluated_vector)\n sorted_evaluated_vector_with_gold_scores = []\n ''' now we replace the eval score with the gold score '''\n for (key, score) in sorted_evaluated_vector:\n if (key in gold_map.keys()):\n gold_score = gold_map.get(key)\n else:\n gold_score = 0\n sorted_evaluated_vector_with_gold_scores.append([key, gold_score])\n evaluated_vector_accumulated = GeneralizedAveragePrecision.accumulate_score(sorted_evaluated_vector_with_gold_scores)\n\n ''' this is sum of precisions over all recall points '''\n i = 0\n nominator = 0.0\n for (key, accum_score) in evaluated_vector_accumulated:\n i += 1\n if (key in gold_map.keys()) and (gold_map.get(key) > 0):\n nominator += accum_score/i\n\n ''' this is the optimal sum of precisions possible based on the gold standard ranking '''\n i = 0\n denominator = 0\n for (key, accum_score) in gold_vector_accumulated:\n if gold_map.get(key) > 0:\n i += 1\n denominator += accum_score/i\n\n if (denominator == 0.0):\n gap = -1\n else:\n gap = nominator/denominator\n\n return gap\n\n\n @staticmethod\n def calcTopN(gold_vector, evaluated_vector, n, measure_type):\n gold_map = {}\n for [key, value] in gold_vector:\n gold_map[key]=value\n gold_vector_sorted = sorted(gold_vector, key=itemgetter(1), reverse=True)\n gold_top_score_sum = sum([float(score) for (key, score) in gold_vector_sorted[0:n]])\n\n evaluated_top_score_sum = 0\n sorted_evaluated_vector = sorted(evaluated_vector, key=itemgetter(1), reverse=True)\n for (key, score) in sorted_evaluated_vector[0:n]:\n if key in gold_map:\n gold_score = gold_map[key]\n else:\n gold_score = 0\n evaluated_top_score_sum += float(gold_score)\n\n if measure_type == 'sap' or measure_type == 'wap':\n denominator = n\n else:\n denominator = gold_top_score_sum\n\n return evaluated_top_score_sum/denominator\n\n\n'''\nUsed to compute GAP score for the LST ranking task\n\n'''\n\nimport sys\nimport random\nimport re\n\n#take.v 25 :: consider 2;accept 1;include 1;think about 1;\ndef read_gold_line(gold_line, ignore_mwe):\n segments = gold_line.split(\"::\")\n instance_id = segments[0].strip()\n gold_weights = []\n line_candidates = segments[1].strip().split(';')\n for candidate_count in line_candidates:\n if len(candidate_count) > 0:\n delimiter_ind = candidate_count.rfind(' ')\n candidate = candidate_count[:delimiter_ind]\n if ignore_mwe and ((len(candidate.split(' '))>1) or (len(candidate.split('-'))>1)):\n continue\n count = candidate_count[delimiter_ind:]\n try:\n gold_weights.append((candidate, int(count)))\n except ValueError as e:\n print(e)\n print(gold_line)\n print(\"cand=%s count=%s\" % (candidate,count))\n sys.exit(1)\n\n return instance_id, gold_weights\n\n#RESULT find.v 71 show 0.34657\ndef read_eval_line(eval_line):\n eval_weights = []\n segments = eval_line.split(\"\\t\")\n instance_id = segments[1].strip()\n for candidate_weight in segments[2:]:\n if len(candidate_weight) > 0:\n delimiter_ind = candidate_weight.rfind(' ')\n candidate = candidate_weight[:delimiter_ind]\n weight = candidate_weight[delimiter_ind:]\n if ignore_mwe and ((len(candidate.split(' '))>1) or (len(candidate.split('-'))>1)):\n continue\n try:\n eval_weights.append((candidate, float(weight)))\n except:\n print(\"Error appending: %s %s\" % (candidate, weight))\n\n return instance_id, eval_weights\n\n\nif __name__ == '__main__':\n\n epath = sys.argv[1]\n opath = sys.argv[2]\n\n try:\n dataset = sys.argv[3]\n except IndexError:\n dataset = 'lst'\n\n try:\n measure = sys.argv[4]\n except IndexError:\n measure = None\n\n if dataset == 'lst':\n gfile = epath + '/lst.gold'\n elif dataset == 'cic':\n gfile = epath + '/cic.gold'\n else:\n raise AssertionError('dataset not supported')\n\n if measure is None:\n measures = ['add', 'baladd', 'mult', 'balmult']\n else:\n measures = [measure, ]\n\n for measure in measures:\n resultsfile = opath + '/' + measure + '/results.ranked'\n out = opath + '/' + measure + '/gap.out'\n\n gold_file = open(gfile, 'r', encoding='iso-8859-1')\n eval_file = open(resultsfile, 'r', encoding='iso-8859-1')\n out_file = open(out, 'w')\n\n ignore_mwe = True\n randomize = False\n\n gold_data = {}\n eval_data = {}\n\n i=0\n sum_gap = 0.0\n for eval_line in eval_file:\n eval_instance_id, eval_weights = read_eval_line(eval_line)\n eval_data[eval_instance_id] = eval_weights\n\n for gold_line in gold_file:\n gold_instance_id, gold_weights = read_gold_line(gold_line, ignore_mwe)\n gold_data[gold_instance_id] = gold_weights\n\n ignored = 0\n for gold_instance_id, gold_weights in gold_data.items():\n eval_weights = eval_data[gold_instance_id]\n gap = GeneralizedAveragePrecision.calc(gold_weights, eval_weights, randomize)\n if (gap < 0): # this happens when there is nothing left to rank after filtering the multi-word expressions\n ignored += 1\n continue\n out_file.write(gold_instance_id + \"\\t\" + str(gap) + \"\\n\")\n i += 1\n sum_gap += gap\n\n mean_gap = sum_gap/i\n out_file.write(\"\\ngold_data %d eval_data %d\\n\" % (len(gold_data),len(eval_data)))\n out_file.write(\"\\nRead %d test instances\\n\" % i)\n out_file.write(\"\\nIgnored %d test instances (couldn't compute gap)\\n\" % ignored)\n out_file.write(\"\\nMEAN_GAP\\t\" + str(mean_gap) + \"\\n\")\n\n\n gold_file.close()\n eval_file.close()\n out_file.close()\n","sub_path":"gap.py","file_name":"gap.py","file_ext":"py","file_size_in_byte":7712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"532192065","text":"from time import strftime, localtime\nimport time\nimport subprocess\nimport os\n\n#settings\n#military time\nlightTime = 600\ndarkTime = 1900\nlightTheme = \"Breeze-Light\"\ndarkTheme = \"Breeze-Dark\"\ncurrTheme = 2 #0 = light; 1 = dark;\n\ndef log(input): #function for writing to log file (write append)\n log = open(os.getcwd() + '/log.txt', 'a')\n log.write(strftime(\"%d %b %Y %H:%M:%S - \", time.localtime()) + input + '\\n')\n log.close()\n\nlog(\"initializing\")\n\n#Loop used to constantly check if a proper time has been met with the if statements.\n#Wait commands are used so the script isn't checking every possible tick.\nwhile True:\n if (int(strftime(\"%H%M\", time.localtime())) < darkTime and int(strftime(\"%H%M\", time.localtime())) > lightTime): #switches between dark and light theme depending on the time and only if it's inbetween the bounds\n if (currTheme != 0):\n subprocess.call([\"lookandfeeltool\", \"-a\", lightTheme])\n log(\"light theme applied\")\n currTheme = 0\n else:\n if (currTheme != 1):\n subprocess.call([\"lookandfeeltool\", \"-a\", darkTheme])\n log(\"dark theme applied\")\n currTheme = 1\n\n if (lightTime % 100 == 0 and darkTime % 100 == 0): #this only makes sense if there are only hours in the times\n if (int(strftime(\"%H%M\", time.localtime())) % 100 != 0): #wait until time is in the next hour to check so it can check every hour\n log(\"waiting \" + str(60 - (int(strftime(\"%H%M\", time.localtime())) % 100)) + \" minutes\")\n time.sleep((60 - int(strftime(\"%H%M\", time.localtime())) % 100)*60)\n continue\n else:\n log(\"waiting an hour\")\n time.sleep(3600)\n\n if (lightTime % 100 != 0 or darkTime % 100 != 0): #executed if the time shifts aren't devisible by an hour\n log(\"waiting 5 minutes\")\n time.sleep(300)\n\n","sub_path":"themeScript_KDE.py","file_name":"themeScript_KDE.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"299371741","text":"# coding=utf-8\nimport filemodule\nimport re\nimport difflib\n\nbooks = {}\n\n\ndef filter(linenum, line):\n return linenum % 5 != 0\n\n\ndef handle(block_count, block_line_num, block):\n global books\n book_name = block[0]\n try:\n list.append(books[book_name], ''.join(block[3:]))\n except KeyError:\n print('发现书籍:《', book_name, '》')\n books[book_name] = []\n\n\ndef diff_and_shrink(strs):\n new_strs = []\n i = 0\n while i < len(strs):\n cursor = i + 1\n max_length_str = strs[i]\n # 相似性检测实现去重\n while cursor < len(strs) and difflib.SequenceMatcher(None, max_length_str,\n strs[cursor][0:len(max_length_str)]).quick_ratio() > 0.90:\n max_length_str = max_length_str if len(max_length_str) >= len(strs[cursor]) else strs[cursor]\n cursor += 1\n new_strs.append(max_length_str)\n i = cursor\n return new_strs\n\n\ndef main():\n file = 'clippings.txt'\n filemodule.read_text_as_list(file=file, separator='==========', handle=handle)\n\n for k, v in books.items():\n match = re.search('(|\\(|\\?', k)\n pos = len(k) if match == None else match.start()\n print(k)\n v = diff_and_shrink(v)\n # 替换非法字符\n filemodule.write_to_file(file=re.sub(r'[\\/\\\\\\:\\*\\?\\\"\\<\\>\\|]', '_', k[0:pos]) + '.txt', lines=v)\n input()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"297632664","text":"from __future__ import print_function\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport plotly.plotly as py\n\nfrom keras import backend as K\n\nfrom sklearn import cluster\nimport glob\nimport os\nfrom os.path import basename\nfrom Bio.PDB import *\nfrom Bio.PDB.Polypeptide import three_to_one\nfrom Bio import SeqIO\n\nimport json\n\nfrom Bio import pairwise2\n\nfrom Bio.SubsMat import MatrixInfo as matlist\n\nfrom keras.models import Sequential\nfrom keras.layers import recurrent, RepeatVector, Activation, TimeDistributed, Dense, Dropout\n\n# Hash table\n\ndef dist2(u,v):\n return sum([(x-y)**2 for (x, y) in zip(u, v)])\n\nclass AcidEmbedding(object):\n\n def __init__(self, maxlen):\n self.maxlen = maxlen\n\n self.chars = list('rndeqkstchmavgilfpwybzuxXo')\n\n self.embed = [[-4.5, 1, 9.09, 71.8],\n [-3.5, 0, 8.8, 2.4],\n [-3.5, -1, 9.6, 0.42],\n [-3.5, -1, 9.67, 0.72],\n [-3.5, 0, 9.13, 2.6],\n [-3.9, 1, 10.28, 200],\n [-0.8, 0, 9.15, 36.2],\n [-0.7, 0, 9.12, 200],\n [2.5, 0, 10.78, 200],\n [-3.2, 1, 8.97, 4.19],\n [1.9, 0, 9.21, 5.14],\n [1.8, 0, 9.87, 5.14],\n [4.2, 0, 9.72, 5.6],\n [-0.4, 0, 9.6, 22.5],\n [4.5, 0, 9.76, 3.36],\n [3.8, 0, 9.6, 2.37],\n [2.8, 0, 9.24, 2.7],\n [-1.6, 0, 10.6, 1.54],\n [-0.9, 0, 9.39, 1.06],\n [-1.3, 0, 9.11, 0.038],\n [1, 0.5, 8.95, 37.1],\n [1, -0.5, 9.40, 1.66],\n [250, -250, 250, -250],\n [0, 0, 0, 0],\n [500, 500, 500, 500],\n [-500, -500, -500, -500]]\n\n self.embed = [[x for x in X] for X in self.embed]\n\n self.char_indices = dict((c, i) for i, c in enumerate(self.chars))\n self.indices_char = dict((i, c) for i, c in enumerate(self.chars))\n\n def encode(self, C, maxlen=None):\n maxlen = maxlen if maxlen else self.maxlen\n X = np.zeros((maxlen, 4))\n for i, c in enumerate(C):\n X[i] = self.embed[self.char_indices[c]]\n return X\n\n def get_charge(self, C):\n charge = 0\n for c in C:\n charge += self.embed[char_indices[c]][1]\n return charge\n\n def get_hydro(self, C):\n hydro = 0\n for c in C:\n hydro += self.embed[char_indices[c]][0]\n return hydro\n\n def decode(self, X):\n prob = [[-dist2(x, y) for y in self.embed] for x in X]\n prob = (np.array(prob)).argmax(axis=-1)\n return ''.join(self.indices_char[x] for x in prob)\n\n\nclass CharacterTable(object):\n '''\n Given a set of characters:\n + Encode them to a one hot integer representation\n + Decode the one hot integer representation to their character output\n + Decode a vector of probabilties to their character output\n '''\n def __init__(self, chars, maxlen):\n self.chars = sorted(set(chars))\n self.char_indices = dict((c, i) for i, c in enumerate(self.chars))\n self.indices_char = dict((i, c) for i, c in enumerate(self.chars))\n self.maxlen = maxlen\n\n def encode(self, C, maxlen=None):\n maxlen = maxlen if maxlen else self.maxlen\n X = np.zeros((maxlen, len(self.chars)))\n for i, c in enumerate(C):\n X[i, self.char_indices[c]] = 1\n return X\n\n def decode(self, X, calc_argmax=True):\n if calc_argmax:\n X = X.argmax(axis=-1)\n return ''.join(self.indices_char[x] for x in X)\n\n# Initial parameters\n \nchars = 'rndeqkstchmavgilfpwybzuxXo'\nctable = CharacterTable(chars, 11)\nlookup = AcidEmbedding(11)\n\nACIDS = 26\nencoding_dim = 10\n\n# Data Generating\n\nprint(\"Generating data...\")\n\ndata = []\ntest = []\n\ndataNames = []\n\n# Parsing fasta file\n\nrecord = SeqIO.parse(\"../../../data/smallData.fa\", \"fasta\")\n\nproteins = []\nUniqNames = []\n\nfor rec in record:\n proteins.append([a for a in rec.seq])\n UniqNames.append(rec.name)\n\nnameInd = dict((c, i) for i, c in enumerate(UniqNames))\n\nprint(len(UniqNames))\n\nrecord = SeqIO.parse(\"../../../data/smallData.fa\", \"fasta\")\n\n# parsing PDB files\n\nPDB_list = glob.glob(\"../../../../PDBMining/*/*.ent\")\n\np = PDBParser()\n\nValid = [False for _ in proteins]\nPDBNames = []\nfor f in PDB_list:\n name = os.path.splitext(basename(f))[0]\n PDBNames.append(name)\n struct = p.get_structure(name,f)\n res_list = Selection.unfold_entities(struct, 'R')\n try:\n seq = [three_to_one(a.get_resname()).lower() for a in res_list]\n except (KeyError):\n seq = []\n try:\n if seq == proteins[nameInd[name]]:\n Valid[nameInd[name]] = True\n except KeyError:\n pass\n\nPDBInd = dict((c, i) for i, c in enumerate(PDBNames))\n\noccurences = [-1 for _ in proteins]\n\nind = -1\nfor rec in record:\n ind +=1\n if ind > 13000:\n break\n if not Valid[nameInd[rec.name]]:\n continue\n if not (ind % 800 == 0):\n continue\n occurences[nameInd[rec.name]] = len(data)\n for k in range(len(rec.seq) // 3 - 4):\n data.append([rec.seq[3 * k + i] for i in range(11)])\n dataNames.append(rec.name)\n\nprint(len(data))\n \n# Encoding data\n\nX = np.zeros((len(data), 11, len(chars)), dtype=np.bool)\n\nfor i, sentence in enumerate(data):\n X[i] = ctable.encode(sentence, maxlen=11)\n\n\nprint(\"Creating model...\")\nmodel = Sequential()\n\n#Recurrent encoder\nmodel.add(recurrent.LSTM(encoding_dim, input_shape=(11, ACIDS), return_sequences=True, dropout_W=0.1, dropout_U=0.1))\nmodel.add(recurrent.LSTM(encoding_dim, return_sequences=True, dropout_W=0.1, dropout_U=0.1))\nmodel.add(recurrent.LSTM(encoding_dim, dropout_W=0.1, dropout_U=0.1))\n\nmodel.add(RepeatVector(11))\n\n#And decoding\nmodel.add(recurrent.LSTM(ACIDS, return_sequences=True))\n\nmodel.add(TimeDistributed(Dense(ACIDS)))\n\nmodel.add(Activation('softmax'))\n\nmodel.load_weights(\"RecOneb.h5\")\n\nmodel.compile(optimizer='rmsprop', loss='binary_crossentropy')\n\nget_summary = K.function([model.layers[0].input, K.learning_phase()], [model.layers[2].output])\n\nprint(\"Let's go!\")\n\nEmbed = [[0 for _ in range(encoding_dim)] for _ in range(len(X))]\n\nfor i in range(len(X)):\n row = X[np.array([i])]\n preds = model.predict_classes(row, verbose=0)\n correct = ctable.decode(row[0])\n intermediate = get_summary([row, 0])[0][0]\n Embed[i] = intermediate\n\n# Preparing data for correlating\n\nProperties = np.zeros(((len(data)**2 - len(data))//2, 15)) \nk = 0\n\nmatrix = matlist.blosum62\n\ndata = [[c.upper() for c in l] for l in data] \n\nfor i in range(len(data)):\n for j in range(i+1, len(data)):\n # latent distance\n Properties[k][0] = np.linalg.norm(Embed[i] - Embed[j])\n #Dimensional orientation\n for k in range(encoding_dim):\n Properties[i][k+1] = Embed[i][k] - Embed[j][k]\n # Alignment scores\n Properties[k][11] = pairwise2.align.globalxx(data[i],data[j], score_only=1)\n Properties[k][12] = pairwise2.align.localxx(data[i],data[j], score_only=1)\n Properties[k][13] = pairwise2.align.globaldx(data[i],data[j], matrix, score_only=1) #BLOSUM!\n # Structural score\n off1 = i - occurences[nameInd[dataNames[i]]]\n off2 = j - occurences[nameInd[dataNames[j]]]\n use1 = [False for _ in proteins[nameInd[dataNames[i]]]]\n for l in range(11):\n use1[3 * off1 + l] = True\n use2 = [False for _ in proteins[nameInd[dataNames[j]]]]\n for l in range(11):\n use2[3 * off2 + l] = True\n file1 = PDB_list[PDBInd[dataNames[i]]]\n file2 = PDB_list[PDBInd[dataNames[j]]]\n struct1 = PDBParser().get_structure(\"1\", file1)[0]\n struct2 = PDBParser().get_structure(\"2\", file2)[0]\n ref_atoms = []\n alt_atoms = []\n res_list1 = Selection.unfold_entities(struct1, 'R')\n res_list2 = Selection.unfold_entities(struct2, 'R')\n for ref_res, allow in zip(res_list1, use1):\n if allow:\n #CA = alpha carbon\n ref_atoms.append(ref_res['CA']) \n for alt_res, allow in zip(res_list2, use2):\n if allow:\n #CA = alpha carbon\n alt_atoms.append(alt_res['CA'])\n super_imposer = Superimposer()\n super_imposer.set_atoms(ref_atoms, alt_atoms)\n Properties[k][14] = super_imposer.rms\n k += 1\n\nf = open(\"pairs.txt\", 'w')\njson.dump(Properties.tolist(), f)\nf.close()\n \n","sub_path":"Code/Autoencoding/Embed/Recurrent/EmbedRecHeatPair.py","file_name":"EmbedRecHeatPair.py","file_ext":"py","file_size_in_byte":8669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"190307618","text":"import arcpy\n\n##arcpy.env.workspace = r\"C:\\JNP_local\\dannySamples\\John_Samples_July23.xlsx\"\n##fromTbl = r\"C:\\JNP_local\\2017_HPMS_Samples\\GID_135.dbf\"\n##fromTbl = r\"C:\\JNP_local\\dannySamples\\John_Samples_July23.csv\"\nfromTbl = r\"C:\\JNP_local\\dannySamples\\samples.gdb\\hmps2018\"\ntoTbl = r\"C:\\TxDOT\\BulkLoad\\AssetTables\\AssetTables_HPMSDannySamples.gdb\\HpmsSample\"\n\nsCursor = arcpy.da.SearchCursor(fromTbl,['GID','FRM_DFO','TO_DFO','HPMSID'])\n\nsDict = {}\n\n##with open(fromTbl,'r') as c:\n## cRead\n\n\nfor row in sCursor:\n sDict[str(row)] = row\n\niCursor = arcpy.da.InsertCursor(toTbl,['RDBD_GMTRY_LN_ID','ASSET_LN_BEGIN_DFO_MS','ASSET_LN_END_DFO_MS','HPMS_SAMP_NBR'])\n\nfor item in sDict.keys():\n iRow = sDict[item]\n iCursor.insertRow(iRow)\n\n\ndel iCursor\ndel sCursor","sub_path":"AdvancedScripts/TablePopulationCursor.py","file_name":"TablePopulationCursor.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"153654497","text":"# Copyright (C) 2019 GreenWaves Technologies\n# All rights reserved.\n\n# This software may be modified and distributed under the terms\n# of the BSD license. See the LICENSE file for details.\n\nfrom collections import OrderedDict\n\nfrom graph.nngraph import NNGraph\nfrom graph.types import (Conv2DParameters, FcParameters,\n FusionParameters, InputParameters, Parameters,\n SoftMaxParameters, PoolingParameters)\nfrom utils.stats_funcs import (STATS_BITS, bits, closest_greater)\nfrom utils.node_id import NodeId\n\nfrom .qtype import QType\nfrom .quantization_record import (FilterQuantizationRecord, QuantizationRecord)\nfrom .quantizer import Quantizer\n\n\nclass SimpleQuantizer(Quantizer):\n def __init__(self, activation_stats, filter_stats, min_qsnr=None, force_width=None):\n self._activation_stats = activation_stats\n self._filter_stats = filter_stats\n self._min_qsnr = min_qsnr\n self._force_width = force_width\n\n # pylint: disable=too-many-locals\n def calculate_filter_q(self, node: Parameters, astats, fstats,\n in_q: QType, min_qsnr, force_width,\n acc_as_calc=False, bias_as_out=True):\n fstats = node.stats\n w_q = self.get_quantization(fstats['weights'], min_qsnr, force_width)\n o_q = self.get_quantization(astats, min_qsnr, force_width)\n calc_width = closest_greater(in_q.bits + w_q.bits)\n calc_q = in_q.q + w_q.q\n\n acc_bits = bits(astats['max_acc'], astats['min_acc'])\n act_bits = bits(astats['max'], astats['min'])\n act_acc_bits = max(acc_bits, act_bits)\n\n calc_int_bits = calc_width - calc_q\n if calc_int_bits < act_acc_bits:\n # we don't have enough space for the integer portion so reduce the precision of\n # the weights\n missing_bits = act_acc_bits - calc_int_bits\n # TODO - This needs improving\n assert w_q.q >= missing_bits, \"no space in weights to reduce precision\"\n w_q.q = w_q.q - missing_bits\n calc_q = in_q.q + w_q.q\n\n c_q = QType(bits=calc_width, q=calc_q, signed=True)\n\n if 'biases' in fstats:\n b_q = self.get_quantization(fstats['biases'], min_qsnr, force_width)\n if bias_as_out:\n o_q.q = min(b_q.q, o_q.q)\n b_q.q = o_q.q\n else:\n b_q = o_q.q\n\n if acc_as_calc or acc_bits > o_q.bits - o_q.q:\n acc_q = c_q\n else:\n acc_q = o_q\n\n norm = c_q.q - o_q.q\n\n node.quantization = {\"input_q\": in_q, \"weights_q\": w_q,\n \"biases_q\": b_q, \"norm\": norm, \"calc_q\": c_q,\n \"acc_q\": acc_q}\n return FilterQuantizationRecord(in_qs=[in_q], out_qs=[o_q], calc_q=c_q,\n acc_q=acc_q, biases_q=b_q, weights_q=w_q)\n\n @staticmethod\n def get_quantization(stats, min_qsnr, force_width):\n qstats = stats['qstats']\n if force_width is not None:\n return QType(bits=force_width,\n q=qstats[force_width]['q'],\n signed=True)\n for width in STATS_BITS:\n if qstats[width]['qsnr'] > min_qsnr:\n return QType(bits=width,\n q=qstats[width]['q'],\n signed=True)\n raise ValueError(\"no solution for this QSNR could be found\")\n\n def calculate_q(self, node, astats, fstats, in_qs, min_qsnr, force_width):\n if isinstance(node, InputParameters):\n qreq = QuantizationRecord(in_qs=in_qs,\n out_qs=[self.get_quantization(astats, min_qsnr, force_width)])\n elif isinstance(node, Conv2DParameters):\n qreq = self.calculate_filter_q(node, astats, fstats, in_qs[0], min_qsnr, force_width)\n elif isinstance(node, FcParameters):\n qreq = self.calculate_filter_q(node, astats, fstats, in_qs[0], min_qsnr, force_width,\n acc_as_calc=True)\n # TODO - put back when fixed, bias_as_out=False)\n elif isinstance(node, SoftMaxParameters):\n # softmax always outputs Q15\n qreq = QuantizationRecord(in_qs=in_qs, out_qs=[QType(16, 15, True)])\n else:\n qreq = QuantizationRecord(in_qs=in_qs, out_qs=in_qs)\n return qreq\n\n def quantize(self, G: NNGraph) -> OrderedDict:\n edge_recs = {}\n result = OrderedDict()\n for step in G.graph_state.steps:\n node = step['node']\n if isinstance(node, InputParameters):\n in_qs = []\n else:\n in_qs = [edge_recs[edge.params]\n for edge in G.indexed_in_edges(node.name)]\n if isinstance(node, FusionParameters):\n fin_qs = in_qs\n for fnode in node.contained_nodes():\n fkey = NodeId(node, fnode)\n qrec = self.calculate_q(\n fnode,\n self._activation_stats.get(fkey),\n self._filter_stats.get(fkey),\n fin_qs,\n self._min_qsnr,\n self._force_width)\n result[fkey] = qrec\n fin_qs = qrec.out_qs\n\n key = NodeId(node, None)\n qrec = self.calculate_q(\n node,\n self._activation_stats.get(key),\n self._filter_stats.get(key),\n in_qs,\n self._min_qsnr,\n self._force_width)\n result[key] = qrec\n if not qrec:\n break\n\n for edges in G.indexed_out_edges(node.name):\n for edge in edges:\n edge_recs[edge.params] = qrec.out_qs[edge.from_idx]\n return result\n","sub_path":"tools/nntool/quantization/simple_quantizer.py","file_name":"simple_quantizer.py","file_ext":"py","file_size_in_byte":5942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"210744143","text":"import faker\nimport faker.providers\nimport json\nimport jsonschema\nimport random\nimport copy\nimport collections\nimport unittest\nimport os\n\nimport rstr\n\n\nclass JSONProvider(faker.providers.BaseProvider):\n @staticmethod\n def _find_reference_in_schema(path, schema):\n path_elements = path.split(\"/\")\n if path.startswith(\"#\"):\n path_elements = path_elements[1:]\n if not path_elements:\n return schema\n\n cschema = schema[path_elements[0]]\n if len(path_elements) == 1:\n return cschema\n else:\n return JSONProvider._find_reference_in_schema(\"/\".join(path_elements[1:]), cschema)\n\n @staticmethod\n def value_for_schema_element(schema_element, root_schema_element, fake=faker.Faker(), overrides={}):\n\n if \"oneOf\" in schema_element.keys():\n se = random.choice(schema_element[\"oneOf\"])\n elif \"allOf\" in schema_element.keys():\n se = dict()\n for rs in schema_element['allOf']:\n se.update(rs)\n elif \"anyOf\" in schema_element.keys():\n se = collections.defaultdict(list)\n\n for d in (schema_element[\"anyOf\"]):\n for key, value in d.items():\n se[key].append(value)\n else:\n se = copy.copy(schema_element)\n\n if \"$ref\" in se.keys():\n se = JSONProvider._find_reference_in_schema(se['$ref'], root_schema_element)\n if \"type\" not in se.keys():\n element_type = \"string\"\n elif type(se['type']) == list:\n element_type = random.choice(se['type'])\n else:\n element_type = se[\"type\"]\n\n if element_type == 'null':\n return None\n elif element_type == 'string':\n if se.get('pattern', None) is not None:\n return rstr.xeger(se['pattern'])\n elif se.get('enum', None) is not None:\n return random.choice(se['enum'])\n else:\n return fake.password(length=30, special_chars=True, digits=True, upper_case=True, lower_case=True)\n\n elif element_type == 'number':\n return round(random.uniform(se.get('minimum', -100000000), se.get('maximum', 10000000)),\n random.randint(0, 5))\n\n elif element_type == 'integer':\n n = random.randint(se.get('minimum', 0), se.get('maximum', 10000000))\n return n - (n % se.get('multipleOf', 1))\n\n elif element_type == 'boolean':\n return fake.boolean(chance_of_getting_true=50)\n\n elif element_type == 'array':\n array_value = list()\n for _ in range(0, random.randint(0, random.randint(se.get('minItems', 3), se.get('maxItems', 100)))):\n array_value.append(JSONProvider.value_for_schema_element(se.get('items',\n {\"type\": random.choice(\n [\"string\", \"boolean\", \"number\",\n \"integer\"])}),\n root_schema_element,\n fake,\n overrides))\n # P TODO need to support 'unique items'\n return array_value\n\n elif element_type == 'object':\n object_value = dict()\n for k, v in se.get('properties', {}).items():\n if k in overrides.keys():\n object_value[k] = overrides[k]()\n else:\n object_value[k] = JSONProvider.value_for_schema_element(v,\n root_schema_element,\n fake,\n overrides)\n return object_value\n\n else:\n raise ValueError(\"Don't know have to create value for schema element type [{}]\".format(se['type']))\n\n def json(self, json_schema):\n return self.value_for_schema_element(json_schema, json_schema)\n\n\nclass JSONProviderUnitTest(unittest.TestCase):\n def test_example_schemas(self):\n fake = faker.Faker()\n fake.add_provider(JSONProvider)\n\n schmeapath = os.getcwd() + os.sep + \"example_schemas\" + os.sep\n schema_files = [os.path.join(schmeapath, f) for f in os.listdir(schmeapath) if\n os.path.isfile(os.path.join(schmeapath, f))]\n print(schema_files)\n for schema_file in schema_files:\n try:\n with open(schema_file) as f:\n schema = json.load(f)\n jsonschema.validate(fake.json(schema), schema)\n except Exception as e:\n self.fail(\"File <{}> failed with exception <{}>\".format(schema_file, e))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"jsonprovider.py","file_name":"jsonprovider.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"309896269","text":"from __future__ import print_function\nimport json\nimport time\nfrom copy import deepcopy\n\nfrom sqlalchemy import Column, String, ForeignKey, select, join\n\nfrom dataservices.mixins import DownloadTable\nfrom dataservices.recipe import *\nfrom dataservices.redshift_connectionbase import *\nfrom dataservices.servicebase import *\nfrom dataservices.recipe_pool import RecipePool\nfrom dataservices.renderers import OptionChooserRenderer\nfrom dataservices.servicebasev3 import RecipeServiceBaseV3\n\n# -------------\n# Connect to the database\n# -------------\nfrom sqlalchemy.orm import relationship\n\nfrom hashr.utils import hash_and_store_data\n\nengine = redshift_create_engine()\n\n# Instantiate the base class for declarative (table) class instances\n# ------------------------------------------------------------------\n\nBase = declarative_base()\n\ncurrent_milli_time = lambda: int(round(time.time() * 1000))\n\n# -------------\n# Step 1: Define the tables used in your application\n# -------------\n\n\nclass DivLookup(Base):\n __table__ = Table(\n \"state_census_div_lookup\",\n Base.metadata,\n Column(\"census_division\", String(), primary_key=True),\n Column(\"name\", String()),\n schema=\"demo\",\n extend_existing=True,\n )\n\n\nclass StateFact(Base):\n \"\"\"\n The `demo.census` table defined statically. This is the preferred way to do things\n as Juicebox starts up faster and can be more flexible.\n\n Again, a primary key is defined but will not be used.\n \"\"\"\n\n __table__ = Table(\n \"state_fact\",\n Base.metadata,\n Column(\"id\", String()),\n Column(\"name\", String(), primary_key=True),\n Column(\"abbreviation\", String()),\n Column(\"country\", String()),\n Column(\"type\", String()),\n Column(\"sort\", String()),\n Column(\"status\", String()),\n Column(\"occupied\", String()),\n Column(\"notes\", String()),\n Column(\"fips_state\", String()),\n Column(\"assoc_press\", String()),\n Column(\"standard_federal_region\", String()),\n Column(\"census_region\", String()),\n Column(\"census_region_name\", String()),\n Column(\"census_division\", String(), ForeignKey(DivLookup.census_division)),\n Column(\"census_division_name\", String()),\n Column(\"circuit_court\", String()),\n schema=\"demo\",\n extend_existing=True,\n )\n\n\nclass Census(Base):\n \"\"\"\n The `demo.census` table defined statically. This is the preferred way to do things\n as Juicebox starts up faster and can be more flexible.\n\n Again, a primary key is defined but will not be used.\n \"\"\"\n\n __table__ = Table(\n \"census\",\n Base.metadata,\n Column(\"state\", String(30), ForeignKey(StateFact.name), primary_key=True),\n Column(\"sex\", String(1)),\n Column(\"age\", Float()),\n Column(\"pop2000\", Float()),\n Column(\"pop2008\", Float()),\n schema=\"demo\",\n extend_existing=True,\n )\n state_fact = relationship(StateFact)\n\n\n# Another approach is to create a joined view\nclass CensusJoined(Base):\n __table__ = (\n select([Census, StateFact])\n .select_from(join(Census, StateFact, Census.state == StateFact.name))\n .alias()\n )\n\n\n# -------------\n# Step 2) Define a base class with metrics on the `metric_shelf` and dimensions\n# on the dimension_shelf\n# -------------\n\n\nclass CensusService(RecipeServiceBaseV3):\n # Metrics are defined as an SQLAlchemy expression, and a label.\n metric_shelf = {\n \"pop2000\": Metric(\n func.sum(Census.pop2000),\n label=\"Population 2000\",\n format=\".3s\",\n singular=\"Population 2000\",\n plural=\"Population 2000\",\n ),\n \"pop2008\": Metric(\n func.sum(Census.pop2008), singular=\"Population 2008\", format=\".3s\"\n ),\n \"popdiff\": Metric(\n func.sum(Census.pop2008 - Census.pop2000),\n format=\".3s\",\n singular=\"Population Growth\",\n ),\n \"avgage\": Metric(\n func.sum(Census.pop2008 * Census.age) / func.sum(Census.pop2008),\n singular=\"Average Age\",\n format=\".1f\",\n ),\n # A metric using a complex expression\n \"pctfemale\": Metric(\n func.sum(case([(Census.sex == \"F\", Census.pop2008)], else_=0))\n / func.sum(Census.pop2008),\n format=\".1%\",\n singular=\"% Female\",\n ),\n # a metric using a formatter\n \"pctdiff\": Metric(\n func.sum(Census.pop2008 - Census.pop2000) / func.sum(Census.pop2000),\n singular=\"Population Pct Change\",\n # formatters=[\n # lambda x: \"Change is {0:0.1%} percent\".format(\n # x)]\n ),\n }\n\n # Dimensions are ways to split the data.\n dimension_shelf = {\n # Simplest possible dimension, a SQLAlchemy expression and a label.\n \"state\": Dimension(Census.state, singular=\"State\", plural=\"States\", format=\"\"),\n \"first_letter_state\": Dimension(\n func.substring(Census.state, 1, 1), label=\"State\"\n ),\n \"age\": Dimension(Census.age, singular=\"Age\", plural=\"Ages\"),\n \"age_bands\": Dimension(\n case(\n [(Census.age < 21, \"Under 21\"), (Census.age < 49, \"21-49\")],\n else_=\"Other\",\n ),\n label=\"Age Bands\",\n ),\n # This will use the lookup to get display values of \"M\" and \"F\"\n \"sex\": LookupDimension(\n Census.sex,\n singular=\"Gender\",\n plural=\"Genders\",\n lookup={\"M\": \"Menfolk\", \"F\": \"Womenfolk\"},\n ),\n # Formatters apply functions to the response\n \"gender\": Dimension(\n Census.sex, label=\"Sex\", formatters=[lambda x: ord(x), lambda x: x + 100]\n ),\n }\n\n # Automatic filter keys are used for the global filters as well\n automatic_filter_keys = (\n \"sex\",\n \"state\",\n )\n\n def __init__(self, *args, **kwargs):\n super(CensusService, self).__init__(*args, **kwargs)\n # self.Session = Session\n\n\n# -------------\n# Step 3) The data services response.\n# -------------\n\n\nclass FilterService(CensusService):\n def build_response(self):\n self.metrics = (\"pop2000\",)\n recipes = []\n for dim in self.automatic_filter_keys:\n recipe = self.recipe().metrics(*self.metrics).dimensions(dim)\n recipes.append((recipe, dim))\n\n results = RecipePool(recipes).run()\n self.response[\"responses\"] = results\n\n\nclass FirstChooserV3Service(CensusService):\n def build_response(self):\n start = current_milli_time()\n self.metrics = (\"pop2000\", \"pop2008\", \"popdiff\", \"avgage\", \"pctfemale\")\n recipe = self.recipe().metrics(*self.metrics)\n self.response[\"responses\"].append(recipe.render(flavor=\"metric\"))\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass SecondChooserV3Service(CensusService):\n def build_response(self):\n print(\"Metrics: \", self.metrics)\n start = current_milli_time()\n self.metrics = (\"pop2000\",)\n self.dimensions = (\"sex\",)\n recipe = self.recipe().dimensions(*self.dimensions).metrics(*self.metrics)\n self.response[\"responses\"].append(recipe.render())\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass ButtonChooserV3Service(CensusService):\n def build_response(self):\n render_config = {\n \"buttons\": [\n {\"total\": \"total_label\", \"path\": \"path1\"},\n {\"standard\": \"standard_label\", \"path\": \"path2\"},\n {\"vent_trach\": \"Vent/Trach\", \"path\": \"path3\"},\n ],\n \"group_by\": \"exclusion\",\n }\n\n renderer = OptionChooserRenderer(self, None, \"button_name\")\n response = renderer.render(flavor=\"buttons\", render_config=render_config)\n self.response[\"responses\"].append(response)\n\n\nclass DistributionV3Service(CensusService):\n def build_response(self):\n start = current_milli_time()\n self.metrics = (\"pop2000\",)\n self.dimensions = [\"age_bands\", \"age\"]\n recipe1 = (\n self.recipe()\n .dimensions(*self.dimensions)\n .metrics(*self.metrics)\n .order_by(*self.dimensions)\n .filters(*self.filters)\n )\n\n self.dimensions = [\"first_letter_state\", \"state\"]\n\n recipe2 = (\n self.recipe()\n .dimensions(*self.dimensions)\n .metrics(*self.metrics)\n .order_by(*self.dimensions)\n .filters(*self.filters)\n )\n self.dimensions = [\"gender\", \"region\"]\n\n results = RecipePool(\n [\n (recipe1, \"Ages\"),\n (recipe2, \"States\"),\n ]\n ).run()\n self.response[\"responses\"] = results\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass TableV3Service(DownloadTable, CensusService):\n def build_response(self):\n start = current_milli_time()\n self.metrics = (\"pop2000\", \"pop2008\", \"popdiff\")\n self.dimensions = (\"state\", \"sex\")\n recipe1 = self.recipe().metrics(*self.metrics).dimensions(*self.dimensions)\n self.dimensions = (\"age_bands\", \"age\")\n recipe2 = self.recipe().metrics(*self.metrics).dimensions(*self.dimensions)\n\n results = RecipePool(\n [\n (recipe1, \"States\"),\n (recipe2, \"Ages\"),\n ]\n ).run()\n self.response[\"responses\"] = results\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass LeaderboardV3Service(CensusService):\n def build_response(self):\n start = current_milli_time()\n self.metrics = (\"pop2000\", \"pop2008\", \"popdiff\")\n self.dimensions = (\"state\",)\n recipe1 = self.recipe().metrics(*self.metrics).dimensions(*self.dimensions)\n self.dimensions = (\"age\",)\n recipe2 = self.recipe().metrics(*self.metrics).dimensions(*self.dimensions)\n\n results = RecipePool(\n [\n (recipe1, \"States\"),\n (recipe2, \"Ages\"),\n ]\n ).run()\n self.response[\"responses\"] = results\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass RankedListV3Service(CensusService):\n def build_response(self):\n start = current_milli_time()\n self.metrics = (\"avgage\", \"pop2008\")\n self.dimensions = (\"state\",)\n recipe1 = (\n self.recipe()\n .metrics(*self.metrics)\n .dimensions(*self.dimensions)\n .order_by(\"avgage\")\n )\n self.dimensions = (\"sex\",)\n recipe2 = (\n self.recipe()\n .metrics(*self.metrics)\n .dimensions(*self.dimensions)\n .order_by(\"avgage\")\n )\n results = RecipePool(\n [\n (recipe1, \"States\"),\n (recipe2, \"Gender\"),\n ]\n ).run()\n self.response[\"responses\"] = results\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass LollipopV3Service(CensusService):\n def build_response(self):\n start = current_milli_time()\n self.metrics = (\"pctfemale\", \"pctdiff\")\n benchmark = (\n self.recipe()\n .dimensions()\n .metrics(*self.metrics)\n .apply_global_filters(False)\n )\n\n recipe = (\n self.recipe()\n .metrics(*self.metrics)\n .dimensions(*self.dimensions)\n .apply_global_filters(True)\n .filters(*self.filters)\n .compare(benchmark)\n )\n\n self.response[\"responses\"].append(recipe.render(flavor=\"single_benchmark\"))\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass FreeFormV3Service1(CensusService):\n def build_response(self):\n start = current_milli_time()\n self.metrics = (\"popdiff\",)\n self.dimensions = (\"state\",)\n recipe = (\n self.recipe()\n .metrics(*self.metrics)\n .dimensions(*self.dimensions)\n .limit(1)\n .apply_global_filters(False)\n )\n self.response[\"responses\"].append(recipe.render())\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass FreeFormV3Service2(CensusService):\n def build_response(self):\n start = current_milli_time()\n\n data = {\"name\": \"Jason\", \"pastry\": \"cookies\"}\n\n response = self.response_template()\n response[\"data\"][0][\"values\"].append(data)\n\n self.response[\"responses\"].append(response)\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass CardV3Service2(CensusService):\n def build_response(self):\n start = current_milli_time()\n\n self.metrics = (\"popdiff\",)\n self.dimensions = (\"state\",)\n recipe1 = self.recipe().metrics(*self.metrics).dimensions(*self.dimensions)\n\n self.dimensions = (\"sex\",)\n recipe2 = self.recipe().metrics(*self.metrics).dimensions(*self.dimensions)\n\n results = RecipePool(\n [\n (recipe1, \"States\"),\n (recipe2, \"Gender\"),\n ]\n ).run()\n\n self.response[\"responses\"] = results\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass NineBoxV3Service(CensusService):\n def build_response(self):\n start = current_milli_time()\n\n self.metrics = (\"popdiff\", \"pctfemale\")\n self.dimensions = (\"state\",)\n recipe = (\n self.recipe()\n .metrics(*self.metrics)\n .dimensions(*self.dimensions)\n .apply_global_filters(False)\n )\n\n self.response[\"responses\"].append(recipe.render())\n print(\"Ms: \", current_milli_time() - start)\n\n\nclass MatchupV3Service(CensusService):\n def build_response(self):\n self.metrics = (\"popdiff\",)\n self.dimensions = (\"state\",)\n\n recipe = self.recipe().metrics(*self.metrics).dimensions(*self.dimensions)\n\n self.response[\"responses\"].append(recipe.render())\n\n\nclass StackSwitcherService(CensusService):\n def __init__(self, *args, **kwargs):\n super(StackSwitcherService, self).__init__(*args, **kwargs)\n self.custom_filter_keys = self.automatic_filter_keys\n\n def build_response(self):\n hash_data = {\n \"id\": \"58c6a623\",\n \"slug\": \"census2\",\n \"state\": {\"global_filters\": {\"values\": {}}},\n }\n\n global_filters = deepcopy(self.automatic_filters)\n for k in self.automatic_filter_keys:\n if k in self.custom_filters:\n global_filters[k] = [{\"id\": v} for v in self.custom_filters[k]]\n\n hash_data[\"state\"][\"global_filters\"][\"values\"] = global_filters\n context_hash = hash_and_store_data(json.dumps(hash_data))\n\n buttons = [{\"label\": \"Census\", \"url\": \"/jb3demo/census#\" + context_hash}]\n\n response = self.response_template()\n response[\"data\"][0][\"values\"] = buttons\n self.response[\"responses\"].append(response)\n","sub_path":"stacks/census2/censusv2service.py","file_name":"censusv2service.py","file_ext":"py","file_size_in_byte":14960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"514043744","text":"class Solution(object):\n def rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n if len(nums) == 0:\n return 0\n if len(nums) == 1:\n return nums[0]\n if len(nums) == 2:\n return max(nums)\n if len(nums) == 3:\n return max(nums)\n else:\n n = len(nums)\n return max(self.solve(nums,0,n-2),self.solve(nums,1,n-1))\n\n def solve(self,nums,start,end):\n temp = nums[start:end+1]\n temp[1] = max(temp[0],temp[1])\n for i in range(2,len(temp)):\n temp[i] = max(temp[i-1],temp[i-2] + temp[i])\n return max(temp)\n\n","sub_path":"house-robber-ii.py","file_name":"house-robber-ii.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"554738932","text":"from __future__ import annotations\r\n\r\nimport os\r\nimport shutil\r\nfrom abc import ABC, abstractmethod\r\nfrom typing import Union, Optional\r\n\r\nimport tensorflow as tf\r\nfrom numpy import array\r\nfrom pandas import DataFrame\r\n\r\nimport GNN.GNN_metrics as mt\r\nfrom GNN.graph_class import GraphObject\r\n\r\n\r\nclass BaseGNN(ABC):\r\n ## CONSTRUCTORS METHODS ###########################################################################################\r\n def __init__(self,\r\n optimizer: tf.keras.optimizers.Optimizer,\r\n loss_function: tf.keras.losses.Loss,\r\n loss_arguments: Optional[dict],\r\n addressed_problem: str,\r\n extra_metrics: Optional[dict] = None,\r\n extra_metrics_arguments: Optional[dict[str, dict]] = None,\r\n path_writer: str = 'writer/',\r\n namespace='GNN') -> None:\r\n \r\n # check types and values\r\n if addressed_problem not in ['c', 'r']: raise ValueError('param not in [\\'c\\',\\'r\\']')\r\n if not isinstance(extra_metrics, (dict, type(None))): raise TypeError('type of param must be None or dict')\r\n\r\n # set attributes\r\n self.loss_function = loss_function\r\n self.loss_args = dict() if loss_arguments is None else loss_arguments\r\n self.optimizer = optimizer\r\n\r\n # Problem type: c: Classification | r: Regression\r\n self.addressed_problem = addressed_problem\r\n\r\n # Metrics to be evaluated during training process\r\n self.extra_metrics = dict() if extra_metrics is None else extra_metrics\r\n self.mt_args = dict() if extra_metrics_arguments is None else extra_metrics_arguments\r\n\r\n # Writer for Tensorboard - Nets histograms and Distributions\r\n self.path_writer = path_writer if path_writer[-1] == '/' else path_writer + '/'\r\n if os.path.exists(self.path_writer): shutil.rmtree(self.path_writer)\r\n self.namespace = namespace if type(namespace) == list else [namespace]\r\n\r\n # history object (dict) - to summarize the training process, initialized as empty dict\r\n self.history = dict()\r\n\r\n\r\n ## ABSTRACT METHODS ###############################################################################################\r\n @abstractmethod\r\n def copy(self, *, path_writer: str = '', namespace: str = '', copy_weights: bool = True):\r\n pass\r\n\r\n @abstractmethod\r\n def trainable_variables(self) -> tuple[list[list[tf.Tensor]], list[list[tf.Tensor]]]:\r\n pass\r\n\r\n @abstractmethod\r\n def get_weights(self) -> tuple[list[list[array]], list[list[array]]]:\r\n pass\r\n\r\n @abstractmethod\r\n def set_weights(self, weights_state: Union[list[array], list[list[array]]], weights_output: Union[list[array], list[list[array]]]) -> None:\r\n pass\r\n\r\n @abstractmethod\r\n def Loop(self, g: GraphObject, *, nodeplus=None, arcplus=None, training: bool = False) -> tuple[int, tf.Tensor, tf.Tensor]:\r\n pass\r\n\r\n\r\n ## HISTORY METHOD #################################################################################################\r\n def printHistory(self) -> None:\r\n \"\"\" print self.history as a pd.Dataframe. Pandas automatically detects terminal width, so do not print dataframe.to_string() \"\"\"\r\n # CLEAR CONSOLE - only if in terminal, not in a pycharm-like software\r\n # os.system('cls' if os.name == 'nt' else 'clear')\r\n p = DataFrame(self.history)\r\n print(p, end='\\n\\n')\r\n\r\n\r\n ## EVALUATE METHODs ###############################################################################################\r\n def evaluate_single_graph(self, g: GraphObject, class_weights: Union[int, float, list[float]], training: bool) -> tuple:\r\n \"\"\" evaluate method for evaluating one graph single graph. Returns iteration, loss, target and output \"\"\"\r\n pass\r\n\r\n # -----------------------------------------------------------------------------------------------------------------\r\n def evaluate(self, g: Union[GraphObject, list[GraphObject]], class_weights: Union[int, float, list[float]]) -> tuple:\r\n \"\"\" return ALL the metrics in self.extra_metrics + Iter & Loss for a GraphObject or a list of GraphObjects\r\n :param g: element/list of GraphObject to be evaluated\r\n :param class_weights: (list) [w0, w1,...,wc] for classification task, specify the weight for weighted loss\r\n :return: metrics, float(loss) target_labels, prediction_labels, targets_raw and prediction_raw,\r\n \"\"\"\r\n # chech if inputs are GraphObject OR list(s) of GraphObject(s)\r\n if not (type(g) == GraphObject or (type(g) == list and all(isinstance(x, GraphObject) for x in g))):\r\n raise TypeError('type of param must be GraphObject or list of GraphObjects')\r\n if type(g) == GraphObject: g = [g]\r\n \r\n # process input data\r\n iters, losses, targets, outs = zip(*[self.evaluate_single_graph(i, class_weights, training=False) for i in g])\r\n \r\n # concatenate all the values from every graph and take clas labels or values\r\n loss = tf.concat(losses, axis=0)\r\n targets = tf.concat(targets, axis=0)\r\n y_score = tf.concat(outs, axis=0)\r\n y_true = tf.argmax(targets, axis=1) if self.addressed_problem == 'c' else targets\r\n y_pred = tf.argmax(y_score, axis=1) if self.addressed_problem == 'c' else y_score\r\n \r\n # evaluate metrics\r\n metr = {k: float(self.extra_metrics[k](y_true, y_pred, **self.mt_args.get(k, dict()))) for k in self.extra_metrics}\r\n metr['It'] = int(tf.reduce_mean(iters))\r\n metr['Loss'] = float(tf.reduce_mean(loss))\r\n return metr, metr['Loss'], y_true, y_pred, targets, y_score\r\n\r\n\r\n ## TRAINING METHOD ################################################################################################\r\n def train(self, gTr: Union[GraphObject, list[GraphObject]], epochs: int, gVa: Union[GraphObject, list[GraphObject], None] = None,\r\n update_freq: int = 10, max_fails: int = 10, class_weights: Union[int, list[float]] = 1,\r\n *, mean: bool = False, serial_training : bool = False, verbose: int = 3) -> None:\r\n \"\"\" TRAIN PROCEDURE\r\n :param gTr: GraphObject or list of GraphObjects used for the learning procedure\r\n :param epochs: (int) the max number of epochs for the learning procedure\r\n :param gVa: element/list of GraphsObjects for early stopping. Default None, no early stopping performed\r\n :param update_freq: (int) how many epochs must be completed before evaluating gVa and gTr and/or print learning progress. Default 10.\r\n :param max_fails: (int) specifies the max number of failures before early sopping. Default 10.\r\n :param class_weights: (list) [w0, w1,...,wc] in classification task when targets are 1-hot, specify the weight for weighted loss. Default 1.\r\n :param mean: (bool) if False the applied gradients are computed as the sum of every iteration, otherwise as the mean. Default True.\r\n :param verbose: (int) 0: silent mode; 1: print history; 2: print epochs/batches, 3: history + epochs/batches. Default 3.\r\n :return: None\r\n \"\"\"\r\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n def update_history(name: str, val: dict[str, float]) -> None:\r\n \"\"\" update self.history with a dict s.t. val.keys()==self.history.keys()^{'Epoch','Best Loss Va'} \"\"\"\r\n # name must be 'Tr' or 'Va', to update correctly training or validation history\r\n if name not in ['Tr', 'Va']: raise TypeError('param must be \\'Tr\\' or \\'Va\\'')\r\n for key in val: self.history['{} {}'.format(key, name)].append(val[key])\r\n\r\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n def checktype(elem: Optional[Union[GraphObject, list[GraphObject]]]) -> list[GraphObject]:\r\n \"\"\" check if type(elem) is correct. If so, return None or a list og GraphObjects \"\"\"\r\n if elem is None: pass\r\n elif type(elem) == GraphObject: elem = [elem]\r\n elif isinstance(elem, (list, tuple)) and all(isinstance(x, GraphObject) for x in elem): elem = list(elem)\r\n else: raise TypeError('Error - and/or are not GraphObject or LIST/TUPLE of GraphObjects')\r\n return elem\r\n\r\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n def reset_validation(valid_loss: float) -> tuple[float, int, list[list[array]], list[list[array]]]:\r\n \"\"\" inner-method used to reset the validation check parameters and to save the 'best weights until now' \"\"\"\r\n wst, wout = self.get_weights()\r\n return valid_loss, 0, wst, wout\r\n\r\n # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\r\n def training_step(gTr: GraphObject, mean: bool) -> None:\r\n \"\"\" compute the gradients and apply them \"\"\"\r\n with tf.GradientTape() as tape:\r\n iter, loss, *_ = self.evaluate_single_graph(gTr, class_weights, training=True)\r\n wS, wO = self.trainable_variables()\r\n dwbS, dwbO = tape.gradient(loss, [wS, wO])\r\n # average net_state dw and db w.r.t. the number of iteration.\r\n if mean: dwbS = [[j / it for j in i] for it, i in zip([iter] if type(iter) != list else iter, dwbS)]\r\n # apply gradients\r\n zipped = zip([i for j in dwbS + dwbO for i in j], [i for j in wS + wO for i in j])\r\n self.optimizer.apply_gradients(zipped)\r\n\r\n ### TRAINING FUNCTION -----------------------------------------------------------------------------------------\r\n if verbose not in range(4): raise ValueError('param not in [0,1,2,3]')\r\n\r\n # Checking type for gTr and gVa + Initialization of Validation parameters\r\n gTr, gVa = checktype(gTr), checktype(gVa)\r\n\r\n # initialize history attribute and writer directory\r\n if not self.history:\r\n keys = ['Epoch'] + [i + j for i in ['It', 'Loss'] + list(self.extra_metrics) for j in ([' Tr', ' Va'] if gVa else [' Tr'])]\r\n if gVa: keys += ['Fail', 'Best Loss Va']\r\n self.history.update({i: list() for i in keys})\r\n os.makedirs(self.path_writer)\r\n\r\n # Writers: Training, Validation (scalars) + Net_state, Net_output (histogram for weights/biases)\r\n netS_writer = tf.summary.create_file_writer(self.path_writer + 'Net - State')\r\n netO_writer = tf.summary.create_file_writer(self.path_writer + 'Net - Output')\r\n trainining_writer = tf.summary.create_file_writer(self.path_writer + 'Training')\r\n if gVa:\r\n lossVa = self.history['Best Loss Va'][-1] if self.history['Best Loss Va'] else float(1e30)\r\n vbest_loss, vfails, ws, wo = reset_validation(lossVa)\r\n validation_writer = tf.summary.create_file_writer(self.path_writer + 'Validation')\r\n\r\n # pre-Training procedure: check if it's the first learning time to correctly update tensorboard\r\n initial_epoch = self.history['Epoch'][-1] + 1 if self.history['Epoch'] else 0\r\n epochs += initial_epoch\r\n\r\n ### TRAINING PROCEDURE\r\n for e in range(initial_epoch, epochs):\r\n\r\n # TRAINING STEP\r\n for i, elem in enumerate(gTr):\r\n training_step(elem, mean=mean)\r\n if verbose > 2: print(' > Epoch {:4d}/{} \\t\\t> Batch {:4d}/{}'.format(e, epochs, i + 1, len(gTr)), end='\\r')\r\n\r\n # TRAINING EVALUATION STEP\r\n if e % update_freq == 0:\r\n metricsTr, *_ = self.evaluate(gTr, class_weights)\r\n # History Update\r\n self.history['Epoch'].append(e)\r\n update_history('Tr', metricsTr)\r\n # TensorBoard Update Tr: Losses, Interation@Convergence, Accuracies + histograms of weights\r\n self.write_scalars(trainining_writer, metricsTr, e)\r\n for i, j, namespace in zip(*self.get_weights(), self.namespace):\r\n self.write_net_weights(netS_writer, namespace, 'N1', i, e)\r\n self.write_net_weights(netO_writer, namespace, 'N2', j, e)\r\n\r\n # VALIDATION STEP\r\n if (e % update_freq == 0) and gVa:\r\n metricsVa, lossVa, *_ = self.evaluate(gVa, class_weights)\r\n # Validation check\r\n if lossVa < vbest_loss: vbest_loss, vfails, ws, wo = reset_validation(lossVa)\r\n else: vfails += 1\r\n # History Update\r\n self.history['Best Loss Va'].append(vbest_loss)\r\n self.history['Fail'].append(vfails)\r\n update_history('Va', metricsVa)\r\n # TensorBoard Update Va: Losses, Interation@Convergence, Accuracies + histograms of weights\r\n self.write_scalars(validation_writer, metricsVa, e)\r\n # Early Stoping - reached max_fails for validation set\r\n if vfails >= max_fails:\r\n self.set_weights(ws, wo)\r\n print('\\r Validation Stop')\r\n break\r\n\r\n # PRINT HISTORY\r\n if (e % update_freq == 0) and verbose in [1, 3]: self.printHistory()\r\n else: print('\\r End of Epochs Stop')\r\n\r\n # Tensorboard Update FINAL: write BEST WEIGHTS + BIASES\r\n for i, j, namespace in zip(*self.get_weights(), self.namespace):\r\n self.write_net_weights(netS_writer, namespace, 'N1', i, e)\r\n self.write_net_weights(netO_writer, namespace, 'N2', j, e)\r\n\r\n\r\n ## TEST METHOD ####################################################################################################\r\n def test(self, gTe: Union[GraphObject, list[GraphObject]], *, acc_classes: bool = False, rocdir: str = '',\r\n micro_and_macro: bool = False, prisofsdir: str = '') -> dict[str, list[float]]:\r\n \"\"\" TEST PROCEDURE\r\n :param gTe: element/list of GraphObjects for testing procedure\r\n :param accuracy_class: (bool) if True print accuracy for classes\r\n :param rocdir: (str) path for saving ROC images file\r\n :param micro_and_macro: (bool) for computing micro and macro average quantities in roc curve\r\n :param prisofsdir: (str) path for saving Precision-Recall curve with ISO F-Score images file\r\n :return: metrics for gTe\r\n \"\"\"\r\n if type(gTe) != GraphObject and not (type(gTe) == list and all(isinstance(x, GraphObject) for x in gTe)):\r\n raise TypeError('type of param must be GraphObject or list of GraphObjects')\r\n if not all(isinstance(x, str) for x in [rocdir, prisofsdir]):\r\n raise TypeError('type of params and must be str')\r\n\r\n # Evaluate all the metrics in gnn.extra_metrics + Iter and Loss\r\n metricsTe, lossTe, y_true, y_pred, targets, y_score = self.evaluate(gTe, class_weights=1)\r\n\r\n # Accuracy per Class: shape = (1,number_classes)\r\n if acc_classes and self.addressed_problem == 'c':\r\n accuracy_classes = mt.accuracy_per_class(y_true, y_pred)\r\n metricsTe['Acc Classes'] = accuracy_classes\r\n\r\n # ROC e PR curves\r\n if rocdir: mt.ROC(targets, y_score, rocdir, micro_and_macro)\r\n if prisofsdir: mt.PRISOFS(targets, y_score, prisofsdir)\r\n return metricsTe\r\n\r\n\r\n ## K-FOLD CROSS VALIDATION METHOD #################################################################################\r\n def LKO(self, dataset: Union[list[GraphObject], list[list[GraphObject]]], number_of_batches: int = 10, useVa: bool = False,\r\n seed: Optional[float] = None, normalize_method: str = 'gTr', node_aggregation: str='average', acc_classes: bool = False,\r\n epochs: int = 500, update_freq: int = 10, max_fails: int = 10, class_weights: Union[int, float, list[Union[float, int]]] = 1,\r\n mean: bool = True, serial_training: bool = False, verbose: int = 3) -> dict[str, list[float]]:\r\n \"\"\" LEAVE K OUT PROCEDURE\r\n :param dataset: (list) of GraphObject OR (list) of lists of GraphObject on which has to be valuated\r\n > NOTE: for graph-based problem, if type(dataset) == list of GraphObject,\r\n s.t. len(dataset) == number of graphs in the dataset, then i-th class will may be have different frequencies among batches\r\n [so the i-th class may me more present in a batch and absent in another batch].\r\n Otherwise, if type(dataset) == list of lists, s.t. len(dataset) == number of classes AND len(dataset[i]) == number of graphs\r\n belonging to i-th class, then i-th class will have the same frequency among all the batches\r\n [so the i-th class will be as frequent in a single batch as in the entire dataset].\r\n :param node_aggregation: (str) for node aggregation method during dataset creation. See GraphObject for details\r\n :param number_of_batches: (int) define how many batches will be considered in LKO procedure\r\n :param seed: (int or None) for fixed-shuffle options\r\n :param normalize_method: (str) in ['','gTr,'all'], see normalize_graphs for details. If equal to '', no normalization is performed\r\n :param verbose: (int) 0: silent mode; 1:print epochs/batches; 2: print history; 3: history + epochs/batches\r\n :param acc_classes: (bool) return or not the accuracy for each class in metrics\r\n :param epochs: (int) number of epochs for training , the gnn will be trained for all the epochs\r\n :param Va: (bool) if True, Early Stopping is considered during learning procedure; None otherwise\r\n :param update_freq: (int) specifies how many epochs must be completed before evaluating gVa and gTr\r\n :param max_fails: (int) specifies the max number of failures before early sopping\r\n :param class_weights: (list) [w0, w1,...,wc] for classification task, specify the weight for weighted loss\r\n :param mean: (bool) if False the applied gradients are computed as the sum of every iteration, else as the mean\r\n :return: a dict containing all the considered metrics in .history\r\n \"\"\"\r\n from GNN.GNN_utils import normalize_graphs, getbatches\r\n from numpy import random\r\n\r\n # classification vs regression LKO problem: see :param dataset: for details\r\n if all(isinstance(i, GraphObject) for i in dataset): dataset = [dataset]\r\n\r\n # Shuffling procedure: fix/not fix seed parameter, then shuffle classes and/or elements in each class/dataset\r\n if seed: random.seed(seed)\r\n random.shuffle(dataset)\r\n for i in dataset: random.shuffle(i)\r\n\r\n # Dataset creation, based on param \r\n if useVa: number_of_batches += 1\r\n dataset_batches = [getbatches(elem, node_aggregation, -1, number_of_batches, one_graph_per_batch=False) for i, elem in enumerate(dataset)]\r\n flatten = lambda l: [item for sublist in l for item in sublist]\r\n flattened = [flatten([i[j] for i in dataset_batches]) for j in range(number_of_batches)]\r\n\r\n # shuffle again to mix classes inside batches, so that i-th class does not appears there at the same position\r\n for i in flattened: random.shuffle(i)\r\n\r\n # Final dataset for LKO procedure: merge graphs belonging to classes/dataset to obtain 1 GraphObject per batch\r\n dataset = [GraphObject.merge(i, node_aggregation=node_aggregation) for i in flattened]\r\n\r\n # initialize results\r\n metrics = {i: list() for i in list(self.extra_metrics) + ['It', 'Loss']}\r\n if acc_classes: metrics['Acc Classes'] = list()\r\n\r\n # LKO PROCEDURE\r\n len_dataset = len(dataset) - (1 if useVa else 0)\r\n for i in range(len_dataset):\r\n\r\n # split dataset in training/validation/test set\r\n gTr = dataset.copy()\r\n gTe = gTr.pop(i)\r\n gVa = gTr.pop(-1) if useVa else None\r\n\r\n # normalization procedure\r\n if normalize_method: normalize_graphs(gTr, gVa, gTe, based_on=normalize_method)\r\n\r\n # gnn creation, learning and test\r\n print('\\nBATCH K-OUT {0}/{1}'.format(i + 1, len_dataset))\r\n temp = self.copy(copy_weights=False, path_writer=self.path_writer + str(i), namespace='Batch {}-{}'.format(i+1, len(dataset)))\r\n temp.train(gTr, epochs, gVa, update_freq, max_fails, class_weights, mean=mean, serial_training=serial_training, verbose=verbose)\r\n M = temp.test(gTe, acc_classes=acc_classes)\r\n\r\n # evaluate metrics\r\n for m in M: metrics[m].append(M[m])\r\n return metrics\r\n\r\n\r\n ## STATIC METHODs #################################################################################################\r\n @staticmethod\r\n def ArcNode2SparseTensor(ArcNode) -> tf.Tensor:\r\n \"\"\" get the transposed sparse tensor of the ArcNode matrix \"\"\"\r\n # ArcNode Tensor, then reordered to be correctly computable. NOTE: reorder() recommended by TF2.0+\r\n indices = [[ArcNode.row[i], ArcNode.col[i]] for i in range(ArcNode.shape[0])]\r\n arcnode = tf.SparseTensor(indices, values=ArcNode.data, dense_shape=ArcNode.shape)\r\n arcnode = tf.sparse.transpose(arcnode)\r\n arcnode = tf.sparse.reorder(arcnode)\r\n arcnode = tf.cast(arcnode, dtype=tf.float32)\r\n return arcnode\r\n\r\n # -----------------------------------------------------------------------------------------------------------------\r\n @staticmethod\r\n def write_scalars(writer: tf.summary.SummaryWriter, metrics: dict[str, float], epoch: int) -> None:\r\n \"\"\" TENSORBOARD METHOD: writes scalars values of the metrics \"\"\"\r\n if type(metrics) != dict: raise TypeError('type of param must be dict')\r\n names = {'Acc': 'Accuracy', 'Bacc': 'Balanced Accuracy', 'Ck': 'Cohen\\'s Kappa', 'Js': 'Jaccard Score',\r\n 'Fs': 'F1-Score', 'Prec': 'Precision Score', 'Rec': 'Recall Score', 'Tpr': 'TPR', 'Tnr': 'TNR',\r\n 'Fpr': 'FPR', 'Fnr': 'FNR', 'Loss': 'Loss', 'It': 'Iteration @ Convergence'}\r\n\r\n namescopes = {**{i: 'Accuracy & Loss' for i in ['Acc', 'Bacc', 'It', 'Loss']},\r\n **{i: 'F-Score, Precision and Recall' for i in ['Fs', 'Prec', 'Rec']},\r\n **{i: 'Positive and Negative Rates' for i in ['Tpr', 'Tnr', 'Fpr', 'Fnr']},\r\n **{i: 'Other Scores' for i in ['Ck', 'Js']}}\r\n\r\n with writer.as_default():\r\n for i in metrics:\r\n with tf.name_scope(namescopes[i]):\r\n tf.summary.scalar(names[i], metrics[i], step=epoch, description=names[i])\r\n\r\n # -----------------------------------------------------------------------------------------------------------------\r\n @staticmethod\r\n def write_net_weights(writer: tf.summary.SummaryWriter, namespace: str, net_name: str, val_list: list[array], epoch: int) -> None:\r\n \"\"\" TENSORBOARD METHOD: writes histograms of the nets weights \"\"\"\r\n W, B, names_layers = val_list[0::2], val_list[1::2], ['{} L{}'.format(net_name, i) for i in range(len(val_list)//2)]\r\n assert len(names_layers) == len(W) == len(B)\r\n\r\n with writer.as_default():\r\n for n, w, b in zip(names_layers, W, B):\r\n with tf.name_scope('{}: Weights'.format(namespace)):\r\n tf.summary.histogram(n, w, step=epoch)\r\n with tf.name_scope('{}: Biases'.format(namespace)):\r\n tf.summary.histogram(n, b, step=epoch)\r\n","sub_path":"GNN/GNN_BaseClass.py","file_name":"GNN_BaseClass.py","file_ext":"py","file_size_in_byte":23916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"588774213","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom flask import Flask, request, abort, Response\n\nfrom linebot import (\n\tLineBotApi, WebhookHandler\n)\nfrom linebot.exceptions import (\n\tInvalidSignatureError , LineBotApiError\n)\nfrom linebot.models import (\n\tMessageEvent, TextMessage, ImageMessage, TextSendMessage,ImageSendMessage\n)\n\nimport logging, sys\nimport json\nimport re,requests\nimport datetime\nfrom dateutil import relativedelta\nfrom big_down.quick_prediction import prediction, genset_model\nfrom big_down.graph_name import get_name_price,gen_graph\nimport os\n\n\n\nmodel_dic = {}\nmodel_dic.update({\"category\":genset_model(\"big_category\")})\nmodel_dic.update({\"時計\":genset_model(\"watch\")})\nmodel_dic.update({\"バッグ\":genset_model(\"bag\")})\nmodel_dic.update({\"ジュエリー\":genset_model(\"juery\")})\n\ngenre_path_dic = {\"category\":\"big_category\",\n\t\t\"時計\":\"watch\",\n\t\t\"バッグ\":\"bag\",\n\t\t\"ジュエリー\":\"juery\"}\n\napp = Flask(__name__)\n\n\n@app.route(\"/fltest\")\ndef fltest():\n import keras\n return \"Hello flask !! from fltest second\"\n\n\n@app.route('/flpost', methods=['GET','POST'])\ndef test_post():\n return request.method\n\n@app.route(\"/prediction\", methods=['GET','POST'])\ndef get_prediction():\n\tgenre = \"category\"\n\tthe_file = request.files['file']\n\timage_path = os.path.join(\"/tmp\",\"webAPI\",the_file.filename)\n\tthe_file.save(image_path)\n\tgenre = prediction(image_path,model_dic[genre],genre_path_dic[genre])[0][0]\n\tif genre not in genre_path_dic:\n\t\treturn json.dumps({\"genre\":genre})\n\telse:\n\t\tresults = prediction(image_path,model_dic[genre],genre_path_dic[genre])\n\t\tresults_dic = {\"genre\":genre,\"result_ids\":[]}\n\t\tfor result in results:\n\t\t\tresults_dic[\"result_ids\"].append(result[0])\n\t\treturn json.dumps(results_dic)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\",port=80)\n","sub_path":"image_recognition_API.py","file_name":"image_recognition_API.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"237634930","text":"import Queue\nimport threading\n\nclass MessageBusException(Exception):\n def __init__(self, msg):\n self.msg = msg\n\n def __str__(self):\n return self.msg\n\nclass NoSuchModuleException(MessageBusException):\n pass\n \nclass ModuleAlreadyRegisteredException(MessageBusException):\n pass\n\nclass NoSuchGroupException(MessageBusException):\n pass\n\nclass GroupAlreadyRegisteredException(MessageBusException):\n pass\n \nclass MessageBus:\n\n def __init__(self):\n '''\n Constructor for the MessageBus.\n '''\n # -----------------------------------------------------------------------------\n # _registered_modules - A list of the string names of all modules currently\n # registered with the MessageBus.\n # -----------------------------------------------------------------------------\n self._registered_modules = []\n\n # -----------------------------------------------------------------------------\n # _module_callbacks - A dictionary mapping string module names to callback\n # functions to be called when a message is to be sent to a module.\n # -----------------------------------------------------------------------------\n self._module_callbacks = {}\n\n # -----------------------------------------------------------------------------\n # _module_response_queue - An instance of Queue.Queue that the MessageBus\n # will listen to in order to capture the responses of modules to the message\n # that are sent to them. The queue is thread safe.\n # -----------------------------------------------------------------------------\n self._module_response_queue = Queue.LifoQueue()\n\n # -----------------------------------------------------------------------------\n # _is_listening - A boolean value representing whether or not the MessageBus is\n # still listening for responses from the modules.\n # -----------------------------------------------------------------------------\n self._is_listening = True\n\n # -----------------------------------------------------------------------------\n # self._module_groups - A dictionary of lists. The keys of the dictionary\n # are the names of \"module groups\" - message types that modules can subscribe\n # to. If _module_groups[HELLO_MESSAGE] = [EchoModule], then EchoModule will\n # receive all messages of type HELLO_MESSAGE that come through the message\n # bus.\n # -----------------------------------------------------------------------------\n self._module_groups = {}\n \n\n def send(self, message):\n '''\n Sends a message to the bus. If the message has a \"type\" field, then it\n will be routed to all modules subscribed to that type. Otherwise, the\n message will just be sent to everybody.\n\n @param message - The message to be sent to the bus\n @returns Nothing.\n @throws NoSuchGroupException if the message has a type and the type hasn't\n been registered with the bus.\n '''\n if hasattr(message, \"type\"):\n # send to all modules registered to the type of the message\n if not message.type in self._module_groups:\n raise NoSuchGroupException('Message type {} not registered with the bus'.format(message.type))\n for module in self._module_groups[message.type]:\n self._dispatch_callback(module, message)\n else:\n for module in self._registered_modules:\n self._dispatch_callback(module, message)\n\n def register(self, name, callback_function):\n '''\n Register registers a module and a callback function with the message bus. The\n callback function is called by the MessageBus when there is a message that\n is to be sent.\n\n @param name [string] - The name of the module to be registered\n @param callback_function [function] - A function of the form func(INPUT_MSG, Queue.Queue),\n where INPUT_MSG is the message that the bus will send to the callback\n function, and Queue.Queue is an instance of the python Queue.Queue class. When\n the callback function completes processing of the input message, it will\n put its response on the queue.\n @returns Nothing.\n @throws ModuleAlreadyRegisteredException - if the module has already been registered.\n '''\n if self.has_module(name):\n raise ModuleAlreadyRegisteredException(\"{} has already been registered\".format(name))\n\n # if the module hasn't already been registered, register it\n self._registered_modules.append(name)\n self._module_callbacks[name] = callback_function\n\n def register_group(self, group_name):\n '''\n Registers a new group for the MessageBus. All messages with this group will\n be routed only to modules subscribed to that group.\n\n @param group_name - The name of the group to be added\n @returns Nothing.\n @throws GroupAlreadyRegisteredException if the group already exists.\n '''\n if group_name in self._module_groups.keys():\n raise GroupAlreadyRegisteredException(\"Group {} already exists\".format(group_name))\n self._module_groups[group_name] = []\n\n def unregister(self, module):\n '''\n Unregisters a module from the MessageBus.\n\n @param module - The module to be removed\n @throws NoSuchModuleException - if the module doesn't exist\n '''\n if not self.has_module(module):\n raise NoSuchModuleException(\"Module {} not registered with bus\".format(module))\n self._registered_modules.remove(module)\n\n def unregister_group(self, group):\n '''\n Unregisters a group from the MessageBus. BE WARNED, if the only group that a module\n is subscribed to is unregistered, that module won't get any messages!\n\n @param group - The group to be unregistered\n @throws NoSuchGroupException - if the group doesn't exist\n '''\n if not self.has_group(group):\n raise NoSuchGroupException(\"Group {} not registered with bus\".format(group))\n self._module_groups.pop(group, None)\n\n def get_modules_in_group(self, group):\n '''\n Returns a list of modules currently subscribed to a group.\n\n @param group - The group to use\n @returns A list of modules currently subscribed to that group\n @throws NoSuchGroupException if the group isn't registered with the bus.\n '''\n if not self.has_group(group):\n raise NoSuchGroupException(\"Group {} not registered with bus\".format(group))\n return self._module_groups[group]\n\n def add_module_to_group(self, module, group):\n '''\n Adds a module to a group. All messages with the type equal to the group\n are routed to this module.\n\n @param module - The module to add to the group\n @param group - The name of the group\n @returns Nothing.\n @throws NoSuchModuleException - If the module isn't registered with the bus\n @throws NoSuchGroupException - If the group isn't registered with the bus\n '''\n if not self.has_module(module):\n raise NoSuchModuleException(\"Module {} not registered with bus\".format(module))\n if not self.has_group(group):\n raise NoSuchGroupException(\"Group {} not registered with bus\".format(group))\n self._module_groups[group].append(module)\n\n def has_module(self, module):\n '''\n Returns whether or not the param module is registered with the bus.\n\n @param module - The module to check\n @returns boolean, whether or not the module is registered\n '''\n return module in self._registered_modules\n\n def has_group(self, group):\n '''\n Returns whether or not the param group is registered with the bus.\n\n @param group - The group to check\n @returns boolean, whether or not the module is registered\n '''\n return group in self._module_groups.keys()\n\n def get_subscriptions(self, module):\n '''\n Returns the groups that module is subscribed to.\n\n @param module - The module to check\n @returns A list of groups that the module is subscribed to\n '''\n output_list = []\n if not self.has_module(module):\n raise NoSuchModuleException(\"Module {} not registered with the bus\")\n for group, group_sub_list in self._module_groups:\n if module in group_sub_list:\n output_list.append(group)\n return output_list\n\n \n def listen_for_responses(self):\n '''\n Listen_for_responses waits on the event queue, and does one of two things\n depending on how the bus was constructed:\n 1) If the MessageBus was created with an ouput argument, the response\n will be output directly to that socket.\n 2) If the MessageBus was not created with an output argument (that is,\n self._output_stream == None), this function yields the captured\n response.\n\n It is advised to run this in a separate thread then the rest of the MessageBus.\n '''\n while self._is_listening:\n response_event = self._module_response_queue.get()\n yield response_event\n self._module_response_queue.task_done()\n\n def poll_for_responses(self):\n '''\n Polls the event queue once, and if there isn't anything in the queue, return None.\n\n @returns An element of the event queue, or None if empty.\n '''\n try:\n response = self._module_response_queue.get_nowait()\n except Queue.Empty:\n response = None\n else:\n self._module_response_queue.task_done()\n return response\n\n def stop_listening(self):\n '''\n Stop listening for responses.\n '''\n self._is_listening = False\n\n def _dispatch_callback(self, module, message):\n '''\n Dispatches a thread to call the callback function. This function is\n not sanity checked for speed.\n\n @param module - The name of the module whose callback will be called\n @param message - The message to be sent\n '''\n callback_func = self._module_callbacks[module]\n dispatch_thread = threading.Thread(target=callback_func,\n args=(message, self._module_response_queue))\n dispatch_thread.start()\n\n \n ","sub_path":"src/messagebus.py","file_name":"messagebus.py","file_ext":"py","file_size_in_byte":10666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"253148861","text":"# @welcome()\n# It works with welcome screen\n\ndef welcome():\n\n print('\\nBem-vindo ao jogodo NIM! Escolha : \\n')\n\n\n# @menu()\n# and menu selecting the type of departure of the user.\n# Is return a boolean, being true for isolated start, and false for championship\n\ndef menu():\n\n option = int(input('1 - para jogar uma partida isolada \\n2 - para jogar um campeonato '))\n\n return (option == 1)\n\t\n'''\n\nque recebe, como parâmetros, \nos números n e m descritos acima \ne devolve um inteiro correspondente \nà próxima jogada do computador de acordo com a estratégia vencedora.\n\n'''\n\n#arrumar este trem, esta dano erro\n\ndef computador_escolhe_jogada(n,m):\n\n n = n - m\n print('\\nComputador retirou ', m, 'peça(s) do jogo, restam ', n)\n return n\n\n\n'''\n\nque recebe os mesmos parâmetros, \nsolicita que o jogador informe sua jogada \ne verifica se o valor informado é válido. \nSe o valor informado for válido, \na função deve devolvê-lo; \ncaso contrário, deve solicitar novamente ao usuário que informe uma jogada válida.\n\n'''\n\n\ndef usuario_escolhe_jogada(n,m):\n\t\n\ttest = True\n\n\twhile (test):\n\t\t\n\t\tplayed = int (input('\\nQuantas peças você vai tirar? '))\n\n\t\tif ((played <= m) and (n - played > 0) ):\n\t\t\tbreak\n\t\telse : \n\t\t\tprint('Oops! Jogada inválida! Tente de novo.')\n\n\treturn played\n\n'''\n\nque não recebe nenhum parâmetro, \nsolicita ao usuário que informe os valores de n e m \ne inicia o jogo, \nalternando entre jogadas do computador e do usuário \n(ou seja, chamadas às duas funções anteriores). \nA escolha da jogada inicial deve ser feita em função da estratégia vencedora, \ncomo dito anteriormente. \nA cada jogada, deve ser impresso na tela o estado atual do jogo, \nou seja, quantas peças foram removidas na última jogada \ne quantas restam na mesa. Quando a última peça é removida, \nessa função imprime na tela \na mensagem \"O computador ganhou!\" ou \"Você ganhou!\" conforme o caso.\n\n\n'''\ndef partida(numberPerGame,maximumPerShift) :\n\n\t#actual = numberPerGame\n\ttemp = 0\n\tturn = True\n\t\n\twhile (numberPerGame != 0) :\n\n\t\tif (turn) :\n\t\t\t\n\t\t\ttemp = usuario_escolhe_jogada(numberPerGame,maximumPerShift)\n\t\t\tnumberPerGame = numberPerGame - temp \n\n\t\t\tprint(\"Você tirou\",temp,\" peças\")\n\t\t\tprint(\"Agora resta apenas\",numberPerGame,\" peça no tabuleiro.\")\n\n\t\t\tif (numberPerGame == 1):\n\t\t\t\tprint('Fim do jogo! Você ganhou!')\n\t\t\t\treturn True\n\t\t\t\tbreak\n\n\t\t\tturn = False\n\n\t\telse :\n\n\t\t\ttemp = computador_escolhe_jogada(numberPerGame,maximumPerShift)\n\t\t\tnumberPerGame = numberPerGame - temp \n\n\t\t\tprint(\"O computador tirou\",temp,\" peças\")\n\t\t\tprint(\"Agora resta apenas\",numberPerGame,\" peça no tabuleiro.\")\n\n\t\t\tif (numberPerGame == 1):\n\t\t\t\tprint('Fim do jogo! O computador ganhou!')\n\t\t\t\treturn False\n\t\t\t\tbreak\n\n\t\t\tturn = True\n\n\n#---------------------------------------------------------------------------------\n# ----------------------------------- CALLS --------------------------------------\n#---------------------------------------------------------------------------------\n\nwelcome()\n\nif ( menu() ) :\n\n print('\\nVocê escolheu um partida isolada! ')\n\n n = 0\n m = 1\n\n while(n < m):\n \tn = int(input('\\nQuantas peças? '))\n \tm = int(input('Limite de peças por jogada? '))\n\n if (partida(n,m)) :\n \tprint('voce ganhou')\n else :\n \tprint('o computador ganhou')\n\nelse :\n\n\tprint('\\nVocê escolheu um campeonato! ')\n\n\tcomputer = 0\n\tyou = 0\n\tgames = 0 \n\n\tn = 0\n\tm = 1\n\t\n\twhile(n < m):\n\t\tn = int(input('\\nQuantas peças? '))\n\t\tm = int(input('Limite de peças por jogada? '))\n\n\twhile (games < 3):\n\t\t\n\t\tif (partida(n,m)) :\n\n\t\t\tyou = you + 1\n\t\t\t\n\t\telse :\n\n\t\t\tcomputer = computer + 1\n\n\t\tgames = games + 1 \n\n\tprint('Placar: Você',you,' X ',computer,' Computador')\n\n\n","sub_path":"inicial/4_Function/nim2.py","file_name":"nim2.py","file_ext":"py","file_size_in_byte":3709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"182475163","text":"# Regression test based on linear wave convergence problem\n# for full radiation hydro equations, using the\n# explicit radiation hydro module and AMR\n\n# Modules\nimport logging\nimport scripts.utils.athena as athena\nimport sys\nsys.path.insert(0, '../../vis/python')\nimport athena_read # noqa\nathena_read.check_nan_flag = True\nlogger = logging.getLogger('athena' + __name__[7:]) # set logger name based on module\n\n\n# Prepare Athena++\ndef prepare(**kwargs):\n logger.debug('Running test ' + __name__)\n athena.configure('nr_radiation',\n prob='rad_linearwave',\n coord='cartesian',\n flux='hllc', **kwargs)\n athena.make()\n\n\n# Run Athena++\ndef run(**kwargs):\n # L-going fast wave (set by default in input)\n arguments = ['time/cfl_number=0.3', # default =0.4, but tolerances measured w/ 0.3\n 'time/ncycle_out=100'\n ]\n athena.run('radiation/athinput.rad_linearwave_amr', arguments)\n\n\n# Analyze outputs\ndef analyze():\n # read data from error file\n filename = 'bin/linearwave-errors.dat'\n data = []\n with open(filename, 'r') as f:\n raw_data = f.readlines()\n for line in raw_data:\n if line.split()[0][0] == '#':\n continue\n data.append([float(val) for val in line.split()])\n\n if data[0][4] > 1.05e-8:\n print(\"error in regime 8: \", data[0][4])\n return False\n\n return True\n","sub_path":"tst/regression/scripts/tests/nr_radiation/amr_linwave.py","file_name":"amr_linwave.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"62644267","text":"import os\nimport re\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom IPython.display import display, HTML\nimport math\nimport time\n\ndef animal_read(inpath, filename, sheet):\n '''\n Returns corresponding animals for sheets\n Reads data into dataframe with long header removed.\n Uses correct labels as column labels.\n Uses time as row indexes.\n '''\n filepath = os.path.join(inpath,filename)\n try:\n df = pd.read_excel(filepath,sheetname=sheet,skip_footer=35,index_col=0)\n except:\n return(-1,-1,-1)\n\n anim_loc = df.index.get_loc('Animal ID')\n animal = df.iloc[anim_loc][0]\n\n ctx_loc = df.index.get_loc('Trial Control settings')\n context = df.iloc[ctx_loc][0]\n\n skiprows = df.index.get_loc('Trial time') + 1\n print(\"{} {} is {} in {}\".format(filename, sheet, animal, context))\n\n df = pd.read_excel(filepath,sheetname=sheet,skiprows=skiprows,index_col=0,headers=0)\n df = df[1:]\n df.replace(to_replace='-',value=0,inplace=True)\n return(animal,context,df)\n\ndef find_tones(df, ntones):\n '''\n Creates dictionary of each tone. Values are\n dataframes for times at which each tone == 1.\n '''\n tones = {}\n i = 1\n while i <= ntones: # number of tones\n num = str(i)\n try:\n label = 'Tone ' + num\n tone = pd.DataFrame(df[df[label] == 1])\n except:\n label = 'Tone' + num\n tone = pd.DataFrame(df[df[label] == 1])\n tones[i] = tone\n i += 1\n return(tones)\n# TODO -- Create an equivilent function (e.g. find_baseline) to get the first two minutes of the recording IOT calculate baseline freezing\ndef find_baseline(df):\n '''\n Creates a dictionary of the first 120 seconds\n of the recording in order to calculate\n baseline freezing.\n '''\n baseline = {}\n label = 'Recording time'\n baseline = df[df[label]<=120.000]\n return(baseline)\n \ndef find_pretones(df, ntones):\n '''\n Creates dictionary of each pretone. Values\n are dataframes for 30s before tone == 1\n '''\n pretones = {}\n i = 1\n while i<= ntones:\n num = str(i)\n try:\n label = 'Tone ' + num #Column label for each tone\n tone = df[df[label] == 1] #Tone dataframe\n except:\n label = 'Tone' + num #Column label for each tone\n tone = df[df[label] == 1] #Tone dataframe\n\n tonestart = tone.iloc[0] #Time for tone start\n\n starttime = math.floor(tonestart['Recording time']-30) #Time for pretone start\n endtime = math.floor(tonestart['Recording time']) #Time for pretone end\n itime = df.index.get_loc(starttime,method='bfill') #Index for pretone start\n etime = df.index.get_loc(endtime,method='bfill') #Index for pretone end\n\n pretone = df.iloc[itime:etime] #df for pretone\n pretones[i] = pretone #dictionary for all pretones\n i += 1\n return(pretones)\n\ndef find_shock_responses(df, ntones):\n '''\n Creates dictionary of each shock response. Values\n are dataframes for 5s after tone == 1\n '''\n sresponses = {}\n i = 1\n while i<= ntones:\n num = str(i)\n try:\n label = 'Tone ' + num #Column label for each tone\n tone = df[df[label] == 1] #Tone dataframe\n except:\n label = 'Tone' + num #Column label for each tone\n tone = df[df[label] == 1] #Tone dataframe\n toneend = tone.iloc[-1] #Time for tone end\n\n starttime = math.floor(toneend['Recording time']) #Time for sresponse start\n endtime = math.floor(toneend['Recording time'] + 5) #Time for sresponse end\n itime = df.index.get_loc(starttime,method='bfill') #Index for sresponse start\n etime = df.index.get_loc(endtime,method='bfill') #Index for sresponse end\n\n sresponse = df.iloc[itime:etime] #df for sresponse\n sresponses[i] = sresponse #dictionary for all sresponse\n i += 1\n return(sresponses)\n\ndef find_postshocks(df, ntones):\n '''\n Creates dictionary of each postshock. Values\n are dataframes for 5s to 30s after tone == 1\n '''\n pshocks = {}\n i = 1\n while i<= ntones:\n num = str(i)\n try:\n label = 'Tone ' + num #Column label for each tone\n tone = df[df[label] == 1] #Tone dataframe\n except:\n label = 'Tone' + num #Column label for each tone\n tone = df[df[label] == 1] #Tone dataframe\n toneend = tone.iloc[-1] #Time for tone end\n\n #starttime = math.floor(toneend['Recording time'] + 5) #Time for pshock start\n #endtime = math.floor(toneend['Recording time'] + 35) #Time for pshock end\n starttime = math.floor(toneend['Recording time'] + 0) #Time for pshock start\n endtime = math.floor(toneend['Recording time'] + 15) #Time for pshock end\n itime = df.index.get_loc(starttime,method='bfill') #Index for pshock start\n etime = df.index.get_loc(endtime,method='bfill') #Index for pshock end\n\n pshock = df.iloc[itime:etime] #df for pshock\n pshocks[i] = pshock #dictionary for all sresponse\n i += 1\n return(pshocks)\n\ndef get_means(datadict,timebin, ntones):\n '''\n Returns a dataframe of mean velocity of timebin at each tone.\n '''\n meanlist = []\n i = 1\n while i <= ntones:\n epoch = datadict[i]\n vels = epoch['Velocity']\n mean = round(np.mean(vels),3)\n meanlist.append(mean)\n i += 1\n means = pd.DataFrame(meanlist,columns=[timebin + ' Mean Velocity'])\n means.index = np.arange(1, len(meanlist) + 1)\n return(means)\n\ndef get_meds(datadict,timebin, ntones):\n '''\n Returns a dataframe of median velocity of timebin at each tone.\n '''\n medlist = []\n i = 1\n while i <= ntones:\n epoch = datadict[i]\n vels = epoch['Velocity']\n med = round(np.median(vels),3)\n medlist.append(med)\n i += 1\n meds = pd.DataFrame(medlist,columns=[timebin + ' Median Velocity'])\n meds.index = np.arange(1, len(meds) + 1)\n return(meds)\n\ndef get_SEMs(datadict,timebin, ntones):\n '''\n Returns a dataframe of median velocity of timebin at each tone.\n '''\n SEMlist = []\n i = 1\n while i <= ntones:\n epoch = datadict[i]\n vels = epoch['Velocity']\n SEM = round(np.std(vels),3)\n SEMlist.append(SEM)\n i += 1\n SEMs = pd.DataFrame(SEMlist,columns=[timebin + 'SEM'])\n SEMs.index = np.arange(1, len(SEMs) + 1)\n return(SEMs)\n\ndef get_vels(df, ntones):\n '''\n Creates data of all velocities from original dataframe for plotting.\n '''\n tonevels = {}\n i = 1\n while i <= ntones: # number of tones\n vels = []\n num = str(i)\n try:\n label = 'Tone ' + num\n tone = pd.DataFrame(df[df[label] == 1])\n except:\n label = 'Tone' + num\n tone = pd.DataFrame(df[df[label] == 1])\n vels.append(tone['Velocity'])\n tonevels[i] = vels\n i += 1\n return(tonevels)\n\ndef get_top_vels(datadict,nmax, ntones):\n '''\n Returns dataframe of nmax (int) maximum velocities for a timebin.\n The second section adds a column for an average of the maxima.\n '''\n nmaxes = pd.DataFrame()\n i = 1\n while i <= ntones:\n epoch = datadict[i]\n vels = epoch['Velocity']\n vlist = vels.tolist()\n vlist.sort()\n topvels = pd.DataFrame([vlist[-nmax:-1]])\n nmaxes = nmaxes.append(topvels)\n i += 1\n\n nmaxes.index = np.arange(1, nmaxes.shape[0] + 1)\n nmaxes.columns = np.arange(1, nmaxes.shape[1] + 1)\n\n nmaxes['Mean'] = nmaxes.mean(axis = 1)\n\n return(nmaxes)\n\ndef find_tone_vels(df,i):\n '''\n '''\n tone = pd.DataFrame()\n num = str(i)\n \n try:\n label = 'Tone ' + num\n tone = pd.DataFrame(df[df[label] == 1])\n except:\n label = 'Tone' + num\n tone = pd.DataFrame(df[df[label] == 1])\n \n tone = tone['Velocity']\n return(tone)\n\ndef find_shock_vels(df, i):\n '''\n '''\n sresponse = pd.DataFrame()\n num = str(i)\n try:\n label = 'Tone ' + num\n tone = df[df[label] == 1] #Tone dataframe\n except:\n label = 'Tone' + num\n tone = df[df[label] == 1] #Tone dataframe\n toneend = tone.iloc[-1] #Time for tone end\n\n starttime = math.floor(toneend['Recording time']) #Time for sresponse start\n endtime = math.floor(toneend['Recording time'] + 5) #Time for sresponse end\n itime = df.index.get_loc(starttime,method='bfill') #Index for sresponse start\n etime = df.index.get_loc(endtime,method='bfill') #Index for sresponse end\n\n sresponse = df.iloc[itime:etime] #df for sresponse\n sresponse = sresponse['Velocity']\n\n return(sresponse)\ndef get_baseline_freezing(datadict, freezingThreshold, binSecs):\n freezing = pd.DataFrame()\n freezingSecs = 0\n nonfreezingSecs = 0\n freezingTimes = []\n\n\n toneLabel = 'Baseline Freezing'\n\n epoch = datadict\n vels = epoch['Velocity']\n\n startSec = int(round(vels.index[0],0))\n endSec = int(round(vels.index[-1],0))\n # print('\\nNumber of indices - ', vels.index.size,'\\nLost frames leading - ',(vels.index[0] - startSec),'\\nLost frames after - ',(vels.index[-1] - endSec))\n counter = 0\n for n in range(startSec, endSec-1, binSecs):\n startOfSecond = vels.index.get_loc(n, method='bfill')\n endOfSecond = vels.index.get_loc(n+(binSecs-0.1), method='bfill')\n velsInSec = []\n #counter += endOfSecond-startOfSecond\n for frame in range(startOfSecond, endOfSecond):\n velocity = float(vels.iloc[frame])\n velsInSec.append(velocity)\n counter += 1\n if np.mean(velsInSec) < freezingThreshold:\n freezingSecs += 1\n freezingTimes.append([n,n+binSecs])\n else:\n nonfreezingSecs += 1\n # print('\\nCounter - ', counter)\n percentFreezing = 100.0 * round(freezingSecs/(freezingSecs + nonfreezingSecs),3)\n toneFreezing = pd.DataFrame({toneLabel: [freezingSecs, nonfreezingSecs, percentFreezing]},index=['Freezing', 'Nonfreezing','Percent Freezing']).T\n freezing = pd.concat([freezing, toneFreezing])\n freezingSecs = 0\n nonfreezingSecs = 0\n return(freezing, freezingTimes)\n\ndef get_freezing(datadict, ntones, freezingThreshold, binSecs):\n freezing = pd.DataFrame()\n freezingSecs = 0\n nonfreezingSecs = 0\n freezingTimes = []\n\n i = 1\n while i <= ntones:\n toneLabel = 'Tone {}'.format(str(i))\n\n epoch = datadict[i]\n vels = epoch['Velocity']\n\n startSec = int(round(vels.index[0],0))\n endSec = int(round(vels.index[-1],0))\n # print('\\nNumber of indices - ', vels.index.size,'\\nLost frames leading - ',(vels.index[0] - startSec),'\\nLost frames after - ',(vels.index[-1] - endSec))\n counter = 0\n for n in range(startSec, endSec-1, binSecs):\n startOfSecond = vels.index.get_loc(n, method='bfill')\n endOfSecond = vels.index.get_loc(n+(binSecs-0.1), method='bfill')\n velsInSec = []\n #counter += endOfSecond-startOfSecond\n for frame in range(startOfSecond, endOfSecond):\n velocity = float(vels.iloc[frame])\n velsInSec.append(velocity)\n counter += 1\n if np.mean(velsInSec) < freezingThreshold:\n freezingSecs += 1\n freezingTimes.append([n,n+binSecs])\n else:\n nonfreezingSecs += 1\n # print('\\nCounter - ', counter)\n percentFreezing = 100.0 * round(freezingSecs/(freezingSecs + nonfreezingSecs),3)\n toneFreezing = pd.DataFrame({toneLabel: [freezingSecs, nonfreezingSecs, percentFreezing]},index=['Freezing', 'Nonfreezing','Percent Freezing']).T\n freezing = pd.concat([freezing, toneFreezing])\n freezingSecs = 0\n nonfreezingSecs = 0\n i += 1\n return(freezing, freezingTimes)\n\ndef get_darting(datadict, ntones, dartThreshold, binSecs):\n darting = pd.DataFrame()\n dartingTimes = []\n nDarts = 0\n\n i = 1\n while i <= ntones:\n toneLabel = 'Tone {}'.format(str(i))\n\n epoch = datadict[i]\n vels = epoch['Velocity']\n\n startSec = int(round(vels.index[0],0))\n endSec = int(round(vels.index[-1],0))\n\n for n in range(startSec, endSec-1, binSecs):\n startOfSecond = vels.index.get_loc(n, method='bfill')\n endOfSecond = vels.index.get_loc(n+(binSecs-0.1), method='bfill')\n velsInSec = []\n for frame in range(startOfSecond, endOfSecond):\n velocity = float(vels.iloc[frame])\n velsInSec.append(velocity)\n for v in velsInSec:\n if v > dartThreshold:\n nDarts += 1\n dartingTimes.append([n,n+binSecs])\n break\n\n toneDarting = pd.DataFrame({toneLabel: nDarts},index=['Darts']).T\n darting = pd.concat([darting, toneDarting])\n nDarts = 0\n i += 1\n return(darting, dartingTimes)\n\ndef scaredy_read_FC_max(csv_dir,prefix):\n maxCSV = []\n\n for root, dirs, names in os.walk(csv_dir):\n for file in names:\n if file.startswith(prefix):\n f = os.path.join(root,file)\n maxCSV.append(f)\n return (maxCSV)\n\ndef scaredy_read_ext(csv_dir):\n meancsv = []\n SEMcsv = []\n medcsv = []\n\n for file in os.listdir(csv_dir):\n if file.startswith(\"ext-mean-\"):\n f = os.path.join(csv_dir, file)\n meancsv.append(f)\n if file.startswith(\"ext-SEM-\"):\n f = os.path.join(csv_dir, file)\n SEMcsv.append(f)\n if file.startswith(\"ext-med-\"):\n f = os.path.join(csv_dir,file)\n medcsv.append(f)\n return(meancsv,SEMcsv,medcsv)\n\ndef scaredy_read_ext_ret(csv_dir):\n meancsv = []\n SEMcsv = []\n medcsv = []\n\n for file in os.listdir(csv_dir):\n if file.startswith(\"ext-ret-mean-\"):\n f = os.path.join(csv_dir, file)\n meancsv.append(f)\n if file.startswith(\"ext-ret-SEM-\"):\n f = os.path.join(csv_dir, file)\n SEMcsv.append(f)\n if file.startswith(\"ext-ret-med-\"):\n f = os.path.join(csv_dir,file)\n medcsv.append(f)\n return(meancsv,SEMcsv,medcsv)\n\ndef scaredy_find_csvs(csv_dir, prefix):\n csvlist = []\n\n for root, dirs, names in os.walk(csv_dir):\n for file in names:\n if file.startswith(prefix):\n f = os.path.join(root, file)\n csvlist.append(f)\n\n return(csvlist)\n\ndef get_anim(csv, n):\n m = re.split('[-.]', csv)\n anim = m[n]\n return(anim)\n\ndef compress_data(csvlist,tbin):\n '''\n tbins:\n 0 = tone\n 1 = pretone\n 2 = shock\n 3 = postshock\n '''\n allanims = pd.DataFrame()\n for csv in csvlist:\n anim = get_anim(csv,-2)\n df = pd.read_csv(csv,index_col=0).transpose()\n\n tonevels = pd.DataFrame(df.iloc[tbin]).transpose()\n tonevels.set_index([[anim]],inplace=True)\n\n allanims = pd.concat([allanims,tonevels])\n\n return(allanims)\n\ndef compress_ext_ret_data(csvlist,tbin):\n allanims = pd.DataFrame()\n for csv in csvlist:\n anim = get_anim(csv,-2)\n df = pd.read_csv(csv,index_col=0).transpose()\n\n tonevels = pd.DataFrame(df.iloc[tbin]).transpose()\n tonevels.set_index([[anim]],inplace=True)\n\n allanims = pd.concat([allanims,tonevels])\n return(allanims)\n\ndef concat_data(means, SEMs, meds, ntones):\n allData = pd.DataFrame()\n ix = []\n for n in range(ntones):\n allData = allData.append(means.iloc[:,n])\n ix.append('Tone {} Mean'.format(n+1))\n for n in range(ntones): \n allData = allData.append(SEMs.iloc[:,n])\n ix.append('Tone {} SEM'.format(n+1))\n for n in range(ntones): \n allData = allData.append(meds.iloc[:,n]) \n ix.append('Tone {} Median'.format(n+1))\n\n allData.index = ix\n allData = allData.transpose()\n\n return(allData)\n\ndef concat_all_FC_freezing(csvlist, tbin):\n freezing = pd.DataFrame()\n for csv in csvlist:\n anim = get_anim(csv,-2)\n df = pd.read_csv(csv, index_col=0).T\n loc = (tbin * 3) + 2\n percentF = pd.DataFrame([df.iloc[loc]], index=[anim])\n freezing = pd.concat([freezing, percentF])\n\n return(freezing)\n\ndef concat_all_FC_max(csvlist):\n maxes = pd.DataFrame()\n\n for csv in csvlist:\n anim = get_anim(csv,-2)\n df = pd.read_csv(csv,index_col=0)\n meanMax = pd.DataFrame({anim: df['Mean']}).T\n maxes = pd.concat([maxes, meanMax])\n\n return(maxes)\n\ndef concat_all_FC_darting(csvlist, loc):\n freezing = pd.DataFrame()\n for csv in csvlist:\n anim = get_anim(csv,-2)\n df = pd.read_csv(csv, index_col=0).T\n percentF = pd.DataFrame([df.iloc[loc]], index=[anim])\n freezing = pd.concat([freezing, percentF])\n\n return(freezing)\n\ndef concat_all_habituation_freezing(csvlist, tbin):\n freezing = pd.DataFrame()\n for csv in csvlist:\n anim = get_anim(csv,-2)\n df = pd.read_csv(csv, index_col=0).T\n loc = (tbin * 3) + 2\n percentF = pd.DataFrame([df.iloc[loc]], index=[anim])\n freezing = pd.concat([freezing, percentF])\n\n return(freezing)\n\ndef compress_FC_max_data(csvlist):\n anims = []\n maxVels = pd.DataFrame()\n\n for csv in csvlist:\n anim = get_anim(csv,-2)\n anims.append(anim)\n\n df = pd.read_csv(csv,index_col=0).transpose()\n df = df.iloc[-1,:]\n maxVels = maxVels.append(df)\n\n maxVels.index = anims\n return(maxVels)\n","sub_path":"src/scaredyrattools.py","file_name":"scaredyrattools.py","file_ext":"py","file_size_in_byte":17666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"340491030","text":"#Question 15\n#Level 2\n\n#Question:\n#Write a program that computes the value of a+aa+aaa+aaaa with a given digit as the value of a.\n#Suppose the following input is supplied to the program:\n#9\n#Then, the output should be:\n#11106\n\n#Hints:\n#In case of input data being supplied to the question, it should be assumed to be a console input.\n\n\n\ndef task15(a):\n a=int(\"%s\" %(a))\n b=int(\"%s%s\" %(a,a))\n c=int(\"%s%s%s\" %(a,a,a))\n d=int(\"%s%s%s%s\" %(a,a,a,a))\n\n e=a+b+c+d\n return e\n\n\npierwsze=input(\"t/n: \")\nif pierwsze==\"t\":\n a=input(\"wpisz: \")\n beniz=task15(a)\n print(beniz)\nelse:\n import sys\n sys.exit()\n \n","sub_path":"task15.py","file_name":"task15.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"565129029","text":"################################################################################\n#\n# Copyright (c) 2019, the Perspective Authors.\n#\n# This file is part of the Perspective library, distributed under the terms of\n# the Apache License 2.0. The full license can be found in the LICENSE file.\n#\n\nfrom perspective.table import Table\n\n\nclass TestRemove(object):\n\n def test_remove_all(self):\n tbl = Table([{\"a\": \"abc\", \"b\": 123}], index=\"a\")\n tbl.remove([\"abc\"])\n assert tbl.view().to_records() == []\n # assert tbl.size() == 0\n\n def test_remove_nonsequential(self):\n tbl = Table([{\"a\": \"abc\", \"b\": 123}, {\"a\": \"def\", \"b\": 456}, {\"a\": \"efg\", \"b\": 789}], index=\"a\")\n tbl.remove([\"abc\", \"efg\"])\n assert tbl.view().to_records() == [{\"a\": \"def\", \"b\": 456}]\n # assert tbl.size() == 1\n\n def test_remove_multiple_single(self):\n tbl = Table({\"a\": int, \"b\": str}, index=\"a\")\n for i in range(0, 10):\n tbl.update([{\"a\": i, \"b\": str(i)}])\n for i in range(1, 10):\n tbl.remove([i])\n assert tbl.view().to_records() == [{\"a\": 0, \"b\": \"0\"}]\n # assert tbl.size() == 0\n","sub_path":"python/perspective/perspective/tests/table/test_remove.py","file_name":"test_remove.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"522759421","text":"\"\"\"This file is a TaleoEENonsitemap spider created on top of the TaleoEE.\n\nscrapy crawl taleo_batch_nonsitemap -a mining_job_id=9999 -a iteration=1 \\\n-a url=\"http://frb.taleo.net/careersection/sitemap.jss?portalCode=2&lang=en\" \\\n-a extract=1\n\nsample url:\n http://familydollar.taleo.net/careersection/sitemap.jss?portalCode=8&lang=en\n https://dtt.taleo.net/careersection/sitemap.jss?portalCode=12060&lang=en\n http://assocbank.taleo.net/careersection/sitemap.jss?portalCode=bgi&lang=en\n\"\"\"\nimport re\n\nfrom urlparse import urljoin, urlparse, parse_qs\nfrom urllib import unquote\nfrom math import ceil\n\nfrom scrapy.http import Request, FormRequest, Response\nfrom scrapy.selector import Selector\nfrom scrapy.exceptions import CloseSpider\n\nfrom brightcorp.base.taleo_ee import TaleoEE\nfrom brightcorp.processors import Replace\n\nWS_RE = re.compile(r\"^\\s+\")\n\n\nclass TaleoEENonsitemap(TaleoEE):\n\n \"\"\"Crawler for Taleo NonSitemap.\"\"\"\n\n name = \"taleo_batch_nonsitemap\"\n\n allowed_domains = [\"taleo.net\"]\n company_xpath = None\n desc_replace = {'processors': [Replace('Listing Info')]}\n\n def start_requests(self):\n \"\"\" Convert url to request. Remove whitespace.\"\"\"\n for url in self.start_urls:\n yield Request(WS_RE.sub('+', url), callback=self.parse_jobs)\n\n def parse_jobs(self, response):\n \"\"\"Parse jobs items/links.\"\"\"\n if 'redirectRequest' in response.body:\n if 'https' not in response.url:\n yield Request(\n response.url.replace('http', 'https'),\n callback=self.parse_jobs)\n return\n\n # Set language\n self.set_meta_language(response)\n\n # Initiate the selector and remove the name spaces\n sel = Selector(response)\n sel.remove_namespaces()\n\n # Look for the jobs\n job_urls = sel.xpath('//url/loc/text()').extract()\n\n # Parse the jobs if there are any\n if len(job_urls) > 0:\n for url in job_urls:\n url = url.replace('\\n', '')\n yield Request(url, callback=self.parse_job_callback())\n else:\n raise CloseSpider('There are no jobs for this site.')\n","sub_path":"brightcorp/brightcorp/spiders/taleo_ee_nonsitemap.py","file_name":"taleo_ee_nonsitemap.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"362526281","text":"try:\n import Tkinter as tk\nexcept ImportError:\n import tkinter as tk\n\ntry:\n from Files.backend import *\nexcept ImportError:\n from backend import *\n\nclass MatrixInput(tk.Text):\n def read(self):\n text = self.get(tk.START, tk.END)\n text = text.split('\\n')\n for x in range(len(text)):\n text[x] = text[x].split()\n for y in range(len(text[x])):\n text[x][y] = float(text[x][y])\n\n r = Matrix(len(text[0]), len(text))\n\n for x in range(len(text)):\n for y in range(len(x)):\n r[x, y] = text[x][y]\n\n return r\n\nclass CreateObjectWindow(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.r=None #Return variable\n\n self.go = tk.Button(self, text='OK', command=self.OK) #OK button\n self.abort = tk.Button(self, text='Cancel', command=self.Cancel) #Cancel Button\n \n self.bind('', self.OK)\n self.bind('', self.Cancel)\n \n self.protocol('WM_DELETE_WINDOW', self.Cancel)\n\n def quit(self):\n tk.Tk.quit(self) #Exit mainloop\n self.destroy() #Destroy the window\n\n def OK(self, event=None): #OK protocol for use when the user follows through\n self.r = self.getret(self)\n self.quit()\n\n def Cancel(self, event=None): #Cancel for when the user aborts\n self.r = self.getblank(self)\n self.quit()\n\n def getret(self, event=None): #Filler\n return None\n\n def getblank(self, event=None): #Filler\n return None\n\nclass CreatePointWindow(CreateObjectWindow):\n def __init__(self, *args, **kwargs):\n CreateObjectWindow.__init__(self, *args, **kwargs)\n \n #self.x = tk.DoubleVar() #X variable\n #self.y = tk.DoubleVar() #Y variable\n #self.name = tk.StringVar() #Name variable\n\n self.namel = tk.Label(self, text='Name') #Label for name box\n self.namebox = tk.Entry(self)#, textvariable=self.name) #Name box\n self.openparen = tk.Label(self, text='(') #Open parenthesis\n self.xe = tk.Entry(self)#, textvariable=self.x, width=5) #Entry for X\n self.comma = tk.Label(self, text=',') #Comma\n self.ye = tk.Entry(self)#, textvariable=self.y, width=5) #Entry for Y\n self.closeparen = tk.Label(self, text=')') #Close parenthesis\n\n #Line everything up\n self.namel.grid(column=0, row=0)\n self.namebox.grid(column=1, row=0, columnspan=4)\n self.openparen.grid(column=0, row=1)\n self.xe.grid(column=1, row=1)\n self.comma.grid(column=2, row=1)\n self.ye.grid(column=3, row=1)\n self.closeparen.grid(column=4, row=1)\n \n self.abort.grid(column=1, row=2)\n self.go.grid(column=3, row=2)\n\n self.title('Create Point') #Window Title\n\n def getret(self, event=None):\n return (self.namebox.get(), Point((float(self.xe.get()), float(self.ye.get())))) #Return tuple \"(Name, (X, Y))\"\n\n def getblank(self, event=None): #Return point on cancellation\n return(None, (None, None))\n\nclass CreateLineWindow(CreateObjectWindow):\n def __init__(self, *args, **kwargs):\n CreateObjectWindow.__init__(self, *args, **kwargs)\n\nclass CalculatorWindow(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.stuff = None\n\nclass StandardCalculatorWindow(CalculatorWindow):\n pass\n\nclass ScientificCalculatorWindow(CalculatorWindow):\n pass\n\nclass ProgrammerCalculatorWindow(CalculatorWindow):\n pass\n\nclass StatisticsCalculatorWindow(CalculatorWindow):\n pass\n\nif __name__ == '__main__': #Test\n cpw = CreatePointWindow()\n cpw.mainloop()\n print(cpw.r)\n","sub_path":"Files/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"543904735","text":"#!/usr/bin/python\n\nimport sys\n\ndef readData(datafile):\n file = open(datafile,'r')\n all_lines = file.readlines()\n i=0\n new_data = []\n for i in xrange(len(all_lines[::1])):\n new_data.append([float(x) for x in all_lines[i].split()])\n file.close()\n return new_data\n\n\n\ndef makeHisto(dataArr, startInterval, maxTime=2000, error=False):\n \"Create histogram from input data array\"\n histo = [[[0 for x in range(100)] for x in range(100)] for x in range(100)]\n norm=0\n boxsize=10\n for pos in dataArr:\n x = (int)(pos[1] % boxsize / boxsize * 100) # % returns the modulo of a division\n y = (int)(pos[2] % boxsize / boxsize * 100)\n z = (int)(pos[3] % boxsize / boxsize * 100)\n histo[x][y][z] += 1\n norm += 1\n \n # for x in range(100):\n # for y in range(100):\n # for z in range(100):\n # histo[x][y][z] /= norm\n\n\n\ndef exportMSD():\n maxTime=2000\n avgInterval=float(sys.argv[1])\n data = readData('trajectory.txt')\n msd = makeMSD(data, avgInterval, maxTime)\n MSDfile = open('msd.txt','w')\n timestep = (data[1][0] - data[0][0])\n for i in xrange((int)(maxTime*1.0/timestep)):\n t = i * timestep\n line = str(t) + '\\t' + str(msd[i]) + '\\n'\n MSDfile.write(line)\n\n\nexportMSD()\n","sub_path":"posHistofromTraj.py","file_name":"posHistofromTraj.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"267477733","text":"import os\nimport openai\nimport numpy as np\n\nopenai.api_key = os.environ[\"OPENAI_API_KEY\"]\n\n\ndef filter_logprob(prompt, filter):\n combined = prompt + filter\n response = openai.Completion.create(\n engine=\"ada\",\n prompt=combined,\n temperature=0.7,\n max_tokens=0,\n echo=True,\n top_p=1,\n n=1,\n logprobs=0\n )\n\n positions = response.choices[0][\"logprobs\"][\"text_offset\"]\n logprobs = response.choices[0][\"logprobs\"][\"token_logprobs\"]\n # tokens = response.choices[0][\"logprobs\"][\"tokens\"]\n\n word_index = positions.index(len(prompt))\n\n total_conditional_logprob = sum(logprobs[word_index:])\n\n return total_conditional_logprob\n\n\ndef filter_top_probs(preprompt, content, filter, quiet=0):\n index = 0\n logprobs = []\n substrings = []\n for word in content.split():\n index += len(word) + 1\n substring = content[:(index - 1)]\n prompt = preprompt + substring\n logprob = filter_logprob(prompt, filter)\n logprobs.append(logprob)\n substrings.append(substring)\n if not quiet:\n print(substring)\n print('logprob: ', logprob)\n\n return substrings, logprobs\n\n\ndef n_top_logprobs(preprompt, content, filter, n=5, quiet=0):\n substrings, logprobs = filter_top_probs(preprompt, content, filter, quiet)\n sorted_logprobs = np.argsort(logprobs)\n top = []\n for i in range(n):\n top.append({'substring': substrings[sorted_logprobs[-(i + 1)]],\n 'logprob': logprobs[sorted_logprobs[-(i + 1)]]})\n\n return top\n\nf = open(\"preprompt.txt\", \"r\")\npreprompt = f.read()[:-1]\ng = open(\"content.txt\", \"r\")\ncontent = g.read()[:-1]\nh = open(\"filter.txt\", \"r\")\nfilter = h.read()[:-1]\n\nprint('preprompt\\n', preprompt)\nprint('\\ncontent\\n', content)\nprint('\\nfilter\\n', filter)\n\ntop = n_top_logprobs(preprompt, content, filter, 10)\nprint(top)\n\nfor t in top:\n print('\\ncutoff: ', t['substring'][-100:])\n print('logprob: ', t['logprob'])\n","sub_path":"conditional.py","file_name":"conditional.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"244831682","text":"# @Email: jmaggio14@gmail.com\n# @Website: https://www.imagepypelines.org/\n# @License: https://github.com/jmaggio14/imagepypelines/blob/master/LICENSE\n# @github: https://github.com/jmaggio14/imagepypelines\n#\n# Copyright (c) 2018 Jeff Maggio, Nathan Dileas, Ryan Hartzell\nimport numpy as np\nimport cv2\nfrom scipy.cluster.vq import kmeans, vq\nfrom scipy.stats import wasserstein_distance as wd\n\nclass VBOW(object):\n\t\"\"\"Eventually this will inherit from the overarching FEATURE_VECTOR class\"\"\"\n\n\tdef __init__(self, descriptors, descriptor_type='SIFT', sampling=4):\n\n\t\tself.step = float(1/sampling)\n\t\tself.descriptor_type = descriptor_type\n\n\t\tdesc_norms = np.sum(descriptors, axis=1)/len(descriptors[0])\n\t\tself.desc_norms = np.asarray([[norm] for norm in desc_norms])\n\n\t\tcodes = np.arange(0, 256, self.step)\n\t\tself.codes = np.asarray([[code] for code in codes])\n\n\t\tself.histogram = []\n\n\t\tdel desc_norms\n\t\tdel codes\n\n\t\t# MAKE VBOW SUMMARY VECTOR (FINGERPRINT)\n\t\tself.construct_vector()\n\n\tdef construct_vector(self):\n\t\t\"\"\"For now, technically only supports SIFT (ORB needs special attention)\"\"\"\n\t\tidx, _ = vq(self.desc_norms, self.codes)\n\n\t\tfor i in range(len(self.codes)):\n\n\t\t\thist = len(self.desc_norms[idx==i])\n\t\t\tself.histogram.append(hist)\n\n\t\treturn np.asarray(self.histogram)\n\ndef compare_euclidean(hist1, hist2):\n\treturn np.sum(np.abs(np.asarray(hist2) - np.asarray(hist1)))\n\ndef compare_wasserstein(hist1, hist2):\n\treturn wd(hist1, hist2)\n\nif __name__ == '__main__':\n\n\tsift = cv2.xfeatures2d.SIFT_create()\n\n\tim1 = cv2.imread('../data/00001.png',0)\n\tkp, desc = sift.detectAndCompute(im1, None)\n\n\tVBOW1 = VBOW(desc)\n\thistogram1 =VBOW1.construct_vector()\n\n\thist1sum = np.sum(histogram1)\n\thistogram1norm = histogram1/hist1sum\n\n\tprint(histogram1norm)\n\tprint(hist1sum)\n\n\tim2 = cv2.imread('../data/00102.png',0)\n\tkp2, desc2 = sift.detectAndCompute(im2, None)\n\n\tVBOW2 = VBOW(desc2)\n\thistogram2 = VBOW2.construct_vector()\n\n\thist2sum = np.sum(histogram2)\n\thistogram2norm = histogram2/hist2sum\n\n\tprint(histogram2norm)\n\tprint(hist2sum)\n\n\t# diff_sum = np.sum(np.abs(np.asarray(histogram2) - np.asarray(histogram1)))\n\t# print(diff_sum)\n\n\tprint('Here\\'s the Earth Mover\\'s Distance (Wasserstein): ', compare_wasserstein(histogram1norm, histogram2norm)*100000)\n","sub_path":"imagepypelines/ml/visualbagofwords.py","file_name":"visualbagofwords.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"97201824","text":"import os\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memory:',\n }\n}\n\nINSTALLED_APPS = (\n 'discover_runner',\n 'geetar',\n 'test_app',\n)\n\nSECRET_KEY = \"geetarT3st!\"\n\nTEST_RUNNER = 'discover_runner.DiscoverRunner'\n\nTEST_DISCOVER_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'tests')\n\nGOOGLE_MAPS_API_KEY = 'AIzaSyCuJe82BXhTESkKmlo3V4Rft_IsxGhJwDU'","sub_path":"geetar/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"147144986","text":"from django.conf.urls import url\nfrom django.http import HttpResponse\nfrom django.template.loader import render_to_string\n\n\nDEBUG = True\nSECRET_KEY = '4l0ngs3cr3tstr1ngw3lln0ts0l0ngw41tn0w1tsl0ng3n0ugh'\nROOT_URLCONF = __name__\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [\n '/home/projects/myproject/templates/'\n ],\n },\n]\n\n\ndef home(request):\n color = request.GET.get('color', '')\n return HttpResponse('

    Welcome to the Tinyapp\\'s Homepage!

    ')\n\ndef about(request):\n title = 'Tinyapp'\n author = 'Vitor Freitas'\n html = render_to_string('about.html', {'title': title, 'author': author})\n return HttpResponse(html)\n\n\nurlpatterns = [\n url(r'^$', home, name='homepage'),\n url(r'^about/$', about, name='aboutpage'),\n]\n","sub_path":"test1/searchapp.py","file_name":"searchapp.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"573774870","text":"from datetime import datetime\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import ValidationError\n\nclass Shipment(models.Model):\n _name = \"erky.vehicle.shipment\"\n _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin']\n\n name = fields.Char(\"Ref\", readonly=1, default=\"New\")\n shipment_type = fields.Selection([('good_shipment', \"Good Shipment\"), ('container_shipment', \"Container Shipment\")],\n string=\"Shipment Type\", required=1)\n export_form_id = fields.Many2one(\"erky.export.form\", string=\"Export Form Ref\", required=1)\n internal_contract_id = fields.Many2one(related=\"export_form_id.contract_id\", string=\"Contract Ref\", store=True, required=1)\n purchase_contract_id = fields.Many2one(related=\"export_form_id.purchase_contract_id\", string=\"Purchase Contract\", store=True, required=0)\n agent_id = fields.Many2one(\"res.partner\", \"Truck\", required=1, domain=[('is_truck', '=', True)])\n shipment_date = fields.Date(\"Shipment Date\", default=fields.Date.context_today)\n driver_id = fields.Many2one(\"res.partner\", \"Driver Name\", required=1, domain=[('is_driver', '=', True)])\n phone_no = fields.Char(related=\"driver_id.phone\", string=\"Driver Phone\")\n front_plate_no = fields.Char(\"Front Plate No\")\n back_plate_no = fields.Char(\"Back Plate No\")\n source_location = fields.Many2one(\"erky.location\", \"Origin\", domain=[('is_origin', '=', True)])\n destination_location = fields.Many2one(\"erky.location\", \"Destination\", required=1, domain=[('is_dest', '=', True)])\n customer_broker_id = fields.Many2one(\"res.partner\", \"Clearance\", domain=[('is_clearance', '=', True)])\n product_id = fields.Many2one(related=\"internal_contract_id.product_id\", store=True)\n product_uom_id = fields.Many2one(\"uom.uom\", string=\"Product UOM\", required=1)\n\n package_qty = fields.Float(\"Package Qty\", required=1)\n in_container_qty = fields.Float(\"Pack Qty/Container\", compute=\"compute_shipment_qty\", store=True)\n residual_qty = fields.Float(\"Pack Qty/Residual\", compute=\"compute_shipment_qty\", store=True)\n package_uom_id = fields.Many2one(\"uom.uom\", string=\"Package UOM\", required=1, domain=[('is_weight_packing', '=', True)])\n net_weight = fields.Float(\"Net Weight/KGS\")\n gross_weight = fields.Float(\"Gross Weight/KGS\")\n package_as_ton_weight = fields.Float(\"Package Weight/TON\")\n\n # SHIPMENT WEIGHT\n sh_weight_kgs_1 = fields.Float('SH Weight - 1/KGS')\n sh_weight_kgs_2 = fields.Float('SH Weight - 2/KGS')\n sh_weight_kgs_net = fields.Float('SH Weight - NET/KGS', compute='_get_sh_net_weight', store=True)\n sh_weight_ton = fields.Float('SH Weight/TON')\n sh_weight_package_uom = fields.Float('SH Weight/Package UOM')\n sh_weight_attachment_id = fields.Binary(\"SH Weight Attachment\", attachment=True,)\n # DISCHARGE WEIGHT\n ds_weight_kgs_1 = fields.Float('DS Weight - 1/KGS')\n ds_weight_kgs_2 = fields.Float('DS Weight - 2/KGS')\n ds_weight_kgs_net = fields.Float('DS Weight - NET/KGS', compute='_get_ds_net_weight', store=True)\n ds_weight_ton = fields.Float('DS Weight/TON')\n ds_weight_package_uom = fields.Float('DS Weight/Package UOM')\n ds_weight_attachment_id = fields.Binary(\"DS Weight Attachment\", attachment=True)\n\n unit_cost = fields.Float(\"Unit Cost\", required=1, track_visibility='onchange')\n unit_qty = fields.Float(\"Unit Qty\", default=1, track_visibility='onchange')\n total_other_cost = fields.Float(\"Total Other Cost\", compute=\"_compute_cost\", store=True, track_visibility='onchange')\n total_packing_cost = fields.Float(\"Total Packing Cost\", compute=\"_compute_cost\", store=True, track_visibility='onchange')\n total_cost = fields.Float(\"Total Cost\", compute=\"_compute_cost\", store=True, track_visibility='onchange')\n shipment_cost_ids = fields.One2many(\"erky.shipment.cost\", \"shipment_id\")\n other_shipment_cost = fields.Float(\"Other Cost\", compute=\"_compute_cost\", store=True)\n currency_id = fields.Many2one('res.currency', string='Currency', readonly=False,\n default=lambda self: self.env.user.company_id.currency_id, required=1, track_visibility='onchange')\n note = fields.Text(\"Note\")\n state = fields.Selection([('draft', \"Draft\"), ('under_shipment', \"Under Shipment\"), ('under_discharge', 'Under Discharge'), ('done', \"Done\"), ('canceled', \"Canceled\")], default='draft')\n shipment_container_ids = fields.One2many(\"erky.container.shipment\", \"vehicle_shipment_id\")\n picking_ids = fields.One2many(\"stock.picking\", \"vehicle_shipment_id\")\n in_store_qty = fields.Float(compute=\"_compute_in_store_qty\", store=True)\n cost_posted = fields.Boolean()\n\n @api.constrains('shipment_container_ids', 'picking_ids', 'residual_qty')\n def check_container_shipment_qty(self):\n for rec in self:\n if rec.shipment_container_ids:\n shipment_qty = sum(rec.shipment_container_ids.mapped('shipment_qty'))\n if shipment_qty > rec.package_qty or rec.residual_qty < 0:\n raise ValidationError(\"Qty shipped in containers + transfer to store must be less than package qty.\")\n\n @api.constrains('unit_cost', 'unit_qty')\n def check_unit_cost_and_qty(self):\n for rec in self:\n if rec.unit_qty < 0 or rec.unit_cost < 0:\n raise ValidationError(\"Negative cost not allowed.\")\n\n @api.onchange('package_uom_id', 'package_qty')\n def set_default_weights(self):\n for rec in self:\n package_uom_id = self.package_uom_id\n rec.net_weight = self.package_qty * package_uom_id.net_weight_kgs\n rec.gross_weight = self.package_qty * package_uom_id.gross_weight_kgs\n rec.package_as_ton_weight = self.package_qty * package_uom_id.weight_in_ton\n\n @api.depends('sh_weight_kgs_1', 'sh_weight_kgs_2', 'package_uom_id')\n def _get_sh_net_weight(self):\n for rec in self:\n sh_weight_kgs_net = rec.sh_weight_kgs_2 - rec.sh_weight_kgs_1\n rec.sh_weight_kgs_net = sh_weight_kgs_net\n\n @api.depends('ds_weight_kgs_1', 'ds_weight_kgs_2', 'package_uom_id')\n def _get_ds_net_weight(self):\n for rec in self:\n ds_weight_kgs_net = rec.ds_weight_kgs_2 - rec.ds_weight_kgs_1\n rec.ds_weight_kgs_net = ds_weight_kgs_net\n\n @api.onchange('sh_weight_kgs_net', 'package_uom_id')\n def _get_sh_ton_weigh(self):\n self.sh_weight_ton = self.sh_weight_kgs_net/1000\n\n @api.onchange('ds_weight_kgs_net', 'package_uom_id')\n def _get_ds_ton_weight(self):\n self.ds_weight_ton = self.ds_weight_kgs_net/1000\n\n @api.onchange('sh_weight_ton', 'package_uom_id')\n def _get_sh_package_weight(self):\n if self.package_uom_id.weight_in_ton != 0 and self.sh_weight_ton:\n self.sh_weight_package_uom = self.sh_weight_ton / (self.package_uom_id.weight_in_ton)\n\n @api.onchange('ds_weight_ton', 'package_uom_id')\n def _get_ds_package_weight(self):\n if self.package_uom_id.weight_in_ton != 0 and self.ds_weight_ton:\n self.ds_weight_package_uom = self.ds_weight_ton / (self.package_uom_id.weight_in_ton)\n\n\n @api.onchange('driver_id')\n def get_driver_agent(self):\n for rec in self:\n rec.agent_id = self.driver_id.truck_id.id\n\n @api.depends(\"unit_cost\", 'unit_qty', \"shipment_cost_ids\")\n def _compute_cost(self):\n for rec in self:\n rec.total_packing_cost = rec.unit_cost * rec.unit_qty\n other_cost = 0\n if rec.shipment_cost_ids:\n other_cost = sum(rec.shipment_cost_ids.mapped(\"amount\"))\n rec.total_other_cost = other_cost\n rec.total_cost = other_cost + (rec.unit_cost * rec.unit_qty)\n\n @api.model\n def create(self, vals):\n if vals.get('name', _('New')) == _('New'):\n vals['name'] = self.env['ir.sequence'].next_by_code('erky.vehicle.shipment') or _('New')\n res = super(Shipment, self).create(vals)\n return res\n\n @api.multi\n def action_shipment(self):\n for rec in self:\n rec.state = 'under_shipment'\n\n @api.multi\n def action_discharge(self):\n for rec in self:\n if rec.sh_weight_kgs_net <= 0:\n raise ValidationError(\"Net of shipment weight must be greater than zero.\")\n rec.ds_weight_kgs_1 = rec.sh_weight_kgs_1\n rec.ds_weight_kgs_2 = rec.sh_weight_kgs_2\n rec.state = 'under_discharge'\n\n @api.multi\n def action_done(self):\n for rec in self:\n if rec.ds_weight_kgs_net <= 0:\n raise ValidationError(\"Net Of discharge weight must be greater than zero.\")\n self.create_expense()\n rec.state = 'done'\n\n @api.multi\n def action_canceled(self):\n for rec in self:\n rec.state = 'canceled'\n\n @api.multi\n def action_set_to_draft(self):\n for rec in self:\n rec.state = 'draft'\n\n @api.depends('shipment_container_ids', 'picking_ids')\n def compute_shipment_qty(self):\n for rec in self:\n shipment_qty = sum(rec.shipment_container_ids.mapped('shipment_qty'))\n ton_weight = round((rec.package_qty / rec.package_as_ton_weight), 2) if rec.package_as_ton_weight else 0\n in_store_qty = rec.in_store_qty * ton_weight\n rec.residual_qty = rec.package_qty - (shipment_qty + in_store_qty)\n rec.in_container_qty = shipment_qty\n\n @api.multi\n def transfer_to_store_action(self):\n ctx = self.env.context.copy()\n containers_qty = sum(self.shipment_container_ids.mapped('ton_weight'))\n residual_qty = self.package_as_ton_weight - containers_qty\n if residual_qty <= 0:\n raise ValidationError(\"Qty to transfer must be greater than zero.\")\n ctx.update({'default_shipment_id': self.id,\n 'default_location_id': self.env.user.company_id.temp_location_id.id,\n 'default_product_id': self.product_id.id,\n 'default_uom_id': self.product_uom_id.id,\n 'default_qty': residual_qty})\n return {\n 'name': \"Transfer To Store\",\n 'res_model': 'transfer.to.store',\n 'type': 'ir.actions.act_window',\n 'context': ctx,\n 'view_mode': 'form',\n 'view_type': 'form',\n 'view_id': self.env.ref(\"erky_base.wizard_transfer_to_store_view\").id,\n 'target': 'new'\n }\n\n @api.depends('picking_ids', 'shipment_container_ids')\n def _compute_in_store_qty(self):\n for rec in self:\n tran_qty = 0\n for p in rec.picking_ids:\n done_qty = sum(p.move_ids_without_package.mapped('quantity_done'))\n tran_qty += done_qty\n rec.in_store_qty = tran_qty\n\n\n @api.multi\n def action_open_picking(self):\n picking_ids = self.picking_ids\n action = self.env.ref('stock.action_picking_tree_all').read()[0]\n action['domain'] = [('id', 'in', picking_ids.ids)]\n return action\n\n @api.multi\n def create_expense(self):\n for rec in self:\n other_cost_ids = rec.shipment_cost_ids.filtered(lambda c: c.is_posted == False)\n expense_obj = self.env['hr.expense']\n if other_cost_ids:\n employee_id = self.env['hr.employee'].search([('user_id', '=', rec.env.user.id)], limit=1)\n if not employee_id:\n raise ValidationError(\"To create other expense. need valid employee linked to you user.\")\n for exp in other_cost_ids:\n name = rec.name + \"[\" + rec.driver_id.name + \"] - \" + \"[\" + exp.service_id.name + \"]\"\n expense_id = expense_obj.create({'name': name,\n 'product_id': exp.service_id.id,\n 'export_form_id': rec.export_form_id.id,\n 'unit_amount': exp.amount,\n 'quantity': 1,\n 'employee_id': employee_id.id\n })\n if expense_id:\n exp.expense_id = expense_id.id\n exp.is_posted = True\n\n\n\nclass ShipmentContainer(models.Model):\n _name = \"erky.container.shipment\"\n\n vehicle_shipment_id = fields.Many2one(\"erky.vehicle.shipment\", \"Vehicle Shipment\")\n name = fields.Char(required=0)\n state = fields.Selection(related=\"vehicle_shipment_id.state\", store=True)\n ref_id = fields.Many2one(\"erky.container\", \"Container\")\n product_id = fields.Many2one(related=\"vehicle_shipment_id.product_id\", store=True)\n container_size = fields.Selection([('20_feet', \"20 Feet\"), ('40_feet', \"40 Feet\")])\n export_form_id = fields.Many2one(related=\"vehicle_shipment_id.export_form_id\", string=\"Export Form\", store=True)\n internal_contract_id = fields.Many2one(related=\"export_form_id.contract_id\", string=\"Contract\", required=0,\n store=True)\n purchase_contract_id = fields.Many2one(related=\"export_form_id.purchase_contract_id\", string=\"Purchase_Contract\",\n required=0, store=True)\n shipment_qty = fields.Integer(\"Shipment Qty\", required=0)\n shipment_uom_id = fields.Many2one(related=\"vehicle_shipment_id.package_uom_id\", string=\"UOM\", store=True, required=0)\n net_weight = fields.Float(\"Net Weight/KGS\")\n in_container_qty = fields.Float(\"Pack Qty/Container\", compute=\"compute_in_container_qty\")\n gross_weight = fields.Float(\"Gross Weight/KGS\")\n ton_weight = fields.Float(\"Weight/TON\")\n\n _sql_constraints = [\n ('container_ref_uniq', 'unique(ref_id, vehicle_shipment_id, container_size, export_form_id)', 'The container ref must be unique !'),\n ]\n\n @api.onchange('ref_id')\n def set_container_info(self):\n for rec in self:\n if rec.ref_id:\n rec.container_size = rec.ref_id.size\n\n @api.onchange(\"shipment_qty\", \"shipment_uom_id\")\n def _get_default_weight(self):\n for rec in self:\n if rec.shipment_uom_id and rec.shipment_uom_id.is_weight_packing:\n qty = rec.shipment_qty\n ton = net = gross = 0\n if rec.vehicle_shipment_id.package_qty != 0:\n if rec.vehicle_shipment_id.package_as_ton_weight != 0:\n ton = (1/(rec.vehicle_shipment_id.package_qty/rec.vehicle_shipment_id.package_as_ton_weight))\n if rec.vehicle_shipment_id.net_weight != 0:\n net = (1/(rec.vehicle_shipment_id.package_qty/rec.vehicle_shipment_id.net_weight))\n if rec.vehicle_shipment_id.gross_weight != 0:\n gross = (1/(rec.vehicle_shipment_id.package_qty/rec.vehicle_shipment_id.gross_weight))\n rec.net_weight = round(qty * net, 2)\n rec.gross_weight = round(qty * gross, 2)\n rec.ton_weight = round(qty * ton, 2)\n\n @api.depends('shipment_qty')\n def compute_in_container_qty(self):\n for rec in self:\n export_form_id = rec.export_form_id\n if export_form_id:\n #In Store Qty Is Ton -> Convert Ton Qty To Package\n shipped_from_store_qty = sum(export_form_id.store_container_shipment_ids.filtered(\n lambda s: s.picking_created == True and s.container_id.id == rec.ref_id.id)\n .mapped('package_qty'))\n shipped_from_shipment_qty = sum(export_form_id.container_shipment_ids.filtered(\n lambda c: c.state != 'canceled' and c.ref_id == rec.ref_id).mapped('shipment_qty'))\n qty = shipped_from_shipment_qty + shipped_from_store_qty\n rec.in_container_qty = qty\n\nclass ShipmentCost(models.Model):\n _name = \"erky.shipment.cost\"\n\n shipment_id = fields.Many2one(\"erky.vehicle.shipment\", required=1)\n internal_contract_id = fields.Many2one(\"erky.contract\", required=1)\n purchase_contract_id = fields.Many2one(\"erky.purchase.contract\", required=0)\n export_form_id = fields.Many2one(\"erky.export.form\", required=1)\n service_id = fields.Many2one(\"product.product\", \"Service\", domain=[('is_ship_service', '=', 1), ('type', '=', 'service')], required=1)\n amount = fields.Float(\"Amount\")\n expense_id = fields.Many2one(\"hr.expense\")\n is_posted = fields.Boolean()\n\n @api.onchange('service_id')\n def get_default_amount(self):\n for rec in self:\n rec.amount = rec.service_id.lst_price\n\n\n","sub_path":"erky_base/models/erky_shipment.py","file_name":"erky_shipment.py","file_ext":"py","file_size_in_byte":16731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"298823506","text":"import scipy.io\nimport numpy as np\nimport pandas as pd\nfrom numpy import array, genfromtxt\nimport csv\nimport os\n\nnp.random.seed(123) # for reproducibility\n\nNUMBER_OF_SUBJECTS = 10\nNUMBER_OF_TRIALS = 5 #per subject\ndef transform_kinect_files_to_matrix():\n csv_data_directory = f'Skeleton_Data/csv_data/'\n process_data_directory = f'Skeleton_Data/matrix_numpy_data/'\n\n for filename in os.listdir(csv_data_directory):\n if \"DS_Store\" not in filename:\n output_data = []\n\n processed_filename = filename[:-4]\n\n f= open('{}{}'.format(process_data_directory, processed_filename),\"w+\")\n datafile = open('{}{}'.format(csv_data_directory, filename), 'r')\n\n x_data = []\n y_data = []\n z_data = []\n\n data = genfromtxt(datafile, delimiter=',')\n joint_data = []\n for i in range(1, 17):\n for j in range(1, len(data)):\n if data[j][4] == i:\n x_data.append(data[j][5])\n y_data.append(data[j][6])\n z_data.append(data[j][7])\n\n joint_data.append(x_data)\n joint_data.append(y_data)\n joint_data.append(z_data)\n output_data.append(joint_data)\n output_data = np.asarray(output_data)\n np.save('{}{}'.format(process_data_directory, processed_filename), output_data)\ntransform_kinect_files_to_matrix()\n","sub_path":"csv_to_matrix.py","file_name":"csv_to_matrix.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"408532475","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ndf_beer = pd.read_csv('/Users/MarcusJohansson/Documents/Skola/TNM108/Projekt/beer_reviews3.csv', delimiter = ';')\n\n\n#Helper function to retrieve the name of the beer from its index\ndef get_name_from_index(index):\n return df_beer[\"Beer\"].iloc[index]\n#Helper function to retrieve the index of the beer from the name\ndef get_index_from_name(name):\n return df_beer.index[df_beer['Beer'] == name]\n\ndef combine_features(row):\n try:\n return row[\"Aroma\"] + \" \" + row[\"Appearance\"] + \" \" + row[\"Taste\"]+ \" \" + row[\"Palate\"]+ \" \" + row[\"Overall\"]+ \" \" + row[\"Comments\"]+ \" \" + row[\"Country\"]+ \" \" + row[\"Style\"]\n except ValueError as err:\n pass\n \nfeatures = [\"Aroma\", \"Appearance\", \"Taste\", \"Palate\", \"Overall\",\"Comments\",\"Country\",\"Style\"]\n\nfor feature in features:\n df_beer[feature] = df_beer[feature].fillna('')\n\ndf_beer[\"combined_features\"] = df_beer.apply(combine_features,axis=1)\n\ncv = CountVectorizer()\ncount_matrix = cv.fit_transform(df_beer[\"combined_features\"])\ncosine_sim = cosine_similarity(count_matrix)\n\nbeer_user_likes = \"Nils Oscar Brown Ale\"\n\n#Getting the index of the beer in the Data Frame\nbeer_index = get_index_from_name(beer_user_likes)\n\nsimilar_beers = list(enumerate(cosine_sim[beer_index[0]]))\n\n#Sorting the beers in descending similarity order\nsorted_similar_beers = sorted(similar_beers, key=lambda x:x[1],reverse=True)[1:]\n\nfor beer in sorted_similar_beers:\n print(get_name_from_index(beer[0]))\n ","sub_path":"Project/.ipynb_checkpoints/beer_review-checkpoint.py","file_name":"beer_review-checkpoint.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"485052337","text":"\ndef corr_rank(x, axis=0):\n \"\"\"Spearman's Rho as Rank Correlation Matrix(for ordinal data)\n\n Parameters\n ----------\n x : ndarray\n data set\n\n axis : int, optional\n Variables as columns is the default (axis=0).\n If variables are in the rows use axis=1\n\n Returns\n -------\n r : ndarray\n Correlation Matrix\n\n p : ndarray\n p-values\n \"\"\"\n # load modules\n from scipy.stats import spearmanr\n import numpy as np\n import oxyba as ox\n import warnings\n\n # transpose if axis<>0\n if axis is not 0:\n x = x.T\n\n # read dimensions and\n n, c = x.shape\n\n # check if enough variables provided\n if c < 2:\n raise Exception(\"Only \" + str(c) +\n \" variables provided. At least 2 variables required\")\n #\n # check if ordinal or send warning message\n for i in range(x.shape[1]):\n flag, msg = ox.isordinal(x[:, i])\n if not flag:\n warnings.warn(msg)\n\n # allocate variables\n r = np.ones((c, c))\n p = np.zeros((c, c))\n\n # compute each (i,j)-th correlation\n for i in range(0, c):\n for j in range(i + 1, c):\n r[i, j], p[i, j] = spearmanr(x[:, i], x[:, j])\n r[j, i] = r[i, j]\n p[j, i] = p[i, j]\n\n # done\n return r, p\n","sub_path":"oxyba/corr_rank.py","file_name":"corr_rank.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"577668826","text":"# Copyright 2013 OpenStack Foundation\n# All Rights Reserved.\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 uuid\nfrom sqlalchemy import orm\nfrom sqlalchemy.schema import (Column, MetaData, Table)\nfrom daisy.db.sqlalchemy.migrate_repo.schema import (Boolean, DateTime,\n String, create_tables,\n drop_tables)\nfrom daisy.db.sqlalchemy import models\n\n\ndef define_template_config_roles_table(meta):\n template_config_roles = \\\n Table('template_config_roles',\n meta,\n Column('id', String(36), primary_key=True, nullable=False),\n Column('config_id', String(80)),\n Column('role_name', String(36)),\n Column('updated_at', DateTime(), nullable=False),\n Column('deleted_at', DateTime()),\n Column('created_at', DateTime(), nullable=False),\n Column('deleted', Boolean(), nullable=False, default=False,\n index=True),\n mysql_engine='InnoDB',\n extend_existing=True)\n return template_config_roles\n\n\ndef upgrade(migrate_engine):\n print(\"042 upgrade\")\n meta = MetaData()\n meta.bind = migrate_engine\n\n tables = [define_template_config_roles_table(meta)]\n create_tables(tables)\n\n configs = Table('configs', meta, autoload=True)\n template_config_id_reserve = getattr(configs.c, 'template_config_id')\n template_config_id_reserve.alter(type=String(80))\n\n template_config = Table('template_config', meta, autoload=True)\n id_reserve = getattr(template_config.c, 'id')\n id_reserve.alter(type=String(80))\n name_reserve = getattr(template_config.c, 'name')\n name_reserve.alter(type=String(128))\n\n template_func = Table('template_func', meta, autoload=True)\n id_reserve = getattr(template_func.c, 'id')\n id_reserve.alter(type=String(80))\n name_reserve = getattr(template_func.c, 'name')\n name_reserve.alter(type=String(128))\n\n template_func_configs = Table('template_func_configs', meta, autoload=True)\n id_reserve = getattr(template_func_configs.c, 'func_id')\n id_reserve.alter(type=String(80))\n name_reserve = getattr(template_func_configs.c, 'config_id')\n name_reserve.alter(type=String(80))\n\n config_service = Table('config_service', meta, autoload=True)\n config_id_reserve = getattr(config_service.c, 'config_id')\n config_id_reserve.alter(type=String(80))\n\n session = orm.sessionmaker(bind=migrate_engine)()\n session.query(models.TemplateService).\\\n filter(models.TemplateService.service_name == \"compute\").\\\n update({\"service_name\": \"openstack-nova-compute\"})\n template_config_roles_count = session.query(\n models.TemplateConfigRoles).count()\n if not template_config_roles_count:\n session.add_all([\n models.TemplateConfigRoles(id=str(uuid.uuid4()),\n config_id='001',\n role_name=\"COMPUTER\"),\n models.TemplateConfigRoles(id=str(uuid.uuid4()),\n config_id='002',\n role_name=\"COMPUTER\"),\n models.TemplateConfigRoles(id=str(uuid.uuid4()),\n config_id='003',\n role_name=\"COMPUTER\"),\n models.TemplateConfigRoles(id=str(uuid.uuid4()),\n config_id='003',\n role_name=\"COMPUTER\"),\n ])\n session.commit()\n\n\ndef downgrade(migrate_engine):\n print(\"042 downgrade\")\n meta = MetaData()\n meta.bind = migrate_engine\n\n tables = [define_template_config_roles_table(meta)]\n drop_tables(tables)\n\n configs = Table('configs', meta, autoload=True)\n template_config_id_reserve = getattr(configs.c, 'template_config_id')\n template_config_id_reserve.alter(type=String(36))\n\n template_config = Table('template_config', meta, autoload=True)\n id_reserve = getattr(template_config.c, 'id')\n id_reserve.alter(type=String(36))\n name_reserve = getattr(template_config.c, 'name')\n name_reserve.alter(type=String(50))\n\n template_func = Table('template_func', meta, autoload=True)\n id_reserve = getattr(template_func.c, 'id')\n id_reserve.alter(type=String(36))\n name_reserve = getattr(template_func.c, 'name')\n name_reserve.alter(type=String(36))\n\n template_func_configs = Table('template_func_configs', meta, autoload=True)\n id_reserve = getattr(template_func_configs.c, 'func_id')\n id_reserve.alter(type=String(36))\n name_reserve = getattr(template_func_configs.c, 'config_id')\n name_reserve.alter(type=String(36))\n\n config_service = Table('config_service', meta, autoload=True)\n config_id_reserve = getattr(config_service.c, 'config_id')\n config_id_reserve.alter(type=String(36))\n","sub_path":"code/daisy/daisy/db/sqlalchemy/migrate_repo/versions/042_alter_config_template.py","file_name":"042_alter_config_template.py","file_ext":"py","file_size_in_byte":5466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"166222193","text":"from django import template\nfrom django.db.models import Count\nfrom django.utils.safestring import mark_safe\nimport markdown\n\nregister = template.Library()\n\nfrom ..models import Post\n@register.simple_tag\ndef total_posts():\n return Post.objects.all().filter(status=\"published\").count()\n\n@register.inclusion_tag('blog/post/latest_posts.html')\ndef show_latest_posts(count=5):\n latest_posts = Post.objects.all().filter(status=\"published\").order_by('-publish')[:count]\n return {'latest_posts': latest_posts, 'title': \"ostatnie posty: \"}\n\n@register.inclusion_tag('blog/post/most_commented.html')\ndef show_most_commented_posts(count=5):\n most_commented_posts = Post.objects.all().filter(status=\"published\").annotate(total_comments=Count('comments')).order_by('-total_comments')[:count]\n return {'most_commented_posts': most_commented_posts, 'title': \"najczęściej komentowane posty: \"}\n\n@register.filter(name='markdown')\ndef markdown_format(text):\n return mark_safe(markdown.markdown(text))","sub_path":"blog/templatetags/blog_tags.py","file_name":"blog_tags.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"316491886","text":"import cv2 as cv\r\nimport numpy as np\r\n\r\ndef rescaleFrame ( frame, scale=0.75):\r\n # This method will works for images, videos and live videos\r\n width = int(frame.shape[1] * scale)\r\n height = int(frame.shape[0] * scale)\r\n dimensions = (width, height)\r\n return cv.resize(frame, dimensions, interpolation=cv.INTER_AREA)\r\n\r\nimg = rescaleFrame(cv.imread('Images/Ruhul.jpg'), scale=0.2)\r\n\r\n# img = cv.imread('Images/bg.jpg')\r\ncv.imshow('Image', img)\r\n\r\n# Averaging\r\naverage = cv.blur(img, (7,7))\r\ncv.imshow('Average Blur', average)\r\n\r\n# Gaussian Blur\r\ngauss = cv.GaussianBlur(img, (3,3), 0)\r\ncv.imshow('Gaussian Blur', gauss)\r\n\r\n# median Blur\r\nmedian = cv.medianBlur(img, 3)\r\ncv.imshow('Median Blur', median)\r\n\r\n# Bilateral\r\nbilateral = cv.bilateralFilter(img, 5, 55, 35)\r\ncv.imshow('Bilateral', bilateral)\r\n\r\ncv.waitKey(0)","sub_path":"smoothing.py","file_name":"smoothing.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"525388555","text":"# pylint: disable=no-value-for-parameter\n# pylint: disable=redefined-outer-name\n# pylint: disable=unused-argument\n# pylint: disable=unused-variable\n# pylint: disable=too-many-arguments\n\n\nfrom typing import Any, Awaitable, Callable, Iterator, Mapping\nfrom unittest import mock\n\nimport aiodocker\nimport pytest\nfrom fastapi import FastAPI\nfrom pydantic import ByteSize, parse_obj_as\nfrom pytest_mock.plugin import MockerFixture\nfrom simcore_service_autoscaling.core.settings import ApplicationSettings\nfrom simcore_service_autoscaling.dynamic_scaling_core import check_dynamic_resources\nfrom simcore_service_autoscaling.modules.docker import get_docker_client\nfrom simcore_service_autoscaling.modules.ec2 import get_ec2_client\nfrom types_aiobotocore_ec2.client import EC2Client\n\n\n@pytest.fixture\ndef aws_instance_private_dns() -> str:\n return \"ip-10-23-40-12.ec2.internal\"\n\n\n@pytest.fixture\ndef mock_start_aws_instance(\n mocker: MockerFixture,\n aws_instance_private_dns: str,\n) -> Iterator[mock.Mock]:\n mocked_start_aws_instance = mocker.patch(\n \"simcore_service_autoscaling.modules.ec2.AutoscalingEC2.start_aws_instance\",\n autospec=True,\n return_value=aws_instance_private_dns,\n )\n yield mocked_start_aws_instance\n\n\n@pytest.fixture\ndef mock_wait_for_node(mocker: MockerFixture) -> Iterator[mock.Mock]:\n mocked_wait_for_node = mocker.patch(\n \"simcore_service_autoscaling.dynamic_scaling_core.utils_docker.wait_for_node\",\n autospec=True,\n )\n yield mocked_wait_for_node\n\n\n@pytest.fixture\ndef mock_tag_node(mocker: MockerFixture) -> Iterator[mock.Mock]:\n mocked_tag_node = mocker.patch(\n \"simcore_service_autoscaling.dynamic_scaling_core.utils_docker.tag_node\",\n autospec=True,\n )\n yield mocked_tag_node\n\n\n@pytest.fixture\ndef minimal_configuration(\n docker_swarm: None,\n disabled_rabbitmq: None,\n disable_dynamic_service_background_task: None,\n aws_subnet_id: str,\n aws_security_group_id: str,\n aws_ami_id: str,\n aws_allowed_ec2_instance_type_names: list[str],\n) -> Iterator[None]:\n yield\n\n\nasync def test_check_dynamic_resources_with_no_services_does_nothing(\n minimal_configuration: None,\n initialized_app: FastAPI,\n mock_start_aws_instance: mock.Mock,\n):\n await check_dynamic_resources(initialized_app)\n mock_start_aws_instance.assert_not_called()\n\n\nasync def test_check_dynamic_resources_with_service_with_too_much_resources_starts_nothing(\n minimal_configuration: None,\n async_docker_client: aiodocker.Docker,\n initialized_app: FastAPI,\n create_service: Callable[[dict[str, Any]], Awaitable[Mapping[str, Any]]],\n task_template: dict[str, Any],\n create_task_reservations: Callable[[int, int], dict[str, Any]],\n assert_for_service_state: Callable[\n [aiodocker.Docker, Mapping[str, Any], list[str]], Awaitable[None]\n ],\n mock_start_aws_instance: mock.Mock,\n):\n task_template_with_too_many_resource = task_template | create_task_reservations(\n 1000, 0\n )\n service_with_too_many_resources = await create_service(\n task_template_with_too_many_resource\n )\n await assert_for_service_state(\n async_docker_client,\n service_with_too_many_resources,\n [\"pending\"],\n )\n\n await check_dynamic_resources(initialized_app)\n mock_start_aws_instance.assert_not_called()\n\n\nasync def test_check_dynamic_resources_with_pending_resources_starts_r5n_4xlarge_instance(\n minimal_configuration: None,\n app_settings: ApplicationSettings,\n async_docker_client: aiodocker.Docker,\n initialized_app: FastAPI,\n create_service: Callable[[dict[str, Any]], Awaitable[Mapping[str, Any]]],\n task_template: dict[str, Any],\n create_task_reservations: Callable[[int, int], dict[str, Any]],\n assert_for_service_state: Callable[\n [aiodocker.Docker, Mapping[str, Any], list[str]], Awaitable[None]\n ],\n mock_start_aws_instance: mock.Mock,\n mock_wait_for_node: mock.Mock,\n mock_tag_node: mock.Mock,\n aws_instance_private_dns: str,\n):\n task_template_for_r5n_4x_large_with_256Gib = (\n task_template | create_task_reservations(4, parse_obj_as(ByteSize, \"128GiB\"))\n )\n service_with_too_many_resources = await create_service(\n task_template_for_r5n_4x_large_with_256Gib\n )\n await assert_for_service_state(\n async_docker_client,\n service_with_too_many_resources,\n [\"pending\"],\n )\n\n await check_dynamic_resources(initialized_app)\n mock_start_aws_instance.assert_called_once_with(\n get_ec2_client(initialized_app),\n app_settings.AUTOSCALING_EC2_INSTANCES,\n instance_type=\"r5n.4xlarge\",\n tags=mock.ANY,\n startup_script=mock.ANY,\n )\n mock_wait_for_node.assert_called_once_with(\n get_docker_client(initialized_app),\n aws_instance_private_dns[: aws_instance_private_dns.find(\".\")],\n )\n mock_tag_node.assert_called_once()\n\n\nasync def test_check_dynamic_resources_with_pending_resources_actually_starts_new_instances(\n minimal_configuration: None,\n async_docker_client: aiodocker.Docker,\n initialized_app: FastAPI,\n create_service: Callable[[dict[str, Any]], Awaitable[Mapping[str, Any]]],\n task_template: dict[str, Any],\n create_task_reservations: Callable[[int, int], dict[str, Any]],\n assert_for_service_state: Callable[\n [aiodocker.Docker, Mapping[str, Any], list[str]], Awaitable[None]\n ],\n ec2_client: EC2Client,\n mock_wait_for_node: mock.Mock,\n mock_tag_node: mock.Mock,\n):\n # we have nothing running now\n all_instances = await ec2_client.describe_instances()\n assert not all_instances[\"Reservations\"]\n\n task_template_for_r5n_8x_large_with_256Gib = (\n task_template | create_task_reservations(4, parse_obj_as(ByteSize, \"128GiB\"))\n )\n service_with_too_many_resources = await create_service(\n task_template_for_r5n_8x_large_with_256Gib\n )\n await assert_for_service_state(\n async_docker_client,\n service_with_too_many_resources,\n [\"pending\"],\n )\n\n await check_dynamic_resources(initialized_app)\n\n # check that the instances are really started\n all_instances = await ec2_client.describe_instances()\n assert len(all_instances[\"Reservations\"]) == 1\n running_instance = all_instances[\"Reservations\"][0]\n assert \"Instances\" in running_instance\n assert len(running_instance[\"Instances\"]) == 1\n running_instance = running_instance[\"Instances\"][0]\n assert \"InstanceType\" in running_instance\n assert running_instance[\"InstanceType\"] == \"r5n.4xlarge\"\n assert \"PrivateDnsName\" in running_instance\n instance_private_dns_name = running_instance[\"PrivateDnsName\"]\n assert instance_private_dns_name.endswith(\".ec2.internal\")\n\n mock_wait_for_node.assert_called_once_with(\n get_docker_client(initialized_app),\n instance_private_dns_name[: instance_private_dns_name.find(\".\")],\n )\n mock_tag_node.assert_called_once()\n","sub_path":"services/autoscaling/tests/unit/test_dynamic_scaling_core.py","file_name":"test_dynamic_scaling_core.py","file_ext":"py","file_size_in_byte":6987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"372736391","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\n# Copyright 2019 The FATE Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nfrom federatedml.param.base_param import BaseParam\nfrom federatedml.util import consts\nfrom federatedml.util import LOGGER\n\n\nclass ColumnExpandParam(BaseParam):\n \"\"\"\n Define method used for expanding column\n\n Parameters\n ----------\n append_header : None or str or List[str], default: None\n Name(s) for appended feature(s). If None is given, module outputs the original input value without any operation.\n method : str, default: 'manual'\n If method is 'manual', use user-specified `fill_value` to fill in new features.\n fill_value : int or float or str or List[int] or List[float] or List[str], default: 1e-8\n Used for filling expanded feature columns. If given a list, length of the list must match that of `append_header`\n need_run: bool, default: True\n Indicate if this module needed to be run.\n \"\"\"\n\n def __init__(self, append_header=None, method=\"manual\",\n fill_value=consts.FLOAT_ZERO, need_run=True):\n super(ColumnExpandParam, self).__init__()\n self.append_header = append_header\n self.method = method\n self.fill_value = fill_value\n self.need_run = need_run\n\n def check(self):\n descr = \"column_expand param's \"\n if not isinstance(self.method, str):\n raise ValueError(f\"{descr}method {self.method} not supported, should be str type\")\n else:\n user_input = self.method.lower()\n if user_input == \"manual\":\n self.method = consts.MANUAL\n else:\n raise ValueError(f\"{descr} method {user_input} not supported\")\n\n BaseParam.check_boolean(self.need_run, descr=descr)\n\n self.append_header = [] if self.append_header is None else self.append_header\n if not isinstance(self.append_header, list):\n raise ValueError(f\"{descr} append_header must be None or list of str. \"\n f\"Received {type(self.append_header)} instead.\")\n for feature_name in self.append_header:\n BaseParam.check_string(feature_name, descr + \"append_header values\")\n\n if isinstance(self.fill_value, list):\n if len(self.append_header) != len(self.fill_value):\n raise ValueError(\n f\"{descr} `fill value` is set to be list, \"\n f\"and param `append_header` must also be list of the same length.\")\n else:\n self.fill_value = [self.fill_value]\n for value in self.fill_value:\n if type(value).__name__ not in [\"float\", \"int\", \"long\", \"str\"]:\n raise ValueError(\n f\"{descr} fill value(s) must be float, int, or str. Received type {type(value)} instead.\")\n\n LOGGER.debug(\"Finish column expand parameter check!\")\n return True\n","sub_path":"python/federatedml/param/column_expand_param.py","file_name":"column_expand_param.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"550046927","text":"import re\r\nimport sys\r\nimport itertools\r\nfrom pyspark import SparkConf, SparkContext\r\n\r\nconf = SparkConf()\r\nsc = SparkContext(conf=conf)\r\n# built the environment\r\nlines = sc.textFile(sys.argv[1])\r\n# read in the parameter 1 to open the data\r\npairs = lines.map(lambda l: (re.split(r'[\\t]+', l)))\r\n# basic transformation on the data to split them\r\nalreadyFriends = pairs.flatMap(lambda user: [((each_friend,user[0]),0) if user[0] > each_friend else ((user[0],each_friend),0) for each_friend in user[1].split(',')])\r\nfriendConnect = pairs.flatMap(lambda user: [((each_pair[1],each_pair[0]),1) if each_pair[0] > each_pair[1] else ((each_pair[0],each_pair[1]),1) for each_pair in itertools.combinations(user[1].split(','),2)])\r\n# find the pairs that are already friends and possible friends connections\r\nfriendConnect.cache()\r\nalreadyFriends.cache()\r\nrrdAll = friendConnect.union(alreadyFriends)\r\n# union combine the two rrd\r\ncomm_friend = rrdAll.groupByKey().filter(lambda user: 0 not in user[1])\r\n# remove the pairs which are already friends\r\ncomm_friend = comm_friend.map(lambda x: (x[0], sum(x[1])))\r\n# count the number of common friends\r\nrrdRecommend = comm_friend.flatMap(lambda user : [(user[0][0],(user[0][1],user[1])),(user[0][1],(user[0][0],user[1]))])\r\n# construct maps for recommendation rank\r\nuser_recommends = rrdRecommend.groupByKey()\r\n# groupby and get a person's possible new friends\r\nuser_recommends_top_10 = user_recommends.mapValues(lambda v: sorted(v, key = lambda x:(-x[1],int(x[0])))[:10]).sortBy(lambda x:int(x[0]))\r\n\r\n# sort the possible friends by the number of their common friends numbers by descending order and only get the top ten\r\ndef outputstring(raw):\r\n host = raw[0]\r\n friends = raw[1]\r\n lst = []\r\n for friend in friends:\r\n lst.append(friend[0])\r\n string = host+\"\\t\"+\",\".join(lst) + \"\\r\"\r\n return string\r\n# write a helper function to convert the recommendations into string\r\n\r\nuser_recommends_output = user_recommends_top_10.map(lambda user: outputstring(user))\r\nuser_recommends_output.saveAsTextFile(sys.argv[2])\r\n\r\nseperate_users = user_recommends_top_10.filter(lambda x:x[0] in ['924', '8941', '8942', '9019', '9020', '9021', '9022', '9990', '9992', '9993'])\r\nseperate_output = seperate_users.map(lambda user: outputstring(user))\r\nseperate_output_file = sys.argv[2]+\"seperate\"\r\nseperate_output.saveAsTextFile(seperate_output_file)\r\n# output 10 specific user's friends separately\r\nsc.stop()\r\n","sub_path":"Spark Collaborative Filtering/Friends Recommendation.py","file_name":"Friends Recommendation.py","file_ext":"py","file_size_in_byte":2448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"250654513","text":"\n\ndef add_word(word, word_count_dict):\n \"\"\"Update the word frequency: word is the key, frequency is the value.\"\"\"\n if word in word_count_dict:\n word_count_dict[word] += 1\n else:\n word_count_dict[word] = 1\n\nimport string\ndef process_line(line, word_count_dict):\n \"\"\"Process the line to get lowercase words to add to the dictionary.\"\"\"\n line = line.strip()\n word_list = line.split()\n for word in word_list:\n #ignore the \"--\" that is in the file\n if word != \"-\":\n word = word.lower()\n word = word.strip()\n # get commas, periods, and other punctuations out as well\n word = word.strip(string.punctuation)\n add_word(word, word_count_dict)\n\ndef pretty_print(word_count_dict):\n \"\"\"Print nicely from highest to lowset frequency.\"\"\"\n # create a list of tuples, (value, key)\n # value_key_list = [(val, key), for key, val in d.items()]\n value_key_list = []\n for key,val in word_count_dict.items():\n if len(key) > 3 and val > 2:\n value_key_list.append((val,key))\n # sort method sorts on list's first element, the frequency.\n # Reverse to get the biggest first\n value_key_list.sort(reverse=True)\n\n print(\"{:11s}{:11s}\".format(\"Word\", \"Count\"))\n print(\"_\"*21)\n for val,key in value_key_list:\n print(\"{:12s} {:<3d}\".format(key, val))\n\ndef main():\n word_count_dict = {}\n gba_file = open(\"gettysburg.txt\", \"r\")\n for line in gba_file:\n process_line(line, word_count_dict)\n print(\"Length of dictionary:\", len(word_count_dict))\n pretty_print(word_count_dict)\n\nmain()","sub_path":"Random_programs/GettysburgAddress_dict.py","file_name":"GettysburgAddress_dict.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"301845079","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nRun this file.\r\n\r\nTakes a .txt file with GPS data and returns a plot of liquid water content of\r\na snowpack through time based on that GPS data. Calls liquid_water_content.py \r\nto convert signal strength above and below the snowpack, snow depth, and elevation \r\nangle to a liquid water content value. A PDF of the plot is also saved.\r\nThe liquid water content (LWC) values are averaged over a certain timestep.\r\n\r\nAdjustable interval of time for averaging LWC values ('time_step') is on line 40.\r\nTo change files, change the name variable to your desired file's name. The name\r\nvariable is on line 34.\r\n\r\nThe PDF of the plot will be saved under the same name as the text file being read\r\nbut with '_SWEplotted.pdf' added. For example, reading a file 'hour_test_1.txt' \r\nwill save a PDF titled 'hour_test_1_SWEplotted.pdf.'\r\n\r\nAuthor: Keenen Francois-King\r\n\"\"\"\r\n\r\n#import modules. liquid_water_content calculates the liquid water content (LWC) based\r\n#on the snow depth, elevation angle of the received signal, and the signal strengths\r\n#above and below the snow.\r\nimport liquid_water_content\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.backends.backend_pdf import PdfPages\r\nfrom collections import defaultdict\r\nimport datetime as dt\r\nfrom matplotlib.dates import DateFormatter\r\n\r\n#Change this name to the name of the .txt file you want to read. It will then \r\n#read the file and save the plots into a PDF of the same name\r\nname = 'hour_test_2'\r\n\r\nf = open(name + '.txt')\r\npdf = PdfPages(name + '_SWEplotted.pdf')\r\n\r\n#adjust this to change how large of a timestep of SWE vals is averaged.\r\ntime_step = 100 #[sec]\r\n\r\ntext = f.readlines()\r\n\r\n#We don't have GPS readings above snowpack or snowpack depth. Eventually we will \r\n#and can use the readings in the txt files from that GPS and the depth sensor to solve \r\n#for LWC. For now we will use the constants strength_above and snow_depth.\r\nstrength_above = 50 #signal strength at GPS above snowpack. Use C/N0 value [dBHz]\r\nsnow_depth = 1 #[m]\r\nsat = []\r\nsat_SNR = []\r\nsat_LWC = []\r\nsat_dict = defaultdict(list)\r\nsat_dict_ave = defaultdict(list)\r\ntime = []\r\nstrength = []\r\nangle = []\r\n\r\n\r\ncurrent_time = None\r\ni = -1\r\nz = 0\r\nset_vals = False\r\n\r\n\r\nfor line in text:\r\n check_line = line.split(',')\r\n \r\n #$GPGGA gives the current timestamp and after it comes the $GPGSV which contains\r\n #the SNR value. Store the timestamp as current_time so that SNR can later be \r\n #plotted against time\r\n \r\n if check_line[0] == '$GPGGA':\r\n current_time = str(check_line[1])\r\n \r\n #append 2-item long lists containing time and SNR value to corresponding satellite's list\r\n elif check_line[0] == '$GPGSV':\r\n try:\r\n #The GPS recieves data at a frequency of 1575.42MHz. We can convert \r\n #the C/N0 value from the GPS which is in dB-Hz to an SNR value in dB \r\n #which is used in calculating the SWE. Reciever frequency = 1575.42MHz. \r\n #Bandwidth = 10*log(1575.42*1,000,000) = 91.973963545486232243880870991767 dB.\r\n #SNR = C/N0 - BW = C/N0 - 91.973963545486232243880870991767.\r\n sat_SNR.append([int((int(current_time[:2])*3600)+(int(current_time[2:4])*60)+\\\r\n (int(current_time[4:6]))), float((strength_above)-91.973963545486232243880870991767), \\\r\n float(float(check_line[7])-91.973963545486232243880870991767), snow_depth, float(check_line[5])])\r\n except (ValueError, IndexError):\r\n continue\r\n else:\r\n continue\r\n\r\n#This function calls liquid_water_content. This will convert the values of SNR to\r\n#values of LWC.\r\ndef fx(x):\r\n all_converted = []\r\n for instance in list(map(lambda y: liquid_water_content.LWE(y).solve_equations(), x)):\r\n all_converted.append(instance)\r\n return all_converted \r\n\r\n#Call function above. Convert SNR vals in sat_SNR to LWC values in sat_LWC\r\nsat_LWC = fx(sat_SNR)\r\n\r\nsat_data = []\r\nprev = sat_LWC[0][0]\r\ncount = 0\r\ntotal_count = 0\r\nsihvola = 0\r\ndenoth = 0\r\nroth = 0\r\n\r\n#average LWC values for all repeated times so that way we have no repeats in time.\r\nfor i in sat_LWC:\r\n total_count += 1\r\n if i[0] == prev and total_count != len(sat_LWC):\r\n count += 1\r\n sihvola += i[1]\r\n denoth += i[2]\r\n roth += i[3]\r\n else:\r\n if count == 0:\r\n count += 1\r\n if total_count == len(sat_LWC):\r\n count += 1\r\n sihvola += i[1]\r\n denoth += i[2]\r\n roth += i[3]\r\n sat_data.append([prev, (sihvola/count), (denoth/count), (roth/count)])\r\n prev = i[0]\r\n count = 1\r\n sihvola = i[1]\r\n denoth = i[2]\r\n roth = i[3]\r\n\r\nstart = sat_data[0][0]\r\nsat_data_ave = []\r\ninterval = 0\r\ncount = 0\r\ntotal_count = 1\r\ntime_ave = 0\r\nsihvola_ave = 0\r\ndenoth_ave = 0\r\nroth_ave = 0\r\n\r\n#Average SWE values for a certain timestep set above. Time and all SWE values will \r\n#be averaged.\r\n#If there is still time left in the interval we will enter the if statement.\r\n#The time between the current data and previous is then taken from the interval.\r\n#If the interval becomes greater than the timestep, we have reached the end\r\n#of the timestep and will move on to the else statement, append the average\r\n#and start a new interval.\r\nfor i in sat_data:\r\n\r\n if time_step > (i[0]-start) and total_count != len(sat_data):\r\n interval = (i[0]-start)\r\n count += 1\r\n time_ave += i[0]\r\n sihvola_ave += i[1]\r\n denoth_ave += i[2]\r\n roth_ave += i[3]\r\n total_count += 1\r\n else:\r\n #two cases will result in an error if we don't do this step. Those are\r\n #cases where we have a data point that is not within the time_step of\r\n #another point or when we are at the last data point. We need to then\r\n #add the values for those cases.\r\n if count == 0 or total_count == len(sat_SNR):\r\n time_ave += i[0]\r\n sihvola_ave += i[1]\r\n denoth_ave += i[2]\r\n roth_ave += i[3]\r\n count += 1\r\n \r\n #average the values for time and LWC and append to new list\r\n sat_data_ave.append([int(time_ave/count), (sihvola_ave/count), \\\r\n (denoth_ave/count), (roth_ave/count)])\r\n total_count += 1\r\n #reset these values so we can start averaging a new interval of data points\r\n start = i[0]\r\n count = 1\r\n interval = 0\r\n time_ave = i[0]\r\n sihvola_ave = i[1]\r\n denoth_ave = i[2]\r\n roth_ave = i[3]\r\n\r\n#separate data to make plotting and formatting easier\r\ntime = []\r\nsihv = []\r\ndeno = []\r\nroth = []\r\nfor x in sat_data_ave:\r\n time.append(str(int(x[0]/3600)) + ':' + str(int((float(x[0]/3600)-int(x[0]/3600))*60))\\\r\n + ':' + str(int(int((((float(x[0]/3600) - int(x[0]/3600))*60)-\\\r\n (int((float(x[0]/3600)-int(x[0]/3600))*60)))*60))))\r\n sihv.append(x[1])\r\n deno.append(x[2])\r\n roth.append(x[3]) \r\n\r\nplottable_time = []\r\nfor x in time:\r\n time_plot = dt.datetime.strptime(x, '%H:%M:%S')\r\n plottable_time.append(time_plot)\r\nprint(len(plottable_time))\r\n#plot data\r\nfig = plt.figure(figsize = (18,5))\r\nax = plt.subplot(111)\r\nax.set_title('Liquid Water Content (averaged at ' + str(time_step) + \\\r\n ' second intervals)', fontsize=15, fontweight='bold')\r\nax.set_ylabel('Liquid Water Content [%]')\r\nax.set_xlabel('UTC Time [HH:MM:SS]')\r\nax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))\r\nax.plot(plottable_time, sihv, 'ro', markersize=3, label = 'Sihvola')\r\nax.plot(plottable_time, deno, 'bo', markersize=3, label = 'Denoth')\r\nax.plot(plottable_time, roth, 'go', markersize=3, label = 'Roth')\r\nax.legend(loc = 'center left', bbox_to_anchor=(1, 0.5))\r\npdf.savefig()\r\nplt.show()\r\npdf.close()\r\n \r\n","sub_path":"Plot_LWC/plot_LWC.py","file_name":"plot_LWC.py","file_ext":"py","file_size_in_byte":7892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"135244248","text":"#!/usr/bin/env python3.4\n# -*- coding: utf-8 -*-\n\nfrom jsonrpc import dispatcher\nfrom database import Database, _Account\n \n\nclass Account():\n\n @dispatcher.add_method\n def CreateAccount(**kwargs):\n \tsession = Database.session()\n\n \taccount = _Account(name=kwargs[\"name\"])\n \t\n \tsession.add(account)\n \tsession.commit()\n \taccount_id = account.account_id;\n \tsession.close()\n\n \treturn {\"account_id\" : account_id}\n \t\n \t","sub_path":"src/entity/Account.py","file_name":"Account.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"635202766","text":"\nimport unittest\nimport common\nimport json\n\n_schema = 'ctypes'\n\ndef setUpModule():\n url = 'schema/%s' % _schema\n r = common.primary_session.get(url)\n if r.status_code == 404:\n # idempotent because unittest can re-enter module several times... :-(\n common.primary_session.post(url)\n\ndef add_etype_vk_wk_rk(klass, vk, wk, rk):\n def check_json(self):\n r = self.session.get(self._read_urls()[rk])\n self.assertHttp(r, 200, 'application/json')\n self.assertJsonEqual(r.json(), self._data(vk))\n setattr(klass, 'test_%s_%s_json_2_read_%s' % (vk, wk, rk), check_json)\n\n def check_csv(self):\n r = self.session.get(self._read_urls()[rk], headers={\"Accept\": \"text/csv\"})\n self.assertHttp(r, 200, 'text/csv')\n self.assertEqual(r.content, self._data_csv(vk))\n setattr(klass, 'test_%s_%s_csv_2_read_%s' % (vk, wk, rk), check_csv)\n\ndef add_etype_vk_wk(klass, vk, wk):\n def load_json(self):\n self.assertHttp(self.session.put(self._write_urls()[wk], json=self._data(vk)), 200)\n setattr(klass, 'test_%s_%s_json_1_load' % (vk, wk), load_json)\n\n def load_csv(self):\n self.assertHttp(\n self.session.put(\n self._write_urls()[wk],\n data=self._data_csv(vk),\n headers={'Content-Type': 'text/csv'}\n ), 200)\n setattr(klass, 'test_%s_%s_csv_1_load' % (vk, wk), load_csv)\n\n for rk in klass._read_urls().keys():\n add_etype_vk_wk_rk(klass, vk, wk, rk)\n\n def check_query(self):\n if self.etype == 'jsonb':\n r = self.session.get(self._query_url(self._values[vk]))\n self.assertHttp(r, 200, 'application/json')\n self.assertJsonEqual(r.json(), self._data(vk))\n setattr(klass, 'test_%s_%s_pred_3' % (vk, wk), check_query)\n\ndef add_etype_tests(klass):\n # generate a dense set of related tests by nested loops over value, write URL, read URL, and content-types\n for vk in klass._values.keys():\n for wk in klass._write_urls().keys():\n add_etype_vk_wk(klass, vk, wk)\n return klass\n\n@add_etype_tests\nclass EtypeJson (common.ErmrestTest):\n etype = 'json'\n\n @classmethod\n def _table_name(cls):\n return 'test_%s' % cls.etype\n\n @classmethod\n def _table_def(cls):\n return {\n \"kind\": \"table\",\n \"schema_name\": _schema,\n \"table_name\": cls._table_name(),\n \"column_definitions\": [ \n { \"type\": { \"typename\": \"int8\" }, \"name\": \"id\", \"nullok\": False },\n { \"type\": { \"typename\": \"text\" }, \"name\": \"name\" },\n { \"type\": { \"typename\": cls.etype }, \"name\": \"payload\" }\n ],\n \"keys\": [ { \"unique_columns\": [ \"id\" ] } ]\n }\n\n @classmethod\n def setUpClass(cls):\n common.primary_session.post('schema/%s/table' % _schema, json=cls._table_def()).raise_for_status()\n\n @classmethod\n def _write_urls(cls):\n return {\n \"1entity\": 'entity/%s:%s' % (_schema, cls._table_name()),\n \"2attributegroup\": 'attributegroup/%s:%s/id;name,payload' % (_schema, cls._table_name())\n }\n\n def _query_url(self, value):\n return 'entity/%s:%s/payload=%s' % (_schema, self._table_name(), common.urlquote(json.dumps(value)))\n\n @classmethod\n def _read_urls(cls):\n return {\n k: v + '@sort(id)'\n for k, v in cls._write_urls().items() + [(\"attribute\", 'attribute/%s:%s/id,name,payload' % (_schema, cls._table_name()))]\n }\n\n _values = {\n \"number\": 5,\n \"string\": \"foo\",\n \"object\": {\"foo\": \"bar\"},\n \"numbers\": [5, 6],\n \"strings\": [\"foo\", \"bar\"],\n \"objects\": [{\"foo\": \"bar\"}, {\"foo\": \"bar\"}],\n \"null\": None\n }\n\n def _data(self, key):\n return [\n {\"id\": 1, \"name\": \"row1\", \"payload\": self._values[key]}\n ]\n\n def _data_csv(self, key):\n val = json.dumps(self._values[key])\n if val.find('\"') >= 0 or val.find(',') >= 0:\n val = '\"%s\"' % val.replace('\"', '\"\"')\n return \"\"\"id,name,payload\n1,row1,%s\n\"\"\" % val\n\nclass EtypeJsonb (EtypeJson):\n etype = 'jsonb'\n\n\nclass CtypeText (common.ErmrestTest):\n ctype = 'text'\n cval = 'one'\n pattern = 'one'\n\n def _table_name(self):\n return 'test_%s' % self.ctype\n\n def _qual_table_name(self):\n return '%s:%s' % (_schema, self._table_name())\n \n def _entity_url(self):\n return 'entity/%s' % (self._qual_table_name())\n\n def _pattern_url(self, colname):\n return '%s/%s::regexp::%s' % (\n self._entity_url(),\n colname,\n self.pattern\n )\n\n def _table_def(self):\n return {\n \"kind\": \"table\",\n \"schema_name\": _schema,\n \"table_name\": self._table_name(),\n \"column_definitions\": [\n {\"type\": {\"typename\": \"serial\"}, \"name\": \"sid\", \"nullok\": False},\n {\"type\": {\"typename\": self.ctype}, \"name\": \"column1\"},\n {\"type\": {\"typename\": \"text\"}, \"name\": \"column2\"},\n {\"type\": {\"typename\": \"%s[]\" % self.ctype, \"is_array\": True, \"base_type\": {\"typename\": self.ctype}}, \"name\": \"column3\"}\n ],\n \"keys\": [ {\"unique_columns\": [\"sid\"]}, {\"unique_columns\": [\"column1\"]} ]\n }\n \n def _data(self):\n return [\n {\"sid\": 1, \"column1\": self.cval, \"column2\": \"value1\", \"column3\": None}, \n {\"sid\": 2, \"column1\": None, \"column2\": \"value2\", \"column3\": [self.cval, self.cval]},\n {\"sid\": 3, \"column1\": None, \"column2\": \"value3\", \"column3\": []},\n ]\n \n def test_01_create(self):\n self.assertHttp(self.session.post('schema/%s/table' % _schema, json=self._table_def()), 201)\n\n def test_02_queryempty(self):\n self.assertHttp(self.session.get(self._entity_url()), 200, 'application/json')\n\n def test_03_introspect(self):\n r = self.session.get('schema/%s/table/%s' % (_schema, self._table_name()))\n self.assertHttp(r, 200, 'application/json')\n doc = r.json()\n self.assertEqual(doc['column_definitions'][1]['type']['typename'], self.ctype)\n\n def test_04_load(self):\n self.assertHttp(\n self.session.post(\n self._entity_url(),\n data=common.array_to_csv(self._data()),\n headers={\"content-type\": \"text/csv\"}\n ),\n 200\n )\n self.assertHttp(self.session.put(self._entity_url(), json=self._data()), 200)\n\n def _pattern_check(self, colname, expected_count):\n r = self.session.get(self._pattern_url(colname))\n self.assertHttp(r, 200, 'application/json')\n got_count = len(r.json())\n self.assertEqual(\n got_count,\n expected_count,\n 'Column %s should match %s %s times, not %s.\\n%s\\n' % (colname, self.pattern, expected_count, got_count, r.content)\n )\n \n def test_05a_patterns(self):\n self._pattern_check('column1', 1)\n self._pattern_check('column3', 1)\n self._pattern_check('*', 2)\n\n def test_05b_empty_array_input(self):\n # this test is useless but harmless for the subclasses that disable array storage for column3...\n r = self.session.get(self._entity_url() + '/sid=3')\n self.assertHttp(r, 200, 'application/json')\n self.assertEqual(r.json()[0][\"column3\"], self._data()[2][\"column3\"])\n\n def test_06_retrieve(self):\n self.assertHttp(self.session.get(self._entity_url()), 200, 'application/json')\n self.assertHttp(self.session.get(self._entity_url(), headers={\"Accept\": \"text/csv\"}), 200, 'text/csv')\n\n def test_07_drop(self):\n self.assertHttp(self.session.delete('schema/%s/table/%s' % (_schema, self._table_name())), 204)\n\nclass CtypeBoolean (CtypeText):\n ctype = 'boolean'\n cval = 'True'\n pattern = 't'\n\nclass CtypeJsonb (CtypeText):\n ctype = 'jsonb'\n cval = {\"foo\": \"bar\"}\n pattern = 'foo.%2Abar'\n \n def _data(self):\n # override because we don't want to deal w/ test suite limitations\n # SQL NULL vs JSON null vs empty string for JSON vs CSV inputs\n return [\n {\"sid\": 1, \"column1\": self.cval, \"column2\": \"value1\", \"column3\": None}, \n {\"sid\": 2, \"column1\": 5, \"column2\": \"value2\", \"column3\": [self.cval, self.cval]},\n {\"sid\": 3, \"column1\": 10, \"column2\": \"value3\", \"column3\": []},\n ]\n\nclass CtypeFloat4 (CtypeText):\n ctype = 'float4'\n cval = 1.0\n pattern = '1'\n\nclass CtypeFloat8 (CtypeFloat4): ctype = 'float8'\n\nclass CtypeInt2 (CtypeText):\n ctype = 'int2'\n cval = 1\n pattern = '1'\n\nclass CtypeInt4 (CtypeInt2): ctype = 'int4'\n\nclass CtypeInt8 (CtypeInt2): ctype = 'int8'\n\nclass CtypeTimestamptz (CtypeText):\n ctype = 'timestamptz'\n cval = '2015-03-11T11:32:56-0000'\n pattern = '56'\n\nclass CtypeTimestamp (CtypeTimestamptz):\n ctype = 'timestamp'\n cval = '2015-03-11T11:32:56'\n\nclass CtypeTimetz (CtypeTimestamptz):\n ctype = 'timetz'\n cval = '11:32:56-0000'\n\nclass CtypeTime (CtypeTimestamptz):\n ctype = 'time'\n cval = '11:32:56'\n\nclass CtypeDate (CtypeInt2):\n ctype = 'date'\n cval = '2015-03-11'\n\nclass CtypeUuid (CtypeInt2):\n ctype = 'uuid'\n cval = '2648a44e-c81d-11e4-b6d7-00221930f5cc'\n \nclass CtypeInterval (CtypeInt2):\n ctype = 'interval'\n cval = 'P1Y2M3DT4H5M6S'\n\nclass CtypeSerial2 (CtypeInt2):\n ctype = 'serial2'\n\n def _table_def(self):\n \"\"\"Don't make arrays of this type.\"\"\"\n doc = CtypeInt2._table_def(self)\n doc['column_definitions'][3] = {\"type\": {\"typename\": self.ctype}, \"name\": \"column3\"}\n return doc\n\n def _data(self):\n \"\"\"Don't make arrays of this type.\"\"\"\n return [\n {\"sid\": 1, \"column1\": None, \"column2\": \"value1\", \"column3\": self.cval },\n {\"sid\": 2, \"column1\": None, \"column2\": \"value1\", \"column3\": self.cval },\n {\"sid\": 3, \"column1\": None, \"column2\": \"value2\", \"column3\": self.cval },\n {\"sid\": 4, \"column1\": None, \"column2\": \"value2\", \"column3\": self.cval },\n ]\n \n def test_04_load(self):\n self.assertHttp(\n self.session.post(\n self._entity_url() + '?defaults=column1',\n data=common.array_to_csv(self._data()[0:3]),\n headers={\"content-type\": \"text/csv\"}\n ),\n 200\n )\n self.assertHttp(\n self.session.post(\n self._entity_url() + '?defaults=column1',\n json=self._data()[3:]\n ),\n 200\n )\n\n def test_05a_patterns(self):\n self._pattern_check('column1', 1)\n self._pattern_check('*', 4)\n\nclass CtypeSerial4 (CtypeSerial2): ctype = 'serial4'\n\nclass CtypeSerial8 (CtypeSerial2): ctype = 'serial8'\n\nclass CtypeLongtext (CtypeText):\n ctype = 'longtext'\n cval = 'oneoneone'\n\n def _table_def(self):\n \"\"\"Don't make arrays of this type.\"\"\"\n doc = CtypeText._table_def(self)\n doc['column_definitions'][3] = {\"type\": {\"typename\": self.ctype}, \"name\": \"column3\"}\n return doc\n\n def _data(self):\n \"\"\"Don't make arrays of this type.\"\"\"\n doc = CtypeText._data(self)\n doc[1][\"column3\"] = self.cval\n doc[2][\"column3\"] = None\n return doc\n \nclass CtypeMarkdown (CtypeLongtext):\n ctype = 'markdown'\n cval = '**one**'\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"test/resttest/ctypes_test.py","file_name":"ctypes_test.py","file_ext":"py","file_size_in_byte":11491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"554355383","text":"import json\nimport socket\nfrom threading import Lock, Event\n\n\nclass PublisherSocket:\n \"\"\"\n This class is a socket handler for a Publisher client. It listens for incoming messages from the client and forwards\n these messages to subscriber clients subscribed to the topic.\n \"\"\"\n\n def __init__(self, con: socket.socket, addr, topic: str, subscribers: dict, identifier: str, event, timeout=1):\n \"\"\"\n Constructor for the PublisherSocket class.\n\n :param con: The socket connection to handle\n :param addr: The address of the client\n :param topic: The publisher topic\n :param subscribers: A complete list from the server containing all topic -> subscriber mappings.\n :param identifier: The publisher's identifier\n :param event: An Event object for notifying the server that the connection is dead.\n :param timeout: The timeout duration for socket receive function\n \"\"\"\n self.con = con\n self.addr = addr\n self.topic = topic\n self.subscribers = subscribers[topic] # List of subscribers for the publisher's topic\n self.id = identifier\n self.event_flag = event\n self.shutdown = False\n self.subscriber_lock = Lock()\n\n self.con.settimeout(timeout)\n\n def add_subscriber(self, subscriber):\n \"\"\"\n Add a subscriber to this publisher\n\n :param subscriber: the new subscriber\n :return: None\n \"\"\"\n with self.subscriber_lock:\n if subscriber not in self.subscribers:\n self.subscribers.append(subscriber)\n\n def remove_subscriber(self, subscriber):\n \"\"\"\n Remove a subscriber from this publisher\n\n :param subscriber: the subscriber to remove\n :return: None\n \"\"\"\n with self.subscriber_lock:\n if subscriber in self.subscribers:\n self.subscribers.remove(subscriber)\n\n def stop(self):\n \"\"\"\n Set shutdown flag for this connection\n\n :return: None\n \"\"\"\n self.shutdown = True\n\n def run(self):\n \"\"\"\n Run loop for the connection. Listens for incoming messages and forwards them to subscribers.\n Sets the disconnect event flag at end of run.\n\n :return:\n \"\"\"\n with self.con:\n while not self.shutdown:\n try:\n data = self.con.recv(2**16)\n if not data:\n self.shutdown = True\n break\n data_list = self._check_for_multiple(data)\n for item in data_list:\n jdata = json.loads(item)\n self._forward_msg(jdata)\n except socket.timeout as e:\n pass\n except ConnectionResetError as e:\n print(self, ':: Connection was forcibly closed by remote')\n self.shutdown = True\n except json.JSONDecodeError:\n print(f'{self} :: Exception caught when attempting to load the following as JSON:\\n{data}')\n self.event_flag.set()\n\n def _check_for_multiple(self, input_data: bytes):\n \"\"\"\n Check received data for multiple JSON objects / messages and separate them into a list.\n\n :param input_data: the received data as bytes\n :return: list of individual messages\n \"\"\"\n separated_data = input_data.split(b'}{')\n n = len(separated_data)\n if n > 1:\n for i in range(1, n):\n separated_data[i - 1] = separated_data[i - 1] + b'}'\n separated_data[i] = b'{' + separated_data[i]\n return separated_data\n\n def _forward_msg(self, json_obj):\n \"\"\"\n Forward message to subscribers\n\n :param json_obj: the message to forward\n :return: None\n \"\"\"\n with self.subscriber_lock:\n for subscriber in self.subscribers:\n subscriber.add_msg(json_obj)\n\n\nclass SubscriberSocket:\n \"\"\"\n This class is a socket handler for a Subscriber client. It waits for incoming messages from publishers and forwards\n these messages to the client.\n \"\"\"\n\n def __init__(self, con: socket.socket, addr, topics: list, identifier: str, event, timeout=1):\n \"\"\"\n Constructor for the SubscriberSocket\n\n :param con: The socket connection to handle\n :param addr: The address of the client\n :param topics: The subscribed topics\n :param identifier: The subscriber's identifier\n :param event: An Event object for notifying the server that the connection is dead.\n :param timeout: The timeout duration for socket receive function\n \"\"\"\n self.con = con\n self.addr = addr\n self.topics = topics # List of topics this subscriber subscribes to\n self.id = identifier\n self.event_flag = event\n\n self.shutdown = False\n self.inbox = {key: [] for key in self.topics}\n self.inbox_lock = Lock()\n self.inbox_event = Event()\n self.con.settimeout(timeout)\n\n def run(self):\n \"\"\"\n Run loop for the subscriber socket. Sets the disconnect event flag at end of run.\n\n :return: None\n \"\"\"\n with self.con:\n while not self.shutdown:\n event = self.inbox_event.wait(timeout=1)\n if event:\n self._forward_msgs()\n self.event_flag.set()\n\n def stop(self):\n \"\"\"\n Set the shutdown flag to true\n\n :return: None\n \"\"\"\n self.shutdown = True\n self.inbox_event.clear()\n\n def add_msg(self, msg):\n \"\"\"\n Add a message to this subscriber socket's inbox and notify about new message\n\n :param msg: the message to add\n :return: None\n \"\"\"\n topic = msg['topic']\n with self.inbox_lock:\n self.inbox[topic].append(msg)\n self._notify()\n\n def _forward_msgs(self):\n \"\"\"\n Forward messages in inbox to the client.\n\n :return: None\n \"\"\"\n if not self.shutdown:\n with self.inbox_lock:\n for key in self.topics:\n for msg in self.inbox[key]:\n try:\n self.con.sendall(json.dumps(msg).encode('utf-8'))\n except ConnectionResetError:\n print(self, 'attempted to send to dead subscriber. (ConnectionResetError)')\n self.shutdown = True\n except ConnectionAbortedError:\n print(self, 'receiver has closed connection. (ConnectionAbortedError)')\n self.shutdown = True\n self.inbox = {key: [] for key in self.topics}\n self.inbox_event.clear()\n\n def _notify(self):\n \"\"\"\n Notify about new message in inbox.\n\n :return: None\n \"\"\"\n self.inbox_event.set()\n","sub_path":"process-communication/proccom/master/server_util.py","file_name":"server_util.py","file_ext":"py","file_size_in_byte":7039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"213829226","text":"import cv2 # py -m pip install opencv-python\n# 可能默认下载的模块跟你的Python环境不匹配,到下面的镜像中找和你版本匹配\nimport os,sys\nimport shutil\nimport datetime\n\n# img=cv2.imread(r'G:\\BaiduNetdiskDownload\\beauty\\mmexport1628082858289.png',cv2.IMREAD_UNCHANGED)\n# cv2.imshow('image',img) # 路径中不要有中文\n#input video\nvideoName=r\"G:\\BaiduNetdiskDownload\\weishitongAIVideo\\1628348593.mp4\"\nsavedpath=r\"G:\\BaiduNetdiskDownload\\weishitongAIVideo\\1628348593\"\n\n# 计时\nstart_time=datetime.datetime.now()\nisExists=os.path.exists(savedpath)\nif not isExists:\n os.makedirs(savedpath)\n print('path of %s is build' % savedpath)\nelse:\n shutil.rmtree(savedpath)\n os.makedirs(savedpath)\n print('path of %s already exists and rebuild' % savedpath)\n\nfps=14.91\n\n# the gap of frame\ncount=10\nvideo_cap=cv2.VideoCapture(videoName)\nskip_frame=True\nstep=4\n# print(videoCapture.size())\ni=0\nj=0\n\nwhile True:\n success,frame=video_cap.read()\n # 跳帧\n if skip_frame:\n video_cap.set(cv2.CAP_PROP_POS_FRAMES,i)\n success,frame=video_cap.read() # 读取一帧数据\n else:\n succes,frame=video_cap.read()\n \n if not success:\n print('video is all read')\n break\n if(i%count==0):\n j+=1\n savedname=savedpath.split('\\\\')[3]+'_'+str(j)+'_'+str(i)+'.jpg'\n imgPath=savedpath+\"\\\\\"+savedname\n cv2.imwrite(imgPath,frame)\n # cv2.imshow('image',imgPath)\n print('image of %s is being saved' % imgPath)\n i+=step\n\nend_time=datetime.datetime.now()\nprint(end_time)\nprint(\"finished. %s seconds elapsed\" % (end_time-start_time).seconds)\n\n\n\n\n","sub_path":"tests/视频AI/视频抽帧.py","file_name":"视频抽帧.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"544106067","text":"import random\n\n\nprint(\"Guessing Game 1 - 20 (3 tries only)\")\n\nsecretnum = random.randint(0, 2) + 1\n\ni = 1;\n\nwhile (i <= 3):\n guess = int(input(f\"Guess no.{i}: \"))\n if guess == secretnum:\n print(\"You won\")\n break\n i += 1\nelse:\n print(\"You Lost_\")","sub_path":"GuessingGame/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"40252920","text":"def lengthOfLIS(nums):\n if len(nums) == 0:\n return 0\n else:\n dp = {0: (1, nums[0])}\n\n for i, num in enumerate(nums):\n if i > 0:\n lis = 0\n for j, v in dp.items():\n if j < i and v[0] > lis and v[1] < num:\n lis = v[0]\n dp[i] = (lis + 1, num)\n\n return max(dp.values())[0]\n\n\ndef lengthOfLIS_again(nums):\n if len(nums) > 0:\n\n dp = [(0, 0)] * len(nums)\n dp[0] = (1, nums[0])\n\n largest_lis = 1\n\n for i, num in enumerate(nums):\n if i > 0:\n current_lis = 0\n current_num = 0\n previous_largest_dp_index = 0\n for j, (lis, smallest_value) in enumerate(dp):\n if i > j:\n if num > smallest_value and lis >= current_lis:\n current_num = num\n current_lis = lis\n previous_largest_dp_index = j\n\n dp[i] = (dp[previous_largest_dp_index][0] + 1, current_num) if current_lis != 0 else (1, num)\n\n largest_lis = max(largest_lis, dp[i][0])\n\n return largest_lis\n else:\n return 0\n\n\ndef lengthOfLIS_again2(nums):\n n = len(nums)\n\n if n > 0:\n dp = [0] * n\n\n longest = 0\n\n for i in range(n):\n current_longest = 1\n\n for j in range(i):\n if dp[j] >= current_longest and nums[j] < nums[i]:\n current_longest = dp[j] + 1\n\n dp[i] = current_longest\n\n longest = max(dp[i], longest)\n\n return longest\n\n else:\n return 0\n","sub_path":"leetcode/dp/medium/longest_increasing_subsequence.py","file_name":"longest_increasing_subsequence.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"190538180","text":"# -*- coding: utf-8 -*-\n''' VISUO 3D\n v.17.03.12\n Written by Mike Cichonski\n for the Science of Imagination Laboratory\n Carleton University\n\n File: progress_bar.py\n Provides a simple progress bar for prepare_data.py\n and working_combos.py.'''\n\ndef update (iteration, total, prefix = '', \\\n suffix = '', decimals = 1, \\\n length = 33, fill = '█'):\n '''initialize or update the current progress bar'''\n percent = (\"{0:.\"+str(decimals)+\"f}\").format(100*(iteration/float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n print ('\\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix),end='\\r',)\n if iteration == total:\n print ('')\n","sub_path":"modules/progress_bar.py","file_name":"progress_bar.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"401625367","text":"import logging\n\nimport yaml\nfrom toscaparser.nodetemplate import NodeTemplate\nfrom toscaparser.tosca_template import ToscaTemplate\nfrom toscaparser.topology_template import TopologyTemplate\n\nimport operator\n\nfrom service.simple_spec_alayzer import SimpleAnalyzer\nfrom util import tosca_helper\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\ndef add_requirement(node, missing_requirement, capable_node_name):\n \"\"\"Add the requirement to the node \"\"\"\n first_key = next(iter(missing_requirement))\n missing_requirement[first_key]['node'] = capable_node_name\n if isinstance(node, NodeTemplate):\n contains_requirement = False\n for node_requirement in node.requirements:\n if node_requirement == missing_requirement:\n contains_requirement = True\n break\n if not contains_requirement:\n node.requirements.append(missing_requirement)\n elif isinstance(node, dict):\n type_name = next(iter(node))\n if 'requirements' not in node[type_name]:\n node[type_name]['requirements'] = []\n node_requirements = node[type_name]['requirements']\n contains_requirement = False\n for node_requirement in node_requirements:\n if node_requirement == missing_requirement:\n contains_requirement = True\n break\n if not contains_requirement:\n node[type_name]['requirements'].append(missing_requirement)\n return node\n\n\ndef get_default_value(node_property):\n if node_property and node_property.required and isinstance(node_property.value, dict) and 'required' in \\\n node_property.value and 'type' in node_property.value:\n if node_property.default:\n return {node_property.name: node_property.default}\n if node_property.constraints:\n for constraint in node_property.constraints:\n print(constraint)\n if node_property and node_property.required and node_property.value:\n return {node_property.name: node_property.value}\n return None\n\n\nclass Planner:\n\n def __init__(self, tosca_path=None, yaml_dict_tpl=None, spec_service=None):\n if tosca_path:\n with open(tosca_path) as file:\n yaml_dict_tpl = yaml.load(file, Loader=yaml.FullLoader)\n\n self.yaml_dict_tpl = yaml_dict_tpl\n logger.info('yaml_dict_tpl:\\n' + str(yaml.dump(yaml_dict_tpl)))\n if 'workflows' in yaml_dict_tpl['topology_template']:\n self.workflows = yaml_dict_tpl['topology_template'].pop('workflows')\n logger.info(\"Ignoring workflows: \" + str(self.workflows))\n self.tosca_template = ToscaTemplate(yaml_dict_tpl=yaml_dict_tpl)\n\n self.tosca_node_types = self.tosca_template.nodetemplates[0].type_definition.TOSCA_DEF\n self.all_custom_def = self.tosca_template.nodetemplates[0].custom_def\n self.all_node_types = {}\n self.all_node_types.update(self.tosca_node_types.items())\n self.all_node_types.update(self.all_custom_def.items())\n self.required_nodes = []\n\n self.spec_service = spec_service\n\n def add_required_nodes_to_template(self, required_nodes):\n for req_node in required_nodes:\n node_template = tosca_helper.node_type_2_node_template(req_node, self.all_custom_def)\n self.tosca_template.nodetemplates.append(node_template)\n return self.tosca_template\n\n def set_default_node_properties(self, node):\n logger.info('Setting properties for: ' + str(node.type))\n ancestors_properties = tosca_helper.get_all_ancestors_properties(node, self.all_node_types,\n self.all_custom_def)\n default_properties = {}\n if ancestors_properties:\n for ancestors_property in ancestors_properties:\n for node_prop in node.get_properties_objects():\n if ancestors_property.name == node_prop.name and isinstance(node_prop.value,dict) \\\n and 'required' in node_prop.value and 'type' in node_prop.value:\n default_property = get_default_value(ancestors_property)\n if default_property:\n node_prop.value = default_property\n default_properties[next(iter(default_property))] = default_property[\n next(iter(default_property))]\n if default_properties:\n for default_property in default_properties:\n for node_prop_obj in node.get_properties_objects():\n if default_property == node_prop_obj.name and not node_prop_obj.value:\n node.get_properties_objects().append(default_property)\n\n node_name = next(iter(node.templates))\n if 'properties' in node.templates[node_name]:\n for prop_name in node.templates[node_name]['properties']:\n if isinstance(node.templates[node_name]['properties'][prop_name], dict) or \\\n isinstance(node.templates[node_name]['properties'][prop_name], str):\n if 'required' in node.templates[node_name]['properties'][prop_name] and \\\n node.templates[node_name]['properties'][prop_name]['required'] and \\\n 'default' in node.templates[node_name]['properties'][prop_name] and \\\n prop_name not in default_properties:\n default_properties[prop_name] = node.templates[node_name]['properties'][prop_name][\n 'default']\n\n logger.info(\n 'Adding to : ' + str(node.templates[node_name]) + ' properties: ' + str(default_properties))\n node.templates[node_name]['properties'] = default_properties\n return node\n\n def set_node_templates_properties(self):\n for node_template in self.tosca_template.nodetemplates:\n self.set_default_node_properties(node_template)\n\n specification_analyzer = SimpleAnalyzer(self.tosca_template)\n nodes_with_new_relationship_occurrences = specification_analyzer.set_relationship_occurrences()\n\n added_node_names = []\n for new_spec_occurrences in nodes_with_new_relationship_occurrences:\n for index, node_in_temple in enumerate(self.tosca_template.nodetemplates):\n if new_spec_occurrences.name == node_in_temple.name:\n added_node_names.append(new_spec_occurrences.name)\n self.tosca_template.nodetemplates[index] = new_spec_occurrences\n break\n\n for new_spec_occurrences in nodes_with_new_relationship_occurrences:\n if new_spec_occurrences.name not in added_node_names:\n self.tosca_template.nodetemplates.append(new_spec_occurrences)\n return self.tosca_template\n\n\n def get_node_template_property(self, prop_key, node_prop_dict):\n prop_value = self.spec_service.get_property(prop_key)\n if prop_value:\n return {prop_key: node_prop_dict}\n else:\n if 'required' in node_prop_dict and 'default' in node_prop_dict:\n return node_prop_dict['default']\n if 'constraints' in node_prop_dict:\n constraints = node_prop_dict['constraints']\n for constraint in constraints:\n\n if next(iter(constraint)) == 'greater_or_equal':\n return constraint[next(iter(constraint))]\n return None\n\n def resolve_requirements(self):\n \"\"\" Resolve requirements. Go over all nodes and recursively resolve requirements till node has no\n requirements e.g. docker -> k8s -> cluster -> vm \"\"\"\n for node in self.tosca_template.nodetemplates:\n self.add_interfaces(node)\n self.add_required_nodes(node)\n return self.add_required_nodes_to_template(self.required_nodes)\n\n def add_required_nodes(self, node):\n \"\"\"Adds the required nodes in self.required_nodes for an input node.\"\"\"\n if isinstance(node, NodeTemplate):\n logger.info('Resolving requirements for: ' + node.name)\n elif isinstance(node, dict):\n logger.info('Resolving requirements for: ' + str(next(iter(node))))\n # Get all requirements for node.\n all_requirements = self.get_all_requirements(node)\n if not all_requirements:\n logger.debug('Node: ' + tosca_helper.get_node_type_name(node) + ' has no requirements')\n return\n\n matching_nodes_dict = self.find_best_node_for_requirements(all_requirements)\n for capability in matching_nodes_dict:\n # Only add node that is not in node_templates\n matching_node = matching_nodes_dict[capability]\n matching_node_type_name = next(iter(matching_node))\n matching_node_template = tosca_helper.node_type_2_node_template(matching_node, self.all_custom_def)\n if tosca_helper.contains_node_type(self.tosca_template.nodetemplates, matching_node_type_name):\n logger.debug('Node: ' + tosca_helper.get_node_type_name(node) + ' requirement node: '+matching_node_type_name+ ' is already covered')\n continue\n\n for req in all_requirements:\n req_name = next(iter(req))\n requirement_capability = req[req_name]['capability']\n if capability == requirement_capability:\n # Add the requirements to the node we analyzed. e.g. docker needed host now we added the type and name of host\n node = add_requirement(node, req, matching_node_template.name)\n break\n if not tosca_helper.contains_node_type(self.required_nodes, matching_node_type_name) and \\\n not tosca_helper.contains_node_type(self.tosca_template.nodetemplates, matching_node_type_name):\n logger.info(' Adding: ' + str(matching_node_template.name))\n self.required_nodes.append(matching_node)\n # Find matching nodes for the new node's requirements\n self.add_required_nodes(matching_node)\n\n def get_all_requirements(self, node):\n \"\"\"Returns all requirements for an input node including all parents requirements\"\"\"\n\n node_type_name = tosca_helper.get_node_type_name(node)\n logger.info(' Looking for requirements for node: ' + node_type_name)\n # Get the requirements for this node from its definition e.g. docker: hostedOn k8s\n def_type = self.all_node_types[node_type_name]\n all_requirements = []\n if 'requirements' in def_type.keys():\n all_requirements = def_type['requirements']\n logger.info(' Found requirements: ' + str(all_requirements) + ' for node: ' + node_type_name)\n\n # Get the requirements for this node from the template. e.g. wordpress: connectsTo mysql\n # node_requirements = tosca_helper.get_node_requirements(node)\n # if node_requirements:\n # all_requirements += node_requirements\n\n # Put them all together\n parent_requirements = tosca_helper.get_ancestors_requirements(node, self.all_node_types, self.all_custom_def)\n parent_type = tosca_helper.get_node_type_name(node)\n if parent_type and parent_requirements:\n logger.info(\n ' Adding to : ' + str(node_type_name) + ' parent requirements from: ' + str(parent_type))\n if not all_requirements:\n all_requirements += parent_requirements\n else:\n for all_requirement in all_requirements:\n for parent_requirement in parent_requirements:\n all_requirement_key = next(iter(all_requirement))\n parent_requirement_key = next(iter(parent_requirement))\n if all_requirement_key != parent_requirement_key and all_requirement[all_requirement_key][\n 'capability'] != parent_requirement[parent_requirement_key]['capability']:\n all_requirements.append(parent_requirement)\n\n logger.debug(' all_requirements: ' + str(all_requirements))\n return all_requirements\n\n def get_node_types_by_capability(self, cap):\n \"\"\"Returns all nodes that have the capability: cap and have interfaces. This way we distinguish between\n 'abstract' and 'concrete' \"\"\"\n candidate_nodes = {}\n for tosca_node_type in self.all_node_types:\n if tosca_node_type.startswith('tosca.nodes') and 'capabilities' in self.all_node_types[tosca_node_type]:\n logger.debug(' Node: ' + str(tosca_node_type))\n for caps in self.all_node_types[tosca_node_type]['capabilities']:\n logger.debug(' ' + str(\n self.all_node_types[tosca_node_type]['capabilities'][caps]['type']) + ' == ' + cap)\n if self.all_node_types[tosca_node_type]['capabilities'][caps]['type'] == cap:\n candidate_nodes[tosca_node_type] = self.all_node_types[tosca_node_type]\n logger.debug(' candidate_node: ' + str(tosca_node_type))\n\n candidate_child_nodes = {}\n for node in candidate_nodes:\n candidate_child_nodes.update(self.get_child_nodes(node))\n\n candidate_nodes.update(candidate_child_nodes)\n capable_nodes = {}\n # Only return the nodes that have interfaces. This means that they are not \"abstract\"\n nodes_type_names_with_interface = tosca_helper.get_node_types_with_interface(candidate_nodes)\n for type_name in nodes_type_names_with_interface:\n capable_nodes[type_name] = candidate_nodes[type_name]\n return capable_nodes\n\n def find_best_node_for_requirements(self, all_requirements):\n \"\"\"Returns the 'best' node for a set of requirements. Here we count the number of requiremets that the node\n can cover and return the one which covers the most \"\"\"\n matching_nodes = {}\n number_of_matching_requirement = {}\n met_requirements = {}\n # Loop requirements to find nodes per requirement\n for req in all_requirements:\n key = next(iter(req))\n if not req[key]:\n raise Exception('Requirement: '+str(req)+ ' is not properly defined')\n if 'capability' in req[key]:\n capability = req[key]['capability']\n # Find all nodes in the definitions that have the capability: capability\n logger.info(' Looking for nodes in node types with capability: ' + capability)\n capable_nodes = self.get_node_types_by_capability(capability)\n if not capable_nodes:\n logger.error('Did not find any node with required capability: ' + str(capability))\n raise Exception('Did not find any node with required capability: ' + str(capability))\n matching_nodes[capability] = capable_nodes\n\n\n # if we only found 1 return it\n if len(matching_nodes) == 1:\n return matching_nodes\n\n returning_nodes = {}\n for capability in matching_nodes:\n nodes = matching_nodes[capability]\n key = next(iter(nodes))\n returning_nodes[capability] = {key:nodes[key]}\n return returning_nodes\n # sorted_number_of_matching_requirement = sorted(number_of_matching_requirement.items(),\n # key=operator.itemgetter(1))\n # index = len(sorted_number_of_matching_requirement) - 1\n # winner_type = next(iter(sorted_number_of_matching_requirement[index]))\n # return {winner_type: matching_nodes[winner_type]}\n\n def get_child_nodes(self, parent_node_type_name):\n child_nodes = {}\n for tosca_node_type in self.all_node_types:\n if tosca_node_type.startswith('tosca.nodes') and 'derived_from' in self.all_node_types[tosca_node_type]:\n if parent_node_type_name == self.all_node_types[tosca_node_type]['derived_from']:\n child_nodes[tosca_node_type] = self.all_node_types[tosca_node_type]\n return child_nodes\n\n def add_interfaces(self, node):\n # node_type_interfaces = tosca_helper.get_node_type_interfaces(node)\n # node_template_interfaces = tosca_helper.get_node_template_interfaces(node)\n # if not node_template_interfaces and node_type_interfaces:\n # tosca_helper.add_interfaces(node,node_type_interfaces)\n return node\n","sub_path":"planner/planner.py","file_name":"planner.py","file_ext":"py","file_size_in_byte":16778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"446081469","text":"import maya.mel as mel\nimport maya.cmds as cmds\n\n\ndef locatorParticlesUI():\n \"\"\"\n \"\"\"\n # Define window\n locParticleUI = 'locatorParticleWindow'\n if cmds.window(locParticleUI, q=True, ex=True): cmds.deleteUI(locParticleUI)\n locParticleUI = cmds.window(locParticleUI, t='Generate Particles')\n\n # UI Layout\n cmds.columnLayout(adj=False, cal='left')\n partiTFG = cmds.textFieldGrp('locParticle_particleTFG', label='Particle', text='', cw=[(1, 100)])\n radiusFFG = cmds.floatSliderGrp('locParticle_radiusFSG', label='radius', f=True, min=0.1, max=10.0, fmn=0.01,\n fmx=100.0, pre=2, v=1.0, cw=[(1, 100)])\n rotateLocCBG = cmds.checkBoxGrp('locParticle_rotateCBG', label='Add rotatePP', ncb=1, v1=0, cw=[(1, 100)])\n scaleLocCBG = cmds.checkBoxGrp('locParticle_scaleCBG', label='Add scalePP', ncb=1, v1=0, cw=[(1, 100)])\n selfCollideCBG = cmds.checkBoxGrp('locParticle_selfCollideCBG', label='self collide', ncb=1, v1=0, cw=[(1, 100)])\n\n cmds.button(l='Create Particles', c='glTools.tools.generateParticles.locatorParticlesFromUI()')\n\n # Popup menu\n cmds.popupMenu(parent=partiTFG)\n for p in cmds.ls(type=['particle', 'nParticle']):\n cmds.menuItem(p, c='cmds.textFieldGrp(\"' + partiTFG + '\",e=True,text=\"' + p + '\")')\n\n # Show Window\n cmds.showWindow(locParticleUI)\n\n\ndef locatorParticlesFromUI():\n \"\"\"\n \"\"\"\n # Define window\n locParticleUI = 'locatorParticleWindow'\n if not cmds.window(locParticleUI, q=True, ex=True): return\n\n # Get user selection\n sel = cmds.ls(sl=True)\n if len(sel) == 1:\n if not cmds.objExists(sel[0] + '.localScale'):\n sel = cmds.listRelatives(sel[0], c=True, pa=True)\n locList = [i for i in sel if cmds.objExists(i + '.localScale')]\n\n # Get Particle\n particle = cmds.textFieldGrp('locParticle_particleTFG', q=True, text=True)\n if not particle: particle = 'nParticle1'\n radius = cmds.floatSliderGrp('locParticle_radiusFSG', q=True, v=True)\n selfCollide = cmds.checkBoxGrp('locParticle_selfCollideCBG', q=True, v1=True)\n rt = cmds.checkBoxGrp('locParticle_rotateCBG', q=True, v1=True)\n sc = cmds.checkBoxGrp('locParticle_scaleCBG', q=True, v1=True)\n\n # Execute generate particle command\n locatorParticles(locList, particle, radius, selfCollide, rotatePP=rt, scalePP=sc)\n\n\ndef locatorParticles(locList, particle, radius=1, selfCollide=False, rotatePP=False, scalePP=False):\n \"\"\"\n \"\"\"\n # Check locator list\n if not locList: return\n\n # Check particles\n if not particle: particle = 'particle1'\n if not cmds.objExists(particle):\n particle = cmds.nParticle(n=particle)[0]\n\n # Set Particle Object Attrs\n cmds.setAttr(particle + '.particleRenderType', 4)\n cmds.setAttr(particle + '.radius', cmds.floatSliderGrp('locParticle_radiusFSG', q=True, v=True))\n cmds.setAttr(particle + '.selfCollide', cmds.checkBoxGrp('locParticle_selfCollideCBG', q=True, v1=True))\n\n # Create particles\n ptList = [cmds.pointPosition(i) for i in locList]\n cmds.emit(o=particle, pos=ptList)\n\n # Add and Set RotatePP/ScalePP Values\n if rotatePP:\n\n # Check rotatePP attrs\n if not cmds.objExists(particle + '.rotatePP'):\n addRotatePP(particle)\n\n # Set rotatePP attrs\n for i in range(len(locList)):\n rot = cmds.getAttr(locList[i] + '.r')\n cmds.particle(particle, e=True, at='rotatePP', id=i, vv=rot[0])\n\n if scalePP:\n\n # Check scalePP attrs\n if not cmds.objExists(particle + '.scalePP'):\n addScalePP(particle)\n\n # Set scalePP attrs\n for i in range(len(locList)):\n scl = cmds.getAttr(locList[i] + '.s')\n cmds.particle(particle, e=True, at='scalePP', id=i, vv=scl[0])\n\n # Save Initial State\n cmds.saveInitialState(particle)\n\n\ndef particleLocatorsUI():\n \"\"\"\n \"\"\"\n # Get current frame range\n start = cmds.playbackOptions(q=True, min=True)\n end = cmds.playbackOptions(q=True, max=True)\n\n # Define window\n particleLocatorsUI = 'particleLocatorsWindow'\n if cmds.window(particleLocatorsUI, q=True, ex=True): cmds.deleteUI(particleLocatorsUI)\n particleLocatorsUI = cmds.window(particleLocatorsUI, t='Generate Locators')\n\n # UI Layout\n cmds.columnLayout(adj=False, cal='left')\n partiTFG = cmds.textFieldGrp('partiLoc_particleTFG', label='Particle', text='', cw=[(1, 120)])\n prefixTFG = cmds.textFieldGrp('partiLoc_prefixTFG', label='Prefix', text='', cw=[(1, 120)])\n bakeAnicmdsBG = cmds.checkBoxGrp('partiLoc_bakeAnicmdsBG', label='Bake Animation', ncb=1, v1=0, cw=[(1, 120)])\n startEndIFG = cmds.intFieldGrp('partiLoc_startEndISG', nf=2, label='Frame Range', v1=start, v2=end, cw=[(1, 120)])\n\n rotateLocCBG = cmds.checkBoxGrp('partiLoc_rotateCBG', label='Rotate (rotatePP)', ncb=1, v1=0, cw=[(1, 120)])\n scaleLocCBG = cmds.checkBoxGrp('partiLoc_scaleCBG', label='Scale (scalePP)', ncb=1, v1=0, cw=[(1, 120)])\n\n cmds.button(l='Create Locators', c='glTools.tools.generateParticles.particleLocatorsFromUI()')\n\n # Popup menu\n cmds.popupMenu(parent=partiTFG)\n for p in cmds.ls(type=['particle', 'nParticle']):\n cmds.menuItem(p, c='cmds.textFieldGrp(\"' + partiTFG + '\",e=True,text=\"' + p + '\")')\n\n # Show Window\n cmds.showWindow(particleLocatorsUI)\n\n\ndef particleLocatorsFromUI():\n \"\"\"\n \"\"\"\n # Define window\n particleLocatorsUI = 'particleLocatorsWindow'\n if not cmds.window(particleLocatorsUI, q=True, ex=True): return\n\n # Get Particle\n particle = cmds.textFieldGrp('partiLoc_particleTFG', q=True, text=True)\n if not particle: raise Exception('Particle \"' + particle + '\" does not exist!!')\n\n # Get Options\n prefix = cmds.textFieldGrp('partiLoc_prefixTFG', q=True, text=True)\n bake = cmds.checkBoxGrp('partiLoc_bakeAnicmdsBG', q=True, v1=True)\n st = cmds.intFieldGrp('partiLoc_startEndISG', q=True, v1=True)\n en = cmds.intFieldGrp('partiLoc_startEndISG', q=True, v2=True)\n rotate = cmds.checkBoxGrp('partiLoc_rotateCBG', q=True, v1=True)\n scale = cmds.checkBoxGrp('partiLoc_scaleCBG', q=True, v1=True)\n\n # Create Locators\n particleLocators(particle, bakeSimulation=bake, rotate=rotate, scale=scale, start=st, end=en, prefix=prefix)\n\n\ndef particleLocators(particle, bakeSimulation=False, rotate=False, scale=False, start=0, end=-1, prefix=''):\n \"\"\"\n \"\"\"\n # Check Particle\n if not cmds.objExists(particle):\n raise Exception('Object \"' + nParticle + '\" is not a valid particle or nParticle object!')\n\n # Check Prefix\n if not prefix: prefix = particle\n\n # Get particle count\n count = cmds.getAttr(particle + '.count')\n if not count: raise Exception('Invalid particle count! (' + count + ')')\n\n # Create locators\n partiLocs = [cmds.spaceLocator(n=prefix + '_loc' + str(i))[0] for i in range(count)]\n partiLocsGrp = prefix + '_locGrp'\n if not cmds.objExists(partiLocsGrp): partiLocsGrp = cmds.group(em=True, n=partiLocsGrp)\n cmds.parent(partiLocs, partiLocsGrp)\n\n # For each particle, set locator position\n for i in range(count):\n pt = cmds.pointPosition(particle + '.pt[' + str(i) + ']')\n cmds.setAttr(partiLocs[i] + '.t', *pt)\n if rotate:\n rt = cmds.particle(particle, q=True, at='rotatePP', id=i)\n cmds.setAttr(partiLocs[i] + '.r', *rt)\n if scale:\n sc = cmds.particle(particle, q=True, at='scalePP', id=i)\n cmds.setAttr(partiLocs[i] + '.s', *sc)\n\n # Bake Simulation\n if (bakeSimulation):\n\n # Append particle expression\n expStr = '\\n\\n//--\\n'\n expStr += 'int $id = id;\\n'\n expStr += 'vector $pos = pos;\\n'\n expStr += 'string $loc = (\"' + prefix + '_loc\"+$id);\\n'\n expStr += 'if(`objExists $loc`){'\n expStr += '\\t move -a ($pos.x) ($pos.y) ($pos.z) $loc;\\n'\n if rotate:\n expStr += '\\tvector $rot = rotatePP;\\n'\n expStr += '\\t rotate -a ($rot.x) ($rot.y) ($rot.z) $loc;\\n'\n if scale:\n expStr += '\\tvector $scl = scalePP;\\n'\n expStr += '\\t scale -a ($scl.x) ($scl.y) ($scl.z) $loc;\\n'\n expStr += '}'\n\n # Old expression string\n oldRadStr = cmds.dynExpression(particle, q=True, s=True, rad=True)\n\n # Apply particle expression\n cmds.dynExpression(particle, s=oldRadStr + expStr, rad=True)\n\n # Bake to keyframes\n if end < start:\n start = cmds.playbackOptions(q=True, min=True)\n end = cmds.playbackOptions(q=True, max=True)\n bakeAttrs = ['tx', 'ty', 'tz']\n if rotate: bakeAttrs.extend(['rx', 'ry', 'rz'])\n if scale: bakeAttrs.extend(['sx', 'sy', 'sz'])\n cmds.bakeSimulation(partiLocs, at=bakeAttrs, t=(start, end))\n\n # Restore particle expression\n cmds.dynExpression(particle, s=oldRadStr, rad=True)\n\n\ndef addRotatePP(particle):\n \"\"\"\n Add a per particle vector(Array) attribute named \"rotatePP\", to the specified particle object.\n An initial state attribute \"rotatePP0\" will also be created.\n @param particle: The particle or nParticle object to add the attribute to\n @type particle: str\n \"\"\"\n # Check Particle\n if not cmds.objExists(particle):\n raise Exception('Particle \"' + particle + '\" does not exist!')\n if cmds.objectType(particle) == 'transform':\n particleShape = cmds.listRelatives(particle, s=True)\n if not particleShape:\n raise Exception('Unable to determine particle shape from transform \"' + particle + '\"!')\n else:\n particle = particleShape[0]\n if (cmds.objectType(particle) != 'particle') and (cmds.objectType(particle) != 'nParticle'):\n raise Exception('Object \"' + particle + '\" is not a valid particle or nParticle object!')\n\n # Add rotatePP attribute\n if not cmds.objExists(particle + '.rotatePP0'):\n cmds.addAttr(particle, ln='rotatePP0', dt='vectorArray')\n if not cmds.objExists(particle + '.rotatePP'):\n cmds.addAttr(particle, ln='rotatePP', dt='vectorArray')\n\n # Return Result\n return particle + '.rotatePP'\n\n\ndef addScalePP(particle):\n \"\"\"\n Add a per particle vector(Array) attribute named \"scalePP\", to the specified particle object.\n An initial state attribute \"scalePP0\" will also be created.\n @param particle: The particle or nParticle object to add the attribute to\n @type particle: str\n \"\"\"\n # Check Particle\n if not cmds.objExists(particle):\n raise Exception('Particle \"' + particle + '\" does not exist!')\n if cmds.objectType(particle) == 'transform':\n particleShape = cmds.listRelatives(particle, s=True)\n if not particleShape:\n raise Exception('Unable to determine particle shape from transform \"' + particle + '\"!')\n else:\n particle = particleShape[0]\n if (cmds.objectType(particle) != 'particle') and (cmds.objectType(particle) != 'nParticle'):\n raise Exception('Object \"' + particle + '\" is not a valid particle or nParticle object!')\n\n # Add rotatePP attribute\n if not cmds.objExists(particle + '.scalePP0'):\n cmds.addAttr(particle, ln='scalePP0', dt='vectorArray')\n if not cmds.objExists(particle + '.scalePP'):\n cmds.addAttr(particle, ln='scalePP', dt='vectorArray')\n\n # Return Result\n return particle + '.scalePP'\n","sub_path":"tools/generateParticles.py","file_name":"generateParticles.py","file_ext":"py","file_size_in_byte":11369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"453508216","text":"import pygame, os, json\nfrom .core_funcs import *\n\nCOLORKEY = (0, 0, 0)\n\ndef load_spritesheet(spritesheet):\n rows = []\n spritesheet_dat = []\n for y in range(spritesheet.get_height()):\n c = spritesheet.get_at((0, y))\n c = (c[0], c[1], c[2])\n if c == (255, 255, 0):\n rows.append(y)\n for row in rows:\n row_content = []\n for x in range(spritesheet.get_width()):\n c = spritesheet.get_at((x, row))\n c = (c[0], c[1], c[2])\n if c == (255, 0, 255):\n x2 = 0\n while True:\n x2 += 1\n c = spritesheet.get_at((x + x2, row))\n c = (c[0], c[1], c[2])\n if c == (0, 255, 255):\n width = x2\n break\n y2 = 0\n while True:\n y2 += 1\n c = spritesheet.get_at((x, row + y2))\n c = (c[0], c[1], c[2])\n if c == (0, 255, 255):\n height = y2\n break\n img = clip(spritesheet, x + 1, row + 1, x2 - 1, y2 - 1)\n img.set_colorkey(COLORKEY)\n row_content.append(img)\n spritesheet_dat.append(row_content)\n return spritesheet_dat\n\ndef load_spritesheets(path):\n spritesheet_list = os.listdir(path)\n spritesheets = {}\n spritesheets_data = {}\n for img_file in spritesheet_list:\n if img_file.split('.')[-1] == 'png':\n spritesheet_dat = load_spritesheet(pygame.image.load(path + '/' + img_file).convert())\n spritesheets[img_file.split('.')[0]] = spritesheet_dat\n try:\n dat = read_f(path + '/' + img_file.split('.')[0] + '.json')\n spritesheets_data[img_file.split('.')[0]] = json.loads(dat)\n except FileNotFoundError:\n pass\n\n return spritesheets, spritesheets_data\n\ndef get_img(spritesheets, img_loc):\n return spritesheets[img_loc[0]][img_loc[1]][img_loc[2]]\n","sub_path":"client/scripts/spritesheet_loader.py","file_name":"spritesheet_loader.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"584173670","text":"import Password.class_decode_chr as decode\r\n\r\n\r\nclass pw_cvt_str():\r\n # key_log_numb thứ tự của char trong key log\r\n # key_stt thứ tự của char trong bảng key_log\r\n # Dùng chr(number) để chuyển từ số sang ký tự trong bảng ascii\r\n def __init__(self, str_in):\r\n self.chr_in = str_in\r\n self.str_cvt = []\r\n self.key_log_numb = []\r\n self.key_decode_t9 = []\r\n\r\n # Kiểm tra chuỗi đầu tiên 1,4,7,10,...\r\n def T9_to_chr(self):\r\n for i in self.chr_in:\r\n if i in decode.chr_t9:\r\n self.str_cvt.append(decode.chr_t9[i])\r\n\r\n self.key_decode_t9.append(chr(int(decode.chr_decode_t9[i])))\r\n else:\r\n self.str_cvt.append(i)\r\n return ''.join(self.str_cvt), self.key_decode_t9\r\n\r\n # Kiểm tra chuỗi thứ 2\r\n def numb_chr(self):\r\n for i in self.chr_in:\r\n if not i.isdigit():\r\n if i in decode.chr_t9:\r\n self.str_cvt.append(decode.chr_numb[decode.chr_t9[i].lower()])\r\n self.key_decode_t9.append(chr(int(decode.chr_decode_t9[i])))\r\n self.key_log_numb.append(decode.chr_numb_log[decode.chr_t9[i].lower()])\r\n else:\r\n self.str_cvt.append(decode.chr_numb[i.lower()])\r\n self.key_log_numb.append(decode.chr_numb_log[i.lower()])\r\n else:\r\n self.str_cvt.append(i)\r\n return ''.join(self.str_cvt), self.key_decode_t9, self.key_log_numb\r\n\r\n # KIểm tra chuỗi thứ 3\r\n def super_chr(self):\r\n for i in self.chr_in:\r\n if not i.isdigit():\r\n if i in decode.chr_t9:\r\n numb_i = decode.chr_numb[decode.chr_t9[i].lower()]\r\n self.str_cvt.append(decode.chr_power_str[numb_i])\r\n self.key_decode_t9.append(chr(int(decode.chr_decode_t9[i])))\r\n self.key_log_numb.append(decode.chr_numb_log[decode.chr_t9[i].lower()])\r\n else:\r\n numb_i = decode.chr_numb[i.lower()]\r\n self.str_cvt.append(decode.chr_power_str[numb_i])\r\n self.key_log_numb.append(decode.chr_numb_log[i.lower()])\r\n else:\r\n self.str_cvt.append(decode.chr_power_str[i])\r\n return ''.join(self.str_cvt), self.key_decode_t9, self.key_log_numb\r\n\r\n\r\n'''\r\nVấn đề:\r\nChuỗi đầu tiên nếu có chữ T9 thì phải chuyển về bthg, rồi phải chuyển sang\r\n- Có thể dùng nhận dạng chữ cái và soi chiếu tới keynumb ở cuối dãy để định dạng lại ký tự\r\nChuỗi thứ 2 và thứ 3, sau khi được định dạng sang số, cần 1 bước định dạng nữa để xác định \r\nKý tự đó có số thứ tự trên 1 số 1-9 là stt nào 1-4\r\nSau khi biết được cũng sẽ dùng soi chiếu như với chuỗi đầu tiên\r\nCái khó ở đây là làm saao để chuỗi đầu tiên có thể thực hiện chung bước với x�� lý chuỗi 2-3\r\n\r\n'''\r\n","sub_path":"Password/class_convert_chr.py","file_name":"class_convert_chr.py","file_ext":"py","file_size_in_byte":3089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"507788796","text":"from openpyxl import load_workbook, Workbook\r\nimport itertools\r\n\r\ndef read_xlsx(file_path, start_row=None, sheet_name=None):\r\n '''Will return the values of excel file as list of lists'''\r\n wb = load_workbook(file_path)\r\n if sheet_name:\r\n ws = wb[sheet_name]\r\n else:\r\n ws = wb.active\r\n rows_iter = ws.iter_rows(min_row=start_row)\r\n all_values = [[cell.value for cell in list(row)] for row in rows_iter]\r\n return all_values\r\n\r\n\r\ndef read_xlsx_list_of_dict(file_path, start_row=None, sheet_name=None):\r\n '''Will return the values of excel file as list of dictionaries'''\r\n data = read_xlsx(file_path, start_row=start_row,sheet_name=sheet_name)\r\n output_data = [{data[0][n]:cell for n,\r\n cell in enumerate(row)}for row in data[1:]]\r\n return output_data\r\n\r\n\r\ndef write_xlsx(file_name, data_to_store):\r\n '''Will write list of lists into a XLSX file'''\r\n wb = Workbook()\r\n ws = wb.active\r\n for row in data_to_store:\r\n ws.append(row)\r\n wb.save(filename=file_name)\r\n\r\n\r\ndef write_list_of_dict_xlsx(filename, data_to_store):\r\n '''Will write list of dictionaries into a XLSX file'''\r\n wb = Workbook(write_only=True)\r\n ws = wb.create_sheet()\r\n\r\n headers = list(dict.fromkeys(itertools.chain.from_iterable(data_to_store)))\r\n ws.append(headers)\r\n\r\n for elements in data_to_store:\r\n ws.append([elements.get(h) for h in headers])\r\n\r\n wb.save(filename)\r\n","sub_path":"xlsx_file_handling.py","file_name":"xlsx_file_handling.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"143698736","text":"# Milo Gilad, Ph.D\n# 10/31/16\n# Landscape\n\nfrom graphics import *\n\ndef makeRect(x1, y1, x2, y2, fillColor, win):\n rectName = Rectangle(Point(x1,y1), Point(x2,y2))\n rectName.setFill(fillColor)\n rectName.setWidth(2)\n rectName.draw(win)\ndef makeTri(x1, y1, x2, y2, x3, y3, fillColor, win, outline):\n triName = Polygon(Point(x1, y1), Point(x2, y2), Point(x3, y3), Point(x1, y1))\n triName.setFill(fillColor)\n if outline == True:\n triName.setWidth(2)\n triName.draw(win)\n else:\n triName.draw(win)\ndef makeCirc(x, y, radius, fillColor, win, outline):\n circ = Circle(Point(x, y), radius)\n circ.setFill(fillColor)\n if outline == True:\n circ.draw(win)\n else:\n circ.setWidth(0)\n circ.draw(win)\ndef main():\n win = GraphWin(\"Milo Gilad's Glorious Masterpiece (Autograph Signings Coming Soon)\", 1400, 799)\n makeRect(1400, 1000, 0, 600, \"Green\", win) # Grass\n makeRect(1400, 600, 0, 0, \"Light Blue\", win) # Sky\n makeRect(357, 325, 501, 529, \"White\", win) # Cow Head\n makeCirc(434, 438, 50, \"Pink\", win, True) # Cow Nose\n makeCirc(406, 430, 15, \"Black\", win, True) # Cow Nostril A\n makeCirc(463, 430, 15, \"Black\", win, True) # Cow Nostril B\n makeRect(502, 410, 881, 527, \"White\", win) # Cow Body\n makeCirc(380, 363, 22, \"Black\", win, True) # Cow Eye A\n makeCirc(480, 363, 22, \"Black\", win, True) # Cow Eye B\n makeRect(579, 527, 643, 600, \"White\", win) # Cow Leg 1\n makeRect(825, 527, 885, 600, \"White\", win) # Cow Leg 2\n makeRect(750, 527, 815, 600, \"White\", win) # Cow Leg 3\n makeRect(560, 527, 600, 600, \"White\", win) # Cow Leg 4\n lake = Polygon(Point(1077, 600), Point(1237, 600), Point(1237, 724), Point(1077, 724), Point(1077, 600)) # Pond (part 1)\n lake.setFill(\"Blue\") # Pond (part 2)\n lake.draw(win) # Pond (part 3)\n makeCirc(1386, 80, 100, \"Yellow\", win, False) # Helios, Lord of High Noon\n makeCirc(766, 60, 50, \"White\", win, False) # Cloud 1 Part A\n makeCirc(702, 100, 50, \"White\", win, False) # Cloud 1 Part B\n makeCirc(790, 100, 50, \"White\", win, False) # Cloud 1 Part C\n makeCirc(208, 80, 50, \"White\", win, False) # Cloud 2 Part A\n makeCirc(290, 80, 50, \"White\", win, False) # Cloud 2 Part B\n makeCirc(270, 145, 50, \"White\", win, False) # Cloud 2 Part C\n makeTri(75, 600, 155, 50, 181, 600, \"Brown\", win, True) # Mountain\n makeCirc(250, 335, 60, \"White\", win, True) # Human Head\n makeCirc(215, 320, 10, \"Blue\", win, True) # Human Eye A\n makeCirc(280, 320, 10, \"Blue\", win, True) # Human Eye B\n makeCirc(250, 350, 15, \"Brown\", win, True) # Human Mouth\n makeRect(270, 395, 249, 531, \"White\", win) # Human Body\n poly = Polygon(Point(249, 531), Point(242, 603), Point(231, 586), Point(249, 531)) # Human Leg 1 Part A\n poly.setFill(\"White\") # Human Leg 1 Part B\n poly.draw(win) # Human Leg 1 Part C\n poly = Polygon(Point(270, 531), Point(341, 593), Point(321, 584), Point(270, 531)) # Human Leg 2 Part A\n poly.setFill(\"White\") # Human Leg 2 Part B\n poly.draw(win) # Human Leg 2 Part C\n makeRect(269, 420, 313, 444, \"White\", win) # Human Arm 1\n makeRect(250, 420, 206, 444, \"White\", win) # Human Arm 2\n makeRect(1237, 600, 1267, 300, \"Brown\", win) # Oak Tree Body\n makeCirc(1237, 300, 50, \"Green\", win, False) # Oak Tree Leaf 1\n makeCirc(1267, 300, 50, \"Green\", win, False) # Oak Tree Leaf 2\n makeRect(1077, 600, 1047, 300, \"White\", win) # Birch Tree Body\n makeRect(1047, 450, 947, 480, \"White\", win) # Birch Tree Branch 1\n makeCirc(1047, 300, 50, \"Green\", win, False) # Birch Tree Leaf 1\n makeCirc(1077, 300, 50, \"Green\", win, False) # Birch Tree Leaf 2\n makeCirc(956, 461, 50, \"Green\", win, False) # Birch Tree Leaf 3\n makeRect(1157, 662, 1200, 682, \"Orange\", win) # Fish Body\n makeCirc(1165, 672, 5, \"Black\", win, False) # Fisheye\n makeTri(1202, 665, 1222, 675, 1202, 683, \"Orange\", win, False) # Fish Tail\n makeCirc(60, 300, 20, \"White\", win, True) # Mountie Head\n makeRect(80, 300, 100, 305, \"White\", win) # Mountie Body\n makeRect(101, 300, 115, 300, \"White\", win) # Mountie Leg 1\n makeRect(101, 305, 115, 305, \"White\", win) # Mountie Leg 2\n makeCirc(51, 304, 3, \"Blue\", win, False) # Mountie Eye A\n makeCirc(51, 315, 3, \"Blue\", win, False) # Mountie Eye B\n makeCirc(67, 300, 5, \"Brown\", win, False) # Mountie Mouth\n makeRect(90, 295, 90, 300, \"White\", win) # Mountie Arm 1\n makeRect(90, 305, 90, 310, \"White\", win) # Mountie Arm 2\nmain()\n","sub_path":"Landscape/Landscape.py","file_name":"Landscape.py","file_ext":"py","file_size_in_byte":4487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"622981904","text":"\n\n#calss header\nclass _LO():\n\tdef __init__(self,): \n\t\tself.name = \"LO\"\n\t\tself.definitions = [u'used to tell people to pay attention and look at something interesting']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'exclamations'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/exclamations/_lo.py","file_name":"_lo.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"498500127","text":"# encoding:utf-8\n\n'''\n20190528\n 给所有品种 生命周期 排序\n 幅度大,时间小 - 暴涨暴跌 幅度小,时间大 - 盘整 其他是正常趋势\n\n 按与历史的位置来划分反转的概率 超过80% 的反转概率大,未超过 10%的,可能是假反转,还是在上一个趋势中 的 次级调整\n\n 按周更新,发现可以投资性\n 超过80%的 关注 123 法则 反转\n 如果 其他关注 趋势的发展情况\n 在盘整时,可能会反转,也可以会继续原来的趋势,要尽量避开 降低仓位\n 20190722\n 因为判断时间长度的数量不够,导致半年周都与图表整体走势有相冲突的地方\n 最好的指标 是什么样子呢\n 20190723\n\n'''\nimport datetime\n\nimport requests\nimport demjson\nimport pandas as pd\n\nurl_half_y = \"http://47.94.198.204:8281/json/dataBig.json\"\nurl_season = \"http://47.94.198.204:8281/json/data.json\"\nurl_week = \"http://47.94.198.204:8281/json/dataWeek.json\"\nurl_hour = \"http://47.94.198.204:8281/json/dataHour.json\"\n\nmy_orders_list = ('聚丙', \"*\")\ndict_key_list = ('品种名称', 'halfy-天系数', 'halfy-幅度系数', 'season-天', 'season-幅度', '2周-天',\n '2周-幅度', 'hour-天', 'hour-幅度', '品种机会总描述')\n\n\ndef query_taobao_json(url, date_period):\n htmlText = requests.get(url).text\n # json_life = json.loads(htmlText)\n json_life_two = demjson.decode(htmlText)\n # print(json_life)\n print(type(json_life_two))\n return json_life_two\n pass\n\n\ndef save_data_file(dict_new_result_valid):\n datenow = datetime.datetime.now().strftime('%Y%m%d');\n df_excel = pd.DataFrame(dict_new_result_valid, columns=dict_new_result_valid.keys())\n try:\n df_excel.to_excel(r'..\\..\\..\\file\\calu_life_all_%s.xlsx' % datenow, encoding='utf-8')\n except Exception as e:\n df_excel.to_excel(r'..\\..\\..\\file\\calu_life_all2_%s.xlsx' % datenow, encoding='utf-8')\n\n # df = pd.DataFrame(list(dict_m_k_valid.items()), index=range(0, len(dict_m_k_valid)),\n # columns=['name', 'value']) # 创建一个空的dataframe\n # # df['next'] = list_next_line\n # df = df.sort_values(['value'])\n print(\"共选出 \", len(dict_new_result_valid.get(dict_key_list[0])))\n # df.to_csv(r'..\\..\\..\\file\\calu_life_all.csv', encoding='utf-8')\n pass\n\n\ndef calu_life_weigh(list_week, my_period, current_trend_days, descript):\n '''\n 对取得的生命周期来排序\n :param list_week: : [\"['上证\", '总(上涨天数-下跌天数)', '312', '总(上涨幅度-下跌幅度)', '113.79', '总有效天数,幅度为', '84', '超过历史多少次天数', '13', '超过历史多少次幅度', \"15']\"]\n :param my_period: 是 week , month 周期\n :param current_trend_days: day list 最后一个趋势天数,看正负来判断趋势方向\n :return:\n '''\n base_total_num = (int(list_week[6]) - 1) / 2\n print_str = \"\\n\" + my_period + '\\t' + descript + \"\\n\\t\"\n if base_total_num < 1:\n print_str += \"单边总次数太少,淘汰,为 %s\\n\" % list_week\n return\n current_days = float(list_week[8])\n weigh_day = current_days / base_total_num # 当前超过的天数次数/单边总次数\n current_scale = float(list_week[10].replace(\"']\", \"\"))\n weigh_scale = current_scale / base_total_num\n if weigh_day == 0 or weigh_scale == 0:\n if weigh_day + weigh_scale > 0.1:\n if current_trend_days > 0:\n print_str += \"----反转趋势向 上涨 未确定或者创 新最小区间记录\\n\"\n elif current_trend_days < 0:\n print_str += \"----反转趋势向 下跌 未确定或者创 新最小区间记录\\n\"\n else:\n print_str += \"----反转趋势未确立 很可能只是个小反弹\\n\"\n elif weigh_scale / weigh_day > 1.5:\n if current_trend_days > 0:\n print_str += \"这是相对暴涨-后期会变得盘整\\n\"\n elif current_trend_days < 0:\n print_str += \"这是相对暴跌-后期会变得盘整\\n\"\n elif weigh_scale / weigh_day < 0.4:\n print_str += \"这是相对盘整----后期可能会有现趋势暴发行情\\n\"\n\n if weigh_scale > 0.85 or weigh_day > 0.85:\n if current_trend_days > 0:\n print_str += \"上涨进入高风险区间,关注 右侧 反转\\n\"\n elif current_trend_days < 0:\n print_str += \"下跌进入高风险区间,关注 右侧 反转\\n\"\n elif weigh_scale > 0.01 and weigh_day > 0.01:\n if current_trend_days > 0:\n print_str += \"上涨进入正常趋势区间,关注 进入区间\\n\"\n elif current_trend_days < 0:\n print_str += \"下跌进入正常趋势区间,关注 进入区间\\n\"\n\n print_str += \"单边总次数为 %s 超过天数次数 %s 超过幅度次数 %s \\n\" % (base_total_num, weigh_day, weigh_scale)\n return [my_period, weigh_day, weigh_scale, (weigh_scale + weigh_day) / 2, print_str]\n\n\ndef star_sort(dict_half_y_calu, dict_season_calu, dict_week_calu, dict_hour_calu, dict_half_y):\n '''\n\n :param dict_half_y_calu:\n :param dict_season_calu:\n :param dict_week_calu:\n :param dict_hour_calu: 保存的\n :param dict_half_y: 阿里的字典数据 用来取半年周的单边次数\n :return:\n\n # 依据权重排序 关注点为:::高风险区(可能反转区)和机会区( <0.2\n # 目的 是要找出交易机会 周,月线小于0.2\n month week 同方向 才加, 不同方向 周反向进入 >0.6时 加\n 高 大小周期都要反转,得分高\n 中\n 低\n 未明 趋势不是很明确 不持仓\n '''\n dict_new_result_valid = {dict_key_list[0]: [], dict_key_list[1]: [], dict_key_list[2]: [], dict_key_list[3]: [],\n dict_key_list[4]: [], dict_key_list[5]: [], dict_key_list[6]: [],\n dict_key_list[7]: [], dict_key_list[8]: [], dict_key_list[9]: []} # 保存有用的品种信息 组装DF输出文件用\n list_next_line = [] # 打印拼接字符串\n # index = 0 是半年趋势危险系数 1是季度危险系数 2是周趋势进场系数 3 同向 2周趋势危险提醒系数\n opportunity_danger_coefficient = (0.45, 0.8, 1.6, 0.9)\n for key in dict_season_calu:\n list_next_line.append(\"\\n\")\n tuple_halfy = dict_half_y_calu.get(key) # 时间与幅度的保存的数据\n tuple_m = dict_season_calu.get(key) # 时间与幅度的保存的数据\n tuple_k = dict_week_calu.get(key)\n tuple_hour = dict_hour_calu.get(key)\n '''\n BTC/USD ['month', 0.0, 0.0, 0.0, 'last month 20190604.0 , last week 20190609.0\\nmonth\\t----反转趋势向 下跌 未确定或者创 新最小区间记录\\n单边总次数为 2.0 超过天数次数 0.0 超过幅度次数 0.0 \\n', -4.0] \n ['week', 0.05405405405405406, 0.05405405405405406, 0.05405405405405406, 'week\\t上涨进入正常趋势区间,关注 进入区间\\n单边总次数为 18.5 超过天数次数 0.05405405405405406 超过幅度次数 0.05405405405405406 \\n', 4.0]\n '''\n # print(key, tuple_m, \"\\n\", tuple_k, \"\\n\", tuple_h)\n # -------------------------------------------------------------------\n ###\n day_hour_trend = tuple_hour[5] ## 现在的方向天数\n day_k_trend = tuple_k[5] ## 现在的方向天数\n if tuple_halfy and len((tuple_halfy)) >= 6:\n day_h_trend = tuple_halfy[5]\n else:\n day_h_trend = 0 ## 现在的方向天数\n if tuple_m and len((tuple_m)) >= 6:\n days_m_trend = tuple_m[5]\n else:\n days_m_trend = 0 ## 现在的方向天数\n # -------------------------------------------------------------------\n '''\n \t\t季度周,2周 同方向\t\t\t\t 季度周,2周 不同方向\n半年周,季度周\t危险提示 季度周2周 >0.75 时间+幅度>1.4\t\t危险提示 季度周>0.75 时间+幅度>1.4\t\n,2周,小时\t 机会值为 2周,小时 <0.45\t\t\t\t 机会值为 2周,小时 >0.75 时间+幅度>1.4 \n '''\n if tuple_m:\n str_des_one = '只做顺趋势的交易 不做但监督-反转 没有最高最低,只有更高更低 \\n' # 拼接\n isShow = False # 是否有进场的机会或者 已经进入高风险区\n if tuple_m[2] + tuple_m[1] > opportunity_danger_coefficient[2] \\\n or tuple_m[2] > opportunity_danger_coefficient[1] \\\n or tuple_m[1] > opportunity_danger_coefficient[1]: # 时间或者幅度\n str_des_one = str_des_one + \" 关注同向 季度周高风险区,除非早就上船,否则不做 考虑适当减仓\\n\"\n if tuple_k[2] + tuple_k[1] > opportunity_danger_coefficient[2] \\\n or (tuple_k[2] > opportunity_danger_coefficient[1]\n or tuple_k[1] > opportunity_danger_coefficient[1]): # 时间或者幅度\n str_des_one = str_des_one + \"------------同向 关注 2周高风险区 考虑适当减仓\\n\"\n isShow = True\n if tuple_hour[2] + tuple_hour[1] > opportunity_danger_coefficient[2] or (\n tuple_hour[2] > opportunity_danger_coefficient[1]) or tuple_hour[1] > \\\n opportunity_danger_coefficient[1]: # 小时区 时间或者幅度 在高危区\n str_des_one = str_des_one + \"------------关注 小时区 在高危区 考虑适当减仓\\n\"\n isShow = True\n if days_m_trend < 0 and (str(key).__contains__('XSHG') or str(key).__contains__('XSHE')):\n isShow = False\n # 已经有仓位的要显示情况\n for name in my_orders_list:\n if str(key).__contains__(name):\n isShow = True\n # 超过历史0.9的极危险区要显示\n if tuple_halfy:\n dict_value_dict_half_y = dict_half_y[str(key).strip()] # 一个品种的数据\n # 最后的时间是什么时候\n list_halfy_days = dict_value_dict_half_y['days']\n if (tuple_halfy[1] > opportunity_danger_coefficient[3] or tuple_halfy[2] > opportunity_danger_coefficient[\n 3]) and len(list_halfy_days) > 12:\n isShow = True\n if tuple_m[1] > opportunity_danger_coefficient[3] or tuple_m[2] > opportunity_danger_coefficient[3] \\\n or tuple_k[1] > opportunity_danger_coefficient[3] or tuple_k[2] > opportunity_danger_coefficient[3]:\n isShow = True\n if isShow:\n #### 半年周 只参与警报,不参与 机会\n if tuple_halfy:\n if tuple_halfy[2] + tuple_halfy[1] > opportunity_danger_coefficient[2] or tuple_halfy[2] > \\\n opportunity_danger_coefficient[1] or \\\n tuple_halfy[1] > opportunity_danger_coefficient[1]:\n str_des_one = str_des_one + \"------------关注 半年期高风险区\\n\"\n str_des_one += '半年周方向 %s 季度周方向 %s 2周方向 %s 小时区方向 %s\\t' % (\n day_h_trend, days_m_trend, day_k_trend, day_hour_trend) # 月,周 走势方向\n if tuple_halfy:\n str_des_one = str_des_one + tuple_halfy[4]\n if tuple_m:\n str_des_one = str_des_one + tuple_m[4]\n str_des_one = str_des_one + tuple_k[4]\n str_des_one += tuple_hour[4] + \"\\n\\n\"\n print(key, str_des_one, \"\\n\")\n # ----------------------------\n dict_new_result_valid[dict_key_list[0]].append(str(key).strip())\n if tuple_halfy is not None:\n dict_new_result_valid[dict_key_list[1]].append('%.3f' % tuple_halfy[1])\n dict_new_result_valid[dict_key_list[2]].append('%.3f' % tuple_halfy[2])\n else:\n dict_new_result_valid[dict_key_list[1]].append('0')\n dict_new_result_valid[dict_key_list[2]].append('0')\n dict_new_result_valid[dict_key_list[3]].append('%.3f' % tuple_m[1])\n dict_new_result_valid[dict_key_list[4]].append('%.3f' % tuple_m[2])\n dict_new_result_valid[dict_key_list[5]].append('%.3f' % tuple_k[1])\n dict_new_result_valid[dict_key_list[6]].append('%.3f' % tuple_k[2])\n dict_new_result_valid[dict_key_list[7]].append('%.3f' % tuple_hour[1])\n dict_new_result_valid[dict_key_list[8]].append('%.3f' % tuple_hour[2])\n dict_new_result_valid[dict_key_list[9]].append(str_des_one)\n else:\n print(key, \"没有机会\")\n ########### 保存筛选结果到文件\n save_data_file(dict_new_result_valid)\n pass\n\n\ndef handle_double_day_str(double_day):\n after_day_str = str(double_day)\n return after_day_str[:4] + \"-\" + after_day_str[4:6] + \"-\" + after_day_str[6:8]\n\n\ndef sort_life():\n dict_half_y = query_taobao_json(url_half_y, \"halfY\") # 取得趋势区间文件\n dict_season = query_taobao_json(url_season, \"season\") # 取得趋势区间文件\n dict_week = query_taobao_json(url_week, \"week\")\n dict_hour = query_taobao_json(url_hour, \"hour\")\n print(dict_hour.keys(), \"共 %s 个品种\" % len(dict_hour.keys()))\n # df = pd.DataFrame(columns=[\"name\", \"month\", \"week\", \"avg_m_w\",\"des_m\",\"des_w\"]) # 创建一个空的dataframe\n dict_week_calu = {} # 时间与幅度的保存的数据\n dict_season_calu = {}\n dict_half_y_calu = {}\n dict_hour_calu = {}\n\n for key in dict_week:\n ## 聚乙烯合约_L9999 TA9999\n # if str(key).__contains__(\"EUR-USD\") == False:\n # continue\n # -----------------------------------------------------------------------------------------------\n dict_value_dict_half_y = dict_half_y[key] # 一个品种的数据\n dict_value_season = dict_season[key] # 一个品种的数据\n dict_value_week = dict_week[key]\n dict_value_hour = dict_hour[key]\n\n # 最后的时间是什么时候\n list_halfy_dates = dict_value_dict_half_y['dates']\n list_m_dates = dict_value_season['dates']\n list_k_dates = dict_value_week['dates']\n list_hour_dates = dict_value_hour['dates']\n if list_m_dates[0] > 20150000.0: ## 至少要有四年的数据\n print(key, \"----------------dates 历史数据不多 \", list_m_dates[0])\n continue\n\n list_halfy_days = dict_value_dict_half_y['days']\n list_m_days = dict_value_season['days']\n list_k_days = dict_value_week['days']\n list_hour_days = dict_value_hour['days']\n str_des_one = \"\\n-----------------pre-halfy %s last-halfy %s ,pre-m %s last-m %s , pre-w %s last-w %s, pre-hour %s last-hour %s\\n\" % (\n list_halfy_dates[len(list_halfy_dates) - 2], list_halfy_dates[len(list_halfy_dates) - 1],\n list_m_dates[len(list_m_dates) - 2], list_m_dates[len(list_m_dates) - 1],\n list_k_dates[len(list_k_dates) - 2], list_k_dates[len(list_k_dates) - 1],\n list_hour_dates[len(list_hour_dates) - 2], list_hour_dates[len(list_hour_dates) - 1])\n print(key, \" \", str_des_one)\n\n list_halfy_deript = dict_value_dict_half_y['deript'].__str__().split(\"#\")\n list_month_deript = dict_value_season['deript'].__str__().split(\"#\")\n # : [\"['上证\", '总(上涨天数-下跌天数)', '312', '总(上涨幅度-下跌幅度)', '113.79', '总有效天数,幅度为', '84', '超过历史多少次天数', '13', '超过历史多少次幅度', \"15']\"]\n list_week_deript = dict_value_week['deript'].__str__().split(\"#\")\n list_hour_deript = dict_value_hour['deript'].__str__().split(\"#\")\n # -------------------------------------------------------------------------------------------------\n ########################### 计算 大趋势下的回调连续天数后反转的概率 #########################################################\n\n ########################### 计算 得分 ##########################################################################\n ##先计算 周\n key_name = key + \" \"\n ## ------------------------------------------------------------------ 周数据里要消除 最后趋势天数过低的情况\n # last_right_days_k = find_real_peroid_trend(key, list_k_days)\n last_right_days_k = int(list_k_days[-1]) # 最新趋势的天数\n dict_week_calu[key_name] = calu_life_weigh(list_week_deript, \"week\", last_right_days_k,\n dict_value_week['deript'].__str__())\n ## ------------------------------------------------------------------ 月数据里要消除 最后趋势天数过低的情况\n last_right_days_m = int(list_m_days[-1]) # 最新趋势的天数\n dict_season_calu[key_name] = calu_life_weigh(list_month_deript, \"season\", last_right_days_m,\n dict_value_season['deript'].__str__())\n ## ------------------------------------------------------------------ 月数据里要消除 最后趋势天数过低的情况\n last_right_days_halfy = int(list_halfy_days[-1]) # 最新趋势的天数\n dict_half_y_calu[key_name] = calu_life_weigh(list_halfy_deript, \"halfY\", last_right_days_halfy,\n dict_value_dict_half_y['deript'].__str__())\n ## ------------------------------------------------------------------ 月数据里要消除 最后趋势天数过��的情况\n last_right_days_hour = int(list_hour_days[-1]) # 最新趋势的天数\n dict_hour_calu[key_name] = calu_life_weigh(list_hour_deript, \"hour\", last_right_days_hour,\n dict_value_hour['deript'].__str__())\n ########################################################################################### 设置最后的趋势方向\n dict_hour_calu[key_name].append(last_right_days_hour)\n dict_week_calu[key_name].append(last_right_days_k)\n # print(key)\n # 添加最后一天的正负值用来判断方向\n if last_right_days_m:\n if dict_season_calu[key_name]:\n dict_season_calu[key_name].append(last_right_days_m)\n if last_right_days_halfy:\n if dict_half_y_calu[key_name]:\n dict_half_y_calu[key_name].append(last_right_days_halfy)\n ###############################################################################\n tuple_halfy = dict_half_y_calu.get(key_name); # 时间与幅度的保存的数据\n tuple_m = dict_season_calu.get(key_name); # 时间与幅度的保存的数据\n tuple_k = dict_week_calu.get(key_name);\n tuple_hour = dict_hour_calu.get(key_name);\n if tuple_halfy: # 如果没有月数据就拼接到周描述里\n tuple_halfy[4] = str_des_one + tuple_halfy[4]\n elif tuple_m:\n tuple_m[4] = str_des_one + tuple_m[4]\n elif tuple_k:\n tuple_k[4] = str_des_one + tuple_k[4]\n else:\n tuple_hour[4] = str_des_one + tuple_hour[4]\n\n # df.append(dict_week)\n # df.append(dict_month)\n\n # print(dict_week_calu, \"\\n\")\n # print(dict_month_calu)\n star_sort(dict_half_y_calu, dict_season_calu, dict_week_calu, dict_hour_calu, dict_half_y)\n # print(df)\n pass\n\n\n# def get_des_file():\n# file = open(r'..\\..\\..\\file\\calu_life_all_des.csv', \"w\", encoding='utf-8')\n# return file\n\n\n# def sort_test():\n# df = pd.DataFrame([['a', 1, 'c'], ['a', 3, 'a'], ['a', 2, 'b'],\n# ['c', 3, 'a'], ['c', 2, 'b'], ['c', 1, 'c'],\n# ['b', 2, 'b'], ['b', 3, 'a'], ['b', 1, 'c']], columns=['A', 'B', 'C'])\n# print(df)\n# # df.groupby('A', sort=False).apply(lambda x: x.sort_values('B', ascending=True)).reset_index(drop=True)\n# df = df.sort_values(['A', 'B'],inplace=False)\n# print(df)\n\nif __name__ == '__main__':\n sort_life()\n# sort_test()\n","sub_path":"jqDataFinance/jqdatadir/china/fetch_data/tomcat_insurment_life_sort_two.py","file_name":"tomcat_insurment_life_sort_two.py","file_ext":"py","file_size_in_byte":20000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"164964091","text":"import sys\nimport json\nfrom json.decoder import JSONDecodeError\n\nimport regex as re\n\nfrom utils import paths\n\n\n# Handle special characters, numbers, punctuation\nPATTERN_NUMBERS = [r'(\\d)+', ' ']\nPATTERN_PUNCTUATION = [r'\\p{P}+', ' ']\nPATTERN_NOTERM = [r'\\+|●|\\$|€|\\£||||\\|', ' ']\nSPECIAL = 'ĂăÂâÎîȘșŞşȚțŢţ'\nLATIN_EQUIVALENT = {\n 'Ă': 'A',\n 'ă': 'a',\n 'Â': 'A',\n 'â': 'a',\n 'Î': 'I',\n 'î': 'i',\n 'Ș': 'S',\n 'ș': 's',\n 'Ş': 'S',\n 'ş': 's',\n 'Ț': 'T',\n 'ț': 't',\n 'Ţ': 'T',\n 'ţ': 't'\n}\nPATTERN_SPECIAL = [r'\\w*(' + '|'.join(SPECIAL) + r')\\w*', 'ROM_SPECIAL']\n\n# Both in romanian and english languages\nstopterms = set(['a', 'an', 'in'])\n\n\ndef replace_special(text, method='alias'):\n \"\"\"\n Parameters\n ----------\n method : str\n Either 'alias' (default) or 'latin'. If 'latin' then replace all \n romanian special character with its latin equivalent. \n F.e ă will be replaced with a.\n This is useful in case discrepancy bettween those is not important.\n F.e when terms ălea and alea should be treated as equal.\n \"\"\"\n if method == 'alias':\n return re.sub(PATTERN_SPECIAL[0], PATTERN_SPECIAL[1], text)\n elif method == 'latin':\n for special in SPECIAL:\n text = re.sub(special, LATIN_EQUIVALENT[special], text)\n return text\n else:\n raise ValueError('method arg value is wrong')\n\n\ndef preprocess(text, special):\n \"\"\"\n Remove numbers, punctuation, redundant whitespaces, special signs,\n stopterms. Replaces special romanian characters with ROM_SPECIAL.\n\n Parameters\n ----------\n text:\n \"\"\"\n text = text.lower()\n text = re.sub(PATTERN_NUMBERS[0], PATTERN_NUMBERS[1], text)\n text = re.sub(PATTERN_PUNCTUATION[0], PATTERN_PUNCTUATION[1], text)\n text = re.sub(PATTERN_NOTERM[0], PATTERN_NOTERM[1], text)\n text = replace_special(text)\n terms = text.split()\n terms = [term for term in terms if term not in stopterms]\n text = ' '.join(terms)\n return text\n\n\ndef preprocess(text):\n \"\"\"\n Remove numbers, punctuation, redundant whitespaces, special signs,\n stopterms. Replaces special romanian characters with ROM_SPECIAL.\n \"\"\"\n text = text.lower()\n text = re.sub(PATTERN_NUMBERS[0], PATTERN_NUMBERS[1], text)\n text = re.sub(PATTERN_PUNCTUATION[0], PATTERN_PUNCTUATION[1], text)\n text = re.sub(PATTERN_NOTERM[0], PATTERN_NOTERM[1], text)\n text = replace_special(text)\n terms = text.split()\n terms = [term for term in terms if term not in stopterms]\n text = ' '.join(terms)\n return text\n\n\ndef preprocess_and_write(read_f, write_f):\n \"\"\"\n Merge title and text fields into single text field.\n Preprocess text.\n \"\"\"\n with open(read_f) as fr, open(write_f, 'w') as fw:\n for line in fr:\n try:\n doc = json.loads(line)\n except JSONDecodeError:\n continue\n else:\n try:\n text = doc['title'] + ' ' + doc['text']\n text = preprocess(text)\n doc['text'] = text\n del doc['title']\n except KeyError:\n continue\n text = json.dumps(doc, ensure_ascii=False, sort_keys=True)\n fw.write(text + '\\n')\n\n\nif __name__ == '__main__':\n preprocess_and_write(paths.TEXTS_RAW_JSON, paths.TEXTS_JSON)\n","sub_path":"src/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"539573678","text":"import discord\nimport json\nimport psycopg2\nimport logging\nimport pytz\nimport datetime\nimport os\nfrom dotenv import load_dotenv\nfrom datetime import datetime as dt\nfrom discord.ext import commands\n\nload_dotenv()\n# Loading Discord TOKEN\nTOKEN = os.getenv(\"DISCORD_TOKEN\")\n# Loading Database credentials\ndbname = os.getenv(\"dbname\")\nhost = os.getenv(\"host\")\nuser = os.getenv(\"user\")\npassword = os.getenv(\"password\")\nport=5432\n\n\nbot = commands.Bot(command_prefix= \".\")\nNST = pytz.timezone('Asia/Kathmandu')\n\ndbconn = psycopg2.connect(dbname=dbname, host=host, port=5432, user=user, password=password, sslmode='require')\nlucur = dbconn.cursor()\nschedcur = dbconn.cursor()\n\nbot.remove_command('help')\n\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.DEBUG)\nhandler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\n\n@bot.event\nasync def on_ready():\n await bot.change_presence(activity=discord.Game(name = \"in Islington College\"))\n print(f\"{bot.user.name} is ready to rock.\")\n\n@bot.command(aliases = ['help', 'commands'])\nasync def cmds(ctx):\n embed = discord.Embed(title = \"Help and Commands\", description = \"Hello, I am a basic schedule bot that will provide you with your class schedules for the day. My prefix is `.`\")\n embed.set_thumbnail(url = bot.user.avatar_url_as(format = \"png\", size = 512))\n # embed.add_field(name = \"nextclass\", value = \"(also nc) Look for your next class from the schedule.\")\n embed.add_field(name = \"schedule\", value = \"(also sch) Look for your schedule for the day.\")\n embed.add_field(name = \"lookup\", value = \"(also lu) Lookup Student Info by someone's name/id.\")\n embed.set_footer(text = \"The schedule data were collected and stored as json files.\")\n await ctx.send(embed= embed)\n\n# @bot.command(aliases = ['nc'])\n# async def nextclass(ctx, group:str = None):\n# author = ctx.author\n# # if day is None:\n# day = dt.strftime(dt.now(NST), \"%a\")\n# day = day.upper()\n# if group == None:\n# specialization = author.top_role.name\n# group = getGroupname(author.roles)\n# elif group.startswith(\"C\") or group.startswith(\"c\"): \n# specialization = \"Computing\"\n# elif group.startswith(\"M\") or group.startswith(\"m\"): \n# specialization = \"Multimedia Technologies\"\n# elif group.startswith(\"N\") or group.startswith(\"n\"): \n# specialization = \"Computer Networking & IT Security\"\n# group = group.upper()\n# today = []\n# try:\n# routine = allsched[specialization][group]\n# except KeyError:\n# await ctx.send(\"Group not found.\")\n# for period in routine:\n# if period['Day'] == day:\n# today.append(period)\n# time = dt.strftime(dt.now(NST), \"%I:%M%p\")\n# a = dt.strptime(time, \"%I:%M%p\")\n# for period in today:\n# start = period['Time'][:8]\n# print(start)\n# b = dt.strptime(start, \"%I:%M %p\")\n# if b > a:\n# timerem = b - a\n# embed = discord.Embed(title = f\"{period['Module Code']} - {period['Module Title ']}\", color = discord.Colour.dark_blue())\n# embed.set_thumbnail(url = bot.user.avatar_url_as(format = \"png\", size = 128))\n# embed.add_field(name = \"Class Type\", value = period['Class Type'])\n# embed.add_field(name = \"Lecturer\", value = period['Lecturer'])\n# embed.add_field(name = \"Time\", value = period['Time'], inline = False)\n# return await ctx.send(content = f'Your next class is in {timerem.seconds/60} minutes.\\nHere are the class details', embed = embed)\n# else:\n# return await ctx.send(\"Looks like you have no classes today. But I might be wrong, who knows.\")\n\n@bot.command(aliases = ['lu'])\nasync def lookup(ctx, *, name):\n data = []\n name = name.upper()\n query = f\"SELECT * FROM student WHERE name LIKE '%{name}%'\"\n lucur.execute(query)\n data = lucur.fetchall()\n if len(data) == 0: \n return await ctx.send(f\"There is no student with name {name}. Make sure you spelled it correctly.\")\n msg = f\"I found {len(data)} student/s with that name.\"\n await ctx.send(msg)\n for x in data:\n embed = discord.Embed(color = discord.Colour.dark_blue())\n embed.set_thumbnail(url = bot.user.avatar_url_as(format = \"png\", size = 128))\n embed.add_field(name = \"Name\", value = x[1], inline = False)\n if len(str(x[0])) == 8:\n embed.add_field(name = \"London Met ID\", value = x[0])\n else:\n embed.add_field(name = \"London Met ID\", value = \"null\")\n embed.add_field(name = \"Group\", value = x[2])\n embed.set_footer(text = \"If the id is null, there was no id data when it was collected.\")\n await ctx.send(embed= embed)\n pass\n\n@bot.command(aliases = ['sch', 'test'])\nasync def schedule(ctx, day:str = None, group:str = None):\n author = ctx.author\n if day is None:\n day = dt.strftime(dt.now(NST), \"%a\")\n if len(day) > 3: day = day[:3]\n day = day.upper()\n if group == None:\n group = getGroupname(author.roles)\n group = group.upper()\n query = f\"SELECT classtype, modulecode, title, name as lecturer, starttime, endtime, groups, block, room FROM schedule JOIN teacher ON schedule.lecturer=teacher.teacherid JOIN module ON module.code=schedule.modulecode WHERE day = '{day}' AND (groups LIKE '%{group}%' OR groups = 'C1-C17') ORDER BY starttime;\"\n schedcur.execute(query)\n classes = schedcur.fetchall()\n if len(classes) == 0: return await ctx.send(\"You have no classes on this day.\")\n msg = f\"You have **{len(classes)}** classes.\"\n await ctx.send(msg)\n for x in classes:\n classType = x[0]\n moduleCode = x[1]\n moduleTitle = x[2]\n lecturer = x[3]\n startTime = x[4]\n endTime = x[5]\n block = x[7]\n room = x[8]\n embed = discord.Embed(title = f\"{moduleCode} - {moduleTitle}\", color = discord.Colour.dark_blue())\n embed.set_thumbnail(url = bot.user.avatar_url_as(format = \"png\", size = 128))\n embed.add_field(name = \"Class Type\", value = classType)\n embed.add_field(name = \"Lecturer\", value = lecturer)\n embed.add_field(name = \"Starts at\", value = startTime.strftime(\"%I:%M %p\"))\n embed.add_field(name = \"Block\", value = block)\n embed.add_field(name = \"Room\", value = room)\n await ctx.send(embed = embed)\n\ndef getGroupname(roles):\n for role in roles:\n if len(role.name) > 4:\n continue\n if role.name.startswith(\"C\") or role.name.startswith(\"M\") or role.name.startswith(\"N\"):\n names = role.name.split(\"-\")\n groupName = \"\".join(names)\n return groupName\n\n\n\nbot.run(TOKEN)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"154484394","text":"from mlaut.estimators.mlaut_estimator import MlautEstimator\n\nfrom mlaut.shared.files_io import DiskOperations\nfrom mlaut.shared.static_variables import(GENERALIZED_LINEAR_MODELS,\n ENSEMBLE_METHODS, \n SVM,\n NEURAL_NETWORKS,\n NAIVE_BAYES,\n REGRESSION, \n CLASSIFICATION,\n GRIDSEARCH_NUM_CV_FOLDS,\n GRIDSEARCH_CV_NUM_PARALLEL_JOBS,\n VERBOSE)\nfrom mlaut.shared.static_variables import PICKLE_EXTENTION, HDF5_EXTENTION\n\nfrom tensorflow.python.keras.models import Sequential, load_model, model_from_json\nfrom tensorflow.python.keras.layers import Dense, Activation, Dropout\nfrom tensorflow.python.keras.wrappers.scikit_learn import KerasRegressor, KerasClassifier\nfrom tensorflow.python.keras import optimizers\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import GridSearchCV\nimport numpy as np\nimport wrapt\n\nimport tensorflow as tf\n\n\n\nclass Deep_NN_Classifier(MlautEstimator):\n # \"\"\"\n # Wrapper for a `keras sequential model `_. \n # \"\"\"\n properties = {'estimator_family':[NEURAL_NETWORKS], \n 'tasks':[CLASSIFICATION], \n 'name':'NeuralNetworkDeepClassifier'}\n hyperparameters = {'epochs': 1, \n 'batch_size': None}\n def keras_model(num_classes, input_dim):\n nn_deep_model = OverwrittenSequentialClassifier()\n nn_deep_model.add(Dense(288, input_dim=input_dim, activation='relu'))\n nn_deep_model.add(Dense(144, activation='relu'))\n nn_deep_model.add(Dropout(0.5))\n nn_deep_model.add(Dense(12, activation='relu'))\n nn_deep_model.add(Dense(num_classes, activation='softmax'))\n\n model_optimizer = optimizers.Adam(lr=0.001)\n nn_deep_model.compile(loss='mean_squared_error', optimizer=model_optimizer, metrics=['accuracy'])\n\n return nn_deep_model\n \n def __init__(self,\n properties=properties,\n hyperparameters=hyperparameters, \n keras_model=keras_model, \n verbose=VERBOSE, \n n_jobs=GRIDSEARCH_CV_NUM_PARALLEL_JOBS,\n num_cv_folds=GRIDSEARCH_NUM_CV_FOLDS, \n refit=True):\n \n self._hyperparameters = hyperparameters\n self._keras_model = keras_model\n self.properties = properties\n self._verbose = verbose\n self._n_jobs = n_jobs\n self._num_cv_folds = num_cv_folds\n self._refit = refit\n\n if 'epochs' not in self._hyperparameters.keys():\n raise ValueError('You need to specify number of epochs as hyperparameter to keras models')\n if 'batch_size' not in self._hyperparameters.keys():\n raise ValueError('You need to specify batch_size as hyperparameter to keras models')\n \n\n \n def set_properties(self,\n estimator_family=None, \n tasks=None, \n name=None, \n data_preprocessing=None):\n \"\"\"\n Alternative method for setting the properties of the estimator. Used when creating a generic estimator by inehriting from an already created class.\n\n \"\"\"\n if estimator_family is not None:\n self._estimator_family = estimator_family\n if tasks is not None:\n self._tasks = tasks\n if name is not None:\n self._name = name\n if data_preprocessing is not None:\n self._data_preprocessing = data_preprocessing\n \n def get_name(self):\n return self._name\n def build(self, **kwargs):\n \"\"\"\n Builds and returns estimator.\n \n Args:\n kwargs (key-value(int)): The user must specify ``input_dim`` and ``num_samples``.\n\n Returns:\n `sklearn pipeline` object: pipeline for transforming the features and training the estimator\n \"\"\"\n\n\n if 'input_dim' not in kwargs:\n raise ValueError('You need to specify input dimensions when building the model.')\n if 'num_samples' not in kwargs:\n raise ValueError('You need to specify num_samples when building the keras model.')\n if 'num_classes' not in kwargs:\n raise ValueError('You need to specify num_classes when building the keras model.')\n\n \n input_dim=kwargs['input_dim']\n num_samples = kwargs['num_samples']\n num_classes = kwargs['num_classes']\n \n \n #the arguments of ``build_fn`` are not passed directly. Instead they should be passed as arguments to ``KerasClassifier``.\n estimator = KerasClassifier(build_fn=self._keras_model, \n num_classes=num_classes, \n input_dim=input_dim,\n batch_size=self._hyperparameters['batch_size'], \n epochs=self._hyperparameters['epochs'])\n\n # grid = GridSearchCV(estimator=estimator, \n # param_grid=self._hyperparameters, \n # cv=self._num_cv_folds, \n # refit=self._refit,\n # verbose=self._verbose)\n return self._create_pipeline(estimator=estimator)\n\n \n\n \n def save(self, dataset_name):\n \"\"\"\n Saves estimator on disk.\n\n Args:\n dataset_name (str): name of the dataset. Estimator will be saved under default folder structure `/data/trained_models//`\n \"\"\"\n #set trained model method is implemented in the base class\n trained_model = self._trained_model\n disk_op = DiskOperations()\n disk_op.save_keras_model(trained_model=trained_model,\n model_name=self.properties['name'],\n dataset_name=dataset_name)\n \n #overloading method from parent class\n def load(self, path_to_model):\n \"\"\"\n Loads saved keras model from disk.\n\n Args:\n path_to_model (str): path on disk where the object is saved.\n \"\"\"\n #file name could be passed with .* as extention. \n #split_path = path_to_model.split('.')\n #path_to_load = split_path[0] + HDF5_EXTENTION \n model = load_model(path_to_model,\n custom_objects={\n 'OverwrittenSequentialClassifier':OverwrittenSequentialClassifier\n })\n self.set_trained_model(model)\n\n def get_trained_model(self):\n \"\"\"\n Getter method.\n\n Returns:\n `keras object`: Trained keras model.\n \"\"\"\n\n return self._trained_model\n\n\n\n\n\nclass Deep_NN_Regressor(Deep_NN_Classifier):\n \"\"\"\n Wrapper for a `keras sequential model `_. \n \"\"\"\n properties = {'estimator_family':[NEURAL_NETWORKS], \n 'tasks':[REGRESSION], \n 'name':'NeuralNetworkDeepRegressor'}\n\n def nn_deep_classifier_model(self, input_dim):\n nn_deep_model = Sequential()\n nn_deep_model.add(Dense(288, input_dim=input_dim, activation='relu'))\n nn_deep_model.add(Dense(144, activation='relu'))\n nn_deep_model.add(Dropout(0.5))\n nn_deep_model.add(Dense(12, activation='relu'))\n nn_deep_model.add(Dense(1, activation='sigmoid'))\n \n\n model_optimizer = optimizers.Adam(lr=self._hyperparameters['learning_rate'])\n nn_deep_model.compile(loss='mean_squared_error', optimizer=model_optimizer, metrics=['accuracy'])\n\n\n return nn_deep_model\n\n def build(self, **kwargs):\n \"\"\"\n Builds and returns estimator.\n \n Args:\n kwargs (key-value(int)): The user must specify ``input_dim`` and ``num_samples``.\n\n Returns:\n `sklearn pipeline` object: pipeline for transforming the features and training the estimator\n \"\"\"\n\n\n if 'input_dim' not in kwargs:\n raise ValueError('You need to specify input dimensions when building the model.')\n if 'num_samples' not in kwargs:\n raise ValueError('You need to specify num_samples when building the keras model.')\n if 'num_classes' not in kwargs:\n raise ValueError('You need to specify num_classes when building the keras model.')\n\n input_dim=kwargs['input_dim']\n num_samples = kwargs['num_samples']\n num_classes = kwargs['num_classes']\n \n \n #the arguments of ``build_fn`` are not passed directly. Instead they should be passed as arguments to ``KerasClassifier``.\n estimator = KerasRegressor(build_fn=self._keras_model, \n input_dim=input_dim)\n grid = GridSearchCV(estimator=estimator, \n param_grid=self._hyperparameters, \n cv=self._num_cv_folds, \n refit=self._refit,\n verbose=self._verbose)\n return self._create_pipeline(estimator=estimator)\n \n\n\n# def __init__(self, verbose=VERBOSE, \n# n_jobs=GRIDSEARCH_CV_NUM_PARALLEL_JOBS,\n# num_cv_folds=GRIDSEARCH_NUM_CV_FOLDS, \n# refit=True):\n# super().__init__(verbose=verbose, \n# n_jobs=n_jobs, \n# num_cv_folds=num_cv_folds, \n# refit=refit)\n# self._hyperparameters = {'loss':'mean_squared_error', \n# 'learning_rate':0.001,\n# 'optimizer': 'Adam',\n# 'metrics': ['accuracy'],\n# 'epochs': [50,100], \n# 'batch_size': 0 }\n\n# def _nn_deep_classifier_model(self, input_dim):\n# nn_deep_model = Sequential()\n# nn_deep_model.add(Dense(288, input_dim=input_dim, activation='relu'))\n# nn_deep_model.add(Dense(144, activation='relu'))\n# nn_deep_model.add(Dropout(0.5))\n# nn_deep_model.add(Dense(12, activation='relu'))\n# nn_deep_model.add(Dense(1, activation='sigmoid'))\n \n# optimizer = self._hyperparameters['optimizer']\n# if optimizer is 'Adam':\n# model_optimizer = optimizers.Adam(lr=self._hyperparameters['learning_rate'])\n \n# nn_deep_model.compile(loss=self._hyperparameters['loss'], \n# optimizer=model_optimizer, \n# metrics=self._hyperparameters['metrics'])\n# return nn_deep_model\n \n# def build(self, **kwargs):\n# \"\"\"\n# Builds and returns estimator.\n \n# Args:\n# kwargs (key-value(int)): The user must specify ``input_dim`` and ``num_samples``.\n\n# Returns:\n# `sklearn pipeline` object: pipeline for transforming the features and training the estimator\n# \"\"\"\n# if 'input_dim' not in kwargs:\n# raise ValueError('You need to specify input dimentions when building the model')\n# if 'num_samples' not in kwargs:\n# raise ValueError('You need to specify num_samples when building the keras model.')\n# input_dim=kwargs['input_dim']\n# num_samples = kwargs['num_samples']\n \n# estimator = KerasRegressor(build_fn=self._nn_deep_classifier_model, \n# input_dim=input_dim,\n# verbose=self._verbose)\n\n \n# return self._create_pipeline(estimator=estimator)\n# # return GridSearchCV(model, \n# # hyperparameters, \n# # verbose = self._verbose,\n# # n_jobs=self._n_jobs,\n# # refit=self._refit)\n\n\n# def save(self, dataset_name):\n# \"\"\"\n# Saves estimator on disk.\n\n# Args:\n# dataset_name (str): name of the dataset. Estimator will be saved under default folder structure `/data/trained_models//`\n# \"\"\"\n# #set trained model method is implemented in the base class\n# trained_model = self._trained_model\n# disk_op = DiskOperations()\n# disk_op.save_keras_model(trained_model=trained_model,\n# model_name=self.properties['name'],\n# dataset_name=dataset_name)\n \n# #overloading method from parent class\n# def load(self, path_to_model):\n# \"\"\"\n# Loads saved keras model from disk.\n\n# Args:\n# path_to_model (string): path on disk where the object is saved.\n# \"\"\"\n# #file name could be passed with .* as extention. \n# model = load_model(path_to_model,\n# custom_objects={\n# 'OverwrittenSequentialClassifier':OverwrittenSequentialClassifier\n# })\n# self.set_trained_model(model)\n \n\nclass OverwrittenSequentialClassifier(Sequential):\n \"\"\"\n Keras sequential model that overrides the default :func:`tensorflow.python.keras.models.fit` and :func:`tensorflow.python.keras.models.predict` methods.\n \"\"\"\n\n\n def fit(self, X_train, y_train, **kwargs):\n \n \"\"\"\n Overrides the default :func:`tensorflow.python.keras.models.fit` and reshapes the `y_train` in one hot array. \n\n Args:\n X_train: training data\n y_train: Labels that will be converted to onehot array.\n\n\n Returns:\n :func:`tensorflow.python.keras.models.fit` object\n\n \"\"\"\n onehot_encoder = OneHotEncoder(sparse=False)\n len_y = len(y_train)\n reshaped_y = y_train.reshape(len_y, 1)\n y_train_onehot_encoded = onehot_encoder.fit_transform(reshaped_y)\n \n # if 'epochs' not in self._hyperparameters:\n # epochs = 1\n # else:\n # epochs = self._hyperparameters\n\n return super().fit(X_train, \n y_train_onehot_encoded, \n batch_size=kwargs['batch_size'],\n epochs=kwargs['epochs'])\n\n \n\n def predict(self, X_test, batch_size=None, verbose=VERBOSE):\n \"\"\"\n Overrides the default :func:`tensorflow.python.keras.models.predict` by replacing it with a :func:`tensorflow.python.keras.models.predict_classes` \n\n Returns:\n :func:`tensorflow.python.keras.models.predict_classes`\n \"\"\"\n predictions = Sequential.predict(self, X_test, batch_size=batch_size, verbose=verbose)\n return predictions.argmax(axis=1)\n # return super().predict_classes(X_test)","sub_path":"mlaut/estimators/nn_estimators.py","file_name":"nn_estimators.py","file_ext":"py","file_size_in_byte":15125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"11081690","text":"\"\"\"CPU functionality.\"\"\"\n\nimport sys\n\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.pc = 0\n self.ram = [0] * 256\n self.reg = [0] * 8\n # flags 00000LGE\n self.flags = 0\n # stack pointer\n self.reg[7] = 0xf4\n\n @property\n def sp(self):\n return self.reg[7]\n\n @sp.setter\n def sp(self, value):\n self.reg[7] = value\n\n def ram_read(self, MAR):\n return self.ram[MAR]\n\n def ram_write(self, MDR, MAR):\n self.ram[MAR] = MDR\n\n def load(self, path):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n program = []\n\n try:\n with open(path) as f:\n for line in f:\n instruction = line.split('#', 1)[0].strip()\n if len(instruction):\n program.append(int(instruction, 2))\n except FileNotFoundError:\n print(f\"No such file {path}, exiting\")\n sys.exit(2)\n\n for instruction in program:\n self.ram[address] = instruction\n address += 1\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == \"ADD\":\n self.reg[reg_a] += self.reg[reg_b]\n\n elif op == \"SUB\":\n self.reg[reg_a] -= self.reg[reg_b]\n\n elif op == \"MUL\":\n self.reg[reg_a] *= self.reg[reg_b]\n\n elif op == \"AND\":\n self.reg[reg_a] &= self.reg[reg_b]\n\n elif op == \"OR\":\n self.reg[reg_a] |= self.reg[reg_b]\n\n elif op == \"XOR\":\n self.reg[reg_a] ^= self.reg[reg_b]\n\n elif op == \"NOT\":\n self.reg[reg_a] = 0b11111111 - self.reg[reg_a]\n\n elif op == \"CMP\":\n a, b = self.reg[reg_a], self.reg[reg_b]\n if a == b:\n self.flags = 0b00000001\n elif a < b:\n self.flags = 0b00000100\n else:\n self.flags = 0b00000010\n\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n # self.fl,\n # self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n self.running = True\n\n def halt():\n self.running = False\n\n def no_op():\n pass\n\n def load_immediate():\n self.reg[operand_a] = operand_b\n\n def print_numeric():\n print(self.reg[operand_a])\n\n def store():\n self.ram[operand_a] = self.reg[operand_b]\n\n def compare():\n self.alu(\"CMP\", operand_a, operand_b)\n\n def add():\n self.alu(\"ADD\", operand_a, operand_b)\n\n def sub():\n self.alu(\"SUB\", operand_a, operand_b)\n\n def multiply():\n self.alu(\"MUL\", operand_a, operand_b)\n\n def push_stack():\n self.sp -= 1\n self.ram[self.sp] = self.reg[operand_a]\n\n def pop_stack():\n self.reg[operand_a] = self.ram[self.sp]\n self.sp += 1\n\n def call():\n self.sp -= 1\n self.ram[self.sp] = self.ram[self.pc + 2]\n self.pc = self.reg[operand_a]\n\n def call_return():\n self.pc = self.ram[self.sp]\n self.sp += 1\n\n def jump():\n self.pc = self.reg[operand_a]\n\n def jump_eq():\n eq = (self.flags & 0b00000001)\n if eq:\n self.pc = self.reg[operand_a]\n else:\n self.pc += 2\n\n def jump_ne():\n eq = (self.flags & 0b00000001)\n if not eq:\n self.pc = self.reg[operand_a]\n else:\n self.pc += 2\n\n def bitwise_and():\n self.alu(\"AND\", operand_a, operand_b)\n\n def bitwise_or():\n self.alu(\"OR\", operand_a, operand_b)\n\n def bitwise_xor():\n self.alu(\"XOR\", operand_a, operand_b)\n\n def bitwise_not():\n self.alu(\"NOT\", operand_a, operand_b)\n\n branchtable = {\n 0b00000000: no_op, # NOP\n 0b00000001: halt, # HTL\n 0b10000010: load_immediate, # LDI\n 0b01000111: print_numeric, # PRN\n 0b10000100: store, # ST\n 0b10100111: compare, # CMP\n 0b10100000: add, # ADD\n 0b10100001: sub, # SUB\n 0b10100010: multiply, # MUL\n 0b01000101: push_stack, # PUSH\n 0b01000110: pop_stack, # POP\n 0b01010000: call, # CALL\n 0b00010001: call_return, # RET\n 0b01010100: jump, # JMP\n 0b01010101: jump_eq, # JEQ\n 0b01010110: jump_ne, # JNE\n 0b10101000: bitwise_and, # AND\n 0b10101010: bitwise_or, # OR\n 0b10101011: bitwise_xor, # XOR\n 0b01101001: bitwise_not, # NOT\n }\n\n while self.running:\n IR = self.ram[self.pc]\n operand_count = (IR & 0b11000000) >> 6\n sets_pc = (IR & 0b00010000) >> 4\n\n operand_a, operand_b = None, None\n if operand_count > 0:\n operand_a = self.ram[self.pc + 1]\n if operand_count > 1:\n operand_b = self.ram[self.pc + 2]\n\n command = branchtable.get(IR)\n\n if not command:\n print(f'Unknown instruction {IR:0b}')\n sys.exit(1)\n\n # print(\n # f'PC {self.pc} IR {IR:08b} {command.__name__}\\n FL {self.flags} OPA {operand_a} OPB {operand_b}')\n\n command()\n if not sets_pc:\n self.pc += (operand_count + 1)\n","sub_path":"ls8/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":6245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"114702478","text":"\"\"\"\nThis game is formatted in the following way (dimensions may vary)\n\nFor example, a 4x4:\n\nC C C C\nC C C C\nC C C C\nC C C C\n\nwhere `C` is a block of color (red or blue)\n\nThe objective of the game is to get all the\nblocks to be the same color\n\n\"\"\"\n\nfrom tkinter import Tk, Button\n\nclass Game():\n \"\"\"\n Base Game Class\n \"\"\"\n \n def __init__(self, master: Tk):\n self.master = master\n\n self.master.title(\"Game\")\n\n self.rows = 6\n self.columns = 6\n\n # Generate buttons #\n self.grid_size = self.rows * self.columns\n self.buttons = [Button(master) for _ in range(self.grid_size)]\n\n # Configure buttons to pass object #\n for button in self.buttons:\n button.configure(command=lambda button=button: self.change_colors(button))\n\n # Assign buttons in a grid #\n self.button_grid = [\n [self.buttons[i] for i in range(self.grid_size // 4)] for _ in range(self.grid_size // 4)\n ]\n\n self.button_width = 27\n self.button_height = self.button_width // 3\n\n # Add Buttons to grid #\n r, c, count = 1, 1, 0\n current_color = \"red\"\n for button in self.buttons:\n button.configure(width=self.button_width, height=self.button_height, highlightbackground=current_color)\n button.grid(row=r, column=c)\n if c % self.rows == 0:\n r += 1\n c = 0\n count += 1\n c += 1\n current_color = \"blue\" if count % 2 == 0 else \"red\"\n count += 1\n\n def change_colors(self, button: object) -> None:\n \"\"\"\n Reverses the current button, and the (NSEW) buttons\n around the button clicked\n\n :param object button: The button whos color is changing\n\n :return: None\n \"\"\"\n # Change clicked button color #\n current_color = button['highlightbackground']\n button['highlightbackground'] = \"blue\" if current_color == \"red\" else \"red\"\n\n # Check entire grid #\n self.check_colors()\n\n def check_colors(self) -> None:\n \"\"\"\n If all the colors are the same, then the window quits\n\n :return: None\n \"\"\"\n all_red = sum(1 if button['highlightbackground'] == \"red\" else 0 for button in self.buttons)\n all_blue = sum(1 if button['highlightbackground'] == \"blue\" else 0 for button in self.buttons)\n\n if all_red == self.grid_size or all_blue == self.grid_size:\n self.master.destroy()\n\ndef run_interface() -> None:\n \"\"\"\n Creates and opens the main window\n \"\"\"\n root = Tk()\n root.resizable(False, False)\n gui = Game(root)\n root.mainloop()\n\nif __name__ == \"__main__\":\n run_interface()","sub_path":"Python/Same_Color/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"100257585","text":"\r\nimport cv2 as cv\r\nimport numpy as np\r\nfrom ImageStackModule import imageStack\r\n\r\nimg1 = cv.imread(\"./Images/lena.jpg\")\r\nimg2 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)\r\nimg3 = cv.GaussianBlur(img2, (5, 5), 2)\r\nimg4 = cv.Canny(img3, 50, 100,)\r\n\r\n\r\n\r\n# def imageStack(imgArray, scale):\r\n# sample = imgArray[0][0]\r\n# x, y, c = sample.shape\r\n# print(x, y, c)\r\n# resizArray1 = []\r\n# resizArray2 = []\r\n# for i, im in enumerate(imgArray[0]):\r\n# img = cv.resize(im, (x, y))\r\n# if len(img.shape) == 2:\r\n# img = np.repeat(img[:, :, np.newaxis], 3, axis=2)\r\n# img = cv.resize(img, None, fx=scale, fy=scale)\r\n# resizArray1.append(img)\r\n# else:\r\n# img = cv.resize(img, None, fx=scale, fy=scale)\r\n# resizArray1.append(img)\r\n#\r\n# imgHor1 = np.hstack(resizArray1)\r\n#\r\n# for i, im in enumerate(imgArray[1]):\r\n# img = cv.resize(im, (x, y))\r\n# if len(img.shape) == 2:\r\n# img = np.repeat(img[:, :, np.newaxis], 3, axis=2)\r\n# img = cv.resize(img, None, fx=scale, fy=scale)\r\n# resizArray2.append(img)\r\n# else:\r\n# img = cv.resize(img, None, fx=scale, fy=scale)\r\n# resizArray2.append(img)\r\n#\r\n# imgHor2 = np.hstack(resizArray2)\r\n#\r\n# imgStack = np.vstack([imgHor1, imgHor2])\r\n#\r\n# return imgStack\r\n\r\nwhile True:\r\n imgHor1 = imageStack([[img1, img2], [img3, img4]], 0.5)\r\n cv.imshow(\"imageStack\", imgHor1)\r\n if cv.waitKey(0) & 0xFF == ord(\"q\"):\r\n break\r\n","sub_path":"Join_images_into_one.py","file_name":"Join_images_into_one.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"564438309","text":"import getpass\nimport json\nimport os\nimport subprocess\nimport tempfile\nimport time\nfrom collections import defaultdict\nfrom typing import Any, DefaultDict, Dict, List, Optional, Union\n\nimport pandas as pd\nfrom helpers import (\n NOW,\n ROOT,\n Chdir,\n Settings,\n create_settings,\n flamegraph_env,\n nix_build,\n run,\n spawn,\n)\nfrom storage import Storage, StorageKind\n\n\ndef percentile(idx: int, run_total: List[int]) -> float:\n total = run_total[len(run_total) - 1]\n if total == 0:\n return 0\n\n return float(run_total[idx]) / total\n\n\ndef more_lines(indices: Dict[str, int], bins: Dict[str, List[List[Any]]]) -> bool:\n for key, value in indices.items():\n if value < len(bins[key]):\n return True\n\n return False\n\n\ndef parse_json_plus(\n jsondata: Dict[str, Any], system: str, stats: Dict[str, List]\n) -> None:\n for jobnum in range(0, len(jsondata[\"jobs\"])):\n bins = {}\n run_total = {}\n operation_set = set([\"read\", \"write\", \"trim\"])\n\n prev_operation = None\n for operation in operation_set:\n if \"bins\" in jsondata[\"jobs\"][jobnum][operation][\"clat_ns\"]:\n bins_loc = \"clat_ns\"\n elif \"bins\" in jsondata[\"jobs\"][jobnum][operation][\"lat_ns\"]:\n bins_loc = \"lat_ns\"\n else:\n raise RuntimeError(\n \"Latency bins not found. \"\n \"Are you sure you are using json+ output?\"\n )\n\n bin = []\n for key, value in jsondata[\"jobs\"][jobnum][operation][bins_loc][\n \"bins\"\n ].items():\n bin.append([int(key), value])\n bins[operation] = bin\n bins[operation] = sorted(bins[operation], key=lambda bin: bin[0])\n\n run_total[operation] = [0 for x in range(0, len(bins[operation]))]\n if len(bins[operation]) > 0:\n run_total[operation][0] = bins[operation][0][1]\n for x in range(1, len(bins[operation])):\n run_total[operation][x] = (\n run_total[operation][x - 1] + bins[operation][x][1]\n )\n\n # Have a counter for each operation\n # In each round, pick the shortest remaining duration\n # and output a line with any values for that duration\n indices = {x: 0 for x in operation_set}\n while more_lines(indices, bins):\n min_lat = 17_112_760_320\n for operation in operation_set:\n if indices[operation] < len(bins[operation]):\n min_lat = min(bins[operation][indices[operation]][0], min_lat)\n\n stats[\"job\"].append(jobnum)\n stats[\"system\"].append(system)\n stats[f\"{bins_loc}ec\"].append(min_lat)\n\n for operation in operation_set:\n if (\n indices[operation] < len(bins[operation])\n and min_lat == bins[operation][indices[operation]][0]\n ):\n count = bins[operation][indices[operation]][1]\n cumulative = run_total[operation][indices[operation]]\n ptile = percentile(indices[operation], run_total[operation])\n stats[f\"{operation}_count\"].append(count)\n stats[f\"{operation}_cumulative\"].append(cumulative)\n stats[f\"{operation}_percentile\"].append(ptile)\n indices[operation] += 1\n else:\n stats[f\"{operation}_count\"].append(None)\n stats[f\"{operation}_cumulative\"].append(None)\n stats[f\"{operation}_percentile\"].append(None)\n\n\ndef benchmark_fio(\n storage: Storage,\n system: str,\n attr: str,\n directory: str,\n stats: Dict[str, List],\n latency_stats: Dict[str, List],\n extra_env: Dict[str, str] = {},\n):\n env = dict(SGXLKL_CWD=directory)\n env.update(flamegraph_env(f\"fio-{system}-{NOW}\"))\n env.update(extra_env)\n enable_sgxio = \"1\" if system == \"sgx-io\" else \"0\"\n env.update(SGXLKL_ENABLE_SGXIO=enable_sgxio)\n threads = \"8\" if system == \"sgx-io\" else \"2\"\n env.update(SGXLKL_ETHREADS=threads)\n env.update(extra_env)\n fio = nix_build(attr)\n stdout: Optional[int] = subprocess.PIPE\n if os.environ.get(\"SGXLKL_ENABLE_GDB\", \"0\") == \"1\":\n stdout = None\n\n proc = run(\n [\n fio,\n \"bin/fio\",\n # \"--debug=io\",\n \"--output-format=json+\",\n \"--eta=always\",\n \"fio-rand-RW.job\"\n # \"fio-seq-RW.job\"\n ],\n extra_env=env,\n stdout=stdout,\n )\n try:\n jsondata = json.loads(proc.stdout)\n except json.decoder.JSONDecodeError:\n print(proc.stdout.decode(\"utf-8\"))\n raise\n parse_json_plus(jsondata, system, latency_stats)\n\n operation_set = set([\"read\", \"write\", \"trim\"])\n for jobnum in range(0, len(jsondata[\"jobs\"])):\n stats[\"system\"].append(system)\n stats[\"job\"].append(jobnum)\n\n for operation in operation_set:\n op_stats = jsondata[\"jobs\"][jobnum][operation]\n stats[f\"{operation}-iobytes\"].append(op_stats[\"io_bytes\"])\n stats[f\"{operation}-iops\"].append(op_stats[\"iops\"])\n stats[f\"{operation}-runtime\"].append(op_stats[\"runtime\"])\n\n\ndef benchmark_native(\n storage: Storage, stats: Dict[str, List], latency_stats: Dict[str, List]\n) -> None:\n with storage.setup(StorageKind.NATIVE) as mnt:\n benchmark_fio(storage, \"native\", \"fio-native\", mnt, stats, latency_stats)\n\n\ndef benchmark_scone(\n storage: Storage, stats: Dict[str, List], latency_stats: Dict[str, List]\n) -> None:\n with storage.setup(StorageKind.NATIVE) as mnt:\n benchmark_fio(storage, \"scone\", \"fio-scone\", mnt, stats, latency_stats)\n\n\ndef benchmark_sgx_lkl(\n storage: Storage, stats: Dict[str, List], latency_stats: Dict[str, List]\n) -> None:\n storage.setup(StorageKind.LKL)\n benchmark_fio(\n storage,\n \"sgx-lkl\",\n \"fio\",\n \"/mnt/nvme\",\n stats,\n latency_stats,\n extra_env=dict(SGXLKL_HDS=\"/dev/nvme0n1:/mnt/nvme\"),\n )\n\n\ndef benchmark_sgx_io(\n storage: Storage, stats: Dict[str, List], latency_stats: Dict[str, List]\n) -> None:\n storage.setup(StorageKind.SPDK)\n benchmark_fio(storage, \"sgx-io\", \"fio\", \"/mnt/spdk0\", stats, latency_stats)\n\n\ndef write_stats(path: str, stats: DefaultDict[str, List]) -> None:\n with open(path, \"w\") as f:\n json.dump(stats, f)\n\n\ndef read_stats(path: str) -> DefaultDict[str, List]:\n stats: DefaultDict[str, List] = defaultdict(list)\n if not os.path.exists(path):\n return stats\n with open(path) as f:\n raw_stats = json.load(f)\n for key, value in raw_stats.items():\n stats[key] = value\n return stats\n\n\ndef main() -> None:\n stats = read_stats(\"stats.json\")\n latency_stats = read_stats(\"latency-stats.json\")\n\n settings = create_settings()\n\n storage = Storage(settings)\n\n system = set(stats[\"system\"])\n\n benchmarks = {\n \"sgx-io\": benchmark_sgx_io,\n \"native\": benchmark_native,\n \"scone\": benchmark_scone,\n \"sgx-lkl\": benchmark_sgx_lkl,\n }\n\n for name, benchmark in benchmarks.items():\n if name in system:\n print(f\"skip {name} benchmark\")\n continue\n benchmark(storage, stats, latency_stats)\n write_stats(\"stats.json\", stats)\n write_stats(\"latency-stats.json\", latency_stats)\n\n csv = f\"fio-throughput-{NOW}.tsv\"\n print(csv)\n throughput_df = pd.DataFrame(stats)\n throughput_df.to_csv(csv, index=False, sep=\"\\t\")\n throughput_df.to_csv(\"fio-throughput-latest.tsv\", index=False, sep=\"\\t\")\n\n csv = f\"fio-latency-{NOW}.tsv\"\n print(csv)\n latency_df = pd.DataFrame(latency_stats)\n latency_df.to_csv(csv, index=False, sep=\"\\t\")\n latency_df.to_csv(\"fio-latency-latest.tsv\", index=False, sep=\"\\t\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"apps/nix/fio.py","file_name":"fio.py","file_ext":"py","file_size_in_byte":8008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"84005439","text":"# Copyright (c) 2018 Rui Shu\nimport argparse\nimport numpy as np\nimport torch\nimport torch.utils.data\nimport utils as ut\nfrom torch import nn, optim\nfrom torch.nn import functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\n\nclass EncoderRGB(nn.Module):\n def __init__(self, x_dim, z_dim, y_dim=0):\n super().__init__()\n self.z_dim = z_dim\n self.y_dim = y_dim\n self.net = nn.Sequential(\n nn.Linear(x_dim + y_dim, 600),\n nn.ELU(),\n nn.Linear(600, 600),\n nn.ELU(),\n nn.Linear(600, 2 * z_dim),\n )\n\n def encode(self, x, y=None):\n xy = x if y is None else torch.cat((x, y), dim=1)\n h = self.net(xy)\n m, v = ut.gaussian_parameters(h, dim=1)\n return m, v\n\nclass DecoderRGB(nn.Module):\n def __init__(self, x_dim, z_dim, y_dim=0):\n super().__init__()\n self.z_dim = z_dim\n self.y_dim = y_dim\n self.net = nn.Sequential(\n nn.Linear(z_dim + y_dim, 600),\n nn.ELU(),\n nn.Linear(600, 600),\n nn.ELU(),\n nn.Linear(600, x_dim)\n )\n\n def decode(self, z, y=None):\n zy = z if y is None else torch.cat((z, y), dim=1)\n return self.net(zy)\n\nclass ClassifierRGB(nn.Module):\n def __init__(self, x_dim, y_dim):\n super().__init__()\n self.y_dim = y_dim\n self.net = nn.Sequential(\n nn.Linear(x_dim, 300),\n nn.ReLU(),\n nn.Linear(300, 300),\n nn.ReLU(),\n nn.Linear(300, y_dim)\n )\n\n def classify(self, x):\n return self.net(x)\n\nclass SSVAE(nn.Module):\n def __init__(self, nc, nv, nh, name='ssvae', gen_weight=1, class_weight=100):\n super().__init__()\n self.name = name\n self.z_dim = 64\n self.y_dim = 2\n self.x_dim = nc * nv * nh\n self.gen_weight = gen_weight\n self.class_weight = class_weight\n self.enc = EncoderRGB(x_dim=self.x_dim, z_dim=self.z_dim, y_dim=self.y_dim)\n self.dec = DecoderRGB(x_dim=self.x_dim, z_dim=self.z_dim, y_dim=self.y_dim)\n self.cls = ClassifierRGB(x_dim=self.x_dim, y_dim=self.y_dim)\n\n # Set prior as fixed parameter attached to Module\n self.z_prior_m = torch.nn.Parameter(torch.zeros(1), requires_grad=False)\n self.z_prior_v = torch.nn.Parameter(torch.ones(1), requires_grad=False)\n self.z_prior = (self.z_prior_m, self.z_prior_v)\n\n self.y_prior = torch.nn.Parameter(torch.tensor([0.1]), requires_grad=False)\n\n self.device = \\\n torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n def negative_elbo_bound(self, x):\n \"\"\"\n Computes the Evidence Lower Bound, KL and, Reconstruction costs\n\n Args:\n x: tensor: (batch, dim): Observations\n\n Returns:\n nelbo: tensor: (): Negative evidence lower bound\n kl: tensor: (): ELBO KL divergence to prior\n rec: tensor: (): ELBO Reconstruction term\n \"\"\"\n ################################################################################\n # TODO: Modify/complete the code here\n # Compute negative Evidence Lower Bound and its KL_Z, KL_Y and Rec decomposition\n #\n # To assist you in the vectorization of the summation over y, we have\n # the computation of q(y | x) and some tensor tiling code for you.\n #\n # Note that nelbo = kl_z + kl_y + rec\n #\n # Outputs should all be scalar\n ################################################################################\n y_logits = self.cls.classify(x)\n y_logprob = F.log_softmax(y_logits, dim=1) # <- (batch, y_dim)\n y_prob = torch.softmax(y_logprob, dim=1) # (batch, y_dim)\n\n # Duplicate y based on x's batch size. Then duplicate x\n # This enumerates all possible combination of x with labels (0, 1)\n y = np.repeat(np.arange(self.y_dim), x.size(0)) # <- (batch*y_dim, )\n y = x.new(np.eye(self.y_dim)[y]) # <- (batch*y_dim, )\n x = ut.duplicate(x, self.y_dim) # <- (batch*y_dim, )\n\n m, v = self.enc.encode(x, y)\n z = ut.sample_gaussian(m, v)\n x_logits = self.dec.decode(z, y)\n\n kl_y = ut.kl_cat(y_prob, y_logprob, np.log(1.0/self.y_dim))\n kl_z = ut.kl_normal(m, v, self.z_prior[0], self.z_prior[1]) \n rec = -ut.log_bernoulli_with_logits(x, x_logits)\n\n rec = (y_prob.t()*rec.reshape(self.y_dim, -1)).sum(0)\n kl_z = (y_prob.t()*kl_z.reshape(self.y_dim, -1)).sum(0)\n\n kl_y, kl_z, rec = kl_y.mean(), kl_z.mean(), rec.mean()\n\n nelbo = kl_y + kl_z + rec\n ################################################################################\n # End of code modification\n ################################################################################\n return nelbo, kl_z, kl_y, rec, x_logits\n\n def classification_cross_entropy(self, x, y):\n y_logits = self.cls.classify(x)\n return F.cross_entropy(y_logits, y.argmax(1))\n\n def loss(self, x, xl, yl):\n if self.gen_weight > 0:\n nelbo, kl_z, kl_y, rec, rec_x = self.negative_elbo_bound(x)\n else:\n nelbo, kl_z, kl_y, rec = [0] * 4\n ce = self.classification_cross_entropy(xl, yl)\n loss = self.gen_weight * nelbo + self.class_weight * ce\n\n summaries = dict((\n ('train/loss', loss),\n ('class/ce', ce),\n ('gen/elbo', -nelbo),\n ('gen/kl_z', kl_z),\n ('gen/kl_y', kl_y),\n ('gen/rec', rec),\n ))\n\n return loss, summaries, rec_x\n\n def compute_sigmoid_given(self, z, y):\n logits = self.dec.decode(z, y)\n return torch.sigmoid(logits)\n\n def sample_z(self, batch):\n return ut.sample_gaussian(self.z_prior[0].expand(batch, self.z_dim),\n self.z_prior[1].expand(batch, self.z_dim))\n\n def sample_x_given(self, z, y):\n return torch.bernoulli(self.compute_sigmoid_given(z, y))\n","sub_path":"vaes/ssvae.py","file_name":"ssvae.py","file_ext":"py","file_size_in_byte":6101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"396385070","text":"import datetime # 날짜 계산을 위한 datetime 라이브러리 포함\nimport util # utli.py 함수들 포함\n\ntoday = datetime.date.today() # 오늘 날짜 저장\n\ndef main(): # 메인 함수\n print('\\n\\n\\t창의소프트웨어입문 개인과제\\n\\t 영화예매 프로그램\\n\\n\\t\\t\\t\\t201820908 오병준\\n\\n\\n') # 기본 정보 출력\n input('영화 예매를 시작하려면 ENTER를 누르세요.') # 프로그램 시작 전 사용자 입력 대기를 위한 input\n\n sequence = 0 # 현재 단계\n movieList = None # API에서 불러온 영화 목록\n price = { 'adult': 10000, 'youth': 7000 } # 가격 정보\n theaters = ['1관', '2관', '3관', 'IMAX관'] # 상영관 정보\n timetable = ['오전 1시', '오전 9시', '오후 1시', '오후 5시', '오후 9시'] # 상영 시간 정보\n prevReservation = None # 파일에서 읽어온 기존 예약 정보\n\n target = { # 사용자가 선택한 값들을 저장하는 dictionary\n 'selection': None, # 선택한 영화\n 'customer': { 'adult': 0, 'youth': 0 }, # 선택한 고객 정보\n 'theater': None, # 선택한 상영관\n 'date': None, # 선택한 상영일\n 'time': None, # 선택한 시간\n 'seat': [], # 선택한 좌석\n 'price': None # 결제한 금액\n }\n\n while(True): # 프로그램 종료 전까지 반복\n util.clear() # 콘솔 화면을 지움\n util.printCurrentStatus(target) # 현재까지 선택한 내용 출력\n\n # API로부터 영화 목록을 불러와 저장하는 단계\n if sequence == 0: \n movieList = util.loadMovieList() # 영화 목록을 불러오는 함수를 호출해 목록을 movieList에 저장\n sequence += 1 # 다음 단계로 이동\n\n\n # 사용자로부터 영화 선택값을 입력받는 단계\n elif sequence == 1:\n print('번호\\t영화 이름')\n for movie in movieList: # 영화 목록 list의 각 요소를 movie 변수에 저장하여 반복\n print(f'{movie[\"rank\"]}\\t{movie[\"movieNm\"]}') # 영화 번호와 이름 출력\n\n while(True): # 입력값이 유효할 때까지 무한 반복\n target['selection'] = util.getIntInput('\\n예매할 영화 번호를 입력하세요(예매 취소: -1): ') # 영화 번호를 사용자로부터 입력받아 저장\n\n # 입력값이 유효할 때만(0보다 크고 목록의 길이보다 같거나 작을 때, 또는 취소할 때) 무한 반복을 중단하고 진행\n if target['selection'] == -1 or target['selection'] in range(1, len(movieList) + 1): break\n\n if target['selection'] == -1: break # 사용자가 취소를 택한 경우 프로그램 종료\n else: # 영화를 선택한 경우 선택한 영화 정보 출력\n target['selection'] = movieList[target['selection'] - 1]['movieNm'] # 선택한 영화 번호를 영화 이름으로 바꿔 저장\n sequence += 1 # 다음 단계로 이동\n\n\n # 관람객 숫자를 입력받는 단계\n elif sequence == 2:\n print('관람객 숫자를 입력하세요.\\n이전 단계로 돌아가려면 -1, 예매를 취소하려면 -2를 입력하세요.\\n')\n try:\n adult = util.getIntInput('성인: ') # 성인 관람객 수를 사용자로부터 입력받음. 유효할 때까지 반복\n if adult == -1: raise Error # 사용자가 이전 단계로 돌아가려 할 때 예외 발생\n elif adult == -2: break # 예매를 취소할 경우 프로그램 종료\n target['customer']['adult'] = adult # 입력값을 관람객 수 변수에 저장\n\n # 성인과 같은 방법으로 청소년 관람객 수 입력\n youth = util.getIntInput('청소년: ')\n if youth == -1: raise Error\n elif youth == -2: break\n target['customer']['youth'] = youth\n sequence += 1 # 다음 단계로 이동\n\n except:\n sequence -= 1 # 사용자 입력에 따라 예외 발생 시 이전 단계로 이동\n target['customer']['adult'] = 0\n target['customer']['youth'] = 0 # 선택값 초기화\n\n \n # 상영관 선택 단계\n elif sequence == 3:\n print('번호\\t상영관')\n\n # index와 함께 상영관 목록을 출력하기 위해 enumerate 함수 사용. 인덱스는 1부터 시작\n for index, theater in enumerate(theaters, start=1):\n print(f'{index}\\t{theater}')\n \n print('\\n상영관 번호를 선택하세요.\\n이전 단계로 돌아가려면 -1, 예매를 취소하려면 -2를 입력하세요.\\n')\n while True:\n target['theater'] = util.getIntInput('상영관: ') # 사용자로부��� 상영관 번호 입력\n if target['theater'] in range(1, len(theaters) + 1) or target['theater'] in range(-2, 0): break # 입력값이 유효할 때만 진행\n\n if target['theater'] == -1: # 사용자가 이전 단계로 돌아가려 할 경우\n sequence -= 1 # 단계 값 감소\n target['theater'] = None # 선택 값 제거\n continue # 이후 내용 수행하지 않고 바로 이전 단계로 돌아감\n elif target['theater'] == -2: break # 사용자가 예매를 취소할 경우 반복문 종료\n\n target['theater'] = theaters[target['theater'] - 1] # 선택한 상영관 인덱스를 상영관 이름으로 바꿔 저장\n sequence += 1 # 다음 단계로 이동\n\n\n # 상영일 선택 단계\n elif sequence == 4:\n print('번호\\t상영일')\n for i in range(0, 5): # 오늘부터 5일 뒤까지 날짜 출력\n print(f\"{i + 1}\\t{(today + datetime.timedelta(days=i)).strftime('%Y년 %m월 %d일')}\")\n\n print(f'\\n상영일 번호를 선택하세요.\\n이전 단계로 돌아가려면 -1, 예매를 취소하려면 -2를 입력하세요.\\n')\n while True:\n target[\"date\"] = util.getIntInput('상영일: ') # 사용자로부터 상영일 번호 입력\n if target['date'] in range(1, 6) or target['date'] in range(-2, 0): break # 입력값이 유효할 때만 진행\n\n if target[\"date\"] == -1: # 사용자가 이전 단계로 돌아가려 할 경우\n sequence -= 1 # 단계 값 감소\n target['date'] = None # 선택 값 제거\n continue # 이후 내용 수행하지 않고 달라진 단계로 이동\n elif target[\"date\"] == -2: break # 사용자가 예매를 취소한 경우 반복문 종료\n\n target[\"date\"] = (today + datetime.timedelta(days=target[\"date\"] - 1)).strftime('%Y년 %m월 %d일') # 선택한 상영일 번호를 실제 상영일로 바꿔 저장\n sequence += 1 # 다음 단계로 이동\n\n\n # 상영 시간 선택 단계\n elif sequence == 5:\n print('번호\\t상영 시간')\n\n prevReservation = util.readReservationData() # 파일에서 이전 예매 데이터를 읽어오는 함수 호출\n\n if prevReservation: # 기존 예약이 있는 경우\n existingTimetable = [] # 같은 상영관, 같은 날짜에 다른 영화가 예약된 상영 시간을 저장하는 리스트\n for movie in prevReservation.keys(): # 이미 예약된 모든 영화에 대해 확인\n if movie == target['selection']: continue # 같은 영화는 생략\n\n # 같은 상영관, 같은 날짜에 다른 영화가 예약된 상영 시간을 확인\n if target['theater'] in prevReservation[movie]: # 예약된 영화가 같은 상영관인지 확인\n if target['date'] in prevReservation[movie][target['theater']]: # 예약된 영화가 같은 날짜인지 확인\n # 같은 상영관과 날짜에 예약된 다른 영화 목록을 추가\n existingTimetable += prevReservation[movie][target['theater']][target['date']].keys()\n\n # timetable 중 existingTimetable에 없는 목록만 출력\n for index, time in enumerate([x for x in timetable if x not in existingTimetable], start=1):\n print(f\"{index}\\t{time}\")\n\n else: # 기존 예약이 없는 경우\n # index와 함께 시간표 목록을 출력하기 위해 enumerate 함수 사용. 인덱스는 1부터 시작\n for index, time in enumerate(timetable, start=1):\n print(f\"{index}\\t{time}\")\n\n print(f'\\n상영 시간 번호를 선택하세요.\\n이전 단계로 돌아가려면 -1, 예매를 취소하려면 -2를 입력하세요.\\n')\n target[\"time\"] = util.getIntInput('상영 시간: ') # 사용자로부터 상영 시간 번호 입력\n\n if target[\"time\"] == -1: # 사용자가 이전 단계로 돌아가려 할 경우\n sequence -= 1 # 단계 값 감소\n target['time'] = None # 선택 값 제거\n continue # 이후 내용 수행하지 않고 달라진 단계로 이동\n elif target[\"time\"] == -2: break # 사용자가 예매를 취소한 경우 반복문 종료\n\n target['time'] = timetable[target['time'] - 1] # 상영 시간 번호를 실제 상영 시간으로 바꾸어 저장\n sequence += 1 # 다음 단계로 이동\n\n\n # 좌석 예약 단계\n elif sequence == 6:\n prevReservedSeats = { } # 해당 영화의 같은 상영관, 상영일, 상영 시간에 미리 예약된 좌석의 배열\n try:\n # 파일에 저장되어 있던 같은 영화, 같은 상영관, 같은 상영 시간의 예약된 좌석 정보를 저장\n prevReservedSeats = prevReservation[target['selection']][target['theater']][target['date']][target['time']]\n except KeyError: pass # 같은 상영관에서 같은 시간에 상영하는 동일한 영화가 없을 경우(처음 예약) 발생하는 예외 처리\n\n # 열 번호 및 구분 문자 출력\n print('좌석\\t1\\t2\\t3\\t4\\t5\\t6\\t7\\t8\\t9\\t10\\n\\t┌──────────────────────────────────────────────────────────────────────────')\n rows = 'ABCDEFGHIJ' # 좌석 행 10개\n \n for row in rows: # 각 행 반복\n print(f\"{row}\\t│\", end='') # 행 번호 및 구분 문자 출력\n for col in range(1, 11): # 각 열 반복\n # prevReservedSeats에 해당 좌석 key가 존재할 경우(예약된 경우) 1 출력\n if f'{row}{col}' in prevReservedSeats: print('1\\t', end='')\n else: print(f'0\\t', end='') # 아닌 경우 0 출력\n print() # 한 행 출력 후 줄바꿈\n \n for i in range (0, target['customer']['adult'] + target['customer']['youth']): # 선택한 관람객 수만큼 반복\n while True: # 입력이 유효할 때까지 무한 반복\n # 사용자로부터 좌석 번호 입력\n seat = input(f\"좌석을 선택하세요({i + 1}/{target['customer']['adult'] + target['customer']['youth']}): \")\n\n try: seatRow, seatCol = seat[0], int(seat[1:]) # 입력받은 좌석 번호를 행/열로 분리\n except ValueError: # 좌석의 열이 숫자가 아닐 경우 다시 입력\n print('올바른 좌석이 아닙니다. ', end='')\n continue\n\n if seat in prevReservedSeats: # 좌석이 이미 예약됐는지 확인\n print('이미 예약된 좌석입니다. ', end='')\n continue\n \n if seatRow not in rows or seatCol not in range(1, 11): # 입력한 좌석이 유효한 범위 안에 없으면\n print('올바른 좌석이 아닙니다. ', end='')\n continue\n \n if seat in target['seat']: # 입력한 좌석을 이전에 입력했다면\n print('이전에 입력하신 좌석입니다. ', end='')\n continue\n\n target['seat'].append(seat) # 선택한 좌석 저장 후 무한반복 중지\n break\n\n sequence += 1 # 다음 단계로 이동\n\n\n # 결제 단계\n elif sequence == 7:\n # 결제 금액 계산\n target['price'] = target[\"customer\"][\"adult\"] * price[\"adult\"] + target[\"customer\"][\"youth\"] * price[\"youth\"]\n\n print(f'티켓 가격은 성인 {format(price[\"adult\"], \",\")}원, 청소년 {format(price[\"youth\"], \",\")}원입니다.') # 가격 정보 출력\n print(f'결제할 금액은 총 {format(target[\"price\"], \",\")}원입니다.') # 청구 금액 계산 및 출력\n input('\\n결제를 완료한 후 ENTER를 누르세요.') # 사용자 결제 후 입력 대기\n \n sequence += 1 # 다음 단계로 이동\n\n\n elif sequence == 8:\n print(f'예약이 확정되었습니다. 결제한 금액은 총 {format(target[\"price\"], \",\")}원입니다.') # 최종 확정 정보 출력\n util.writeReservationData(target) # 파일에 쓰기\n break # 프로그램 종료\n\n print('프로그램이 종료되었습니다.')\n\nmain()","sub_path":"Creative_Software_Intro/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"297610271","text":"import requests, json, sys, time, os, argparse\n\n#suppress TLS certificate check omit warnings\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n# ************************ PARAMETER DEFINITIONS: *************************#\n# API url endpoints for SpectX and StackStorm:\nsx_api_root = \"http://localhost:8388/API/v1.0/\"\nss_api_root = \"https://127.0.0.1/api/v1/webhooks/\"\n\n# API access credentials:\n# SpectX API access key must be set to $SX_API_KEY environment variable!\n# StackStorm API access key must be set to $ST2_API_KEY environment variable!\n\n# SpectX query path and webhook url are specified with command line arguments:\n# usage: alert_exec.py [-h] -qp SX_QUERY -wh WEBHOOK_URL\n#\n# SpectX query path and webhook url\n#\n# optional arguments:\n# -h, --help show this help message and exit\n# -qp SX_QUERY path and name of SpectX query script\n# -wh WEBHOOK_URL StackStorm API endpoint (webhook url)\n\n\ndef exec_sx_stored_query(sx_query):\n headers = {\n \"Authorization\": \"Bearer \" + os.getenv(\"SX_API_KEY\", \"\"),\n \"Accept\": \"application/json\"\n }\n prm = {\n \"scriptPath\":sx_query\n }\n http_resp = requests.post(sx_api_root, headers=headers, params=prm)\n\n if http_resp.status_code != 200:\n #post a notification to Slack channel using spect_failure webhook rule\n rc = http_resp.json()\n rc['status_code'] = http_resp.status_code\n rc['script'] = sx_query\n exec_ss_webhook(\"spectx_failure\", rc)\n exit(1)\n return http_resp\n\n\ndef exec_ss_webhook(url, data):\n headers = {\"Content-Type\" : \"application/json\",\n \"St2-Api-Key\" : os.getenv(\"ST2_API_KEY\", \"\")\n }\n resp = requests.post(ss_api_root + url, headers=headers, data=json.dumps(data), verify=False)\n if resp.status_code != 202: #StackStorm API returns 202 on success\n Fatal(\"%s webhook request failed: StackStorm API returned %i\" % resp.status_code)\n\n\ndef parseCmdline():\n if len(sys.argv)-1 != 2:\n Fatal(\"Unexpected number of arguments \" + str(len(sys.argv)))\n\n skip=0\n # Parse command line\n for i in range(1, len(sys.argv)):\n if not skip:\n if sys.argv[i][:3] == \"-sx\": sx_query = sys.argv[i]\n elif sys.argv[i][:3] == \"-wh\": webhook = sys.argv[i]\n else: Fatal(\"unexpected argument '%s'\" % sys.argv[i])\n else: skip = 0\n\n if(len(sx_query)==0 or len(webhook)==0):\n Fatal(\"invalid arguments %s %s\" % (sx_query, webhook))\n\n return (sx_query, webhook)\n\ndef Fatal(msg):\n sys.stderr.write(\"%s: %s\\n\" % (time.strftime('%Y-%m-%d %H:%M:%S %Z'), msg))\n sys.exit(1)\n\ndef main():\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-qp', type=str, required=True, help='path and name of SpectX query script', dest='sx_query')\n parser.add_argument('-wh', type=str, required=True, help='StackStorm API endpoint (webhook url)', dest='webhook_url')\n\n args = parser.parse_args()\n\n result = exec_sx_stored_query(args.sx_query).json()\n rows = len(result)\n if(rows > 0):\n for row in result:\n exec_ss_webhook(args.webhook_url, row)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"etc/alert_exec.py","file_name":"alert_exec.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"333809537","text":"import subprocess\nimport sys\nimport os\nfrom shutil import copyfile\n\n\ncwd = os.getcwd()\n\nclangDir = os.path.expanduser(\"/usr/local/submitty/clang-llvm/\")\n\n\n\nif not os.path.exists(clangDir):\n os.mkdir(clangDir)\nsubprocess.call([\"git\", \"clone\", \"http://llvm.org/git/llvm.git\", clangDir + \"llvm/\"])\nsubprocess.call([\"git\", \"clone\", \"http://llvm.org/git/clang.git\", clangDir + \"llvm/tools/clang\"])\nsubprocess.call([\"git\", \"clone\", \"http://llvm.org/git/clang-tools-extra.git\", clangDir + \"llvm/tools/clang/tools/extra/\"])\n\n#cmake and ninja\nsubprocess.call([\"git\", \"clone\", \"https://github.com/martine/ninja.git\", clangDir + \"ninja/\"])\nos.chdir(clangDir + \"ninja/\")\nsubprocess.call([\"git\", \"checkout\", \"release\"])\nsubprocess.call([\"./bootstrap.py\"])\n\n\ncopyfile(clangDir + \"ninja/ninja\", \"/usr/bin/ninja\")\nsubprocess.call([\"chmod\", \"+x\", \"/usr/bin/ninja\"])\n\nsubprocess.call([\"git\", \"clone\", \"https://gitlab.kitware.com/cmake/cmake.git\", clangDir + \"cmake/\"])\n\nos.chdir(clangDir + \"cmake/\")\nsubprocess.call([\"./bootstrap\"])\nsubprocess.call([\"make\"])\nsubprocess.call([\"make\", \"install\"])\n\n#build clang\nif not os.path.exists(clangDir + \"build/\"):\n os.mkdir(clangDir+ \"build/\")\n\nos.chdir(clangDir + \"build/\")\n\nsubprocess.call([\"cmake\", \"-G\", \"Ninja\", \"../llvm\", \"-DCMAKE_BUILD_TYPE=Release\", \"-DLLVM_TARGETS_TO_BUILD=X86\", \"-DCMAKE_C_COMPILER=/usr/bin/clang-3.8\", \"-DCMAKE_CXX_COMPILER=/usr/bin/clang++-3.8\"])\n\nsubprocess.call([\"ninja\"])\nsubprocess.call([\"ninja\", \"install\"])\n\n\ncmd = \"echo 'add_subdirectory(ASTMatcher)' >> /usr/local/submitty/clang-llvm/llvm/tools/clang/tools/extra/CMakeLists.txt\"\nos.system(cmd)\n\nastMatcherDir = os.path.expanduser(clangDir + \"llvm/tools/clang/tools/extra/ASTMatcher/\")\n\nif not os.path.exists(astMatcherDir):\n os.mkdir(astMatcherDir)\n\nos.chdir(cwd)\n","sub_path":".setup/clangInstall.py","file_name":"clangInstall.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"555534841","text":"# -*- coding: utf-8 -*-\n\"\"\"\nNLP From Scratch: Translation with a Sequence to Sequence Network and Attention\n*******************************************************************************\n**Author**: `Sean Robertson `_\n\nThis is the third and final tutorial on doing \"NLP From Scratch\", where we\nwrite our own classes and functions to preprocess the data to do our NLP\nmodeling tasks. We hope after you complete this tutorial that you'll proceed to\nlearn how `torchtext` can handle much of this preprocessing for you in the\nthree tutorials immediately following this one.\n\nIn this project we will be teaching a neural network to translate from\nFrench to English.\n\n::\n\n [KEY: > input, = target, < output]\n\n > il est en train de peindre un tableau .\n = he is painting a picture .\n < he is painting a picture .\n\n > pourquoi ne pas essayer ce vin delicieux ?\n = why not try that delicious wine ?\n < why not try that delicious wine ?\n\n > elle n est pas poete mais romanciere .\n = she is not a poet but a novelist .\n < she not not a poet but a novelist .\n\n > vous etes trop maigre .\n = you re too skinny .\n < you re all alone .\n\n... to varying degrees of success.\n\nThis is made possible by the simple but powerful idea of the `sequence\nto sequence network `__, in which two\nrecurrent neural networks work together to transform one sequence to\nanother. An encoder network condenses an input sequence into a vector,\nand a decoder network unfolds that vector into a new sequence.\n\n.. figure:: /_static/img/seq-seq-images/seq2seq.png\n :alt:\n\nTo improve upon this model we'll use an `attention\nmechanism `__, which lets the decoder\nlearn to focus over a specific range of the input sequence.\n\n**Recommended Reading:**\n\nI assume you have at least installed PyTorch, know Python, and\nunderstand Tensors:\n\n- https://pytorch.org/ For installation instructions\n- :doc:`/beginner/deep_learning_60min_blitz` to get started with PyTorch in general\n- :doc:`/beginner/pytorch_with_examples` for a wide and deep overview\n- :doc:`/beginner/former_torchies_tutorial` if you are former Lua Torch user\n\n\nIt would also be useful to know about Sequence to Sequence networks and\nhow they work:\n\n- `Learning Phrase Representations using RNN Encoder-Decoder for\n Statistical Machine Translation `__\n- `Sequence to Sequence Learning with Neural\n Networks `__\n- `Neural Machine Translation by Jointly Learning to Align and\n Translate `__\n- `A Neural Conversational Model `__\n\nYou will also find the previous tutorials on\n:doc:`/intermediate/char_rnn_classification_tutorial`\nand :doc:`/intermediate/char_rnn_generation_tutorial`\nhelpful as those concepts are very similar to the Encoder and Decoder\nmodels, respectively.\n\nAnd for more, read the papers that introduced these topics:\n\n- `Learning Phrase Representations using RNN Encoder-Decoder for\n Statistical Machine Translation `__\n- `Sequence to Sequence Learning with Neural\n Networks `__\n- `Neural Machine Translation by Jointly Learning to Align and\n Translate `__\n- `A Neural Conversational Model `__\n\n\n**Requirements**\n\"\"\"\nfrom __future__ import unicode_literals, print_function, division\nfrom io import open\nimport unicodedata\nimport string\nimport re\nimport random\nimport time\nimport math\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import SGD, Adam\nimport torch.nn.functional as F\n\nimport matplotlib.pyplot as plt\nplt.switch_backend('agg')\nimport matplotlib.ticker as ticker\nimport numpy as np\n\nSOS_token = 0\nEOS_token = 1\n\n######################################################################\n# Since there are a *lot* of example sentences and we want to train\n# something quickly, we'll trim the data set to only relatively short and\n# simple sentences. Here the maximum length is 10 words (that includes\n# ending punctuation) and we're filtering to sentences that translate to\n# the form \"I am\" or \"He is\" etc. (accounting for apostrophes replaced\n# earlier).\n#\nMAX_LENGTH = 10\n\neng_prefixes = (\n \"i am \", \"i m \",\n \"he is\", \"he s \",\n \"she is\", \"she s \",\n \"you are\", \"you re \",\n \"we are\", \"we re \",\n \"they are\", \"they re \"\n)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef getDevice():\n return device\n\n\nclass Lang:\n def __init__(self, name):\n self.name = name\n self.word2index = {}\n self.word2count = {}\n self.index2word = {0: \"SOS\", 1: \"EOS\"}\n self.n_words = 2 # Count SOS and EOS\n self.max_length = 0\n\n def addSentence(self, sentence):\n words = sentence.split(' ')\n if len(words) > self.max_length:\n self.max_length = len(words)\n for word in words:\n self.addWord(word)\n\n def addWord(self, word):\n if word not in self.word2index:\n self.word2index[word] = self.n_words\n self.word2count[word] = 1\n self.index2word[self.n_words] = word\n self.n_words += 1\n else:\n self.word2count[word] += 1\n\n\ndef unicodeToAscii(s):\n \"\"\" The files are all in Unicode, to simplify we will turn Unicode\n characters to ASCII, make everything lowercase, and trim most punctuation.\n Turn a Unicode string to plain ASCII, thanks to\n https://stackoverflow.com/a/518232/2809427\n \"\"\"\n return ''.join(\n c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn'\n )\n\n\ndef normalizeString(s):\n \"\"\" Lowercase, trim, and remove non-letter characters\n \"\"\"\n s = unicodeToAscii(s.lower().strip())\n s = re.sub(r\"([.!?])\", r\" \\1\", s)\n s = re.sub(r\"[^a-zA-Z.!?]+\", r\" \", s)\n return s\n\n\ndef readLangs(lang1, lang2, reverse=False):\n \"\"\" To read the data file we will split the file into lines, and then split\n lines into pairs. The files are all English → Other Language, so if we\n want to translate from Other Language → English I added the ``reverse``\n flag to reverse the pairs.\n \"\"\"\n print(\"Reading lines...\")\n\n # Read the file and split into lines\n lines = open('data/%s-%s.txt' % (lang1, lang2), encoding='utf-8').\\\n read().strip().split('\\n')\n\n # Split every line into pairs and normalize\n pairs = [[normalizeString(s) for s in l.split('\\t')] for l in lines]\n\n # Reverse pairs, make Lang instances\n if reverse:\n pairs = [list(reversed(p)) for p in pairs]\n input_lang = Lang(lang2)\n output_lang = Lang(lang1)\n else:\n input_lang = Lang(lang1)\n output_lang = Lang(lang2)\n\n return input_lang, output_lang, pairs\n\n\ndef filterPair(p):\n return len(p[0].split(' ')) < MAX_LENGTH and \\\n len(p[1].split(' ')) < MAX_LENGTH and \\\n p[1].startswith(eng_prefixes)\n\n\ndef filterPairs(pairs):\n return [pair for pair in pairs if filterPair(pair)]\n\n\ndef prepareData(lang1, lang2, reverse=False):\n \"\"\" The full process for preparing the data is:\n - Read text file and split into lines, split lines into pairs\n - Normalize text, filter by length and content\n - Make word lists from sentences in pairs\n \"\"\"\n input_lang, output_lang, pairs = readLangs(lang1, lang2, reverse)\n print(\"Read %s sentence pairs\" % len(pairs))\n pairs = filterPairs(pairs)\n print(\"Trimmed to %s sentence pairs\" % len(pairs))\n print(\"Counting words...\")\n for pair in pairs:\n input_lang.addSentence(pair[0])\n output_lang.addSentence(pair[1])\n print(\"Counted words:\")\n print(input_lang.name, input_lang.n_words)\n print(output_lang.name, output_lang.n_words)\n return input_lang, output_lang, pairs\n\n\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, hidden_size):\n super(EncoderRNN, self).__init__()\n self.hidden_size = hidden_size\n\n self.embedding = nn.Embedding(input_size, hidden_size)\n self.gru = nn.GRU(hidden_size, hidden_size)\n\n def forward(self, input, hidden):\n embedded = self.embedding(input).view(1, 1, -1)\n output = embedded\n output, hidden = self.gru(output, hidden)\n return output, hidden\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size, device=device)\n\n\nclass AttnDecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size, dropout_p=0.1, max_length=MAX_LENGTH):\n super(AttnDecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.dropout_p = dropout_p\n self.max_length = max_length\n\n self.embedding = nn.Embedding(self.output_size, self.hidden_size)\n self.attn = nn.Linear(self.hidden_size * 2, self.max_length)\n self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)\n self.dropout = nn.Dropout(self.dropout_p)\n self.gru = nn.GRU(self.hidden_size, self.hidden_size)\n self.out = nn.Linear(self.hidden_size, self.output_size)\n\n def forward(self, input, hidden, encoder_outputs):\n embedded = self.embedding(input).view(1, 1, -1)\n embedded = self.dropout(embedded)\n\n attn_weights = F.softmax(\n self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1)\n attn_applied = torch.bmm(attn_weights.unsqueeze(0),\n encoder_outputs.unsqueeze(0))\n\n output = torch.cat((embedded[0], attn_applied[0]), 1)\n output = self.attn_combine(output).unsqueeze(0)\n\n output = F.relu(output)\n output, hidden = self.gru(output, hidden)\n\n output = F.log_softmax(self.out(output[0]), dim=1)\n return output, hidden, attn_weights\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size, device=device)\n\n\ndef indexesFromSentence(lang, sentence):\n return [lang.word2index[word] for word in sentence.split(' ')]\n\n\ndef tensorFromSentence(lang, sentence):\n indexes = indexesFromSentence(lang, sentence)\n indexes.append(EOS_token)\n return torch.tensor(indexes, dtype=torch.long, device=device).view(-1, 1)\n\n\ndef tensorsFromPair(input_lang, output_lang, pair):\n input_tensor = tensorFromSentence(input_lang, pair[0])\n target_tensor = tensorFromSentence(output_lang, pair[1])\n return (input_tensor, target_tensor)\n\n\ndef train(input_tensor, target_tensor, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=MAX_LENGTH):\n encoder_hidden = encoder.initHidden()\n\n encoder_optimizer.zero_grad()\n decoder_optimizer.zero_grad()\n\n input_length = input_tensor.size(0)\n target_length = target_tensor.size(0)\n\n encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n loss = 0\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(\n input_tensor[ei], encoder_hidden)\n encoder_outputs[ei] = encoder_output[0, 0]\n\n decoder_input = torch.tensor([[SOS_token]], device=device)\n\n decoder_hidden = encoder_hidden\n\n teacher_forcing_ratio = 0.5\n # \"Teacher forcing\" is the concept of using the real target outputs as\n # each next input, instead of using the decoder's guess as the next input.\n # Using teacher forcing causes it to converge faster but `when the trained\n # network is exploited, it may exhibit\n # instability `__.\n #\n # You can observe outputs of teacher-forced networks that read with\n # coherent grammar but wander far from the correct translation -\n # intuitively it has learned to represent the output grammar and can \"pick\n # up\" the meaning once the teacher tells it the first few words, but it\n # has not properly learned how to create the sentence from the translation\n # in the first place. \n use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False\n\n if use_teacher_forcing:\n # Teacher forcing: Feed the target as the next input\n for di in range(target_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n loss += criterion(decoder_output, target_tensor[di])\n decoder_input = target_tensor[di] # Teacher forcing\n\n else:\n # Without teacher forcing: use its own predictions as the next input\n for di in range(target_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n topv, topi = decoder_output.topk(1)\n decoder_input = topi.squeeze().detach() # detach from history as input\n\n loss += criterion(decoder_output, target_tensor[di])\n if decoder_input.item() == EOS_token:\n break\n\n loss.backward()\n\n encoder_optimizer.step()\n decoder_optimizer.step()\n\n return loss.item() / target_length\n\n\ndef asMinutes(s):\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\n\ndef timeSince(since, percent):\n now = time.time()\n s = now - since\n es = s / (percent)\n rs = es - s\n return '%s (- %s)' % (asMinutes(s), asMinutes(rs))\n\n\ndef showPlot(points):\n plt.figure()\n fig, ax = plt.subplots()\n # this locator puts ticks at regular intervals\n loc = ticker.MultipleLocator(base=0.2)\n ax.yaxis.set_major_locator(loc)\n plt.plot(points)\n\n\ndef trainIters(training_pairs, encoder, decoder, n_iters, print_every=1000, plot_every=100, optim='sgd', learning_rate=0.01, max_length=MAX_LENGTH):\n start = time.time()\n plot_losses = []\n print_loss_total = 0 # Reset every print_every\n plot_loss_total = 0 # Reset every plot_every\n\n if optim == 'sgd':\n encoder_optimizer = SGD(encoder.parameters(), lr=learning_rate)\n decoder_optimizer = SGD(decoder.parameters(), lr=learning_rate)\n elif optim == 'adam':\n encoder_optimizer = Adam(encoder.parameters(), lr=learning_rate)\n decoder_optimizer = Adam(decoder.parameters(), lr=learning_rate)\n criterion = nn.NLLLoss()\n\n for iter in range(1, n_iters + 1):\n training_pair = training_pairs[iter - 1]\n input_tensor = training_pair[0]\n target_tensor = training_pair[1]\n\n loss = train(input_tensor, target_tensor, encoder,\n decoder, encoder_optimizer, decoder_optimizer, criterion, max_length=max_length)\n print_loss_total += loss\n plot_loss_total += loss\n\n if iter % print_every == 0:\n print_loss_avg = print_loss_total / print_every\n print_loss_total = 0\n print('%s (%d %d%%) %.4f' % (timeSince(start, iter / n_iters),\n iter, iter / n_iters * 100, print_loss_avg))\n\n if iter % plot_every == 0:\n plot_loss_avg = plot_loss_total / plot_every\n plot_losses.append(plot_loss_avg)\n plot_loss_total = 0\n\n showPlot(plot_losses)\n\n\ndef evaluate(encoder, decoder, sentence, input_lang, output_lang, max_length=MAX_LENGTH):\n \"\"\" Evaluation is mostly the same as training, but there are no targets so\n we simply feed the decoder's predictions back to itself for each step.\n Every time it predicts a word we add it to the output string, and if it\n predicts the EOS token we stop there. We also store the decoder's\n attention outputs for display later.\n \"\"\"\n with torch.no_grad():\n input_tensor = tensorFromSentence(input_lang, sentence)\n input_length = input_tensor.size()[0]\n encoder_hidden = encoder.initHidden()\n\n encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(input_tensor[ei],\n encoder_hidden)\n encoder_outputs[ei] += encoder_output[0, 0]\n\n decoder_input = torch.tensor([[SOS_token]], device=device) # SOS\n\n decoder_hidden = encoder_hidden\n\n decoded_words = []\n decoder_attentions = torch.zeros(max_length, max_length)\n\n for di in range(max_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n decoder_attentions[di] = decoder_attention.data\n topv, topi = decoder_output.data.topk(1)\n if topi.item() == EOS_token:\n decoded_words.append('')\n break\n else:\n decoded_words.append(output_lang.index2word[topi.item()])\n\n decoder_input = topi.squeeze().detach()\n\n return decoded_words, decoder_attentions[:di + 1]\n\n\ndef evaluateRandomly(pairs, encoder, decoder, n=10):\n \"\"\" We can evaluate random sentences from the training set and print out the\n input, target, and output to make some subjective quality judgements:\n \"\"\"\n for i in range(n):\n pair = random.choice(pairs)\n print('>', pair[0])\n print('=', pair[1])\n output_words, attentions = evaluate(encoder, decoder, pair[0], input_lang, output_lang)\n output_sentence = ' '.join(output_words)\n print('<', output_sentence)\n print('')\n\n\ndef showAttention(input_sentence, output_words, attentions):\n # Set up figure with colorbar\n fig = plt.figure()\n ax = fig.add_subplot(111)\n cax = ax.matshow(attentions.numpy(), cmap='bone')\n fig.colorbar(cax)\n\n # Set up axes\n ax.set_xticklabels([''] + input_sentence.split(' ') +\n [''], rotation=90)\n ax.set_yticklabels([''] + output_words)\n\n # Show label at every tick\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n\n plt.show()\n\n\ndef evaluateAndShowAttention(input_sentence):\n output_words, attentions = evaluate(\n encoder1, attn_decoder1, input_sentence, input_lang, output_lang)\n print('input =', input_sentence)\n print('output =', ' '.join(output_words))\n showAttention(input_sentence, output_words, attentions)\n\n\nif __name__ == '__main__':\n input_lang, output_lang, pairs = prepareData('eng', 'fra', True)\n print(random.choice(pairs))\n\n # Remember that the input sentences were heavily filtered. For this small\n # dataset we can use relatively small networks of 256 hidden nodes and a\n # single GRU layer. After about 40 minutes on a MacBook CPU we'll get some\n # reasonable results.\n hidden_size = 256\n encoder1 = EncoderRNN(input_lang.n_words, hidden_size).to(device)\n attn_decoder1 = AttnDecoderRNN(hidden_size, output_lang.n_words, dropout_p=0.1).to(device)\n\n n_iters = 75000\n training_pairs = [tensorsFromPair(input_lang, output_lang, random.choice(pairs)) for _ in range(n_iters)]\n trainIters(training_pairs, encoder1, attn_decoder1, n_iters, print_every=5000)\n evaluateRandomly(pairs, encoder1, attn_decoder1)\n\n # A useful property of the attention mechanism is its highly interpretable\n # outputs. Because it is used to weight specific encoder outputs of the\n # input sequence, we can imagine looking where the network is focused most\n # at each time step.\n evaluateAndShowAttention(\"elle a cinq ans de moins que moi .\")\n evaluateAndShowAttention(\"elle est trop petit .\")\n evaluateAndShowAttention(\"je ne crains pas de mourir .\")\n evaluateAndShowAttention(\"c est un jeune directeur plein de talent .\")\n\n ######################################################################\n # Exercises\n # =========\n #\n # - Try with a different dataset\n #\n # - Another language pair\n # - Human → Machine (e.g. IOT commands)\n # - Chat → Response\n # - Question → Answer\n #\n # - Replace the embeddings with pre-trained word embeddings such as word2vec or\n # GloVe\n # - Try with more layers, more hidden units, and more sentences. Compare\n # the training time and results.\n # - If you use a translation file where pairs have two of the same phrase\n # (``I am test \\t I am test``), you can use this as an autoencoder. Try\n # this:\n #\n # - Train as an autoencoder\n # - Save only the Encoder network\n # - Train a new Decoder for translation from there\n #","sub_path":"parser/seq2seq.py","file_name":"seq2seq.py","file_ext":"py","file_size_in_byte":20609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"532283326","text":"import numpy as np\nimport tensorflow as tf\nimport gpflow\n\nimport myKernel.convkernels as ckern\nfrom myKernel.NN import NN\nfrom myKernel.LoadData import LoadData\n\nfloat_type = gpflow.settings.dtypes.float_type\nITERATIONS = 1000\n\nclass Ocean:\n input_dim = 150 * 160\n out_dim = 1\n X, Y, Xt, Yt = LoadData.load_ocean()\n\n\ndef ex2():\n minibatch_size = 200\n gp_dim = 15*16\n M = 32\n\n ## placeholders\n X = tf.placeholder(tf.float32, [minibatch_size, Ocean.input_dim]) # fixed shape so num_data works in SVGP\n Y = tf.placeholder(tf.float32, [minibatch_size, 1])\n Xtest = tf.placeholder(tf.float32, [None, Ocean.input_dim])\n\n ## build graph\n with tf.variable_scope('cnn'):\n f_X = tf.cast(NN.cnn_fn(X, gp_dim), dtype=float_type)\n\n with tf.variable_scope('cnn', reuse=True):\n f_Xtest = tf.cast(NN.cnn_fn(Xtest, gp_dim), dtype=float_type)\n\n k = ckern.WeightedConv(gpflow.kernels.RBF(9), [15, 16], [3, 3]) + gpflow.kernels.White(1, 1e-3)\n\n # Z = None\n # if Z is None:\n # Z = (k.kernels[0].init_inducing(f_X, minibatch_size, M, method=\"patches-unique\")\n # if type(k) is gpflow.kernels.Sum else\n # k.init_inducing(f_X, minibatch_size, M, method=\"patches-unique\"))\n\n gp_model = gpflow.models.SVGP(f_X, tf.cast(Y, dtype=float_type),\n k, gpflow.likelihoods.Gaussian(),\n Z=np.zeros((M, gp_dim)), # we'll set this later\n num_latent=1)\n\n loss = -gp_model.likelihood_tensor\n\n m, v = gp_model._build_predict(f_Xtest)\n my, yv = gp_model.likelihood.predict_mean_and_var(m, v)\n\n with tf.variable_scope('adam'):\n opt_step = tf.train.AdamOptimizer(0.001).minimize(loss)\n\n tf_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='adam')\n tf_vars += tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='cnn')\n\n ## initialize\n sess = tf.Session()\n sess.run(tf.variables_initializer(var_list=tf_vars))\n gp_model.initialize(session=sess)\n\n ## reset inducing (they live in a different space as X, so need to be careful with this)\n ind = np.random.choice(Ocean.X.shape[0], minibatch_size, replace=False)\n\n fZ = sess.run(f_X, feed_dict={X:Ocean.X[ind]})\n # Z_0 = kmeans2(fZ, M)[0] might fail\n Z_0 = fZ[np.random.choice(len(fZ), M, replace=True)]\n\n def set_gp_param(param, value):\n sess.run(tf.assign(param.unconstrained_tensor, param.transform.backward(value)))\n\n set_gp_param(gp_model.feature.Z, Z_0)\n\n ## train\n for i in range(ITERATIONS):\n ind = np.random.choice(Ocean.X.shape[0], minibatch_size, replace=True)\n sess.run(opt_step, feed_dict={X:Ocean.X[ind], Y:Ocean.Y[ind]})\n print('step {:.4f}'.format(i))\n if i % 10 == 0:\n rmse = np.mean((sess.run(my, feed_dict={Xtest:Ocean.Xt}) - Ocean.Yt.shape) ** 2) * 0.5\n rmse = np.average(rmse.astype(float))\n print('rmse is {:.4f}'.format(rmse))\n\n ## predict\n rmse = np.mean((sess.run(my, feed_dict={Xtest:Ocean.Xt}) - Ocean.Yt.shape) ** 2) * 0.5\n rmse = np.average(rmse.astype(float)) * 100.\n print('rmse is {:.4f}'.format(rmse))\n\n\nex2()","sub_path":"Model/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"447740384","text":"import DLfromScratch2.common.layers as layers\nimport collections\n\nclass NegativeSamplingLoss:\n def __init__(self, W, corpus, power=0.75, sample_size=5):\n self.sample_size = sample_size\n self.sampler = UnigramSampler(corpus, power, sample_size)\n\n self.loss_layer = [layers.SoftmaxWithLoss() for _ in range(sample_size+1)]\n self.embed_dot_layers = [layers.EmbeddingDot(W) for _ in range(sample_size+1)]\n self.params, self.grads =[], []\n\n for layer in self.embed_dot_layers:\n self.params += layer.params\n self.grad += layer.grads\n\n# 유니그램이란 하나의 연속된 단어. 2개의 연속된 단어는 바이그램. 3개의 연속된 단어는 트라이얼 그램.\n# 유니그램샘플러는 한 단어를 대상으로 확율 분호를 만든다는 의\nclass UnigramSampler:\n def __init__(self, corpus, power, sample_size):\n self.sample_size = sample_size\n self.vocab_size = None\n self.word_p = None\n\n counts = collections.Counter()\n for word_id in corpus:\n counts[word_id] += 1\n\n vocab_size = len(counts)\n self.vocab_size = vocab_size\n\n self.word_p = np.zeros(vocab_size)\n for i in range(vocab_size):\n self.word_p[i] = counts[i]\n\n self.word_p = np.power(self.word_p, power)\n self.word_p /= np.sum(self.word_p)\n\n def get_negative_sample(self, target):\n batch_size = target.shape[0]\n\n if not GPU: # == CPU\n negative_sample = np.zeros((batch_size, self.sample_size), dtype=np.int32)\n\n for i in range(batch_size):\n p = self.word_p.copy()\n target_idx = target[i]\n p[target_idx] = 0 # target이 뽑히지 않게 하기 위함\n p /= p.sum() # 다시 정규화 해줌\n negative_sample[i, :] = np.random.choice(self.vocab_size,\n size=self.sample_size,\n replace=False, p=p)\n\n else:\n # GPU(cupy)로 계산할 때는 속도를 우선한다.\n # 부정적 예에 타깃이 포함될 수 있다.\n negative_sample = np.random.choice(self.vocab_size,\n size=(batch_size, self.sample_size),\n replace=True, p=self.word_p)\n\n return negative_sample","sub_path":"DLfromScratch2/common/negative_sampling_layer.py","file_name":"negative_sampling_layer.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"491609598","text":"#csv load\r\nfrom functions import *\r\nfrom tables import *\r\n\r\ndef csv(sFilename,fun):\r\n filename=open(sFilename)\r\n\r\n src=filename\r\n s=t=None\r\n t = dict()\r\n while True:\r\n s=src.readline()\r\n # print(s)\r\n if s:\r\n\r\n # regex=\"([^,]+)\"\r\n # mo=re.search(regex,s)\r\n # print(\"current mo is printed here\",mo)\r\n\r\n # t=dict()\r\n temp = dict()\r\n for s1 in s.split(','):\r\n if not t:\r\n l = 0\r\n else:\r\n l = len(t)\r\n t[l]=coerce(s1)\r\n # index2 = len(temp) + 1\r\n if not temp:\r\n l = 0\r\n else:\r\n l = len(temp)\r\n temp[l] = coerce(s1)\r\n fun(temp)\r\n # print(t)\r\n\r\n else:\r\n break\r\n\r\n\r\n # print(t)\r\n return t\r\n\r\n\r\n\r\n#Data Class\r\nclass DATA:\r\n index=0\r\n def __init__(self,src):\r\n self.rows=dict()\r\n self.cols=None\r\n\r\n #for the function called fun\r\n def fun(x):\r\n self.add(x)\r\n\r\n\r\n if type(src) is str:\r\n csv(src, fun)\r\n\r\n else:\r\n d=dict()\r\n map_co(src or d,fun)\r\n\r\n def add(self,t):\r\n if self.cols:\r\n t = ROW(t) if type(t) == dict else t\r\n\r\n if not self.rows:\r\n l = 0\r\n else:\r\n l = len(self.rows)\r\n self.rows[l]=t\r\n # DATA.index=DATA.index + 1\r\n # if COLS.index==t.len_row():\r\n # COLS.index=0\r\n self.cols.add(t)\r\n else:\r\n self.cols=COLS(t)\r\n\r\n def clone(self, init_para=0):\r\n data=DATA({self.cols.names})\r\n d={}\r\n map_co(init_para or d,lambda x:data.add(x))\r\n return data\r\n\r\n def stats(self,what, cols, nPlaces):\r\n def fun(k,col):\r\n if what==\"div\":\r\n # print(\"I'm printing col.div() inside of stats function\")\r\n # print(col.div())\r\n val=col.rnd(col.div(), nPlaces)\r\n\r\n elif what==\"mid\":\r\n # print(\"I'm printing col.mid() inside of mid \")\r\n # print(col.mid())\r\n val=col.rnd(col.mid(), nPlaces)\r\n\r\n return val,col.txt\r\n\r\n\r\n\r\n return kap_co(cols or self.cols.y,fun)","sub_path":"src/HW2/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"149221690","text":"from characters.need import Need\n\n\nhunger = Need(\n \"hunger\",\n positive_threshold_messages={0: \"You are no longer starving.\",\n 50: \"You are no longer hungry.\",\n 100: \"You are full.\"},\n negative_threshold_messages={50: \"You are hungry\",\n 0: \"You are very hungry.\",\n -50: \"You are starving!\"},\n threshold_effects={}\n)\n\n\nthirst = Need(\n \"thirst\",\n positive_threshold_messages={0: \"You are still thirsty.\",\n 50: \"You are no longer thirsty.\",\n 100: \"You are full.\"},\n negative_threshold_messages={50: \"You are thirsty\",\n 0: \"You are very thirsty.\",\n -50: \"You are dying of thirst!\"},\n threshold_effects={}\n)","sub_path":"data/python_templates/needs.py","file_name":"needs.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"58744996","text":"#!/usr/bin/python\n\n\"\"\"\n- Author : Nag m\n- Hack : Move s3 objects to Glacier & add a Expiration \n- Info : Move s3 objects to Glacier & add a Expiration \n * 101-s3-aws\n\"\"\"\n\nimport boto\nfrom boto.s3.lifecycle import Lifecycle, Expiration, Rule\n\n\ndef glacier(name):\n bucket = conn.get_bucket(name)\n to_glacier = boto.s3.lifecycle.Transition(days=30, storage_class='GLACIER')\n rule = Rule('ruleid', 'logs/', 'Enabled', transition=to_glacier)\n lifecycle = Lifecycle()\n lifecycle.append(rule)\n lifecycle.add_rule(\"lc1\",\"/\", \"Enabled\",5)\n bucket.configure_lifecycle(lifecycle)\n\nif __name__ == \"__main__\":\n conn = boto.connect_s3()\n bucketname = \"101bucket\"\n glacier(bucketname)\n","sub_path":"101-AWS-S3-Hacks/glacier_lifecycle.py","file_name":"glacier_lifecycle.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"408942139","text":"# decomposer.py \n# ALS 2017/06/01\nimport os\nfrom shutil import copyfile\nfrom astropy.io import fits\nimport astropy.units as u\n\nfrom ..decomposer import Decomposer\nimport matchpsf\n\n\nclass plainDecomposer(Decomposer):\n\n\tdef __init__(self, **kwargs):\n\t\t\"\"\"\n\t\tchild of decomposer\n\n\t\tUse homemade code to do psf matching. Requires psf-{band}.fits files. \n\t\t\"\"\"\n\t\t\n\t\tsuper(plainDecomposer, self).__init__(**kwargs)\n\n\n\tdef get_fp_psf(self, fp_stamp):\n\t\t\"\"\" return the path of a psf file corresponding to that of the stamp \"\"\"\n\n\t\tdirpath = os.path.dirname(fp_stamp)\n\t\tfn_stamp = os.path.basename(fp_stamp)\n\n\t\tfn_psf = 'psf'+fn_stamp[5:]\n\t\tfp_psf = os.path.join(dirpath, fn_psf)\n\n\t\treturn fp_psf\n\n\n\tdef get_fp_psk(self, fp_stamp):\n\t\t\"\"\" return the path of a psf matching kernel file corresponding to that of the stamp \"\"\"\n\n\t\tdirpath = os.path.dirname(fp_stamp)\n\t\tfn_stamp = os.path.basename(fp_stamp)\n\n\t\tfn_psk = 'psk'+fn_stamp[5:]\n\t\tfp_psk = os.path.join(dirpath, fn_psk)\n\n\t\treturn fp_psk\n\n\n\tdef make_stamp_linemap_I(self, bandline, bandconti, line='OIII5008', overwrite=False):\n\t\t\"\"\" \n\t\tmake stamp of line map in rest frame intensity in units of [erg s-1 cm-2 arcsec-2]\n\t\tready for isophotal measurements. \n\n\t\tSee make_stamp_linemap for details. \n\t\t\"\"\"\n\n\t\t# setting\n\t\tfn_in = self.get_fp_stamp_line(line)\n\t\tfn_out = self.get_fp_stamp_line_I(line)\n\n\t\tif not os.path.isfile(fn_out) or overwrite:\n\t\t\tprint(\"[decomposer] making stamp_linemap_I\")\n\n\t\t\tself.make_stamp_linemap(bandline, bandconti, line=line, overwrite=True)\n\t\t\tself._convert_linemap_to_linemapI(fn_in, fn_out)\n\n\t\t\tself._copy_psf(fn_in, fn_out)\n\t\telse:\n\t\t\tprint(\"[decomposer] skip making stamp_linemap_I as files exist\")\n\n\t\treturn os.path.isfile(fn_out)\n\n\n\tdef make_stamp_linemap(self, bandline, bandconti, line='OIII5008', overwrite=False):\n\t\t\"\"\"\n\t\tmake stamp of line map in observed frame with flux in units of [erg s-1 cm-2]\n\n\t\tParams\n\t\t------\n\t\tself\n\t\tbandline (str)\n\t\tbandconti (str)\n\t\tline = 'OIII5008' (str)\n\t\toverwrite = False (bool)\n\t\tmapUnit = u.Unit('1e-17 erg s-1 cm-2') (unit)\n\n\t\tReturn\n\t\t------\n\t\tstatus (bool)\n\n\t\tWrite Output \n\t\t------------\n\t\te.g., stamp-OIII5008.fits\n\t\t\"\"\"\n\t\tfn_in = self.get_fp_stamp_contsub(band=bandline, bandconti=bandconti)\n\t\tfn_out = self.get_fp_stamp_line(line)\n\n\t\tif not os.path.isfile(fn_out) or overwrite:\n\t\t\tprint(\"[decomposer] making stamp_linemap\")\n\n\t\t\t# prep file\n\t\t\tself.make_stamp_contsub(band=bandline, bandconti=bandconti, overwrite=False)\n\t\t\tself._convert_contsub_to_linemap(fn_in, fn_out, bandline, line)\n\n\t\t\tself._copy_psf(fn_in, fn_out)\n\n\t\telse:\n\t\t\tprint(\"[decomposer] skip making stamp_linemap as files exist\")\n\n\t\treturn os.path.isfile(fn_out)\n\n\n\tdef make_stamp_contsub(self, band, bandconti, overwrite=False):\n\t\t\"\"\"\n\t\tmake stamp that is continuum subtracted\n\n\t\tParams\n\t\t------\n\t\tself\n\t\tband (str)\n\t\tbandconti (str)\n\t\toverwrite=False\n\n\t\tReturn\n\t\t------\n\t\tstatus\n\n\t\tWrite Output (e.g., if band = 'i', bandto = 'z')\n\t\t------------\n\t\tstamp-i_contsub-z.fits\n\t\t\"\"\"\n\t\tfn_out = self.get_fp_stamp_contsub(band, bandconti)\n\n\t\tif not os.path.isfile(fn_out) or overwrite:\n\t\t\tprint(\"[decomposer] making stamp_contsub\")\n\n\t\t\tratioconti = self._get_conti_fnu_ratio_from_spector(band, bandconti)\n\n\t\t\t# psf matching accorindg to which psf is larger\n\t\t\tif self._band_has_smaller_psf(band, bandconti):\n\t\t\t\tprint(\"[decomposer] matching psf of {}-band to conti {}-band\".format(band, bandconti))\n\n\t\t\t\tself.make_stamp_psfmatch(band=band, bandto=bandconti, overwrite=overwrite)\n\t\t\t\tfn_band = self.get_fp_stamp_psfmatched(band=band, bandto=bandconti)\n\t\t\t\tfn_cont = self.get_fp_stamp(bandconti)\n\n\t\t\telif self._band_has_smaller_psf(bandconti, band):\n\t\t\t\tprint(\"[decomposer] matching psf of conti {}-band to {}-band\".format(bandconti, band))\n\n\t\t\t\tself.make_stamp_psfmatch(band=bandconti, bandto=band, overwrite=overwrite)\n\t\t\t\tfn_band = self.get_fp_stamp(band)\n\t\t\t\tfn_cont = self.get_fp_stamp_psfmatched(band=bandconti, bandto=band)\n\n\t\t\telse: \n\t\t\t\tprint(\"[decomposer] skip matching psf as they are similar\")\n\t\t\t\tfn_band = self.get_fp_stamp(band)\n\t\t\t\tfn_cont = self.get_fp_stamp(bandconti)\n\n\t\t\t# write subtract continuum\n\t\t\tself._subtract_img_w_ratio(fn1=fn_band, fn2=fn_cont, fnout=fn_out, a1=1., a2=ratioconti, overwrite=overwrite)\n\n\t\t\t# copy psf\n\t\t\tfn_psf_in = self.get_fp_psf(fn_band)\n\t\t\tfn_psf_out = self.get_fp_psf(fn_out)\n\t\t\tcopyfile(fn_psf_in, fn_psf_out)\n\n\t\telse:\n\t\t\tprint(\"[decomposer] skip making stamp_contsub as files exist\")\n\n\t\treturn os.path.isfile(fn_out)\n\n\n\tdef make_stamp_psfmatch(self, band, bandto, overwrite=False, towrite_psk=False):\n\t\t\"\"\" \n\t\tmake file stamp-x_psfmatch-y.fits -- img stamp-x matched to the psf of y.\n\t\tFind best fit moffat convolving kernel which when convolved with psf-x becomes psf-y. \n\n\t\tParams\n\t\t------\n\t\tself\n\t\tband (str)\n\t\tbandto (str)\n\t\toverwrite=False (bool)\n\t\ttowrite_psk=False (bool)\n\t\t\twhether to write psf matching kernel to file\n\n\t\tReturn\n\t\t------\n\t\tstatus (bool)\n\n\t\tWrite Output (e.g., if band = 'i', bandto = 'z')\n\t\t------------\n\t\tstamp-i_psfmt-z.fits\n\t\tpsf-i_psfmt-z.fits\n\t\tpsk-i_psfmt-z.fits\n\t\t\"\"\"\n\n\t\t# define file names\n\t\tfp_img = self.get_fp_stamp(band) # input stamp\n\t\tfp_psf = self.get_fp_psf(fp_img) # input psf\n\t\tfp_psfto = self.get_fp_psf(self.get_fp_stamp(bandto)) # psf to match to\n\n\t\tfp_img_out = self.get_fp_stamp_psfmatched(band, bandto)\n\t\tfp_psf_out = self.get_fp_psf(fp_img_out)\n\t\tfp_psk_out = self.get_fp_psk(fp_img_out)\n\n\n\t\t# operation\n\t\tif not os.path.isfile(fp_img_out) or overwrite:\n\n\t\t\tmatchpsf.match_psf_fits(fp_img, fp_psf, fp_psfto, fp_img_out, fp_psf_out, fp_psk_out, overwrite=overwrite, towrite_psk=towrite_psk)\n\t\telse:\n\t\t\tprint(\"[decomposer] skip making stamp_psfmatch as files exist\")\n\n\t\tstatus = all([os.path.isfile(fn) for fn in [fp_img_out, fp_psf_out]])\n\t\treturn status\n\n\n\tdef _convert_linemap_to_linemapI(self, fn_in, fn_out, mapUnit=u.Unit('1e-15 erg s-1 cm-2 arcsec-2')):\n\t\t\"\"\"\n\t\ttake stamp_linemap in observed frame flux and convert it to stamp_linemap in rest frame intensity\n\t\twrite files. Takes self.z. \n\n\t\tuses F_obs/omega = I_obs --- *(1+z)^-4 ---> I_restframe\n\t\talways overwrites\n\n\t\tParams\n\t\t------\n\t\tfn_in (str): \n\t\t\tinput file path to linemap obs frame flux fits file\n\t\tfn_out (str):\n\t\t\toutput file path to linemap rest frame intensity fits file\n\t\tmapUnit=u.Unit('1e-15 erg s-1 cm-2 arcsec-2') (unit)\n\n\t\t\"\"\"\n\n\t\t# read in\n\t\thdus = fits.open(fn_in)\n\t\timg_in = hdus[0].data * u.Unit(hdus[0].header['BUNIT'])\n\n\t\t# calc ratio\n\t\tinvOmega = 1./(self.pixsize**2)\n\t\tzdimming = (1.+self.z)**4\n\n\t\t# scale to line flux\n\t\timg_out = invOmega*zdimming*img_in\n\t\timg_out = img_out.to(mapUnit)\n\n\t\t# prepare new hdu\n\t\thdus[0].data = img_out.value\n\t\tbunit = img_out.unit.to_string()\n\t\thdus[0].header.set(keyword='BUNIT', value=bunit, comment=\"in rest frame\")\n\t\thdus[0].header.set(keyword='COMMENT', value=\"Scaled to rest frame line intensity by ALS\")\n\t\thdus[0].header.set(keyword='COMMENT', value=\" assuming redshift {}\".format('%.3f'%self.z))\n\n\t\t# write to fits file\n\t\thdus.writeto(fn_out, overwrite=True)\n\n\n\tdef _convert_contsub_to_linemap(self, fn_in, fn_out, bandline, line, mapUnit=u.Unit('1e-17 erg s-1 cm-2')):\n\t\t\"\"\"\n\t\tscale contsub to linemap (flux in obs frame) of the specific line taking into account the fraction of flux in different lines. Assuming all (important) lines have similar spatial distribution. See spector.calc_fline_over_fnuband() for more details. \n\n\t\talways overwrites\n\n\t\tParams\n\t\t------\n\t\tfn_in (str): \n\t\t\tinput file path to stamp_contsub\n\t\tfn_out (str):\n\t\t\toutput file path to stamp_linemap \n\t\tbandline (str)\n\t\tline (str)\n\t\tmapUnit=u.Unit('1e-17 erg s-1 cm-2') (unit)\n\n\t\t\"\"\"\n\n\t\t# read in file\n\t\thdus = fits.open(fn_in)\n\t\timg_band = hdus[0].data * u.Unit(hdus[0].header['BUNIT'])\n\n\t\t# calc ratio\n\t\ts = self._get_spector()\n\t\tr_fline_over_fnuband = s.calc_fline_over_fnuband(band=bandline, line=line)\n\n\t\t# scale to line flux\n\t\timg_line = r_fline_over_fnuband\t* img_band\t\n\t\timg_line = img_line.to(mapUnit)\n\n\t\t# prepare new hdu\n\t\thdus[0].data = img_line.value\n\t\tbunit = img_line.unit.to_string()\n\t\thdus[0].header.set(keyword='BUNIT', value=bunit, comment=\"in observed frame\")\n\t\thdus[0].header.set(keyword='COMMENT', value=\"Scaled to {} line flux by ALS\".format(line))\n\t\thdus[0].header.set(keyword='COMMENT', value=\" with ratio {} applied to {} band\".format(str(r_fline_over_fnuband), bandline))\n\t\thdus[0].header.set(keyword='COMMENT', value=\" bunit converted from nanomaggy to {} in obs frame\".format(bunit))\n\n\t\t# write to fits file\n\t\thdus.writeto(fn_out, overwrite=True)\n\n\n\n\tdef _subtract_img_w_ratio(self, fn1, fn2, fnout, a1=1., a2=1., overwrite=False):\n \n\t\tif not os.path.isfile(fnout) or overwrite:\n\t\t\thdu1 = fits.open(fn1)\n\t\t\timg1 = hdu1[0].data\n\n\t\t\timg2 = fits.getdata(fn2)\n\n\t\t\timgout = a1*img1-a2*img2\n\n\t\t\thduout = hdu1\n\t\t\thduout[0].data = imgout\n\t\t\thduout[0].header['COMMENT'] = 'Image subtracted by ALS'\n\t\t\thduout[0].header['COMMENT'] = ' {}*{} minus {}*{}'.format('%.2f'%a1, fn1.split('/')[-1], '%.2f'%a2, fn2.split('/')[-1])\n\t\t\thduout.writeto(fnout, overwrite=overwrite)\n\n\n\tdef _band_has_smaller_psf(self, band, bandto, fracdiff_threshold=0.1):\n\t\t\"\"\"\n\t\twhether band has smaller psf than bandto by a margin of \"diffpsf_threshold\" in arcsec. \n\t\tget psf size from hsc_xid if the survey = 'hsc'. \n\n\t\tParams\n\t\t------\n\t\tband (str)\n\t\tbandto (str)\n\t\tfracdiff_threshold=0.1:\n\t\t\tthe threshold of psf difference in arcsec. If the diff is larger than return True. \n\n\t\tReturn\n\t\t------\n\t\tanswer (bool)\n\t\t\"\"\"\n\n\t\tfp_stp = self.get_fp_stamp(band=band)\n\t\tfp_stpto = self.get_fp_stamp(band=bandto)\n\n\t\treturn self._stamp_has_smaller_psf(fp_stp, fp_stpto, fracdiff_threshold=fracdiff_threshold)\n\n\n\tdef _stamp_has_smaller_psf(self, fp_stp, fp_stpto, fracdiff_threshold=0.1):\n\t\t\"\"\"\n\t\twhether fp_stp has smaller psf than fp_stpto by a margin of \"diffpsf_threshold\" in arcsec. \n\t\tget psf size from hsc_xid if the survey = 'hsc'. \n\n\t\tParams\n\t\t------\n\t\tfp_stp (str):\n\t\t\tfile path to stamp\n\t\tfp_stpto (str)\n\t\t\tfile path to stamp to compare to \n\t\tfracdiff_threshold=0.1:\n\t\t\tthe threshold of psf difference in arcsec. If the diff is larger than return True. \n\n\t\tReturn\n\t\t------\n\t\tanswer (bool)\n\t\t\"\"\"\n\n\t\tfp_psf = self.get_fp_psf(fp_stp)\n\t\tfp_psfto = self.get_fp_psf(fp_stpto)\n\n\t\tresult = matchpsf.has_smaller_psf_fits(fp_psf, fp_psfto, mode='quick', fracdiff_threshold=fracdiff_threshold)\n\n\t\treturn result\n\n\n\tdef _copy_psf(self, fn_in, fn_out):\n\t\t\"\"\" given stamp paths copy the psf from in to out \"\"\"\n\t\tfn_psf_in = self.get_fp_psf(fn_in)\n\t\tfn_psf_out = self.get_fp_psf(fn_out)\n\t\tcopyfile(fn_psf_in, fn_psf_out)\n\n","sub_path":"bubbleimg/imgdecompose/plain/plaindecomposer.py","file_name":"plaindecomposer.py","file_ext":"py","file_size_in_byte":10501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"487104273","text":"from logging import getLogger\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom api.status import HTTP_201_CREATED\nfrom api.api_views import APIView\nfrom api.exceptions import ExpectationFailed\nfrom api.utils.views import call_api_view\nfrom api.task.response import SuccessTaskResponse, FailureTaskResponse\nfrom api.dns.domain.utils import get_domain, get_domains\nfrom api.dns.domain.serializers import DomainSerializer, ExtendedDomainSerializer\nfrom api.dns.messages import LOG_DOMAIN_CREATE, LOG_DOMAIN_UPDATE, LOG_DOMAIN_DELETE\nfrom api.dc.utils import attach_dc_virt_object\nfrom api.dc.messages import LOG_DOMAIN_ATTACH\nfrom pdns.models import Record\nfrom vms.models import Dc, DefaultDc\n\nlogger = getLogger(__name__)\n\n\nclass DomainView(APIView):\n dc_bound = False\n order_by_default = order_by_fields = ('name',)\n order_by_field_map = {'created': 'id'}\n\n def __init__(self, request, name, data):\n super(DomainView, self).__init__(request)\n self.data = data\n self.name = name\n\n if self.extended:\n self.ser_class = ExtendedDomainSerializer\n else:\n self.ser_class = DomainSerializer\n\n if name:\n self.domain = get_domain(request, name, fetch_dc=self.extended, data=data, count_records=self.extended)\n else: # many\n self.domain = get_domains(request, prefetch_owner=self.full or self.extended, prefetch_dc=self.extended,\n count_records=self.extended, order_by=self.order_by)\n\n def get(self, many=False):\n if many or not self.name:\n if self.full or self.extended:\n if self.domain:\n res = self.ser_class(self.request, self.domain, many=True).data\n else:\n res = []\n else:\n res = list(self.domain.values_list('name', flat=True))\n else:\n res = self.ser_class(self.request, self.domain).data\n\n return SuccessTaskResponse(self.request, res, dc_bound=False)\n\n def post(self):\n request = self.request\n dc1_settings = DefaultDc().settings\n domain = self.domain\n domain.owner = request.user # just a default\n domain.type = dc1_settings.DNS_DOMAIN_TYPE_DEFAULT\n\n if not request.user.is_staff:\n self.data.pop('dc_bound', None) # default DC binding cannot be changed when creating object\n\n ser = DomainSerializer(request, domain, data=self.data)\n\n if not ser.is_valid():\n return FailureTaskResponse(request, ser.errors, obj=domain, dc_bound=False)\n\n ser.object.save()\n res = SuccessTaskResponse(request, ser.data, status=HTTP_201_CREATED, obj=domain, dc_bound=False,\n msg=LOG_DOMAIN_CREATE, detail_dict=ser.detail_dict())\n\n # Create SOA and NS records for new MASTER/NATIVE domain\n from api.dns.record.views import dns_record\n try:\n if dc1_settings.DNS_SOA_DEFAULT and dc1_settings.DNS_NAMESERVERS:\n soa_attrs = {'hostmaster': dc1_settings.DNS_HOSTMASTER.replace('@', '.'),\n 'nameserver': dc1_settings.DNS_NAMESERVERS[0]}\n soa_data = {'type': Record.SOA, 'name': domain.name,\n 'content': dc1_settings.DNS_SOA_DEFAULT.format(**soa_attrs)}\n call_api_view(request, 'POST', dns_record, domain.name, 0, data=soa_data, log_response=True)\n\n for ns in dc1_settings.DNS_NAMESERVERS:\n ns_data = {'type': Record.NS, 'name': domain.name, 'content': ns}\n call_api_view(request, 'POST', dns_record, domain.name, 0, data=ns_data, log_response=True)\n except Exception as e:\n logger.exception(e)\n\n if domain.dc_bound:\n assert request.dc.id == domain.dc_bound\n attach_dc_virt_object(res.data.get('task_id'), LOG_DOMAIN_ATTACH, domain, request.dc,\n user=request.user)\n\n return res\n\n def put(self):\n request = self.request\n domain = self.domain\n ser = DomainSerializer(request, domain, data=self.data, partial=True)\n\n if not ser.is_valid():\n return FailureTaskResponse(request, ser.errors, obj=domain, dc_bound=False)\n\n ser.object.save()\n res = SuccessTaskResponse(request, ser.data, obj=domain, msg=LOG_DOMAIN_UPDATE, detail_dict=ser.detail_dict(),\n dc_bound=False)\n\n if ser.name_changed:\n # Update SOA and NS records when MASTER/NATIVE Domain name changed\n from api.dns.record.views import dns_record\n try:\n data = {'name': domain.name}\n for record_id in domain.record_set.filter(name__iexact=ser.name_changed,\n type__in=[Record.NS, Record.SOA])\\\n .values_list('id', flat=True):\n call_api_view(request, 'PUT', dns_record, domain.name, record_id, data=data, log_response=True)\n except Exception as e:\n logger.exception(e)\n\n # Update VMS_VM_DOMAIN_DEFAULT if this domain was used as a default DC domain\n from api.dc.base.views import dc_settings\n try:\n for dc in Dc.objects.all():\n if dc.settings.VMS_VM_DOMAIN_DEFAULT == ser.name_changed:\n call_api_view(request, 'PUT', dc_settings, dc.name, data={'VMS_VM_DOMAIN_DEFAULT': domain.name},\n log_response=True)\n except Exception as e:\n logger.exception(e)\n\n return res\n\n def delete(self):\n domain = self.domain\n\n for dc in Dc.objects.all():\n if dc.settings.VMS_VM_DOMAIN_DEFAULT == domain.name:\n raise ExpectationFailed(_('Default VM domain cannot be deleted'))\n\n owner = domain.owner\n obj = domain.log_list\n domain.delete()\n\n return SuccessTaskResponse(self.request, None, obj=obj, owner=owner, msg=LOG_DOMAIN_DELETE, dc_bound=False)\n","sub_path":"api/dns/domain/api_views.py","file_name":"api_views.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"486304892","text":"import json\nimport logging\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\n\nfrom api.models.updates import Update, Confirmation, MessageNew\nfrom api.vk import VkApi\nfrom olya.logic import User\n\nlogging.basicConfig(**{\n 'format': '%(asctime)s %(levelname)s %(name)-15s %(message)s',\n 'datefmt': '%Y-%m-%d %H:%M:%S'\n})\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nvk_api: VkApi = settings.VK_API\n\n\ndef handle_update(user, message):\n if message.is_chat():\n pass\n else:\n vk_api.messages.send(peer_id=message.peer_id, message=message.text)\n\n\ndef callback(request):\n if request.method == 'POST':\n data = json.loads(request.body)\n logging.info(data)\n update = Update.from_dict(data)\n logger.info(update)\n if isinstance(update, Confirmation):\n return HttpResponse(settings.CONFIRMATION_CODE)\n\n if isinstance(update, MessageNew):\n user_id = update.message.from_id\n if user_id is not None:\n user = settings.USERS.find_one({'user_id': user_id})\n if user is None:\n user = User(user_id)\n else:\n user = User.from_dict(user)\n\n handle_update(user, update.message)\n\n settings.USERS.replace_one({'user_id': user_id}, user.to_dict(), upsert=True)\n\n return HttpResponse('ok')\n\n\ndef index(request):\n return HttpResponse('Not responding')\n","sub_path":"olya/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"196795139","text":"DATA_FOLDER = 'mnistdata/files/'\nMINST_DOWNLOAD_INFO = {\n 'BASE_URL': 'http://yann.lecun.com/exdb/mnist/',\n 'TRAIN_DATA': {\n 'NAME_IMAGE': 'train-images-idx3-ubyte.gz',\n 'NAME_LABELS': 'train-labels-idx1-ubyte.gz',\n 'SAMPLES': 60000\n },\n 'TEST_DATA': {\n 'NAME_IMAGE': 't10k-images-idx3-ubyte.gz',\n 'NAME_LABELS': 't10k-labels-idx1-ubyte.gz',\n 'SAMPLES': 10000\n }\n}\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"183037755","text":"def exer_01():\n\n with open(\"planolandia.txt\", \"r\", encoding=\"utf-8\") as arq:\n texto = arq.read()\n\n dic = {\"a\": 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0,\n 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0,\n 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0,\n 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0,\n 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0,\n 'z': 0}\n\n dic2 = {\"a\": 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0,\n 'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0,\n 'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0,\n 'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0,\n 'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0,\n 'z': 0}\n chrs = [[\"a\", \"á\", \"ã\", \"â\"], [\"b\"], [\"c\", \"ç\"], [\"d\"], [\"e\", \"é\", \"ê\", \"ẽ\"], [\"f\"],\n [\"g\"], [\"h\"], [\"i\", \"í\"], [\"j\"], [\"k\"], [\"l\"], [\"m\"], [\"n\"], [\"o\", \"ó\", \"õ\"],\n [\"p\"], [\"q\"], [\"r\"], [\"s\"], [\"t\"], [\"u\", \"ú\"], [\"v\"], [\"w\"], [\"x\"], [\"y\"], [\"z\"]]\n\n for chr in texto:\n for a in chrs:\n if chr.lower() in a:\n dic[a[0]] += 1\n break\n\n if chr.lower() in dic2.keys():\n dic2[chr.lower()] += 1\n\n for chr in dic.keys():\n if dic[chr]:\n print(chr, \"\\t\", dic[chr], \"\\t\", dic2[chr])\n\ndef exer_03():\n import collections as c\n\n with open(\"planolandia.txt\", \"r\") as arq:\n texto = arq.read()\n\n dic = {}\n\n for s in texto.split():\n if s not in dic.keys():\n dic[s.lower()] = 1\n else:\n dic[s.lower()] += 1\n\n l = sorted(dic.items())\n\n for (x, y) in l:\n print(x, y)\n\n\n\n\n\n\n\n\ndef ordena(lista):\n\n dic = {'a': 0, 'b': 1, 'c': 2, 'd': 4, 'e': 5, 'f': 6, 'g': 7,\n 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14,\n 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20,\n 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}\n\n var = lista[0]\n lista2 = []\n\n def ordenar(str1, str2):\n \"\"\"ordena duas strings\"\"\"\n if len(str1) > len(str2):\n str1, str2 = (str2, str1)\n\n for i in range(len(str1)):\n if dic[str1[i]] > dic[str2[i]]:\n return str2, str1\n return str1, str2\n\n for i in range(0, len(lista) - 1):\n for j in range(i + 1, len(lista)):\n lista[i], lista[j] = ordenar(lista[i], lista[j])\n break\n print(lista)\n\ndef exer_04():\n with open(\"planolandia.txt\", \"r\") as arq:\n texto = arq.read()\n palavras = texto.lower().split()\n\n maior = palavras[0]\n maiores = []\n for palavra in palavras:\n if len(palavra) > len(maior):\n maior = palavra\n maiores.clear()\n maiores.append(maior)\n if len(palavra) == len(maior) and not palavra == maior:\n maiores.append(palavra)\n\n\n for i in maiores:\n #if len(i) == len(maior):\n print(i, \"\\t\",len(i))\n\ndef exer_05():\n \"\"\"Escreva um programa que pergunta ao usuário uma frase em portugues\n e imprime a tradução da frase para a língua dos piratas.\"\"\"\n\n pirata = {\"portugues\" : \"pirata\", \"senhor\": \"matey\", \"hotel\" : \"fleabag inn\",\n \"estudante\" : \"swabbie\", \"garoto\" : \"matey\", \"senhora\" : \"proud beauty\",\n \"professor\" : \"foul blaggart\", \"restaurante\" : \"galley\", \"seu\" : \"yer\",\n \"com lisença\" : \"arr\", \"estudantes\" : \"swabbies\", \"sao\" : \"be\",\n \"advogado\" : \"foul blaggart\", \"o\" : \"th’\",\"a\": \"th’\", \"os\": \"th’\",\n \"as\": \"th’\",\"meu\": \"me\", \"minha\": \"me\", \"oi\": \"avast\",\n \"ola\": \"avast\", \"estao\": \"be\",\"homem\": \"matey\", \"e\" : \"be\"}\n\n texto = \"ele e o homem\"\n #texto = input(\"Entre com um texto:\")\n texto = texto.lower()\n traducao = \"\"\n for palavra in texto.split():\n if palavra in pirata.keys():\n traducao = traducao + pirata[palavra] + \" \"\n else:\n traducao = traducao + palavra + \" \"\n print(traducao)\n\nexer_05()\nseq = [1, 2, 3, 4, 5, 6,7]\nx= 2\nfor i in range(len(seq)):\n print(i)","sub_path":"projetos/PensePython/11. Dicionarios/dicionarios.py","file_name":"dicionarios.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"39383429","text":"def trans(s:str): \n s = s.strip() \n if len(s) == 0:\n return 0\n sign = -1 if s[0] == '-' else 1\n if s[0] in ['+','-']:\n s = s[1:len(s)] \n \n res = 0\n for i in s:\n if i.isdigit():\n res = res*10+(ord(i)-ord('0'))\n else:\n break\n res = max(-2**31,min(res*sign,2**31-1))\n return res\nprint(trans('++1'))\n\n \n","sub_path":"Week_06/字符串转换整数.py","file_name":"字符串转换整数.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"654214177","text":"from PyQt5 import QtWidgets, QtCore\nfrom PyQt5.QtWidgets import *\n\nimport layouts.knowledgeEditorLogicallEdit as design\nimport connectionToDatabase as db\n\n\nclass Logical(QtWidgets.QMainWindow, design.Ui_logicalEdit):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setupUi(self) # Это нужно для инициализации нашего дизайна\n self.FeatureName = \"\"\n self.FeatureType = \"Logical\"\n self.setWindowFlag(QtCore.Qt.WindowCloseButtonHint, False)\n\n self.button_goBack_logicalEdit.clicked.connect(self.goto_return)\n self.button_ok_logicalEdit.clicked.connect(self.save_and_return)\n\n def clearData(self):\n self.line_false_logicalEdit.clear()\n self.line_true_logicalEdit.clear()\n\n def set_featureName(self, text):\n self.FeatureName = text\n\n def save_and_return(self):\n textTrue = self.line_true_logicalEdit.text()\n textFalse = self.line_false_logicalEdit.text()\n textTrue = textTrue.strip()\n textFalse = textFalse.strip()\n if textTrue == \"\":\n QMessageBox.question(self, \"Error\", \"No true found\", QMessageBox.Cancel)\n return\n if textFalse == \"\":\n QMessageBox.question(self, \"Error\", \"No false found\", QMessageBox.Cancel)\n return\n if textFalse == textTrue:\n QMessageBox.question(self, \"Error\", \"True is the same as false\", QMessageBox.Cancel)\n return\n db.addLogicalFeatureDef(self.FeatureName, textTrue, textFalse)\n self.parent().show()\n self.close()\n\n def goto_return(self):\n QMessageBox.question(self, \"Error\", \" You have to input values. No way back\",\n QMessageBox.Cancel)\n","sub_path":"knowledgeEditor/Dialog/Logical.py","file_name":"Logical.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"597168211","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport logging\nimport json\nimport utils\nfrom utils import ArticleParser, CityData, ProvinceData\nimport urllib3\nimport re\nfrom html.parser import HTMLParser\n\nlogging.basicConfig(level=logging.INFO, stream=sys.stdout)\nlogger = logging.getLogger()\nlogger.setLevel(level=logging.INFO)\n\ncities = {\n \"东城区\": \"dongcheng\",\n \"西城区\": \"xicheng\",\n \"朝阳区\": \"chaoyang\",\n \"丰台区\": \"fengtai\",\n \"石景山区\": \"shijingshan\",\n \"海淀区\": \"haidian\",\n \"顺义区\": \"shunyi\",\n \"通州区\": \"tongzhou\",\n \"大兴区\": \"daxing\",\n \"房山区\": \"fangshan\",\n \"门头沟区\": \"mentougou\",\n \"昌平区\": \"changping\",\n \"平谷区\": \"pinggu\",\n \"密云区\": \"miyun\",\n \"怀柔区\": \"huairou\",\n \"延庆区\": \"yanqing\",\n \"外地来京人员\": \"waidi\"\n}\n\nroot_url = \"http://wjw.beijing.gov.cn/xwzx_20031/xwfb/\"\nprovinceKey = \"beijing\"\nprovinceName = \"北京\"\napi_prefix = \"/api/v1/provinces/\" + provinceKey\n\n\ndef parse_list_html(raw):\n pattern = re.compile(\n r\"(?s)
    (.*?)<\\/div>\")\n pattern_title = re.compile(r\".*\\d+月\\d+日.*肺炎.*\")\n\n p = ArticleParser()\n for m in pattern.finditer(raw):\n p.feed(m.groups()[0])\n p.close()\n\n latest_url = \"\"\n for res in p.get_articles():\n if pattern_title.match(res[\"title\"]) is not None:\n latest_url = root_url + res[\"href\"][2:]\n break\n return latest_url\n\n\ndef parse_content_html(raw):\n pattern = re.compile(r\"(?s)(.*)\")\n m = pattern.search(raw)\n content = m.groups()[0]\n\n province = ProvinceData(provinceName, provinceKey)\n pattern_confirm = re.compile(r\"累计确诊.*?(\\d+)例\")\n cm = pattern_confirm.search(content)\n if cm is not None:\n province.Confirmed = int(cm.groups()[0])\n pattern_heal = re.compile(r\"出院(\\d+)例\")\n hm = pattern_heal.search(content)\n if hm is not None:\n province.Healed = int(hm.groups()[0])\n pattern_dead = re.compile(r\"死亡(\\d+)例\")\n dm = pattern_dead.search(content)\n if dm is not None:\n province.Dead = int(dm.groups()[0])\n\n city = {}\n pattern_data = re.compile(r\"[。,、]([\\u4E00-\\u9FA5]+)(\\d+)例\")\n for i in pattern_data.finditer(content[content.rfind(\"累计确诊\"):]):\n name = utils.remove_preposition(i.groups()[0])\n if name in cities.keys():\n id = cities[name]\n if id not in city.keys():\n d = CityData(name, id)\n d.Confirmed = int(i.groups()[1])\n city[id] = d\n return province, city\n\n\ndef main_handler(event, content):\n if \"requestContext\" not in event.keys():\n return utils.gen_response({\"errorCode\": 4001, \"errorMsg\": \"event is not come from api gateway\"})\n if event[\"requestContext\"][\"path\"] != api_prefix + \"/cities/{cityName}\" and event[\"requestContext\"][\"path\"] != api_prefix:\n return utils.gen_response({\"errorCode\": 4002, \"errorMsg\": \"request is not from setting api path\"})\n\n http = urllib3.PoolManager()\n list_page = http.request(\"get\", root_url)\n latest_url = parse_list_html(list_page.data.decode())\n if len(latest_url) == 0:\n return utils.gen_response({\"errorCode\": 5001, \"errorMsg\": \"failed to crawl data\"})\n\n content_page = http.request(\"get\", latest_url)\n p, city_data = parse_content_html(content_page.data.decode())\n\n if event[\"requestContext\"][\"path\"] == api_prefix + \"/cities/{cityName}\":\n city = event[\"pathParameters\"][\"cityName\"]\n if city not in city_data.keys():\n return utils.gen_response({\"errorCode\": 4003, \"errorMsg\": \"not found\"})\n return utils.gen_response(utils.serialize(city_data[city]))\n\n p.Cities = list(city_data.values())\n return utils.gen_response(utils.serialize(p))\n","sub_path":"backend/beijing.py","file_name":"beijing.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"60392556","text":"import numpy as np\nimport json, os, sys\nimport tensorflow as tf\nimport gensim\n\nfrom bs4 import BeautifulSoup\nimport sklearn\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\n\nfrom sum_code.ml import constants as ml_constants\nfrom unidecode import unidecode\n\nimport cProfile\n\n\ndef profileit(func):\n def wrapper(*args, **kwargs):\n prof = cProfile.Profile()\n retval = prof.runcall(func, *args, **kwargs)\n prof.print_stats()\n return retval\n\n return wrapper\n\ndef length(sequence):\n used = tf.sign(tf.reduce_max(tf.abs(sequence),\n reduction_indices=2))\n length = tf.reduce_sum(used, reduction_indices=1)\n length = tf.cast(length, tf.int32)\n return length\n\n\ndef data_type_float():\n # depending on compatibility issues (i.e gpu support for\n # floating point ops. change here for consistency in entire project\n return tf.float32\n\n\ndef data_type_int():\n return tf.int32\n\n\ndef text_to_int(unicode_string):\n ascii = unidecode(unicode_string)\n return list(map(lambda s, char2index=ml_constants.Char2Index:\n char2index.get(s, char2index['']), ascii))\n\n\ndef pad_list(list_to_pad, padding, padding_end, num_padding):\n if padding_end not in ['left', 'right']:\n raise ValueError('padding must be left or right!, '\n 'received {}'.format(padding_end))\n if padding_end == 'right':\n return list_to_pad + [padding for _ in range(num_padding)]\n else:\n return [padding for _ in range(num_padding)] + list_to_pad\n\n\ndef pad_variable_length_nested_list(nested_list,\n padding,\n padding_end):\n max_nested_list = reduce(lambda a, b: max(a, b),\n map(lambda l: len(l), nested_list)\n )\n new_list = []\n for inner_list in nested_list:\n num_padding = max_nested_list - len(inner_list)\n new_list.append(pad_list(inner_list,\n padding,\n padding_end,\n num_padding)\n )\n return new_list\n\n\ndef padded_int_source_summary(source, summary, total_length=None):\n padding = ml_constants.Char2Index['']\n eof = ml_constants.Char2Index['']\n go = ml_constants.Char2Index['']\n\n len_source = len(source) +1\n len_summary = len(summary) +1\n\n int_source = text_to_int(source) + [eof]\n int_summary = [go] + text_to_int(summary)\n padded_source = pad_list(int_source,\n padding,\n 'left',\n total_length - len_source)\n\n padded_summary = pad_list(int_summary,\n padding,\n 'left',\n len_source)\n\n padded_summary = pad_list(padded_summary,\n padding,\n 'right',\n total_length - len_source - len_summary)\n if total_length is not None:\n assert len(padded_summary) == total_length\n assert len(padded_source) == total_length\n\n return padded_source, padded_summary\n\n\ndef one_hot_indices(char_indices, num_symbols):\n one_hots = np.zeros([len(char_indices), num_symbols], dtype=np.float32)\n for i, val in enumerate(char_indices):\n one_hots[i][val] = 1.0\n\n return one_hots\n\n\ndef decode(one_hots):\n chars = []\n for one_hot in one_hots:\n char_index = np.argmax(one_hot)\n chars.append(ml_constants.Index2Char[char_index])\n\n return ''.join(chars)\n\n\ndef one_hot_source_summary_batch(source_text_list,\n summary_text_list,\n input_length,\n num_chars):\n one_hot_sources = []\n one_hot_summaries = []\n sample_weights = []\n\n if isinstance(source_text_list, str):\n source_text_list = [source_text_list]\n\n if isinstance(summary_text_list, str):\n summary_text_list = [summary_text_list]\n\n for source, summary in zip(source_text_list, summary_text_list):\n padded_int_source, padded_int_summary = \\\n padded_int_source_summary(source, summary, input_length)\n\n one_hot_source = one_hot_indices(padded_int_source, num_chars)\n one_hot_summary = one_hot_indices(padded_int_summary, num_chars)\n\n one_hot_sources.append(one_hot_source)\n one_hot_summaries.append(one_hot_summary)\n import pdb; pdb.set_trace()\n sample_weight_mask = [0 if x <= len(source)\n or x > (len(source) + len(summary) + 1) else 1\n for x in xrange(input_length)]\n import pdb; pdb.set_trace()\n sample_weights.append(sample_weight_mask)\n\n source_X = np.array(one_hot_sources, dtype=np.float32)\n source_y = np.array(one_hot_summaries, dtype=np.float32)\n sample_weights = np.array(sample_weights, dtype=np.float32)\n\n return source_X, source_y, sample_weights\n\n\ndef padded_w2vec(source, summary, total_length):\n w2v = W2V()\n\n padding = w2v.pad\n\n len_source = len(source)\n len_summary = len(summary)\n\n padded_source = pad_list(source,\n padding,\n 'right',\n total_length - len_source)\n\n # padded_summary = pad_list(summary,\n # padding,\n # 'left',\n # len_source)\n\n padded_summary = pad_list(summary,\n padding,\n 'right',\n total_length - len_summary)\n\n assert len(padded_summary) == total_length\n assert len(padded_source) == total_length\n\n return padded_source, padded_summary\n\n\ndef create_word_vec_batch_array_with_mask(source_list, summary_list, input_length):\n w2v = W2V()\n source_vectors = []\n summary_vectors = []\n source_lens = []\n summary_lens = []\n\n mask_list = []\n\n max_source_len = 0\n max_summary_len = 0\n if not isinstance(source_list, list):\n source_list = [source_list]\n summary_list = [summary_list]\n\n for source_text, summary_text in zip(source_list, summary_list):\n source_vec = [w2v.go] + w2v.vectorize_text(source_text) + [w2v.eof]\n summary_vec = [w2v.go] + w2v.vectorize_text(summary_text) + [w2v.eof]\n source_lens.append(len(source_vec))\n summary_lens.append(len(summary_vec))\n max_source_len = max(max_source_len, len(source_vec))\n max_summary_len = max(max_summary_len, len(summary_vec))\n source_vectors.append(source_vec)\n summary_vectors.append(summary_vec)\n\n padded_source_vectors = []\n padded_summary_vectors = []\n max_len = input_length #max_source_len + max_summary_len\n for source_vec, summary_vec, source_len, summary_len\\\n in zip(source_vectors, summary_vectors, source_lens, summary_lens):\n padded_source, padded_summary = \\\n padded_w2vec(source_vec, summary_vec, max_len)\n\n padded_source_vectors.append(padded_source)\n padded_summary_vectors.append(padded_summary)\n summary_vectors.append(summary_vec)\n sample_mask = [0 if x > summary_len else 1\n for x in xrange(max_len)]\n mask_list.append(sample_mask)\n\n source_array = np.array(padded_source_vectors, dtype=np.float32)\n summary_array = np.array(padded_summary_vectors, dtype=np.float32)\n mask_list = np.array(mask_list, dtype=np.float32)\n\n return source_array, summary_array, mask_list\n\n\ndef log_data(data, file):\n with open(file, 'a') as f:\n f.write('\\n')\n f.write(data)\n sys.stdout.flush()\n\n\nclass SubBatch(object):\n def __init__(self, source_list, summary_list, sub_size):\n self.source_list = source_list\n self.summary_list = summary_list\n self.sub_size = sub_size\n self.ret_count = 0\n\n def __iter__(self):\n return self\n\n def next(self):\n start = self.ret_count * self.sub_size\n end = (self.ret_count + 1) * self.sub_size\n sub_source = np.array(self.source_list[start: end])\n sub_summary = np.array(self.summary_list[start: end])\n self.ret_count +=1\n assert len(sub_source) == len(sub_summary)\n if not len(sub_source):\n raise StopIteration\n return sub_source, sub_summary\n\n\nclass W2V(object):\n \"\"\"\n here we load the pretrained word vectorizer created by google.\n It is loaded as a singleton as it occupies over 8GiB in memory.\n This means that 64bit python is required\n \"\"\"\n instance = None\n\n class __W2V(object):\n acceptable_chars = 'abcdefghijklmnopqrstuvwxyz0123456789\\' '\n _digits = '0123456789'\n\n def __init__(self, data_directory=None):\n\n if data_directory is None:\n data_directory = '/media/xgenadam/SSD_DATA/data' \\\n '/nlp/GoogleNews-vectors-negative300.bin'\n\n self.w2v = gensim.models.KeyedVectors\\\n .load_word2vec_format(data_directory, binary=True)\n\n self.unk = self.w2v.word_vec('UNKNOWN')\n self.eof = self.w2v.word_vec('EOF')\n self.go = self.w2v.word_vec('GO')\n self.pad = self.w2v.word_vec('PAD')\n\n def _clean_text(self, text):\n # text = text.lower()\n text.replace('\\n', ' ')\n\n text = ''.join(\n filter(\n (lambda char, acceptable_chars=self.acceptable_chars:\n char.lower() in acceptable_chars), text\n )\n )\n\n for num in self._digits:\n text = text.replace(num, ' {} '.format(num))\n\n return text\n\n def vectorize_text(self, text):\n # text = text.lower()\n text.replace('\\n', ' ')\n\n text = self._clean_text(text)\n\n vectors = []\n for word in text.split():\n try:\n vectors.append(self.w2v.word_vec(word))\n except KeyError:\n try:\n vectors.append(self.w2v.word_vec(word.lower()))\n except:\n pass\n\n return vectors\n\n def decode_vector_array(self, array):\n words = []\n array_ = array\n if hasattr(array, 'shape') and len(array.shape) ==3:\n array_ = array[0]\n for vector in array_:\n # this actually returns a list of 10 most likely words\n # most likely first\n word = self.w2v.similar_by_vector(vector)[0][0]\n words.append(word)\n\n return ' '.join(words)\n\n def __init__(self, file_location=None):\n if W2V.instance is None:\n print('initializing word2vec')\n W2V.instance = W2V.__W2V(file_location)\n\n def __getattr__(self, name):\n return getattr(self.instance, name)\n\n\nclass CNNStoryBatchReader(object):\n def __init__(self,\n batch_size,\n story_data_directory,\n html_data_directory,\n max_data_length,\n num_eval=None,\n num_test=None,\n max_batches=None,\n summary_start_tag='@highlight',\n resume_file=None):\n self.num_test = num_test\n self.num_eval = num_eval\n self.batch_size = batch_size\n self.story_data_directory = story_data_directory\n self.html_data_directory = html_data_directory\n self.max_data_length = max_data_length\n self.resume_file = resume_file\n self.summary_start_tag = summary_start_tag\n self.max_batches = max_batches\n self._batch_count = 0\n\n self.files = shuffle(list(os.walk(self.story_data_directory))[0][-1],\n random_state=16)\n\n if num_test is None:\n self.num_test = int(len(self.files)/10)\n\n if num_eval is None:\n self.num_eval = int((len(self.files)\n - self.num_test)/20)\n\n self.files.sort()\n self._file_iter = iter(self.files)\n\n self.test = self.get_hidden_batch(num_test)\n self.eval = self.get_hidden_batch(num_eval)\n\n self.approx_num_train = len(self.files) - self.num_test - self.num_eval\n self._approx_num_batches = self.approx_num_train // self.batch_size\n\n def get_hidden_batch(self, batch_size):\n cnt = 0\n\n summaries = []\n titles = []\n masks = []\n\n while cnt < batch_size:\n file_name = next(self._file_iter)\n source, summary = self.get_text_from_file(file_name)\n title = self.get_title(file_name)\n if source is None or source == summary:\n continue\n cnt += 1\n\n s,t,m = create_word_vec_batch_array_with_mask(\n summary,\n title,\n self.max_data_length\n )\n summaries.append(s[0])\n titles.append(t[0])\n masks.append(m[0])\n\n summaries = np.array(summaries, dtype=np.float32)\n titles = np.array(titles, dtype=np.float32)\n masks = np.array(masks, dtype=np.float32)\n\n return summaries, titles, masks\n\n\n @property\n def approx_num_batches(self):\n if self.max_batches is not None:\n return min(self._approx_num_batches, self.max_batches)\n else:\n return self._approx_num_batches\n\n def format_story_file_data(self, text):\n text = ''.join([i if ord(i) < 128 else ' ' for i in text])\n summary_start = text.find(self.summary_start_tag)\n source = text[:summary_start]\n summary = (text[summary_start:]\n .replace('@highlight', '')\n .replace('\\n\\n\\n', '\\n')\n .replace('\\n\\n', '\\n').lstrip())\n\n return source, summary, len(source), len(summary)\n\n def get_text_from_file(self, file_name):\n with open(os.path.join(self.story_data_directory, file_name)) as f:\n text = f.read()\n source, summary, source_len, summary_len = self.format_story_file_data(text)\n if len(summary.split()) + len(self.get_title(file_name).split()) > self.max_data_length:\n # or source_len < self.min_source_length \\\n # or summary_len < self.min_summary_length:\n # import pdb; pdb.set_trace()\n return None, None\n elif source == summary:\n # import pdb; pdb.set_trace()\n return None, None\n return source, summary\n\n def get_title(self, story_file):\n html_file_name = story_file.replace('.story', '.html')\n with open(os.path.join(self.html_data_directory, html_file_name)) as f:\n html = f.read()\n soup = BeautifulSoup(html)\n return soup.title.text\n\n def next(self):\n source_batch = []\n summary_batch = []\n title_batch = []\n c = 0\n self._batch_count += 1\n if self.max_batches is not None and\\\n self._batch_count > self.max_batches:\n raise StopIteration\n while True:\n if c >= self.batch_size:\n break\n file_name = next(self._file_iter)\n source, summary = self.get_text_from_file(file_name)\n title = self.get_title(file_name)\n title_batch.append(title)\n if source is None:\n # print('skipping file {}'.format(file_name))\n continue\n c += 1\n source_batch.append(source)\n summary_batch.append(summary)\n\n if len(source_batch) < self.batch_size \\\n or len(summary_batch) < self.batch_size:\n raise StopIteration\n else:\n\n return source_batch, summary_batch, title_batch\n\n def __iter__(self):\n return self\n\n\nclass JSONDictionaryReader(object):\n\n def __init__(self,\n dict_file=None,):\n if dict_file is None:\n dict_file = ('/media/xgenadam/SSD_DATA/data/nlp/summarizations'\n '/dictionary/dictionary.json')\n with open(dict_file) as f:\n self._data = json.loads(f.read())\n\n data = [(desc.lower(), word.lower()) for word, desc in self._data.items()\n if not word.startswith('-') and 'see ' not in desc.lower()]\n max_length = max([len(desc) + len(word) for desc, word in data])\n\n self.max_length = max_length\n\n # need to call sort as dictionaries have no guaranteed order and json.load has no guaranteed\n data.sort()\n self.descriptions = [desc for desc, word in data]\n self.words = [word for desc, word in data]\n\n self.X, self.y, self.input_lengths = one_hot_source_summary_batch(\n self.descriptions,\n self.words,\n self.max_length,\n ml_constants.VECTOR_INPUT\n )\n\n\n\n","sub_path":"sum_code/ml/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":17228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"171683749","text":"class Solution:\n def numPairsDivisibleBy60(self, time: List[int]) -> int:\n res = 0\n for i in range(len(time)):\n for j in range(i+1, len(time)):\n if (time[i] + time[j]) % 60 == 0:\n res += 1\n \n return res\n \n # TC: O(n^2)\n \n # SC: O(1)\n \n # TLE\n","sub_path":"1010_PairsOfSongsWithTotalDurationsDivisibleBy60/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"244557963","text":"import bioinfo_dicts\n\ndef one_to_three(seq):\n seq=seq.upper()\n\n #Build conversion\n aa_list = []\n for amino_acid in seq:\n if amino_acid in bioinfo_dicts.aa.keys():\n aa_list += [bioinfo_dicts.aa[amino_acid],'-']\n else:\n raise RuntimeError(amino_acid + ' is no a valid amino acid.')\n return ''.join(aa_list[:-1])\n\ntry:\n import gc_content\n have_gc = True\nexcept ImportError as e:\n have_gc = False\n","sub_path":"error_lesson.py","file_name":"error_lesson.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"584927376","text":"\"\"\"Functions for evaluating quizzes in Swift using pass/fail functions.\"\"\"\n\nimport os\nimport falcon.enum as enum\nimport falcon.util as util\nimport falcon.files as files\n\ndef setup_local_test():\n \"\"\"Configure environment (namely the root directory) for local execution.\"\"\"\n util.move_sandbox_files_to_root('swift', ['SwizzleInclude.swift', 'SwizzleBefore.swift', 'StudentMain.swift', 'SwizzleAfter.swift'])\n\ndef setup_remote():\n \"\"\"Configure environment (namely the root directory) for remote execution.\"\"\"\n util.move_sandbox_files_to_root('swift', ['SwizzleInclude.swift'])\n\ndef tear_down_local_test():\n \"\"\"Tear down environment (namely the root directory) after local execution.\"\"\"\n util.remove_files_from_root(['SwizzleInclude.swift', 'SwizzleBefore.swift', 'StudentMain.swift', 'SwizzleAfter.swift', 'SwizzledMain.swift'])\n\ndef test(run_local, bash_config):\n \"\"\"Test (run) student's code without evaluating it for correctness.\n\n This function should store the output of the student's code in\n files.STUDENT_OUT. It is recommended that you use util.run_program()\n to pipe the results of executing the student's code into\n files.STUDENT_OUT (stdout) and files.STUDENT_ERR (stderr).\n\n Args:\n run_local (bool): flag indicating if test is being run locally\n bash_config (string): bash commands for configuing environment\n\n Raises:\n Any errors stemming from the exection of the program(s) required to\n run the student's code.\n \"\"\"\n try:\n util.run_program(['swift', 'StudentMain.swift'], files.STUDENT_OUT, files.STUDENT_ERR)\n except:\n raise\n\ndef submit(run_local, bash_config):\n \"\"\"Evaluate the student's code by testing it for correctness.\n\n This function should store the output of evaluating the student's code\n in files.RESULTS_OUT. It is recommended that you use util.run_program()\n to pipe the results of evaluating the student's code into\n files.RESULTS_OUT (stdout) and files.RESULTS_ERR (stderr).\n\n Args:\n run_local (bool): flag indicating if test is being run locally\n bash_config (string): bash commands for configuing environment\n\n Raises:\n Any errors stemming from the exection of the program(s) required to\n evalute the student's code.\n \"\"\"\n try:\n # generate swizzled main\n filenames = ['SwizzleInclude.swift', 'SwizzleBefore.swift', 'StudentMain.swift', 'SwizzleAfter.swift']\n errors = []\n with open('SwizzledMain.swift', 'w') as outfile:\n for fname in filenames:\n try:\n with open(fname) as infile:\n outfile.write(infile.read())\n except IOError:\n errors.append('file ' + fname + ' not found')\n else:\n outfile.write('\\n')\n if len(errors) > 0:\n # pipe errors to file\n util.run_program(['echo', str(errors)], files.RESULTS_ERR, files.RESULTS_ERR)\n else:\n # run swizzled main\n util.run_program(['swift', '-suppress-warnings', 'SwizzledMain.swift'], files.RESULTS_OUT, files.RESULTS_ERR)\n # run student main (for extra debugging)\n util.run_program(['swift', 'StudentMain.swift'], files.STUDENT_OUT, files.STUDENT_ERR)\n except:\n raise\n\ndef submit_files():\n \"\"\"Specifies a list of file paths to include in results when student submits quiz.\"\"\"\n return ['StudentMain.swift']\n\ndef transform(test_output):\n \"\"\"Transforms contents of 'files.RESULTS_OUT' into a classroom-friendly format.\n\n Currently, the classroom understands the following tags:\n - \n - \n - \n\n All lines prepended with these tags will be auto-formatted:\n - \n represents something the student did correctly and is displayed\n in the \"What Went Well\" section\n - \n represents something the student did incorrectly and is displayed\n in the \"What Went Wrong\" section\n - \n additional feedback to either guide or congradulate the student\n that appears in the \"Feedback\" section\n\n Note: If the contents of 'files.RESULTS_OUT' already use tags, then\n you can simply return the eval_output unmodified.\n\n Args:\n eval_output (string): Contents of 'files.RESULTS_OUT'\n\n Returns:\n A string with classroom-friendly tags that represents the results of\n evaluating the student's code for a programming quiz.\n \"\"\"\n return test_output\n","sub_path":"udfalcon/stack/swift.py","file_name":"swift.py","file_ext":"py","file_size_in_byte":4600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"80212271","text":"#Data Transformation :\n\n# Prepare the Data For Machine Learning\n#***************************************\n\n# 4 Ways to Prepare the Data For Machine Learning\n#-------------------------------------------------\n#1. Rescale data. (custom range)\n#2. Standardize data.\n#3. Normalize data. ( 0 to 1)\n#4. Binarize data.\n\n#Steps of Data Transforms\n#------------------------\n#Step-1: Load the dataset from a URL.\n\n#Step-2: Split the dataset into the input and\n# output variables for machine learning.\n\n#Step-3: Apply a pre-processing transformation\n# technique to transform the input variables.\n\n#Step-4: Summarize the data to show the change.\n\n\n#1.Rescale data. (custom range)\nimport pandas as pd\nfrom numpy import set_printoptions\nfrom sklearn.preprocessing import MinMaxScaler\n\nfilename = 'indians-diabetes.data.csv'\nhnames = ['preg', 'plas', 'pres', 'skin', 'test',\n 'mass', 'pedi', 'age', 'class']\ndataframe = pd.read_csv(filename, names=hnames)\n\narray = dataframe.values\n# separate array into input and output components\nX = array[ : , 0:8] # [ row , cols ]\nY = array[ : , 8]\nscaler = MinMaxScaler( feature_range=(1,10) ) #Range\n\n#First Method\nrescaledX = scaler.fit_transform(X)\n\n\n# summarize transformed data\nset_printoptions(precision=2)\n\nprint( rescaledX [ 0:30 , : ] ) # [ row , cols ]\n","sub_path":"mlpackage/MLPractical40.py","file_name":"MLPractical40.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"262885585","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\n\ntry:\n from external import six\nexcept ImportError:\n from .external import six\n\nPY2 = six.PY2\n\n\ndef mkdir_safe(p, safeguard):\n if not os.path.exists(p) and p.startswith(safeguard):\n os.makedirs(p)\n\n\nplugin_name = 'Robot Framework Assistant'\n__version__ = VERSION = plugin_version = '1.2.2'\nplugin_home = 'https://github.com/andriyko/sublime-robot-framework-assistant'\npy_version = '2' if PY2 else '3'\nuser_agent = '{0}/{1}/{2}'.format(plugin_name, plugin_version, py_version)\n\nsyntax_file = 'robot.tmLanguage'\nsettings_filename = '{0}.sublime-settings'.format(plugin_name)\nno_manifest_file = lambda x: 'Failed to open manifest file. ' \\\n 'Please download manifest first. No such file: {0}'.format(x)\nno_libs_dir = lambda x: 'Failed to open libraries directory. ' \\\n 'Please download packages first. No such file or directory: {0}'.format(x)\nno_python_path = lambda x: 'Could not add path to system.path. ' \\\n 'No such file or directory: {0}'.format(x)\n\nno_python_interpreter = lambda x: \\\n 'Could not use Python interpreter. No such file or directory: {0}. ' \\\n 'Please specify Python interpreter with Robot Framework installed.'.format(x)\n\npackage_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\n\nrobot_data_dir_path = os.path.join(package_dir, 'robot_data')\nmkdir_safe(robot_data_dir_path, package_dir)\n\ncurrent_tmp_dir_path = os.path.join(robot_data_dir_path, 'current')\nmkdir_safe(current_tmp_dir_path, robot_data_dir_path)\n\ndynamic_data_file_path = os.path.join(current_tmp_dir_path, 'current_data.json')\n\nrfdocs_update_url = \"http://rfdocs.org/api/v1/\"\n\nrfdocs_base_dir_path = os.path.join(robot_data_dir_path, 'rfdocs')\nmkdir_safe(rfdocs_base_dir_path, package_dir)\n\nrfdocs_manifest_path = os.path.join(rfdocs_base_dir_path, 'manifest.json')\n\nrfdocs_dir_path = os.path.join(rfdocs_base_dir_path, 'libraries')\nmkdir_safe(rfdocs_dir_path, package_dir)\n\nrfdocs_tmp_dir_path = os.path.join(rfdocs_base_dir_path, 'tmp')\nmkdir_safe(rfdocs_tmp_dir_path, package_dir)\n\nscanner_config_path = os.path.join(package_dir, 'scanners.example.json')\n\nuser_scanners_dir_path = os.path.join(package_dir, 'user_scanners')\n\npython_libs_dir_path = os.path.join(robot_data_dir_path, 'libraries')\nmkdir_safe(python_libs_dir_path, package_dir)\n\nresources_dir_path = os.path.join(robot_data_dir_path, 'resources')\nmkdir_safe(resources_dir_path, package_dir)\n\nvariables_dir_path = os.path.join(robot_data_dir_path, 'variables')\nmkdir_safe(variables_dir_path, package_dir)\n\nrflint_setting_filename = '{0} Rflint.sublime-settings'.format(plugin_name)\n\nif PY2:\n robot_tm_language_path = os.path.join(package_dir, syntax_file)\nelse:\n robot_tm_language_path = \"Packages/{0}/{1}\".format(plugin_name, syntax_file)\n","sub_path":"rfassistant/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"336169027","text":"import sys\nimport numpy as np\n\nn, a, *x = map(int, sys.stdin.read().split())\n\ndef main():\n dp = np.zeros((n + 1, 2501), dtype=np.int64)\n dp[0, 0] = 1\n for i in range(n):\n dp[1:, x[i]:] += dp[:-1, :-x[i]].copy()\n i = np.arange(1, n + 1)\n print(dp[i, i * a].sum())\n\nif __name__ == '__main__':\n main()","sub_path":"Python_codes/p04013/s299444668.py","file_name":"s299444668.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"24155025","text":"import torch\nfrom torch.cuda.amp import autocast\n\nfrom horch.train.learner import Learner, convert_tensor, backward, optimizer_step\n\nfrom hinas.models.darts.search.darts import Network\n\ndef requires_grad(network: Network, arch: bool, model: bool):\n for p in network.arch_parameters():\n p.requires_grad_(arch)\n for p in network.model_parameters():\n p.requires_grad_(model)\n\n\nclass DARTSLearner(Learner):\n\n def __init__(self, model: Network, criterion, optimizer_arch, optimizer_model, lr_scheduler,\n grad_clip_norm=5, search_loader=None, **kwargs):\n self.train_arch = True\n self.search_loader = search_loader\n self.search_loader_iter = None\n super().__init__(model, criterion, (optimizer_arch, optimizer_model),\n lr_scheduler, grad_clip_norm=grad_clip_norm, **kwargs)\n\n def get_search_batch(self):\n if self.search_loader_iter is None:\n self.search_loader_iter = iter(self.search_loader)\n try:\n return next(self.search_loader_iter)\n except StopIteration:\n self.search_loader_iter = iter(self.search_loader)\n return self.get_search_batch()\n\n def train_batch(self, batch):\n state = self._state['train']\n model = self.model\n optimizer_arch, optimizer_model = self.optimizers\n lr_scheduler = self.lr_schedulers[0]\n\n model.train()\n input, target = convert_tensor(self, batch)\n\n if self.train_arch:\n input_search, target_search = convert_tensor(self, self.get_search_batch())\n requires_grad(model, arch=True, model=False)\n optimizer_arch.zero_grad(True)\n with autocast(enabled=self.fp16):\n logits_search = model(input_search)\n loss_search = self.criterion(logits_search, target_search)\n backward(self, loss_search)\n optimizer_step(self, optimizer_arch)\n # optimizer_arch.step()\n\n requires_grad(model, arch=False, model=True)\n lr_scheduler.step(state['epoch'] + (state['step'] / state['steps']))\n optimizer_model.zero_grad(True)\n with autocast(enabled=self.fp16):\n logits = model(input)\n loss = self.criterion(logits, target)\n backward(self, loss)\n optimizer_step(self, optimizer_model, model.model_parameters())\n\n state.update({\n \"loss\": loss.item(),\n \"batch_size\": input.size(0),\n \"y_true\": target,\n \"y_pred\": logits.detach(),\n })\n\n def eval_batch(self, batch):\n state = self._state['eval']\n model = self.model\n\n model.eval()\n input, target = convert_tensor(self, batch)\n with autocast(enabled=self.fp16):\n with torch.no_grad():\n output = model(input)\n\n state.update({\n \"batch_size\": input.size(0),\n \"y_true\": target,\n \"y_pred\": output,\n })\n\n def test_batch(self, batch):\n state = self._state['test']\n model = self.model\n\n model.eval()\n input, target = convert_tensor(self, batch)\n with autocast(enabled=self.fp16):\n with torch.no_grad():\n output = model(input)\n\n state.update({\n \"batch_size\": input.size(0),\n \"y_pred\": output,\n })\n","sub_path":"hinas/train/darts/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"81495633","text":"\"\"\"\nActivity 1 - all together\n\nRead the courses from courses.txt in the Resources file.\nThen, remove the courses titled Remotely Operated Vehicle Robotics\nand Robotics, and replace them with a course called Engineering I: Introduction to Engineering.\nMake sure the changes are saved back to courses.txt\n\"\"\"\n\noriginal = open('/Users/tkmuro/PycharmProjects/tkProgramming/Resources/courses.txt', \"r\")\nread_original = original.readlines()\nprint(\"Original Courses: \", read_original)\nappending_courses = open('/Users/tkmuro/PycharmProjects/tkProgramming/Resources/courses.txt', \"w\")\nfor item in read_original:\n if item != 'Remotely Operated Vehicle Robotics\\n' and item != 'Robotics\\n':\n appending_courses.write(item)\n if item == 'Robotics\\n':\n appending_courses.write('Engineering I: Introduction to Engineering\\n')\n\n\n\"\"\"\nActivity 2 - separate tasks, then merge together\n\nA class of students have been studying the countries and their capitals.\nThere are 196 potential countries, but they will only be asked 25 at random.\nTogether, you and your partner are going to generate a quiz for a student to take. \n\nPARTNER 1:\nRead the countries and capitals in from countries_and_capitals.csv in the Resources file.\nStore it in a 2-dimensional list without the header row. For example:\n\n[[\"Afghanistan\", \"Kabul\"],\n [\"Albania\", \"Tirana\"],\n ...\n [\"Zimbabwe\", \"Harare\"]]\n\n\nPARTNER 2:\nAssume you will receive a 2-dimensional list similar to what's shown above.\nRandomly select 25 Countries and their capitals. \nWrite code that will loop through those countries and capitals, \nand ask the user which country has a capital of the given capital. \nWrite their answers and the correct answer to a file called answers.csv in the following format:\n\nUser Answer,Correct Answer\nSweden, Sweden\nArgentina, Colombia\n\n\nTOGETHER:\n\n!!!!! do not move onto this until both tasks above are completed !!!!!\n!!!!! if you need to help each other out to finish those tasks first, please do so !!!!!\n\nMerge your code, and then work on the final task:\nModify your code to read the countries and capitals into a dictionary instead of a list of lists.\nFor example:\n\n{\n \"Afghanistan\": \"Kabul\",\n \"Albania\": \"Tirana\",\n ...\n \"Zimbabwe\": \"Harare\"\n}\n\nAlthough this is a structural change in your code, the functionality of your code should not change\nas a results of this modification. Please make all the necessary modifications for your code to \nfunction the same as it did with the list of lists.\n\"\"\"\n\n\n# Part 1 (alex)\nimport csv\ncountries_capitals = open('/Users/tkmuro/PycharmProjects/tkProgramming/Resources/countries_and_capitals.csv')\nreader = csv.reader(countries_capitals)\ndict_reader = list(csv.DictReader(countries_capitals))\nfor item in dict_reader:\n print(item)\n\nprint(dict_reader[5][\"Country\"])\n\n\n# Part 2 (tk, but more collaborative)\nimport random\n\noutput_file = open('partner_activity.csv', 'w')\noutput_writer = csv.writer(output_file)\noutput_writer.writerow(['Country', 'Correct answer', 'User answer'])\n\nnumbers = []\nfor i in range(25):\n number = random.randint(0, len(dict_reader))\n while number in numbers:\n number = random.randint(0, len(dict_reader))\n user_answer = input(\"{0} is the capital of: \".format(dict_reader[number][\"Capital\"]))\n output_writer.writerow([dict_reader[number][\"Country\"], dict_reader[number][\"Capital\"], str(user_answer)])\n numbers.append(number)\n","sub_path":"InClassActivities/reading_and_writing_to_files.py","file_name":"reading_and_writing_to_files.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"633764173","text":"import datetime\nimport openpyxl\nimport Functions as help\n\n# Open Workbooks\nEntry = openpyxl.load_workbook('BookForProgramDirector.xlsx')\nData = openpyxl.load_workbook('BookForPython.xlsx')\n\n# Constants for Session Dates sheet\nSESSION_DATES_SHEET = Entry[\"Session Dates\"]\nSESSION_COLUMN = 1\nSESSION_START_COLUMN = 2\nSESSION_END_COLUMN = 3\nA1_ROW = 2\nA2_ROW = 3\nB1_ROW = 4\nB2_ROW = 5\nC_ROW = 6\nA1_START = SESSION_DATES_SHEET.cell(row=A1_ROW, column=SESSION_START_COLUMN)\nA2_START = SESSION_DATES_SHEET.cell(row=A2_ROW, column=SESSION_START_COLUMN)\nA1_END = SESSION_DATES_SHEET.cell(row=A1_ROW, column=SESSION_END_COLUMN)\n\n\n# Constants for Full Day, Half Day, and Duty sheets\nFULL_DAY_SHEET = Entry[\"Full Day\"]\nHALF_DAY_SHEET = Entry[\"Half Day\"]\nDUTY_SCHEDULE_SHEET = Entry[\"Duty Schedule\"]\nSTAFFING_SHEET = Entry[\"Official Staffing\"]\nDATE_COLUMN = 2\nDATE_ROW = 2\nNAME_COLUMN_A = 2\nTYPE_COLUMN_A = 1\n\n# Constants for Staff Roster\nSTAFF_ROSTER_SHEET = Entry[\"Staff Roster\"]\nNAME_COLUMN = 1\nTYPE_COLUMN = 2\ntotalStaff = (STAFF_ROSTER_SHEET.cell(row=2, column=12)).value\ntypeList = [\"JB\", \"JG\", \"BB\", \"BG\", \"IB\", \"IG\", \"SB\", \"SG\", \"SSB\", \"SSG\", \"LT\", \"SPEC\", \"TRIPPER\"]\n\n\n# Constants for Jinci Boys and Jinci Girls Rotation, Jinci Boys and Jinci Girls Schedule\nJB_ROTATION_SHEET = Data[\"Jinci Boys Rotation\"]\nJG_ROTATION_SHEET = Data[\"Jinci Girls Rotation\"]\nJB_SCHEDULE_SHEET = Entry[\"Jinci Boys Schedule\"]\nJG_SCHEDULE_SHEET = Entry[\"Jinci Girls Schedule\"]\nROTATION_COLUMN = 1\nCABIN_COLUMN = 2\nOFFSET_COLUMN = 3\nCABIN1_ROW = 2\nCABIN2_ROW = 3\nCABIN3_ROW = 4\nTotalCabinsJB = (JB_ROTATION_SHEET.cell(row=2, column=4)).value\n\n# Create lists from rotation column\nrotationJB = help.create_list_from_column(2, JB_ROTATION_SHEET, ROTATION_COLUMN)\nrotationLengthJB = len(rotationJB)\n\nrotationJG = help.create_list_from_column(2, JG_ROTATION_SHEET, ROTATION_COLUMN)\nrotationLengthJG = len(rotationJG)\n\n# Create Jinci Cabin Schedules from Rotation Sheet\nhelp.create_jinci_schedules(2, JB_ROTATION_SHEET, JB_SCHEDULE_SHEET, rotationJB)\nhelp.create_jinci_schedules(2, JG_ROTATION_SHEET, JG_SCHEDULE_SHEET, rotationJG)\n\n# Take names from Staff Roster and print onto Duty Schedule Sheet\nhelp.sort_names_by_type(STAFF_ROSTER_SHEET, 2, totalStaff, NAME_COLUMN, DUTY_SCHEDULE_SHEET, 3, NAME_COLUMN_A,\n typeList, TYPE_COLUMN, TYPE_COLUMN_A)\n\n# Take names from Staff Roster and print onto Official Staffing sheet\nstart_row = 2\nwhile (STAFF_ROSTER_SHEET.cell(row=start_row, column=NAME_COLUMN)).value:\n name = (STAFF_ROSTER_SHEET.cell(row=start_row, column=NAME_COLUMN)).value\n STAFFING_SHEET.cell(row=start_row, column=NAME_COLUMN, value=name)\n start_row += 1\n\n# Take dates from Session Dates and print onto Full Day Sheet, Half Day Sheet, and Duty Schedule Sheet\nhelp.print_dates_to_column_from_table(A1_ROW, C_ROW, SESSION_START_COLUMN, SESSION_END_COLUMN, SESSION_DATES_SHEET,\n DATE_COLUMN, 2, FULL_DAY_SHEET)\nhelp.print_dates_to_column_from_table(A1_ROW, C_ROW, SESSION_START_COLUMN, SESSION_END_COLUMN, SESSION_DATES_SHEET,\n DATE_COLUMN, 2, HALF_DAY_SHEET)\nhelp.print_dates_to_row_from_table(A1_ROW, C_ROW, SESSION_START_COLUMN, SESSION_END_COLUMN, SESSION_DATES_SHEET,\n DATE_ROW, NAME_COLUMN_A + 1, DUTY_SCHEDULE_SHEET)\n\n\nEntry.save(\"BookForProgramDirector.xlsx\")\n","sub_path":"Initialize.py","file_name":"Initialize.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"323853638","text":"from django.db import models\n\nfrom wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel\nfrom wagtail.core.fields import StreamField\nfrom wagtail.core.models import Page\n\nfrom ..alerts.models import AlertMixin\nfrom .blocks import HomePageStreamBlock\n\nclass HomePage(AlertMixin, Page):\n\n body = StreamField(HomePageStreamBlock, blank=True, null=True)\n\n content_panels = Page.content_panels + [\n StreamFieldPanel('body'),\n ]\n settings_panels = Page.settings_panels + AlertMixin.settings_panels\n\n def get_context(self, request):\n context = super().get_context(request)\n\n context[\"etna_index_pages\"] = [\n {\n \"title\": \"Collection Explorer\",\n \"introduction\": \"A new way to discover collections at The National Archives, through records hand-picked by our experts.\",\n \"url\": \"#\",\n },\n {\n \"title\": \"Collection Insights\",\n \"introduction\": \"Learn about the people, themes and events featured in our records, told through words, pictures and audio - discover the human stories behind the collection.\",\n \"url\": \"#\",\n },\n {\n \"title\": \"Collection Details\",\n \"introduction\": \"View and navigate records from The National Archives catalogue.\",\n \"url\": \"#\",\n },\n ]\n\n return context\n","sub_path":"etna/home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"428041603","text":"import discord\nfrom redbot.core import checks, commands, bank\nfrom redbot.core.utils.chat_formatting import box\n\nfrom .abc import MixinMeta\nimport math\nimport random\nimport asyncio\nfrom .utils import checkReacts\nfrom string import ascii_uppercase\n\n\nclass SimsetMixin(MixinMeta):\n \"\"\"Simulation Settings\"\"\"\n\n @checks.admin_or_permissions(manage_guild=True)\n @commands.group(autohelp=True)\n async def simset(self, ctx):\n \"\"\"Simulation Settings.\"\"\"\n if ctx.invoked_subcommand is None:\n guild = ctx.guild\n # Display current settings\n gametime = await self.config.guild(guild).gametime()\n htbreak = await self.config.guild(guild).htbreak()\n results = await self.config.guild(guild).resultchannel()\n bettoggle = await self.config.guild(guild).bettoggle()\n maxplayers = await self.config.guild(guild).maxplayers()\n redcardmodif = await self.config.guild(guild).redcardmodifier()\n transfers = await self.config.guild(guild).transferwindow()\n mentions = await self.config.guild(guild).mentions()\n msg = \"\"\n msg += \"Game Time: 1m for every {}s.\\n\".format(gametime)\n msg += \"Team Limit: {} players.\\n\".format(maxplayers)\n msg += \"HT Break: {}s.\\n\".format(htbreak)\n msg += \"Red Card Modifier: {}% loss per red card.\\n\".format(redcardmodif)\n msg += \"Posting Results: {}.\\n\".format(\"Yes\" if results else \"No\")\n msg += \"Transfer Window: {}.\\n\".format(\"Open\" if transfers else \"Closed\")\n msg += \"Accepting Bets: {}.\\n\".format(\"Yes\" if bettoggle else \"No\")\n msg += \"Mentions on game start: {}.\\n\".format(\"Yes\" if mentions else \"No\")\n\n if bettoggle:\n bettime = await self.config.guild(guild).bettime()\n betmax = await self.config.guild(guild).betmax()\n betmin = await self.config.guild(guild).betmin()\n msg += \"Bet Time: {}s.\\n\".format(bettime)\n msg += \"Max Bet: {}.\\n\".format(betmax)\n msg += \"Min Bet: {}.\\n\".format(betmin)\n await ctx.send(box(msg))\n\n @simset.command()\n async def maxplayers(self, ctx, amount: int):\n \"\"\"Set the max team players.\"\"\"\n if amount < 3 or amount > 7:\n return await ctx.send(\"Amount must be between 3 and 7.\")\n await self.config.guild(ctx.guild).maxplayers.set(amount)\n await ctx.tick()\n\n @simset.command()\n async def redcardmodifier(self, ctx, amount: int):\n \"\"\"Set the the handicap per red card.\"\"\"\n if amount < 1 or amount > 30:\n return await ctx.send(\"Amount must be between 1 and 30.\")\n await self.config.guild(ctx.guild).redcardmodifier.set(amount)\n await ctx.tick()\n\n @simset.command()\n async def addstat(self, ctx, param=None):\n \"\"\"Add standings stat keys.\"\"\"\n teams = await self.config.guild(ctx.guild).teams()\n headers = [\n \"played\",\n \"wins\",\n \"losses\",\n \"points\",\n \"gd\",\n \"gf\",\n \"ga\",\n \"draws\",\n \"reds\",\n \"yellows\",\n \"fouls\",\n \"chances\",\n ]\n if param not in headers:\n return await ctx.send(f\"Stat to add must be one of {', '.join(headers)}.\")\n for team in teams:\n async with self.config.guild(ctx.guild).standings() as standings:\n stats = standings[team].keys()\n if param not in stats:\n standings[team][param] = 0\n else:\n await ctx.send(f\"Stat '{param}' already exists (league).\")\n async with self.config.guild(ctx.guild).cupstandings() as cupstandings:\n if team not in cupstandings:\n cupstandings[team] = {\n \"played\": 0,\n \"wins\": 0,\n \"losses\": 0,\n \"points\": 0,\n \"gd\": 0,\n \"gf\": 0,\n \"ga\": 0,\n \"draws\": 0,\n \"reds\": 0,\n \"yellows\": 0,\n \"fouls\": 0,\n \"chances\": 0,\n }\n else:\n stats = cupstandings[team].keys()\n if param not in stats:\n cupstandings[team][param] = 0\n else:\n await ctx.send(f\"Stat '{param}' already exists (cup).\")\n await ctx.tick()\n\n @simset.command()\n async def addplayerstat(self, ctx, param=None):\n \"\"\"Add player stat keys.\"\"\"\n async with self.config.guild(ctx.guild).stats() as stats:\n stats[param] = {}\n async with self.config.guild(ctx.guild).cupstats() as cupstats:\n cupstats[param] = {}\n await ctx.tick()\n\n @simset.command()\n async def gametime(self, ctx, time: float = 1):\n \"\"\"Set the time each minute takes - 5 seconds is the max. 1 is default.\"\"\"\n if time < 0 or time > 5:\n time = 90\n await self.config.guild(ctx.guild).gametime.set(time)\n await ctx.tick()\n\n @simset.command()\n async def halftimebreak(self, ctx, time: int = 1):\n \"\"\"Set the half time break - 20 seconds is the max. 5 is default.\"\"\"\n if time < 0 or time > 20:\n time = 5\n await self.config.guild(ctx.guild).htbreak.set(time)\n await ctx.tick()\n\n @simset.command()\n async def resultchannel(self, ctx, channel: discord.TextChannel):\n \"\"\"Add a channel for automatic result posting.\"\"\"\n channels = await self.config.guild(ctx.guild).resultchannel()\n for c in channels:\n if c == channel.id:\n await ctx.send(\"Results are already posted in this channel\")\n return\n\n channels.append(channel.id)\n await self.config.guild(ctx.guild).resultchannel.set(channels)\n await ctx.tick()\n\n @simset.command()\n async def resultchannels(self, ctx, option: str):\n \"\"\"Show or clear all result channels.\"\"\"\n if option == \"clear\":\n await self.config.guild(ctx.guild).resultchannel.set([])\n await ctx.tick()\n elif option == \"show\":\n async with self.config.guild(ctx.guild).resultchannel() as result:\n a = []\n for res in result:\n channel = ctx.guild.get_channel(res).name\n a.append(channel)\n embed = discord.Embed(\n title=\"Result channels\", description=\"\\n\".join(a), colour=0xFF0000\n )\n await ctx.send(embed=embed)\n else:\n await ctx.send(\"No parameter for resultchannels, you must choose 'show' or 'clear'\")\n\n @simset.command()\n async def transferchannel(self, ctx, channel: discord.TextChannel):\n \"\"\"Add a channel for automatic transfer posting.\"\"\"\n async with self.config.guild(ctx.guild).transferchannel() as channels:\n if channel.id in channels:\n await ctx.send(\"Transfers are already posted in this channel\")\n return\n\n channels.append(channel.id)\n await ctx.tick()\n\n @simset.command()\n async def transferchannels(self, ctx, option: str):\n \"\"\"Show or clear all transfer channels.\"\"\"\n if option == \"clear\":\n await self.config.guild(ctx.guild).transferchannel.set([])\n await ctx.tick()\n elif option == \"show\":\n async with self.config.guild(ctx.guild).transferchannel() as result:\n a = []\n for res in result:\n channel = ctx.guild.get_channel(res)\n if channel is not None:\n a.append(channel.name)\n embed = discord.Embed(\n title=\"Transfer channels\", description=\"\\n\".join(a), colour=0xFF0000\n )\n await ctx.send(embed=embed)\n else:\n await ctx.send(\"No parameter for transferchannels, you must choose 'show' or 'clear'\")\n\n @simset.command()\n async def window(self, ctx, status: str):\n \"\"\"Open or close the transfer window.\"\"\"\n if status.lower() not in [\"open\", \"close\"]:\n return await ctx.send(\"You must specify either 'open' or 'close'.\")\n if status == \"open\":\n standings = await self.config.guild(ctx.guild).standings()\n sortedstandings = sorted(\n standings,\n key=lambda team: (\n standings[team][\"points\"],\n standings[team][\"gd\"],\n standings[team][\"gf\"],\n ),\n )\n firstteam = None\n for i, team in enumerate(sortedstandings):\n async with self.config.guild(ctx.guild).transfers() as transfers:\n if i == 0:\n firstteam = team\n transfers[team] = {\n \"ready\": True if i == 0 else False,\n \"locked\": None,\n \"swap\": {\"in\": None, \"out\": None},\n \"sign\": {\"in\": None, \"out\": None},\n }\n await self.config.guild(ctx.guild).transferwindow.set(True)\n await ctx.send(\n \"Transfer window is now open. Transfers will start with {}\".format(firstteam)\n )\n else:\n await self.config.guild(ctx.guild).transferwindow.set(False)\n await ctx.send(\"Transfer window is now closed.\")\n\n @simset.command()\n async def lockwindow(self, ctx, status: str):\n \"\"\"Open or close the contract extension window.\"\"\"\n if status.lower() not in [\"open\", \"close\"]:\n return await ctx.send(\"You must specify either 'open' or 'close'.\")\n if status == \"open\":\n await self.config.guild(ctx.guild).extensionwindow.set(True)\n await ctx.send(\n \"Extension window is now open. You can now pick a player to extend for this season.\"\n )\n else:\n await self.config.guild(ctx.guild).extensionwindow.set(False)\n await ctx.send(\"Extension window is now closed.\")\n\n @simset.command()\n async def mentions(self, ctx, bool: bool):\n \"\"\"Toggle mentions on game start.\"\"\"\n if bool:\n await self.config.guild(ctx.guild).mentions.set(True)\n else:\n await self.config.guild(ctx.guild).mentions.set(False)\n\n @simset.command(name=\"updatecache\")\n async def levels_updatecache(self, ctx):\n \"\"\"Update the level cache.\"\"\"\n async with ctx.typing():\n await self.updatecacheall(ctx.guild)\n await ctx.tick()\n\n @simset.command()\n @commands.bot_has_permissions(manage_roles=True)\n async def createroles(self, ctx):\n \"\"\"Create roles for teams and captains.\"\"\"\n roles = await ctx.guild.fetch_roles()\n cptrole = [r for r in roles if r.name == \"Sim Captain\"]\n cptrole = await ctx.guild.create_role(name=\"Sim Captain\") if not cptrole else cptrole[0]\n\n async with self.config.guild(ctx.guild).teams() as teams:\n for team in teams:\n if teams[team][\"role\"] is None:\n role = await ctx.guild.create_role(name=team)\n teams[team][\"role\"] = role.id\n\n teamcaptain = teams[team][\"captain\"]\n captainid = list(teamcaptain.keys())[0]\n member = ctx.guild.get_member(int(captainid))\n if member is not None:\n await ctx.send(f\"Assigning {cptrole.name} to {member.name}\")\n await member.add_roles(cptrole)\n await ctx.tick()\n\n @simset.command()\n @commands.bot_has_permissions(manage_roles=True)\n async def createnatroles(self, ctx):\n \"\"\"Create roles for national teams.\"\"\"\n roles = await ctx.guild.fetch_roles()\n async with self.config.guild(ctx.guild).nteams() as nteams:\n for team in nteams:\n if nteams[team][\"role\"] is None:\n role = await ctx.guild.create_role(name=team)\n nteams[team][\"role\"] = role.id\n else:\n role = ctx.guild.get_role(nteams[team][\"role\"])\n for user in nteams[team][\"members\"]:\n member = ctx.guild.get_member(int(user))\n if member is None:\n await ctx.send(\"Could not find user {}.\".format(user))\n else:\n await member.add_roles(role)\n await ctx.tick()\n\n @simset.command()\n @commands.bot_has_permissions(manage_roles=True)\n async def updateroles(self, ctx):\n \"\"\"Update roles for teammembers.\"\"\"\n teams = await self.config.guild(ctx.guild).teams()\n for team in teams:\n if teams[team][\"role\"] is None:\n self.log.debug(f\"Skipping {team}, no role found.\")\n continue\n role = ctx.guild.get_role(teams[team][\"role\"])\n for user in teams[team][\"members\"]:\n member = ctx.guild.get_member(int(user))\n if member is None:\n await ctx.send(\"Could not find user {}.\".format(user))\n else:\n await member.add_roles(role)\n await ctx.tick()\n\n @simset.command()\n @commands.bot_has_permissions(manage_roles=True)\n async def clearform(self, ctx, team=None):\n \"\"\"Clear streak form for a team or all teams.\"\"\"\n cog = self.bot.get_cog(\"SimLeague\")\n async with cog.config.guild(ctx.guild).teams() as teams:\n if team is not None:\n if team not in teams:\n return await ctx.send(\"This team does not exist.\")\n teams[team][\"form\"] = {\"result\": None, \"streak\": 0}\n else:\n for t in teams:\n teams[t][\"form\"] = {\"result\": None, \"streak\": 0}\n await ctx.tick()\n\n @simset.command()\n @commands.bot_has_permissions(manage_roles=True)\n async def setform(self, ctx, team, result: str, streak: int):\n \"\"\"Set streak form for a team or all teams.\"\"\"\n cog = self.bot.get_cog(\"SimLeague\")\n async with cog.config.guild(ctx.guild).teams() as teams:\n if team not in teams:\n return await ctx.send(\"This team does not exist.\")\n if result not in [\"W\", \"D\", \"L\"]:\n return await ctx.send(\"Result must be one of: W, D, L.\")\n if streak < 0:\n return await ctx.send(\"Streak must be > 0.\")\n teams[team][\"form\"] = {\"result\": result, \"streak\": streak}\n await ctx.tick()\n\n @checks.admin_or_permissions(manage_guild=True)\n @simset.command(name=\"addusers\")\n async def add_users(self, ctx, *userids):\n async with self.config.guild(ctx.guild).users() as users:\n for uid in userids:\n if uid not in users:\n users.append(uid)\n await ctx.tick()\n\n @checks.admin_or_permissions(manage_guild=True)\n @simset.command(name=\"removeusers\")\n async def remove_users(self, ctx, *userids):\n async with self.config.guild(ctx.guild).users() as users:\n for uid in userids:\n if uid in users:\n users.remove(uid)\n await ctx.tick()\n\n @checks.admin_or_permissions(manage_guild=True)\n @simset.command(name=\"viewusers\")\n async def view_users(self, ctx, *userids):\n users = await self.config.guild(ctx.guild).users()\n await ctx.send(users)\n await ctx.tick()\n\n @checks.admin_or_permissions(manage_guild=True)\n @simset.command(name=\"cleanusers\")\n async def clean_users(self, ctx):\n teams = await self.config.guild(ctx.guild).teams()\n async with self.config.guild(ctx.guild).users() as users:\n activeusers = []\n for team in teams:\n for uid in teams[team][\"members\"]:\n activeusers.append(uid)\n for uid in users:\n if uid not in activeusers:\n users.remove(uid)\n await self.config.guild(ctx.guild).users.set(list(dict.fromkeys(activeusers)))\n await ctx.tick()\n\n @simset.command()\n async def createfixtures(self, ctx):\n \"\"\"Create the fixtures for the current teams.\"\"\"\n teams = await self.config.guild(ctx.guild).teams()\n teams = list(teams.keys())\n random.shuffle(teams)\n if len(teams) % 2:\n teams.append(\"DAY OFF\")\n n = len(teams)\n matchs = []\n fixtures = []\n return_matchs = []\n for fixture in range(1, n):\n for i in range(n // 2):\n matchs.append((teams[i], teams[n - 1 - i]))\n return_matchs.append((teams[n - 1 - i], teams[i]))\n teams.insert(1, teams.pop())\n fixtures.insert(len(fixtures) // 2, matchs)\n fixtures.append(return_matchs)\n matchs = []\n return_matchs = []\n\n a = []\n for k, fixture in enumerate(fixtures, 1):\n a.append(f\"Week {k}\\n----------\")\n for i, game in enumerate(fixture, 1):\n a.append(f\"Game {i}: {game[0]} vs {game[1]}\")\n a.append(\"----------\")\n\n await self.config.guild(ctx.guild).fixtures.set(fixtures)\n await ctx.tick()\n\n @simset.command()\n async def createnatfixtures(self, ctx):\n \"\"\"Create international fixtures for the current teams.\"\"\"\n nteams = await self.config.guild(ctx.guild).nteams()\n matchs = []\n fixtures = []\n grouplist = list(ascii_uppercase)[: len(list(nteams.keys())) // 4]\n for group in grouplist:\n teams = {key: value for (key, value) in nteams.items() if value[\"group\"] == group}\n teams = list(teams.keys())\n n = len(teams)\n for fixture in range(1, n):\n for i in range(n // 2):\n matchs.append(\n {\n \"team1\": teams[i],\n \"score1\": None,\n \"team2\": teams[n - 1 - i],\n \"score2\": None,\n }\n )\n teams.insert(1, teams.pop())\n fixtures.insert(len(fixtures) // 2, matchs)\n matchs = []\n a = []\n finalfixtures = []\n\n for j in range(0, len(fixtures), 2):\n roundfixtures = []\n for i, fixture in enumerate(fixtures):\n roundfixtures.append(fixture[j + 0])\n roundfixtures.append(fixture[j + 1])\n\n random.shuffle(roundfixtures)\n finalfixtures.append(roundfixtures)\n await self.config.guild(ctx.guild).nfixtures.set(finalfixtures)\n await ctx.tick()\n\n @simset.command()\n async def drawcupround(self, ctx, *teambyes):\n \"\"\"Draws the current round of Sim Cup.\"\"\"\n teams = await self.config.guild(ctx.guild).teams()\n if len(teambyes):\n for t in list(teambyes):\n if t not in teams:\n return await ctx.send(\"{} is not a valid team.\".format(t))\n cupgames = await self.config.guild(ctx.guild).cupgames()\n async with ctx.typing():\n if len(cupgames):\n keys = list(cupgames.keys())\n if [keys[len(keys) - 1]][0] == \"2\":\n return await ctx.send(\"There is no more game to draw!\")\n lastround = cupgames[keys[len(keys) - 1]]\n unplayedgames = [\n game\n for game in lastround\n if (game[\"score1\"] + game[\"penscore1\"]) == (game[\"score2\"] + game[\"penscore2\"])\n and game[\"team2\"] != \"BYE\"\n ]\n isroundover = False if len(unplayedgames) else True\n if not isroundover:\n return await ctx.send(\n \"You need to finish the current round before drawing the next.\"\n )\n winners = [\n game[\"team1\"]\n if (game[\"score1\"] + game[\"penscore1\"]) > (game[\"score2\"] + game[\"penscore2\"])\n or game[\"team2\"] == \"BYE\"\n else game[\"team2\"]\n for game in lastround\n ]\n teams = {k: v for k, v in teams.items() if k in winners}\n if len(teams):\n roundsize = 2 ** math.ceil(math.log2(len(teams)))\n drawables = [x for x in teams]\n\n n = len(drawables)\n fixtures = []\n for i in range(n // 2):\n draw = []\n msg = await ctx.send(\"Game {}:\".format(i + 1))\n rdteam1 = random.choice(drawables)\n drawables = [x for x in drawables if x is not rdteam1]\n rdteam1mention = ctx.guild.get_role(teams[rdteam1][\"role\"]).mention\n await msg.edit(content=\"Game {}: {} vs ...\".format(i + 1, rdteam1mention))\n rdteam2 = random.choice(drawables)\n rdteam2mention = ctx.guild.get_role(teams[rdteam2][\"role\"]).mention\n await asyncio.sleep(5)\n await msg.edit(\n content=\"Game {}: {} vs {}!\".format(\n i + 1, rdteam1mention, rdteam2mention\n )\n )\n draw.append(\n {\n \"team1\": rdteam1,\n \"score1\": 0,\n \"penscore1\": 0,\n \"team2\": rdteam2,\n \"score2\": 0,\n \"penscore2\": 0,\n }\n )\n fixtures.append(\n {\n \"team1\": rdteam1,\n \"score1\": 0,\n \"penscore1\": 0,\n \"team2\": rdteam2,\n \"score2\": 0,\n \"penscore2\": 0,\n }\n )\n drawables = [x for x in drawables if x is not rdteam2]\n await asyncio.sleep(5)\n\n async with self.config.guild(ctx.guild).cupgames() as cupgames:\n cupgames[str(roundsize)] = fixtures\n else:\n # Get seeds and start draw\n standings = await self.config.guild(ctx.guild).standings()\n sortedstandings = sorted(\n standings,\n key=lambda team: (\n standings[team][\"points\"],\n standings[team][\"gd\"],\n standings[team][\"gf\"],\n ),\n reverse=True,\n )\n byes = []\n if len(teambyes):\n sortedstandings = [x for x in teams if x not in teambyes]\n byes = list(teambyes)\n if len(teams):\n roundsize = 2 ** math.ceil(math.log2(len(teams)))\n drawables = []\n for idx, team in enumerate(sortedstandings):\n if idx < (roundsize - len(teams) - len(teambyes)):\n byes.append(team)\n else:\n drawables.append(team)\n\n n = len(drawables)\n fixtures = []\n byementions = []\n for bye in byes:\n fixtures.append(\n {\n \"team1\": bye,\n \"score1\": 0,\n \"penscore1\": 0,\n \"team2\": \"BYE\",\n \"score2\": 0,\n \"penscore2\": 0,\n }\n )\n byemention = ctx.guild.get_role(teams[bye][\"role\"]).mention\n byementions.append(byemention)\n\n if len(byes):\n await ctx.send(\n \"Teams directly qualified for the next round: {}\".format(\n \", \".join(byementions)\n )\n )\n await asyncio.sleep(5)\n\n for i in range(n // 2):\n draw = []\n msg = await ctx.send(\"Game {}:\".format(i + 1))\n rdteam1 = random.choice(drawables)\n drawables = [x for x in drawables if x is not rdteam1]\n rdteam1mention = ctx.guild.get_role(teams[rdteam1][\"role\"]).mention\n await msg.edit(content=\"Game {}: {} vs ...\".format(i + 1, rdteam1mention))\n rdteam2 = random.choice(drawables)\n rdteam2mention = ctx.guild.get_role(teams[rdteam2][\"role\"]).mention\n await asyncio.sleep(5)\n await msg.edit(\n content=\"Game {}: {} vs {}!\".format(\n i + 1, rdteam1mention, rdteam2mention\n )\n )\n draw.append(\n {\n \"team1\": rdteam1,\n \"score1\": 0,\n \"penscore1\": 0,\n \"team2\": rdteam2,\n \"score2\": 0,\n \"penscore2\": 0,\n }\n )\n fixtures.append(\n {\n \"team1\": rdteam1,\n \"score1\": 0,\n \"penscore1\": 0,\n \"team2\": rdteam2,\n \"score2\": 0,\n \"penscore2\": 0,\n }\n )\n drawables = [x for x in drawables if x is not rdteam2]\n await asyncio.sleep(5)\n\n async with self.config.guild(ctx.guild).cupgames() as cupgames:\n cupgames[str(roundsize)] = fixtures\n\n embed = discord.Embed(\n color=0xFF0000,\n description=\"------------------------- Cup Draw -------------------------\",\n )\n a = []\n for fixture in fixtures:\n if fixture[\"team2\"] == \"BYE\":\n a.append(f\"**{fixture['team1']}** _(qualified directly)_\")\n else:\n a.append(f\"{fixture['team1']} vs {fixture['team2']}\")\n title = \"\"\n if roundsize >= 16:\n title = \"Round of {}\".format(roundsize)\n elif roundsize == 8:\n title = \"Quarter Finals\"\n elif roundsize == 4:\n title = \"Semi Finals\"\n else:\n title = \"Final\"\n embed.add_field(name=title, value=\"\\n\".join(a))\n await ctx.send(embed=embed)\n await ctx.tick()\n\n @checks.admin_or_permissions(manage_guild=True)\n @simset.group(autohelp=True, hidden=True)\n async def probability(self, ctx):\n \"\"\"Simulation Probability Settings. May break the cog if changed.\"\"\"\n if ctx.invoked_subcommand is None:\n proba = await self.config.guild(ctx.guild).probability()\n goals = proba[\"goalchance\"]\n owngoals = proba[\"owngoalchance\"]\n yellow = proba[\"yellowchance\"]\n red = proba[\"redchance\"]\n penalty = proba[\"penaltychance\"]\n penaltyblock = proba[\"penaltyblock\"]\n freekick = proba[\"freekickchance\"]\n freekickblock = proba[\"freekickblock\"]\n corner = proba[\"cornerchance\"]\n cornerblock = proba[\"cornerblock\"]\n var = proba[\"varchance\"]\n varsuccess = proba[\"varsuccess\"]\n comment = proba[\"commentchance\"]\n msg = \"/!\\\\ This has the chance to break the game completely, no support is offered. \\n\\n\"\n msg += \"Goal Chance: {}.\\n\".format(goals)\n msg += \"Own Goal Chance: {}.\\n\".format(owngoals)\n msg += \"Yellow Card Chance: {}.\\n\".format(yellow)\n msg += \"Red Card Chance: {}.\\n\".format(red)\n msg += \"Penalty Chance: {}.\\n\".format(penalty)\n msg += \"Penalty Block Chance: {}.\\n\".format(penaltyblock)\n msg += \"Free Kick Chance: {}.\\n\".format(freekick)\n msg += \"Free Kick Block Chance: {}.\\n\".format(freekickblock)\n msg += \"Corner Chance: {}.\\n\".format(corner)\n msg += \"Corner Block Chance: {}.\\n\".format(cornerblock)\n msg += \"VAR Chance: {}.\\n\".format(var)\n msg += \"VAR Success Chance: {}.\\n\".format(varsuccess)\n msg += \"Commentary Chance: {}.\\n\".format(comment)\n await ctx.send(box(msg))\n\n @probability.command()\n async def goals(self, ctx, amount: int = 96):\n \"\"\"Goal probability. Default = 96\"\"\"\n if amount > 100 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"goalchance\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def owngoals(self, ctx, amount: int = 399):\n \"\"\"Own Goal probability. Default = 399\"\"\"\n if amount > 400 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 400.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"owngoalchance\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def yellow(self, ctx, amount: int = 98):\n \"\"\"Yellow Card probability. Default = 98\"\"\"\n if amount > 100 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"yellowchance\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def red(self, ctx, amount: int = 398):\n \"\"\"Red Card probability. Default = 398\"\"\"\n if amount > 400 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 400.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"redchance\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def penalty(self, ctx, amount: int = 249):\n \"\"\"Penalty Chance probability. Default = 249\"\"\"\n if amount > 250 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 250.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"penaltychance\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def penaltyblock(self, ctx, amount: int = 75):\n \"\"\"Penalty Block probability. Default = 75\"\"\"\n if amount > 100 or amount < 0:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"penaltyblock\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def corner(self, ctx, amount: int = 98):\n \"\"\"Corner Chance probability. Default = 98\"\"\"\n if amount > 100 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"cornerchance\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def cornerblock(self, ctx, amount: int = 20):\n \"\"\"Corner Block probability. Default = 20\"\"\"\n if amount > 100 or amount < 0:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"cornerblock\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def freekick(self, ctx, amount: int = 98):\n \"\"\"Free Kick Chance probability. Default = 98\"\"\"\n if amount > 100 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"freekickchance\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def freekickblock(self, ctx, amount: int = 15):\n \"\"\"Free Kick Block probability. Default = 15\"\"\"\n if amount > 100 or amount < 0:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"freekickblock\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def var(self, ctx, amount: int = 50):\n \"\"\"VAR Chance probability. Default = 50\"\"\"\n if amount > 100 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"varchance\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def varsuccess(self, ctx, amount: int = 50):\n \"\"\"VAR Success Chance probability. Default = 50\"\"\"\n if amount > 100 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"varsuccess\"] = amount\n await ctx.tick()\n\n @probability.command()\n async def commentchance(self, ctx, amount: int = 85):\n \"\"\"Commentary Chance probability. Default = 85\"\"\"\n if amount > 100 or amount < 1:\n return await ctx.send(\"Amount must be greater than 0 and less than 100.\")\n async with self.config.guild(ctx.guild).probability() as probability:\n probability[\"commentchance\"] = amount\n await ctx.tick()\n\n @checks.admin_or_permissions(manage_guild=True)\n @simset.group(autohelp=True)\n async def bet(self, ctx):\n \"\"\"Simulation Betting Settings.\"\"\"\n\n @bet.command()\n async def time(self, ctx, time: int = 180):\n \"\"\"Set the time allowed for betting - 600 seconds is the max, 180 is default.\"\"\"\n if time < 0 or time > 600:\n time = 180\n await self.config.guild(ctx.guild).bettime.set(time)\n await ctx.tick()\n\n @bet.command()\n async def max(self, ctx, amount: int):\n \"\"\"Set the max amount for betting.\"\"\"\n if amount < 1:\n return await ctx.send(\"Amount must be greater than 0.\")\n await self.config.guild(ctx.guild).betmax.set(amount)\n await ctx.tick()\n\n @bet.command()\n async def min(self, ctx, amount: int):\n \"\"\"Set the min amount for betting.\"\"\"\n if amount < 1:\n return await ctx.send(\"Amount must be greater than 0.\")\n await self.config.guild(ctx.guild).betmin.set(amount)\n await ctx.tick()\n\n @bet.command()\n async def toggle(self, ctx, toggle: bool):\n \"\"\"Set if betting is enabled or not.\n Toggle must be a valid bool.\"\"\"\n await self.config.guild(ctx.guild).bettoggle.set(toggle)\n await ctx.tick()\n\n @checks.admin_or_permissions(manage_guild=True)\n @bet.command(name=\"reset\")\n async def bet_reset(self, ctx):\n bettoggle = await self.config.guild(ctx.guild).bettoggle()\n if bettoggle == False:\n return await ctx.send(\"Betting is disabled\")\n await self.config.guild(ctx.guild).active.set(False)\n await self.config.guild(ctx.guild).started.set(False)\n await self.config.guild(ctx.guild).betteams.set([])\n await self.bets_payout(ctx)\n if ctx.guild.id in self.bets:\n self.bets[ctx.guild.id] = {}\n return await ctx.tick()\n\n async def bets_payout(self, ctx):\n bet_refundees = []\n if ctx.guild.id not in self.bets:\n return None\n for better in self.bets[ctx.guild.id]:\n for team, bet in self.bets[ctx.guild.id][better][\"Bets\"]:\n bet_refundees.append(f\"{better.mention} - Refunded: {int(bet)}\")\n await bank.deposit_credits(better, int(bet))\n return await ctx.send(\"\\n\".join(bet_refundees)) if bet_refundees else None\n\n @checks.admin_or_permissions(manage_guild=True)\n @simset.group()\n async def clear(self, ctx):\n \"\"\"SimLeague Clear Settings\"\"\"\n\n @clear.command(name=\"all\")\n async def clear_all(self, ctx):\n \"\"\"Clear all teams, stats etc.\"\"\"\n confirm = await checkReacts(self, ctx, \"This will clear everything. Proceed ?\")\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).clear()\n await self.config.guild(ctx.guild).fixtures.set([])\n await self.config.guild(ctx.guild).standings.set({})\n await self.config.guild(ctx.guild).cupstandings.set({})\n await self.config.guild(ctx.guild).stats.set({})\n await self.config.guild(ctx.guild).cupstats.set({})\n await self.config.guild(ctx.guild).transfers.set({})\n await self.config.guild(ctx.guild).transferred.set([])\n await self.config.guild(ctx.guild).tots.set({\"players\": {}, \"kit\": None, \"logo\": None})\n await ctx.tick()\n\n @clear.command(name=\"stats\")\n async def clear_stats(self, ctx):\n \"\"\"Clear standings and player stats.\"\"\"\n confirm = await checkReacts(\n self, ctx, \"This will clear standings, teams stats, and player stats. Proceed ?\"\n )\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).standings.set({})\n teams = await self.config.guild(ctx.guild).teams()\n async with self.config.guild(ctx.guild).standings() as standings:\n for team in teams:\n standings[team] = {\n \"played\": 0,\n \"wins\": 0,\n \"losses\": 0,\n \"points\": 0,\n \"gd\": 0,\n \"gf\": 0,\n \"ga\": 0,\n \"draws\": 0,\n \"reds\": 0,\n \"yellows\": 0,\n \"fouls\": 0,\n \"chances\": 0,\n }\n await self.config.guild(ctx.guild).stats.set({})\n await ctx.tick()\n\n @clear.command(name=\"notes\")\n async def clear_notes(self, ctx):\n \"\"\"Clear player notes.\"\"\"\n confirm = await checkReacts(self, ctx, \"This will clear all player notes. Proceed ?\")\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).notes.set({})\n await ctx.tick()\n\n @clear.command(name=\"cupstats\")\n async def clear_cupstats(self, ctx):\n \"\"\"Clear cup stats.\"\"\"\n confirm = await checkReacts(\n self,\n ctx,\n \"This will clear cup standings, teams cup stats, and player cup stats. Proceed ?\",\n )\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).cupstandings.set({})\n teams = await self.config.guild(ctx.guild).teams()\n async with self.config.guild(ctx.guild).cupstandings() as cupstandings:\n for team in teams:\n cupstandings[team] = {\n \"played\": 0,\n \"wins\": 0,\n \"losses\": 0,\n \"points\": 0,\n \"gd\": 0,\n \"gf\": 0,\n \"ga\": 0,\n \"draws\": 0,\n \"reds\": 0,\n \"yellows\": 0,\n \"fouls\": 0,\n \"chances\": 0,\n }\n await self.config.guild(ctx.guild).cupstats.set({})\n await ctx.tick()\n\n @clear.command(name=\"transfers\")\n async def clear_transfers(self, ctx):\n confirm = await checkReacts(\n self, ctx, \"This will clear transfers for the current window. Proceed ?\"\n )\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).transferred.set([])\n await ctx.tick()\n\n @clear.command(name=\"lock\")\n async def clear_lock(self, ctx, team=None):\n confirm = await checkReacts(\n self, ctx, \"This will clear contract extensions for the current window. Proceed ?\"\n )\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n teams = await self.config.guild(ctx.guild).teams()\n if team is not None and team not in teams:\n return await ctx.send(\"This team does not exist.\")\n async with self.config.guild(ctx.guild).transfers() as transfers:\n if team is not None:\n transfers[team][\"locked\"] = None\n else:\n for t in transfers:\n transfers[t][\"locked\"] = None\n await ctx.tick()\n\n @clear.command(name=\"fixtures\")\n async def clear_fixtures(self, ctx):\n confirm = await checkReacts(self, ctx, \"This will clear all fixtures. Proceed ?\")\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).fixtures.set([])\n await ctx.tick()\n\n @clear.command(name=\"cup\")\n async def clear_cup(self, ctx):\n confirm = await checkReacts(\n self, ctx, \"This will clear cup fixtures, and cup stats. Proceed ?\"\n )\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).cupgames.set({})\n await self.config.guild(ctx.guild).cupstats.set({})\n await ctx.tick()\n\n @clear.command(name=\"palmares\")\n async def clear_palmares(self, ctx):\n confirm = await checkReacts(self, ctx, \"This will clear all palmares. Proceed ?\")\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).palmares.set({})\n await ctx.tick()\n\n @clear.command(name=\"palmaresseason\")\n async def clear_palmares(self, ctx, season: str):\n confirm = await checkReacts(\n self, ctx, \"This will clear all palmares for season {}. Proceed ?\".format(season)\n )\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n async with self.config.guild(ctx.guild).palmares() as palmares:\n for userid in palmares:\n if season in palmares[userid]:\n del palmares[userid][season]\n await ctx.tick()\n\n @clear.command(name=\"tots\")\n async def clear_tots(self, ctx):\n confirm = await checkReacts(self, ctx, \"This will clear TOTS data. Proceed ?\")\n if confirm == False:\n return await ctx.send(\"Cancelled.\")\n await self.config.guild(ctx.guild).tots.set({\"players\": {}, \"kit\": None, \"logo\": None})\n await ctx.tick()\n","sub_path":"simleague/simset.py","file_name":"simset.py","file_ext":"py","file_size_in_byte":44102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"641598436","text":"from jawa.attributes.inner_classes import InnerClass\n\n\ndef test_inner_classes_read(loader):\n cf = loader['InnerClasses']\n a = cf.attributes.find_one(name='InnerClasses')\n assert a.inner_classes == [\n InnerClass(\n inner_class_info_index=4,\n outer_class_info_index=2,\n inner_name_index=5,\n inner_class_access_flags=2\n )\n ]\n\n\ndef test_exceptions_write(loader):\n cf = loader['InnerClasses']\n a = cf.attributes.find_one(name='InnerClasses')\n assert a.pack() == b'\\x00\\x01\\x00\\x04\\x00\\x02\\x00\\x05\\x00\\x02'\n","sub_path":"tests/attributes/test_inner_classes.py","file_name":"test_inner_classes.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"234656694","text":"import tensorflow as tf\nimport numpy as np\nimport time\nimport os\n\ninput_data = np.random.random((32,64,64,3))\n\ninput = tf.placeholder(dtype=tf.float32, shape=[32,64,64,3])\ntemp_1 = tf.layers.dense(input, 3)\n#branch 1\nfilter1 = np.random.random((256,256,3,3))\nconv1 = temp_1\nconv1 = tf.concat([conv1, conv1], 1)\nconv1 = tf.concat([conv1, conv1], 1)\nconv1 = tf.concat([conv1, conv1], 2)\nconv1 = tf.concat([conv1, conv1], 2)\nfor i in range(100):\n conv1 = tf.nn.conv2d(conv1, filter1, [1,2,2,1], 'SAME')\n conv1 = tf.layers.dense(conv1, 3)\nconv1 = tf.nn.max_pool(conv1, [1,4,4,1], [1,4,4,1], 'SAME')\n#with tf.device('/gpu:1'):\n#branch 2\nfilter2 = np.random.random((256,256,3,3))\nconv2 = temp_1\nconv2 = tf.concat([conv2, conv2], 1)\nconv2 = tf.concat([conv2, conv2], 1)\nconv2 = tf.concat([conv2, conv2], 2)\nconv2 = tf.concat([conv2, conv2], 2)\nfor i in range(100):\n conv2=tf.nn.conv2d(conv2, filter2, [1,2,2,1], 'SAME')\n conv2=tf.layers.dense(conv2, 3)\nconv2 = tf.nn.max_pool(conv2, [1,4,4,1], [1,4,4,1], 'SAME')\n\n#branch3\nfilter3 = np.random.random((256,256,3,3))\nconv3 = temp_1\nconv3 = tf.concat([conv3, conv3], 1)\nconv3 = tf.concat([conv3, conv3], 1)\nconv3 = tf.concat([conv3, conv3], 2)\nconv3 = tf.concat([conv3, conv3], 2)\nfor i in range(100):\n conv3=tf.nn.conv2d(conv3, filter3, [1,2,2,1], 'SAME')\n conv3=tf.layers.dense(conv3, 3)\nconv3 = tf.nn.max_pool(conv3, [1,4,4,1], [1,4,4,1], 'SAME')\n\nres = tf.concat([tf.concat([conv1, conv2], -1), conv3], -1)\n\nsess = tf.Session()\n#os.rename('/home/v-yali6/workspace_yal/rldp/Trial/inception/replace_init.txt', '/home/v-yali6/workspace_yal/rldp/Trial/inception/replace.txt')\nsess.run(tf.global_variables_initializer())\n#os.rename('/home/v-yali6/workspace_yal/rldp/Trial/inception/replace.txt', '/home/v-yali6/workspace_yal/rldp/Trial/inception/replace_init.txt')\n\n#os.rename('/home/v-yali6/workspace_yal/rldp/Trial/inception/replace_train.txt', '/home/v-yali6/workspace_yal/rldp/Trial/inception/replace.txt')\nsess.run(res, feed_dict={input: input_data})\ntime_file = open('running_time.txt', 'w')\n#Train_writer = tf.summary.FileWriter('/tmp/mytestnet0', sess.graph)\nstart = time.time()\nfor i in range(5):\n sess.run(res, feed_dict={input: input_data})\ntime_file.write(str((time.time() - start) / 5))\n#print(end - start)\n#os.rename('/home/v-yali6/workspace_yal/rldp/Trial/inception/replace.txt', '/home/v-yali6/workspace_yal/rldp/Trial/inception/replace_train.txt')\nsess.close()\n\n","sub_path":"Trial/inception/test_net_0_baseline.py","file_name":"test_net_0_baseline.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"582705896","text":"class Solution:\n # 这题还可以用栈,还没看,可以看官方题解。\n # 我用的递归方法。思路就是:遍历,如果是字符,就加到res中。\n # 如果是数字,找完连续的一块数字 作为倍数,然后找接下来的[]内字符串的开始结束索引。\n # 然后对sub_str递归调用本函数,来解决。(因为子字符串内可能还是有[])\n def decodeString(self, s: str) -> str:\n # 递归\n # 遍历字符串,找到 数字+ [] 的始末索引, 正常字符串,\n # 对[] 内递归\n\n res = ''\n\n idx = 0\n while idx < len(s):\n if s[idx].isalpha():\n res += s[idx]\n elif s[idx].isdigit():\n times = s[idx]\n idx += 1\n while s[idx].isdigit():\n times += s[idx]\n idx += 1\n times = int(times)\n\n # 计数一下内部嵌套的左括号\n left_kuohao = 1\n start = idx + 1\n while left_kuohao > 0:\n idx += 1\n if s[idx] == '[':\n left_kuohao += 1\n elif s[idx] == ']':\n left_kuohao -= 1\n\n tmp_str = self.decodeString(s[start:idx])\n\n res += times * tmp_str\n\n idx += 1\n return res\n \n\n# 二刷,我写的栈方法,比上面的递归要简单些。\nclass Solution:\n def decodeString(self, s: str) -> str:\n # 用栈,当遇到右括号,开始弹栈,遇到左括号时,中间的就是要重复的;然后继续弹出,\n # 左括号到字母之间的数字,表示���复的次数。\n stack = []\n for i in s:\n if i != ']':\n stack.append(i)\n else:\n tmp = ''\n while stack[-1] != '[':\n tmp = stack.pop() + tmp\n # 弹出左括号\n stack.pop()\n tmp1 = 0\n pow_nums = 0\n while stack and stack[-1].isdigit():\n tmp1 += int(stack.pop()) * 10 ** pow_nums\n pow_nums += 1\n stack.append(tmp * tmp1)\n return ''.join(stack)\n","sub_path":"题目/栈/394. 字符串解码.py","file_name":"394. 字符串解码.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"471294466","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n\n\nimport argparse\nimport sys\nimport os.path\nfrom urlparse import urlparse\nfrom urllib import urlopen\nfrom rdflib import Graph\n\nfrom lxml import etree\n\nfrom common.converter import XMLTransform\nfrom common import utils\n\nthis_dir = os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))\n\nSTYLESHEET_EXTRACT = os.path.join(this_dir, 'vcard2mlr.xsl')\nSTYLESHEET_DUP = os.path.join(this_dir, 'removedup.xsl')\n\nURL_MLR = 'http://standards.iso.org/iso-iec/19788/'\n\"\"\" The URL for the MLR standards, as a namespace.\"\"\"\n\nURL_MLR_EXT = URL_MLR + 'ext/'\n\"\"\"A namespace for XSLT utility extensions\"\"\"\n\n\"\"\" The stylesheet used by the converter.\"\"\"\n\n\ndef main():\n extensions = {(URL_MLR_EXT, 'vcard_uuid'): utils.vcard_uuid}\n converterExtract = XMLTransform(STYLESHEET_EXTRACT, extensions)\n converterDup = XMLTransform(STYLESHEET_DUP)\n parser = argparse.ArgumentParser(\n description='Extend the vcard of a lom into a xcard')\n parser.add_argument('-f', '--format', default='rawxml',\n help=\"output format: one of 'rawxml', 'xml', 'n3',\"\n \" 'turtle', 'nt', 'pretty-xml', trix'\")\n parser.add_argument('-o', '--output', help=\"Output file\",\n type=argparse.FileType('w'), default=sys.stdout)\n parser.add_argument('infile', help=\"input file or url\", nargs=\"?\")\n converterExtract.populate_argparser(parser)\n #converterDup.populate_argparser(parser)\n args = parser.parse_args()\n converterExtract.set_options_from_dict(vars(args))\n #converterDup.set_options_from_dict(vars(args))\n \n if (urlparse(args.infile).scheme):\n opener = urlopen\n else:\n opener = open\n\n with opener(args.infile) as infile:\n xml = converterExtract.convertfile(infile)\n if xml:\n xml = converterDup.convertxml(xml)\n if xml:\n if args.format == \"rawxml\":\n args.output.write(etree.tounicode(xml, pretty_print=True).encode('utf-8'))\n else:\n rdf = Graph().parse(data=etree.tounicode(xml), format=\"xml\")\n if rdf:\n args.output.write(rdf.serialize(format=args.format, encoding='utf-8'))\n args.output.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"extractvcard/extractvcard.py","file_name":"extractvcard.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"22682030","text":"# coding: utf-8\n#! /usr/bin/env python3\n\n\"\"\"File used to launch the application\nWe manage the argument with the argv import\nThis argument corresponds to the mode of the database_manager\nCreate mode for the first launch and normal for the following ones\npython launcher.py database for creation (first launch)\npython launcher.py for the following\n\"\"\"\n\n# Standard library import\nfrom sys import argv\nfrom sys import exit\n\n# Local application imports\nfrom database.database_manager import DataBaseManager\nfrom app.application_manager import ApplicationManager\n\ndef check_argv():\n \"\"\"We get an additional argument thanks to the argv module\n\n Returns:\n Str: Normal or create mode for the creation of the database\n \"\"\"\n if len(argv) == 2 and argv[1] == \"database\":\n return \"create\"\n if len(argv) == 1:\n return \"normal\"\n exit(\"Create database: python launcher.py database\\nUsage: python launcher.py\")\n\ndef main():\n \"\"\"Function to launch the application\n We use aggregation and create 2 main instances\n One to manage the database\n The second to manage the application\n \"\"\"\n mode = check_argv()\n database_manager = DataBaseManager(mode)\n\n if mode == \"create\":\n exit(\"Création de la base de données terminée avec succès\")\n\n application_manager = ApplicationManager(database_manager)\n application_manager.run()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"launcher.py","file_name":"launcher.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"106508246","text":"from django.urls import path,include\nfrom . import views\nfrom rest_framework import routers\n\nrouter=routers.DefaultRouter()\nrouter.register('Books',views.Book_API_View)\nrouter.register('BarCode',views.Code_API_View)\nrouter.register('Authors',views.Author_API_View)\nrouter.register('Logs',views.Log_API_View)\nrouter.register('Users',views.User_API_View)\nurlpatterns = [\n path('', views.main_page, name='index'),\n path('books/', views.Books.as_view(), name='books'),\n path('authors/',views.Authors.as_view(), name='authors'),\n path('logs/',views.Logged.as_view(), name='logs'),\n #path('admins/',views.admin, name='admin'),\n path('bookadd/',views.book_add_view, name='bookadd'),\n path('barcodeadd/',views.barcodeadd, name='barcodeadd'),\n path('authoradd/',views.authoradd, name='authoradd'),\n path('useradd/',views.useradd, name='useradd'),\n path('log/',views.logger, name='logger'),\n path('API/',include(router.urls)),\n #path('book/', views.BookDetailView.as_view(), name='book-detail'), \n]\n","sub_path":"bookshelf/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"206130459","text":"def verbing(s):\n if len(s) < 3:\n verb = s\n elif s[-3:] == \"ing\":\n verb = s.replace(s[-3:], \"ly\")\n else:\n verb = \"\".join([s, \"ing\"])\n return verb\n\nverbing(\"aaaaing\")\nverbing(\"adsf\")\nverbing(\"qw\")\n\n\na = [\"not\", \"bad\"]\n\ndinner = \"this dinner is not so bad\"\nimport re\n\"is not\" in dinner\n\nre.sub(\"not*bad\", \"good\", dinner)\n\ndinner.replace(\"not * bad\", \"good\")\n\ndir(dinner)\n\ndinner.split(\" \")\n\n\ndinner.split().index(\"not\")\ndinner.split()[3:]\ndinner = \"this dinner is not so bad\"\n\nw = re.search('not', dinner)\n\ndinner.find(\"n\")\n\n\nif w:\n found = w.group(1)\n\nfound\n\nprint(w.group(1))\n\n[\"not\", \"bad\"] in dinner\n\nif \"not\" in dinner.split(\" \"):\n dinner = dinner.replace(\"not\", \"\")\nif \"bad\" in dinner.split(\" \"):\n dinner = dinner.replace(\"bad\", \"\")\ndinner = dinner + \"good\"\ndinner = \" \".join(dinner.split())\nreturn dinner\n\nprint(dinner)\n","sub_path":"modulo_01/google-python-exercises/basic/my-string1.py","file_name":"my-string1.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"341485641","text":"from __future__ import print_function\n\nimport os\nfrom skimage.transform import resize\nfrom skimage.io import imsave\nimport numpy as np\nfrom keras.models import Model\nfrom keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose, Dropout\nfrom keras.optimizers import Adam\nfrom keras.callbacks import ModelCheckpoint,ReduceLROnPlateau,EarlyStopping,CSVLogger\nfrom keras import backend as K\nfrom keras.models import load_model\n\nK.set_image_data_format('channels_last') # TF dimension ordering in this code\n\nimg_rows = 128\nimg_cols = 128\n\nsmooth = 1.\n\n# Change this flag if you want to start the training from scratch\nreloadFlag = True\n\noldmodelwtsfname = 'short_weights_dil1x_4conn_cshpaper_normalize_dropout.h5'\nmodelwtsfname = 'short_weights_dil1x_4conn_cshpaper_normalize_dropout.h5'\n\n\ndef dice_coef(y_true, y_pred):\n y_true_f = K.flatten(y_true)\n y_pred_f = K.flatten(y_pred)\n intersection = K.sum(y_true_f * y_pred_f)\n return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)\n\n\ndef dice_coef_loss(y_true, y_pred):\n return -dice_coef(y_true, y_pred)\n\ndef get_unet_short_dropout():\n inputs = Input((img_rows, img_cols, 1))\n conv1 = Conv2D(64, (3, 3), activation='relu', padding='same')(inputs)\n conv1 = Dropout(0.2)(conv1) \n conv1 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n\n conv2 = Conv2D(128, (3, 3), activation='relu', padding='same')(pool1)\n conv2 = Dropout(0.2)(conv2) \n conv2 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n\n conv3 = Conv2D(256, (3, 3), activation='relu', padding='same')(pool2)\n conv3 = Dropout(0.2)(conv3) \n conv3 = Conv2D(256, (3, 3), activation='relu', padding='same')(conv3)\n\n up3 = concatenate([Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same')(conv3), conv2], axis=3)\n conv4 = Conv2D(128, (3, 3), activation='relu', padding='same')(up3)\n conv4 = Dropout(0.2)(conv4) \n conv4 = Conv2D(128, (3, 3), activation='relu', padding='same')(conv4)\n\n up4 = concatenate([Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same')(conv4), conv1], axis=3)\n conv5 = Conv2D(64, (3, 3), activation='relu', padding='same')(up4)\n conv5 = Dropout(0.2)(conv5) \n conv5 = Conv2D(64, (3, 3), activation='relu', padding='same')(conv5)\n\n conv6 = Conv2D(1, (1, 1), activation='sigmoid')(conv5)\n\n model = Model(inputs=[inputs], outputs=[conv6])\n\n return model\n\ndef train():\n\n print('-'*30)\n print('Loading and preprocessing train data...')\n print('-'*30)\n\n imgs_train_fr = np.load('../input_data/FarRed_Annotated_FISH_Dilation4Conn1Iter_Training_128by128_normalize.npy')\n imgs_mask_train_fr = np.load('../input_data/FarRed_Annotated_FISH_Dilation4Conn1Iter_Training_128by128_normalize_Mask.npy')\n imgs_train_r = np.load('../input_data/Red_Annotated_FISH_Dilation4Conn1Iter_Training_128by128_normalize.npy')\n imgs_mask_train_r = np.load('../input_data/Red_Annotated_FISH_Dilation4Conn1Iter_Training_128by128_normalize_Mask.npy')\n imgs_train_g = np.load('../input_data/Annotated_FISH_Dilation4Conn1Iter_Training_128by128_normalize.npy')\n imgs_mask_train_g = np.load('../input_data/Green_Annotated_FISH_Dilation4Conn1Iter_Training_128by128_normalize_Mask.npy')\n\n # Let's merge them -- we have to make sure that both are of same shape in axis 1 and 2 (x, y) which isn't checked here.\n imgs_train = np.concatenate((imgs_train_fr, imgs_train_r, imgs_train_g), axis=0) \n imgs_mask_train = np.concatenate((imgs_mask_train_fr, imgs_mask_train_r,imgs_mask_train_g), axis=0) \n\n\n imgs_train = imgs_train.astype('float32')\n\n imgs_mask_train = imgs_mask_train.astype('float32')\n imgs_mask_train /= 255. # scale masks to [0, 1]\n\n print('-'*30)\n print('Creating and compiling model...')\n print('-'*30)\n \n model = get_unet_short_dropout()\n model.compile(optimizer=Adam(lr=1e-5), loss=dice_coef_loss, metrics=[dice_coef])\n model.summary()\n\n # Loading previous weights for restarting\n if os.path.isfile(oldmodelwtsfname) and reloadFlag :\n print('-'*30)\n print('Loading previous weights ...')\n model.load_weights(oldmodelwtsfname)\n\n \n model_checkpoint = ModelCheckpoint(modelwtsfname, monitor='val_loss', save_best_only=True)\n reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1,patience=50, min_lr=0.001,verbose=1)\n model_es = EarlyStopping(monitor='val_loss', min_delta=0.00000001, patience=500, verbose=1, mode='auto')\n csv_logger = CSVLogger('short_weights_dil1x_4conn_cshpaper_normalize_dropout_training.log', append=True)\n\n print('-'*30)\n print('Fitting model...')\n print('-'*30)\n imgs_train = np.expand_dims(imgs_train, 3)\n imgs_mask_train = np.expand_dims(imgs_mask_train, 3)\n model.fit(imgs_train, imgs_mask_train, batch_size=2, epochs=5000, verbose=1, shuffle=True,\n validation_split=0.10, callbacks=[model_checkpoint, reduce_lr, model_es, csv_logger])\n\ndef predict():\n print('-'*30)\n print('Loading and preprocessing test data...')\n print('-'*30)\n\n imgs_test = np.load('../input_data/Green_Red_FarRed_Annotated_FISH_Dilation4Conn1Iter_Testing_128by128_normalize.npy')\n imgs_mask_test = np.load('../input_data/Green_Red_FarRed_Annotated_FISH_Dilation4Conn1Iter_Testing_128by128_normalize_Mask.npy')\n imgs_test = imgs_test.astype('float32')\n\n\n print('-'*30)\n print('Loading saved weights...')\n print('-'*30)\n\n model = get_unet_short_dropout()\n model.compile(optimizer=Adam(lr=1e-5), loss=dice_coef_loss, metrics=[dice_coef])\n model.summary()\n\n model.load_weights(modelwtsfname)\n\n print('-'*30)\n print('Predicting masks on test data...')\n print('-'*30)\n imgs_test = np.expand_dims(imgs_test,3)\n imgs_mask_test = model.predict(imgs_test, batch_size=256,verbose=1)\n np.save('../input_data/Green_Red_FarRed_Annotated_FISH_Dilation4Conn1Iter_Testing_128by128_normalize_dropout_Mask_Pred_cshpaper.npy', np.squeeze(imgs_mask_test))\n\nif __name__ == '__main__':\n train()\n predict()\n","sub_path":"Gudla_CSH_2017/CNN_Python_Keras_TF/training/train_short_normalized_dropout_csh_paper_npy.py","file_name":"train_short_normalized_dropout_csh_paper_npy.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"194569472","text":"import json\nimport argparse\n\npar = argparse.ArgumentParser()\npar.add_argument(\"-t\", \"--data_type\", default=\"q\",\n type=str, help=\"origin data path\",\n choices=['q', 'a', 'question', 'answer'])\nargs = par.parse_args()\n\nif 'q' in args.data_type:\n ori_path = 'question_mathQA_ori.json'\n refined_path = 'mathQA_question_1_to_1000.json'\n save_path = 'question_mathQA.json'\nelse:\n ori_path = 'answer_mathQA_ori.json'\n refined_path = 'mathQA_answer_1_to_1000.json'\n save_path = 'answer_mathQA.json'\n\nwith open(ori_path, 'r', encoding=\"utf-8\") as inputfile:\n ori_data = json.load(inputfile)\n\nwith open(refined_path, 'r', encoding=\"utf-8\") as inputfile:\n refined_data = json.load(inputfile)\n\ncount = 0\nfor k in refined_data.keys():\n ori_data[k] = refined_data[k]\n count += 1\n\nwith open(save_path, 'w', encoding=\"utf-8\") as outfile:\n json.dump(ori_data, outfile, indent=4, ensure_ascii=False)\n\nprint(\"{} data refine\".format(count))\n# python3 data_merge.py -t q\n","sub_path":"data/new_data_merge.py","file_name":"new_data_merge.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"592152192","text":"\"\"\"\nURL configuration for core app in hbattle project\n\"\"\"\nfrom django.conf.urls import patterns, url\n\nfrom hbattle.core import views\n\n# URL patterns for core app\nurlpatterns = patterns('hbattle.core.views',\n\n # primary core app views\n url(r'^$', 'home', name='home'),\n url(r'^battle/(\\d+)/$', 'battle', name='battle'),\n url(r'^error/$', 'error', name='error'),\n\n\n # REST API views\n url(r'^api/battle/$', views.APIBattleListView.as_view(),\n name='api-battle-list'),\n url(r'^api/battle/(?P\\d+)/player/$',\n views.APIBattlePlayerListView.as_view(),\n name='api-battle-player-list'),\n url(r'^api/battle/(?P\\d+)/start/$',\n views.APIBattleStartView.as_view(),\n name='api-battle-start'),\n )\n","sub_path":"hbattle/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"83176547","text":"from CTFd.constants import RawEnum\n\n\nclass Languages(str, RawEnum):\n ENGLISH = \"en\"\n GERMAN = \"de\"\n POLISH = \"pl\"\n SPANISH = \"es\"\n CHINESE = \"zh\"\n\n\nLANGUAGE_NAMES = {\n \"en\": \"English\",\n \"de\": \"Deutsch\",\n \"pl\": \"Polski\",\n \"es\": \"Español\",\n \"zh\": \"中文\",\n}\n\nSELECT_LANGUAGE_LIST = [(\"\", \"\")] + [\n (str(lang), LANGUAGE_NAMES.get(str(lang))) for lang in Languages\n]\n","sub_path":"CTFd/constants/languages.py","file_name":"languages.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"73525334","text":"from flask import Blueprint, render_template, redirect, url_for, request, flash\nfrom flask_login import login_user, logout_user, login_required, current_user\n\nfrom werkzeug.urls import url_parse\n\nfrom cmm_app import db\nfrom cmm_app.models import User\nfrom cmm_app.auth.forms import RegistrationForm, LoginForm\n\nauth = Blueprint('auth', __name__, template_folder='templates',\n static_folder='static')\n\n\n@auth.route('/register', methods=['GET', 'POST'])\ndef register():\n form = RegistrationForm(request.form)\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if not user:\n new_user = User(email=form.email.data)\n new_user.set_password(form.password.data)\n\n db.session.add(new_user)\n db.session.commit()\n\n url = url_for('auth.login')\n flash('Registration successful!', 'success')\n return redirect(url)\n\n flash('Email already exists!', 'danger')\n return render_template('auth/register.html', form=form)\n\n\n@auth.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n flash('You are already logged in!', 'warning')\n return redirect(url_for('dashboard.dashboard'))\n\n form = LoginForm(request.form)\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user and user.check_password(form.password.data):\n login_user(user, remember=form.remember_me.data)\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('dashboard.dashboard')\n return redirect(next_page)\n flash('Invalid credentials!', 'danger')\n return render_template('auth/login.html', form=form)\n\n\n@auth.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('You have been logged out!', 'success')\n return redirect(url_for('auth.login'))\n","sub_path":"cmm_app/auth/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"357328957","text":"from flask import request, jsonify, json\nfrom flask_restful import Resource\nfrom flask_jwt import jwt_required, current_identity\nfrom flasgger import swag_from\n\nfrom services.apex_report_service import ApexReportService\n# from services.vendor_service import VendorService\nfrom utils.util import model_to_dict\n\nclass ApexReportResource(Resource):\n\n apex_report_service = ApexReportService()\n\n @swag_from('../../spec/apex_report/search.yml')\n def post(self):\n try :\n res_data = self.apex_report_service.search()\n print(res_data)\n res_json = {'status': 1, 'data': [ model_to_dict(x) for x in res_data ]}\n print(res_json)\n except Exception as e:\n if e.args:\n res_data = e.args[0]\n else:\n res_data = e\n res_json = {'status': 0, 'data': res_data}\n return jsonify(res_json)\n\n @swag_from('../../spec/apex_report/entity.yml')\n def get(self):\n id = request.args['id']\n res_json = { }\n res_json['status']=1\n res_json['data'] = {}\n res_data = res_json['data']\n res_data['id']=id\n return jsonify(res_json)\n","sub_path":"src/resources/apex_report_resource.py","file_name":"apex_report_resource.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"129105193","text":"import socket\nimport pickle5 as pickle\nimport math\n\nHEADER_SIZE = 4\nHOST = \"127.0.0.1\"\nPORT = 12001\n\nden = 20\nrad = 100\ntheta = math.tau / den\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n sock.connect((HOST, PORT)) #connect to server\n\n for step in range(1000):\n i = step%den\n x = math.cos(i*theta) * rad\n y = math.sin(i*theta) * rad\n # data = pickle.dumps((x, y), protocol=0)\n data = b\"hello world\"\n # compute header by taking the byte representation of the int\n header = len(data).to_bytes(HEADER_SIZE, byteorder ='big')\n sock.sendall(header + data)","sub_path":"MultiConnection2_client.py","file_name":"MultiConnection2_client.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"24548513","text":"import lxml.etree\nimport lxml.objectify\nimport zeit.content.cp.testing\nimport zope.lifecycleevent\n\n\nclass OverflowBlocks(zeit.content.cp.testing.FunctionalTestCase):\n\n def setUp(self):\n super(OverflowBlocks, self).setUp()\n self.cp = zeit.content.cp.centerpage.CenterPage()\n self.region = self.cp.create_item('region')\n self.area1 = self.region.create_item('area')\n self.area2 = self.region.create_item('area')\n\n self.area1.block_max = 1\n self.area1.overflow_into = self.area2\n\n def test_adding_more_than_max_blocks_overflows_the_newly_added_block(self):\n t1 = self.area1.create_item('teaser').__name__\n t2 = self.area1.create_item('teaser').__name__\n self.assertEqual([t1], self.area1.keys())\n self.assertEqual([t2], self.area2.keys())\n\n def test_blocks_overflow_into_beginning_of_overflow_area(self):\n t1 = self.area1.create_item('teaser').__name__\n t2 = self.area1.create_item('teaser').__name__\n t3 = self.area1.create_item('teaser').__name__\n self.assertEqual([t1], self.area1.keys())\n # added t3 last, so should be first in overflow area\n self.assertEqual([t3, t2], self.area2.keys())\n\n def test_inserting_blocks_on_top_will_overflow_existing_block(self):\n t1 = self.area1.create_item('teaser', position=0).__name__\n t2 = self.area1.create_item('teaser', position=0).__name__\n t3 = self.area1.create_item('teaser', position=0).__name__\n # inserted t3 last, so should be the only teaser in area1\n self.assertEqual([t3], self.area1.keys())\n self.assertEqual([t2, t1], self.area2.keys())\n\n def test_apply_layout_for_lead_area_works_with_overflow(self):\n \"\"\"Test add and insert(0) when the apply_layout logic is active.\"\"\"\n self.area1.__name__ = 'lead'\n t1 = self.area1.create_item('teaser').__name__\n t2 = self.area1.create_item('teaser', position=0).__name__\n t3 = self.area1.create_item('teaser').__name__\n self.assertEqual([t2], self.area1.keys())\n self.assertEqual([t3, t1], self.area2.keys())\n\n def test_setting_overflow_into_none_is_allowed(self):\n self.area1.overflow_into = None\n self.assertEqual(None, self.area1.overflow_into)\n\n def test_overflow_works_across_multiple_areas(self):\n self.area3 = self.region.create_item('area')\n self.area2.block_max = 1\n self.area2.overflow_into = self.area3\n t1 = self.area1.create_item('teaser').__name__\n t2 = self.area1.create_item('teaser').__name__\n t3 = self.area1.create_item('teaser').__name__\n self.assertEqual([t1], self.area1.keys())\n # added t3 last, so should be first in overflow area\n self.assertEqual([t3], self.area2.keys())\n self.assertEqual([t2], self.area3.keys())\n\n def test_moving_area_below_target_removes_overflow(self):\n region2 = self.cp.create_item('region')\n del self.region[self.area1.__name__]\n region2.add(self.area1)\n self.assertEqual(None, self.area1.overflow_into)\n\n def test_moving_target_above_area_removes_overflow(self):\n region2 = self.cp.create_item('region')\n del self.region[self.area2.__name__]\n region2.add(self.area2)\n\n del region2[self.area2.__name__]\n self.region.insert(0, self.area2)\n self.assertEqual(None, self.area1.overflow_into)\n\n def test_moving_areas_with_proper_order_keeps_overflow(self):\n region2 = self.cp.create_item('region')\n del self.region[self.area2.__name__]\n region2.insert(0, self.area2)\n del self.region[self.area1.__name__]\n region2.insert(0, self.area1)\n self.assertNotEqual(None, self.area1.overflow_into)\n\n def test_sorting_areas_removes_overflow_if_ordered_wrong(self):\n self.region.updateOrder([self.area2.__name__, self.area1.__name__])\n self.assertEqual(None, self.area1.overflow_into)\n\n def test_reducing_block_max_overflows_excessive_blocks(self):\n self.area1.block_max = 2\n t1 = self.area1.create_item('teaser').__name__\n t2 = self.area1.create_item('teaser').__name__\n self.area1.block_max = 1\n zope.lifecycleevent.modified(\n self.area1, zope.lifecycleevent.Attributes(\n zeit.content.cp.interfaces.IArea, 'block_max'))\n self.assertEqual([t1], self.area1.keys())\n self.assertEqual([t2], self.area2.keys())\n\n\nclass AutomaticAreaTest(zeit.content.cp.testing.FunctionalTestCase):\n\n def setUp(self):\n super(AutomaticAreaTest, self).setUp()\n self.repository['cp'] = zeit.content.cp.centerpage.CenterPage()\n\n def test_fills_with_placeholders_when_set_to_automatic(self):\n lead = self.repository['cp']['lead']\n lead.count = 5\n lead.automatic = True\n lead.automatic_type = 'query'\n self.assertEqual(5, len(lead))\n\n def test_fills_with_placeholders_when_teaser_count_changed(self):\n lead = self.repository['cp']['lead']\n lead.count = 5\n lead.automatic = True\n lead.automatic_type = 'query'\n self.assertEqual(5, len(lead))\n lead.count = 7\n self.assertEqual(7, len(lead))\n\n def test_enabling_automatic_preserves_layout(self):\n lead = self.repository['cp']['lead']\n teaser = lead.create_item('teaser')\n teaser.volatile = True\n teaser.read_more = 'foo'\n teaser.layout = zeit.content.cp.layout.get_layout('two-side-by-side')\n lead.count = 1\n lead.automatic = True\n self.assertEqual(None, lead.values()[0].read_more)\n self.assertEqual('two-side-by-side', lead.values()[0].layout.id)\n\n def test_disabling_automatic_preserves_all_teaser_fields(self):\n lead = self.repository['cp']['lead']\n lead.count = 1\n lead.automatic = True\n auto = lead.values()[0]\n auto.read_more = 'foo'\n auto.layout = zeit.content.cp.layout.get_layout('two-side-by-side')\n lead.automatic = False\n self.assertEqual('foo', lead.values()[0].read_more)\n self.assertEqual('two-side-by-side', lead.values()[0].layout.id)\n\n def test_materializing_autopilot_marks_previous_automatic_teasers(self):\n lead = self.repository['cp']['lead']\n lead.count = 1\n lead.automatic = True\n lead.automatic = False\n [teaser] = lead.values()\n self.assertEqual(True, teaser.volatile)\n\n def test_adding_teaser_by_hand_uses_default_for_volatile(self):\n lead = self.repository['cp']['lead']\n teaser = lead.create_item('teaser')\n # assertFalse accepts None as well, so we use assertEqual explicitly\n self.assertEqual(False, teaser.volatile)\n\n def test_materializing_autopilot_keeps_manual_content(self):\n lead = self.repository['cp']['lead']\n lead.count = 0\n lead.automatic = True\n manual_teaser = lead.create_item('teaser')\n\n lead.automatic = False\n self.assertEqual(1, len(lead))\n self.assertEqual([manual_teaser], lead.values())\n\n def test_changing_automatic_count_also_counts_manual_content(self):\n lead = self.repository['cp']['lead']\n lead.count = 2\n lead.automatic = True\n\n manual_teaser = lead.create_item('teaser')\n self.assertEqual(2, len(lead))\n\n lead.count = 1\n self.assertEqual(1, len(lead))\n self.assertEqual([manual_teaser], lead.values())\n\n lead.count = 3\n self.assertEqual(3, len(lead))\n self.assertEqual(manual_teaser, lead.values()[0])\n\n def test_reducing_automatic_count_does_not_delete_manual_content(self):\n lead = self.repository['cp']['lead']\n lead.count = 1\n lead.automatic = True\n manual_teaser = lead.create_item('teaser')\n\n lead.count = 0\n self.assertEqual(1, len(lead))\n self.assertEqual([manual_teaser], lead.values())\n\n def test_autopilot_allows_more_manual_content_than_automatic_count(self):\n lead = self.repository['cp']['lead']\n lead.count = 1\n lead.automatic = True\n teaser1 = lead.create_item('teaser')\n teaser2 = lead.create_item('teaser')\n self.assertEqual(2, len(lead))\n self.assertEqual([teaser1, teaser2], lead.values())\n\n def test_adding_manual_teaser_automatically_removes_last_auto_teaser(self):\n lead = self.repository['cp']['lead']\n lead.count = 2\n lead.automatic = True\n auto_teaser1, auto_teaser2 = lead.values()\n manual_teaser = lead.create_item('teaser')\n self.assertEqual([auto_teaser1, manual_teaser], lead.values())\n\n def test_removing_manual_teaser_automatically_adds_auto_teaser(self):\n from zeit.content.cp.interfaces import IAutomaticTeaserBlock\n\n lead = self.repository['cp']['lead']\n lead.count = 2\n lead.automatic = True\n manual_teaser1 = lead.create_item('teaser')\n manual_teaser2 = lead.create_item('teaser')\n self.assertEqual([manual_teaser1, manual_teaser2], lead.values())\n\n del lead[manual_teaser1.__name__]\n self.assertNotIn(manual_teaser1, lead.values())\n self.assertIn(manual_teaser2, lead.values())\n self.assertTrue(IAutomaticTeaserBlock.providedBy(lead.values()[-1]))\n\n def test_enabling_automatic_removes_all_auto_generated_blocks(self):\n lead = self.repository['cp']['lead']\n lead.count = 1\n teaser = lead.create_item('teaser')\n teaser.volatile = True # generated by AutoPilot\n lead.automatic = True\n self.assertEqual(['auto-teaser'], [x.type for x in lead.values()])\n\n def test_enabling_automatic_keeps_blocks_not_added_by_autopilot(self):\n lead = self.repository['cp']['lead']\n lead.count = 1\n teaser = lead.create_item('teaser')\n teaser.volatile = False # not generated by AutoPilot\n lead.automatic = True\n self.assertEqual([teaser], lead.values())\n\n def test_enabling_automatic_keeps_order_of_manually_placed_blocks(self):\n lead = self.repository['cp']['lead']\n lead.count = 3\n\n teaser1 = lead.create_item('teaser')\n teaser1.volatile = True\n teaser2 = lead.create_item('teaser')\n teaser2.volatile = False\n teaser3 = lead.create_item('teaser')\n teaser3.volatile = True\n\n lead.automatic = True\n self.assertEqual(\n ['auto-teaser', 'teaser', 'auto-teaser'],\n [x.type for x in lead.values()])\n\n def test_enabling_automatic_does_not_break_on_updateOrder(self):\n \"\"\"update_autopilot handler might interfere and creates new blocks\"\"\"\n lead = self.repository['cp']['lead']\n lead.count = 3\n teaser = lead.create_item('teaser')\n teaser.volatile = True\n\n with self.assertNothingRaised():\n lead.automatic = True\n\n def test_disabling_automatic_keeps_order_of_teasers(self):\n from zeit.cms.testcontenttype.testcontenttype import ExampleContentType\n self.repository['t1'] = ExampleContentType()\n self.repository['t2'] = ExampleContentType()\n\n lead = self.repository['cp']['lead']\n lead.count = 2\n lead.automatic = True\n lead.create_item('teaser')\n lead.count = 3\n\n order = lead.keys()\n lead.automatic = False\n self.assertEqual(order, lead.keys())\n\n\nclass AreaDelegateTest(zeit.content.cp.testing.FunctionalTestCase):\n\n def setUp(self):\n super(AreaDelegateTest, self).setUp()\n self.repository['cp'] = zeit.content.cp.centerpage.CenterPage()\n self.area = self.repository['cp']['feature'].create_item('area')\n other = zeit.content.cp.centerpage.CenterPage()\n other.title = 'referenced'\n other.supertitle = 'supertitle'\n self.repository['other'] = other\n self.area.referenced_cp = self.repository['other']\n zope.lifecycleevent.modified(\n self.area, zope.lifecycleevent.Attributes(\n zeit.content.cp.interfaces.IArea, 'referenced_cp'))\n\n def test_attributes_from_referenced_cp_are_copied(self):\n self.assertEqual('referenced', self.area.title)\n self.assertEqual('supertitle', self.area.supertitle)\n\n def test_local_value_takes_precendence(self):\n self.assertEqual('referenced', self.area.title)\n self.area.title = 'local'\n self.assertEqual('local', self.area.title)\n\n def test_local_value_is_not_overwritten(self):\n self.area.title = 'local'\n self.assertEqual('local', self.area.title)\n zope.lifecycleevent.modified(\n self.area, zope.lifecycleevent.Attributes(\n zeit.content.cp.interfaces.IArea, 'referenced_cp'))\n self.assertEqual('local', self.area.title)\n\n def test_read_more_url_is_generated_from_cp(self):\n self.assertEqual('http://www.zeit.de/other', self.area.read_more_url)\n\n\nclass CustomQueryTest(zeit.content.cp.testing.FunctionalTestCase):\n\n def setUp(self):\n super(CustomQueryTest, self).setUp()\n self.repository['cp'] = zeit.content.cp.centerpage.CenterPage()\n\n def test_serializes_via_dav_converter(self):\n area = self.repository['cp']['lead']\n source = zeit.cms.content.interfaces.ICommonMetadata['serie'].source(\n None)\n autotest = source.find('Autotest')\n area.query = (('serie', 'eq', autotest),)\n lxml.objectify.deannotate(area.xml, cleanup_namespaces=True)\n self.assertEllipsis(\n 'Autotest',\n lxml.etree.tostring(area.xml.query))\n self.assertEqual((('serie', 'eq', autotest),), area.query)\n","sub_path":"src/zeit/content/cp/tests/test_area.py","file_name":"test_area.py","file_ext":"py","file_size_in_byte":13709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"524902368","text":"import argparse\nfrom datetime import datetime\nimport requests\nimport whois\n\n\ndef load_urls4check(path):\n with open(path) as urls_file:\n for url in urls_file:\n yield url.strip()\n\n\ndef is_server_respond_with_200(url):\n response = requests.get(url)\n return response.status_code == requests.codes.ok\n\n\ndef get_domain_expiration_date(domain_name):\n domain_info = whois.whois(domain_name)\n expiry_date = domain_info.expiration_date\n if isinstance(expiry_date, list):\n return expiry_date[0]\n return expiry_date\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('filepath', help='path of file with urls')\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n args = get_arguments()\n path_to_file_with_urls = args.filepath\n urls_for_check = load_urls4check(path_to_file_with_urls)\n for url in urls_for_check:\n print(url)\n print('\\tHTTP response status is 200:',\n 'ok' if is_server_respond_with_200(url) else 'False'\n )\n expiry_date = get_domain_expiration_date(url)\n if expiry_date:\n prepaid_period = (expiry_date - datetime.now()).days\n print('\\tDomain prepaid one month ahead:', end=' ')\n if prepaid_period > 30:\n print('ok')\n else:\n print('NO. Domain expires {}'.format(expiry_date))\n else:\n print('\\tExpiry date cannot be evaluated.\\n')\n","sub_path":"check_sites_health.py","file_name":"check_sites_health.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"303381811","text":"from __future__ import division\nimport math\nfrom game.models import *\n\n#------------------------------------USER RELIABILITY STATS----------------------------------#\n# new_spread = 0.75* diff(last_pin_gps, this_pin_gps) + 0.25 * diff(last_bearing, this_bearing)\ndef get_spread(image_pin, latitude, longitude, bearing, is_first):\n if is_first:\n return 0\n raw_distance = get_distance_between_points(image_pin.image_avg_lat, image_pin.image_avg_lng, latitude, longitude)\n raw_bearing = abs(image_pin.image_avg_bearing - bearing) # we store everything in degrees\n return 0.75 * raw_distance + 0.25 * raw_bearing\n\n# user_v = (last_spread * numpins + new_spread) / numpins <-- not numpins + 1\n# for second human pin, last user_v will be 0, numpins will be 1 so multiplied by 0, hence new user_v = new spread / 1\n# for third, last_user_v will be ^, multiplied by 1, hence new_user_v = (old spread + new_spread) / 2 \ndef get_user_v(last, new_spread, is_first):\n if is_first:\n return 0\n pins_sum = math.fsum([last.user_v*(last.user_pins-1), new_spread])\n return float(pins_sum) / last.user_pins\n\n#------------------------------------IMAGE RELIABILITY STATS---------------------------------#\n# new_image_v = (last_v_top + user_r * spread) / (last_v_bottom + user_r) \n# for first, spread = 0, user_v = 0, last_user_r = 1, new top = 0, new bottom = 1 => image_v = 0\n# in second human pin, the new spread will be the true difference between the avg_gps and new_gps data, last_user_v = 0 so user_v = the new spread, last_user_r = 1 (see *), so image_v_top = 1 * spread, image_v_bottom = 0 + 1 (zero because of else statement, it is actually 1), see **), image_v = spread.\n# in third human pin, the new spread will be true diff between agv_gps and new_gps, last_user_pins = 2, new user_v = (old_v*1 + new_spread) / 2, last_user_r = 1/old_spread since we are in the third pin and v != 0, image_v_top = old_spread*1 + last_user_r * true spread, image_v_bottom = 1 + last_user_r, hence image_v = the average of old_spread and the new true spread. \ndef get_image_v(new_top, new_bottom):\n return float(new_top) / new_bottom\n\ndef get_image_v_top(last, spread, last_user_r):\n return last.image_v_top + (last_user_r * spread)\n\ndef get_image_v_bottom(last, last_user_r, is_first):\n if is_first:\n # first pin, avoid / by 0\n return 1\n elif (last.image_pins == 1):\n # second pin, minus one!! since the first pin did not count!\n return 1\n return last.image_v_bottom + last_user_r\n\n# when is_first is true, this is being evaluated during first pin, for the reliability for the last pin (i.e. dummy pin), last_user_v = 0 hence last_user_r = 1, the result of the 1st pin is user_v is 0\n# * hence in second pin, last_user_v = 0, to avoid dividing by 0, last_user_r = 1 again\n# first two cases, v = 0, but separate for clarity \ndef user_r_from_v(v, is_first):\n if (v == 0 or is_first):\n return 1\n return float(1) / v\n\n#------------------------------------IMAGE GPS STATS----------------------------------------#\n# new_lat = (last_image_r * last_avg_lat + user_r * lat) / image_r + user_r\n# for first human pin, last_image_r = 0, user_r = 1, so we just get lat\n# for second human pin, remember we are using it always at the start of the insertion for the LAST pin! last_image_v = 0, hence image_r_from_v produces 0, last_user_r = 1, hence the new image_lat = (0*last_lat + 1*new_lat) / 1 \n# for third human pin, last_image_v = true spread between 1st and 2nd pins, num_pins = LAST_num_pins = 2, last_image_r = log(2) * 1/true_spread (the first spread measurement, multiplied by trustworthiness factor of log(2)), last_user_v = old_spread, hence the new image_lat = (last_image_r * last_lat + 1/old_spread * new lat) / (last_image_r + 1/old_spread) \n\ndef calc_image_lat(last_image_r, last_image_lat, latitude, last_user_r):\n return (last_image_r * last_image_lat + last_user_r * latitude) / (last_image_r + last_user_r)\n\ndef calc_image_lng(last_image_r, last_image_lng, longitude, last_user_r):\n return (last_image_r * last_image_lng + last_user_r * longitude) / (last_image_r + last_user_r)\n\ndef calc_image_bearing(last_image_r, last_image_bearing, bearing, last_user_r):\n return (last_image_r * last_image_bearing + last_user_r * bearing) / (last_image_r + last_user_r)\n\ndef image_r_from_v(v, num_pins, is_first):\n if is_first:\n return 0\n elif (v == 0):\n return 0\n else:\n return math.log(abs(num_pins)) * (float(1) /v)\n\n#------------------------------------USER SCORE STATS----------------------------------------#\n# insertion mechanism\ndef update_score(user_id, other_user_id, image_id, session_id, robot_session_id):\n if (other_user_id != None):\n user_set = Pins_Data.objects.filter(user_id = user_id, image_id=image_id, session_id = session_id)\n user = user_set[0]\n other_user_set = Pins_Data.objects.filter(user_id = other_user_id, image_id = image_id, session_id = session_id)\n other_user = other_user_set[0]\n\n # work out the score\n diff = get_score(user.lat1, user.lng1, user.bearing, \\\n other_user.lat1, other_user.lng1, other_user.bearing)\n # add the increment\n user_new_score = int(user.user_score + diff)\n other_user_new_score = int(other_user.user_score + diff)\n\n # update database\n user_set.update(user_score = user_new_score, user_status = user_status_from_score(user_new_score), updated = 1)\n other_user_set.update(user_score = other_user_new_score, user_status = user_status_from_score(other_user_new_score), updated = 1)\n \n else:\n user_set = Pins_Data.objects.filter(user_id = user_id, image_id=image_id, session_id = session_id)\n user = user_set[0]\n other_user = Pins_Data.objects.filter(image_id = image_id, session_id = robot_session_id)[0]\n\n # work out the score\n diff = get_score(user.lat1, user.lng1, user.bearing, \\\n other_user.image_avg_lat, other_user.image_avg_lng, other_user.image_avg_bearing)\n # add the increment\n user_new_score = int(user.user_score + diff)\n\n # update database\n user_set.update(user_score = user_new_score, user_status = user_status_from_score(user_new_score), updated = 1)\n \n # return the one which is NOT the other player\n return user_new_score\n\n\ndef get_score(lat_0, lng_0, b_0, lat_1, lng_1, b_1):\n # raw data\n raw_distance = 1000*get_distance_between_points(lat_0, lng_0, lat_1, lng_1) # IN METRES!!!\n raw_bearing = abs(b_0 - b_1)\n \n # calculate weight of score_distance, which varies between 50% and 100%\n if (raw_distance > 1000):\n weight_distance = 1\n else:\n # raw_dist must be between 0 and 1000 inclusive\n weight_distance = 0.5 + (raw_distance / 2000)\n \n # fit curves to raw data, yeilding two numbers between 0 and 100\n score_distance = max(0, 100 - (raw_distance / 10)) #max(0, -math.exp((raw_distance * math.log(101))/1000) + 101)\n score_bearing = max(0, 50 * (math.cos(math.radians(raw_bearing)) + 1))\n\n # finally return the weighted score\n # as distance gets larger, its significance gets bigger\n return weight_distance * score_distance + (1-weight_distance) * score_bearing\n\n# Returns score (integer division) 10 to get status as an int\ndef user_status_from_score(score):\n status = 0\n if score >= 250 and score < 1000:\n status = 1\n elif score >= 1000:\n status = score / 500\n return status\n\n#------------------------------------ HELPERS ----------------------------------------#\n\ndef get_distance_between_points(latitude1, longitude1, latitude2, longitude2):\n radius = 6371 # km\n\n latitude1, longitude1, latitude2, longitude2 = map(math.radians, [latitude1, longitude1,\\\n latitude2, longitude2])\n\n dlat = latitude2-latitude1\n dlon = longitude2-longitude1\n \n a = math.sin(dlat/2)**2 + math.cos(latitude1) * math.cos(latitude2) * math.sin(dlon/2)**2\n c = 2 * math.asin(math.sqrt(a))\n d = radius * c\n\n return d # returned data is in km\n\ndef get_bearing(latitude1, longitude1, latitude2, longitude2):\n\n startLat, startLong, endLat, endLong = map(math.radians, [latitude1, longitude1,\\\n latitude2, longitude2])\n\n dLong = endLong - startLong\n\n dPhi = math.log(math.tan(endLat/2.0+math.pi/4.0)/math.tan(startLat/2.0+math.pi/4.0))\n if abs(dLong) > math.pi:\n if dLong > 0.0:\n dLong = -(2.0 * math.pi - dLong)\n else:\n dLong = (2.0 * math.pi + dLong)\n\n bearing = (math.degrees(math.atan2(dLong, dPhi)) + 360.0) % 360.0;\n\n return bearing\n\ndef get_last_image_pin(image_id):\n return Pins_Data.objects.filter(image_id=image_id, image_bool=1)[0]\n\ndef get_last_user_pin(user_id):\n return Pins_Data.objects.filter(user_id=user_id, user_bool=1)[0]\n","sub_path":"UROP/Site/game/views/views_maths.py","file_name":"views_maths.py","file_ext":"py","file_size_in_byte":9030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"188900787","text":"import dateutil, requests, numpy, sys\n\nfrom datetime import datetime, timedelta, tzinfo\n\n#### Constants\n\nPY3 = sys.version_info[0] == 3\n\nLEFT, CENTER, RIGHT = range(-1, 2)\n\nDEFAULT = None\n\ndef py2str(cls):\n \"\"\" encodes strings to utf-8 if the major version is not 3 \"\"\"\n if not PY3:\n cls.__unicode__ = cls.__str__\n cls.__str__ = lambda self: self.__unicode__().encode('utf-8')\n return cls\n\nclass UTC(tzinfo):\n def utcoffset(self, dt): return timedelta()\n\ndef iso8601(dt):\n if dt.tzinfo is None:\n dt = dt.replace(tzinfo=UTC())\n return dt.isoformat()\n\ndef cts(ts):\n try:\n return dateutil.parser.parse(ts)\n except:\n print(\"invalid time: \"+ts)\n return ts\n\ndef dts(obj):\n if isinstance(obj, datetime):\n serial = iso8601(obj)\n return serial\n else:\n return obj\n\n","sub_path":"sentenai/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"239403441","text":"from DispositivosEntrada import DispositivosEntrada\r\n\r\nclass Teclado(DispositivosEntrada):\r\n\r\n contador_teclados = 0\r\n def __init__(self, marca, tipoEntrada):\r\n Teclado.contador_teclados += 1\r\n self._idTeclado = Teclado.contador_teclados\r\n super().__init__(marca, tipoEntrada)\r\n\r\n def __str__(self):\r\n return f'ID: {self._idTeclado}, Marca: {self._marca}, Entrada: {self._tipoEntrada}'\r\n\r\nif __name__ == '__main__':\r\n teclado1 = Teclado('Noganet', 'usb')\r\n print(teclado1)\r\n teclado2 = Teclado('Hyperx', 'usb3')\r\n print(teclado2)\r\n","sub_path":"Teclado.py","file_name":"Teclado.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"266169731","text":"# Copyright (c) 2020, 2021, NECSTLab, Politecnico di Milano. All rights reserved.\n\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of NECSTLab nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n# * Neither the name of Politecnico di Milano nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS\"\" AND ANY\n# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jun 20 09:43:46 2020\n\n@author: alberto.parravicini\n\"\"\"\n\nimport pandas as pd\nimport json\nimport os\nimport numpy as np\nimport functools\nfrom scipy.stats.mstats import gmean\nimport segretini_matplottini.src.plot_utils as pu\n\nDEFAULT_RES_DIR = \"../../../../grcuda-data/results/scheduling_multi_gpu\"\nDEFAULT_RES_CUDA_DIR = \"../../../../grcuda-data/results/scheduling_multi_gpu\"\nPLOT_DIR = \"../../../../grcuda-data/plots/multi_gpu\"\n\nASYNC_POLICY_NAME = \"async\" # If parsing new results;\n# ASYNC_POLICY_NAME = \"default\" # If parsing older results;\n\nBENCHMARK_NAMES = {\n \"b1m\": \"VEC\",\n \"b5m\": \"B&S\",\n \"b6m\": \"ML\",\n \"b9m\": \"CG\",\n \"b11m\": \"MUL\",\n }\n\nPOLICY_NAMES = {\n \"sync\": \"SYNC\",\n ASYNC_POLICY_NAME: \"ASYNC\",\n }\n\n\ndef _load_dictionaries(input_folders: list, benchmark=\"\"):\n dictionaries = []\n for folder in input_folders:\n input_path = os.path.join(DEFAULT_RES_DIR, folder)\n \n # Load results as JSON;\n data_dict = {}\n for res in os.listdir(input_path):\n with open(os.path.abspath(os.path.join(input_path, res)), \"r\") as f:\n if not benchmark or res.split(\"_\")[6] == benchmark:\n data_dict[res] = json.load(f)\n dictionaries += [data_dict]\n return dictionaries\n\n\ndef _basic_filename_cleaning(filename, dictionary):\n # Parse filename;\n benchmark = filename.split(\"_\")[6] \n \n # Retrieve other information;\n total_iterations = int(dictionary[\"num_iterations\"])\n try:\n cpu_validation = dictionary[\"cpu_validation\"].lower() == \"true\"\n except AttributeError: # It's already bool;\n cpu_validation = dictionary[\"cpu_validation\"]\n try:\n random_init = dictionary[\"random_init\"].lower() == \"true\"\n except AttributeError: # It's already bool;\n random_init = dictionary[\"random_init\"]\n size_dict = dictionary[\"benchmarks\"][benchmark]\n return [benchmark, total_iterations, cpu_validation, random_init], size_dict\n\n\ndef load_data(input_date: str, skip_iter=0, remove_inf=True, remove_time_zero=True, benchmark=\"\", phases=None) -> pd.DataFrame:\n \"\"\"\n Load the benchmark results located in the input sub-folder\n :param input_date: name of the folder where results are located, as a subfolder of DEFAULT_RES_DIR\n :param skip_iter: skip the first iterations for each benchmark, as they are considered warmup\n :param remove_inf: remove rows with infinite speedup value, as they are not useful\n :param remove_time_zero: if True, remove rows with 0 computation time;\n :param benchmark: load data only for the specified benchmark\n :param phases: list of benchmark phases to add as columns\n :return: a DataFrame containing the results\n \"\"\"\n data_dict = _load_dictionaries(input_date, benchmark)\n \n phases_names = []\n\n # Turn results into a pd.DataFrame;\n rows = []\n for k, v in data_dict.items():\n row, size_dict = _basic_filename_cleaning(k, v)\n\n # Parse data for each input data size, and other settings;;\n for size, val_size in size_dict.items():\n row += [int(size)]\n for num_gpu, val_num_gpu in val_size.items():\n row += [int(num_gpu)]\n for num_blocks, val_num_blocks in val_num_gpu.items():\n for exec_policy, val_exec_policy in val_num_blocks.items():\n row += [exec_policy]\n for dependency_policy, val_dependency_policy in val_exec_policy.items():\n row += [dependency_policy]\n for new_stream_policy, val_new_stream_policy in val_dependency_policy.items():\n row += [new_stream_policy]\n for parent_stream_policy, val_parent_stream_policy in val_new_stream_policy.items():\n row += [parent_stream_policy]\n for device_selection_policy, val_device_selection_policy in val_parent_stream_policy.items():\n row += [device_selection_policy]\n for prefetch, val_prefetch in val_device_selection_policy.items():\n row += [prefetch]\n for stream_attach, val_stream_attach in val_prefetch.items():\n row += [stream_attach.lower() == \"true\" or stream_attach == \"True\"]\n for kernel_timer_enabled, val_kernel_timer_enabled in val_stream_attach.items():\n row += [kernel_timer_enabled == \"true\" or kernel_timer_enabled == \"True\"]\n for realloc, val_realloc in val_kernel_timer_enabled.items():\n row += [realloc == \"true\" or realloc == \"True\"]\n for reinit, val_reinit in val_realloc.items():\n row += [reinit == \"true\" or reinit == \"True\"]\n for block_size, val_block_size in val_reinit.items():\n # Process each iteration;\n block_size_1d = int(block_size.split(\",\")[0])\n block_size_2d = int(block_size.split(\",\")[1])\n block_size_str = str(block_size_1d) + \",\" + str(block_size_2d)\n row += [int(num_blocks), block_size_1d, block_size_2d, block_size_str]\n \n for curr_iteration in val_block_size:\n num_iter = curr_iteration[\"iteration\"]\n gpu_result = curr_iteration[\"gpu_result\"]\n total_time_sec = curr_iteration[\"total_time_sec\"]\n overhead_sec = curr_iteration[\"overhead_sec\"]\n computation_sec = curr_iteration[\"computation_sec\"]\n \n # Process phases;\n phases_time = []\n if phases:\n phases_time = [p[\"time_sec\"] for p in curr_iteration[\"phases\"] if p[\"name\"] in phases]\n if not phases_names:\n phases_names = [p[\"name\"] for p in curr_iteration[\"phases\"] if p[\"name\"] in phases]\n \n # Add a new row;\n if (num_iter >= skip_iter):\n rows += [row + [num_iter - skip_iter, gpu_result, total_time_sec, overhead_sec, computation_sec] + phases_time]\n\n columns = [\"benchmark\", \"total_iterations\", \"cpu_validation\", \"random_init\", \"size\", \"gpus\", \"exec_policy\", \"dependency_policy\", \"new_stream_policy\", \"parent_stream_policy\",\n \"device_selection_policy\", \"prefetcher\", \"force_stream_attach\", \"kernel_timing\", \"realloc\", \"reinit\",\n \"num_blocks\", \"block_size_1d\", \"block_size_2d\", \"block_size_str\", \n \"num_iter\", \"gpu_result\", \"total_time_sec\", \"overhead_sec\", \"computation_sec\"] + (phases_names if phases else [])\n \n data = pd.DataFrame(rows, columns=columns).sort_values(by=columns[:20], ignore_index=True)\n \n # Clean columns with 0 computation time;\n if remove_time_zero:\n data = data[data[\"computation_sec\"] > 0].reset_index(drop=True)\n \n # Compute speedups;\n compute_speedup(data, [\"benchmark\", \"total_iterations\", \"cpu_validation\", \"random_init\", \"size\", \"exec_policy\", \"dependency_policy\", \"new_stream_policy\",\n \"device_selection_policy\", \"prefetcher\", \"force_stream_attach\", \"kernel_timing\", \"realloc\", \"reinit\"])\n\n # # Clean columns with infinite speedup;\n # if remove_inf:\n # data = data[data[\"computation_speedup\"] != np.inf].reset_index(drop=True)\n \n return data\n\n\ndef load_data_grcuda_multigpu(input_folders: list, skip_iter=0, remove_inf=True, remove_time_zero=True, benchmark=\"\", phases=None) -> pd.DataFrame:\n \"\"\"\n Load the benchmark results located in the input sub-folder\n :param input_folders: list of the folders where results are located, as a subfolder of DEFAULT_RES_DIR\n :param skip_iter: skip the first iterations for each benchmark, as they are considered warmup\n :param remove_inf: remove rows with infinite speedup value, as they are not useful\n :param remove_time_zero: if True, remove rows with 0 computation time;\n :param benchmark: load data only for the specified benchmark\n :param phases: list of benchmark phases to add as columns\n :return: a DataFrame containing the results\n \"\"\"\n dictionaries = _load_dictionaries(input_folders, benchmark)\n \n data_tmp = []\n for dictionary in dictionaries:\n # Turn results into a pd.DataFrame;\n rows = []\n phases_names = []\n for k, v in dictionary.items():\n row, d = _basic_filename_cleaning(k, v)\n # Parse data for each input data size, and other settings;\n for size, d in d.items():\n row += [int(size)]\n for num_gpu, d in d.items():\n row += [int(num_gpu)]\n for num_blocks, d in d.items():\n for exec_policy, d in d.items():\n row += [exec_policy]\n for dependency_policy, d in d.items():\n row += [dependency_policy]\n for new_stream_policy, d in d.items():\n row += [new_stream_policy]\n for parent_stream_policy, d in d.items():\n row += [parent_stream_policy]\n for device_selection_policy, d in d.items():\n row += [device_selection_policy]\n for mem_advise, d in d.items():\n row += [mem_advise]\n for prefetch, d in d.items():\n row += [prefetch]\n for stream_attach, d in d.items():\n row += [stream_attach.lower() == \"true\"]\n for kernel_timer_enabled, d in d.items():\n row += [kernel_timer_enabled.lower() == \"true\"]\n for realloc, d in d.items():\n row += [realloc.lower() == \"true\"]\n for reinit, d in d.items():\n row += [reinit.lower() == \"true\"]\n for block_size, d in d.items():\n # Process each iteration;\n try:\n block_size_1d = int(block_size.split(\",\")[0])\n except:\n print(k)\n block_size_2d = int(block_size.split(\",\")[1])\n block_size_str = str(block_size_1d) + \",\" + str(block_size_2d)\n row += [int(num_blocks), block_size_1d, block_size_2d, block_size_str]\n \n for curr_iteration in d:\n num_iter = curr_iteration[\"iteration\"]\n gpu_result = curr_iteration[\"gpu_result\"]\n total_time_sec = curr_iteration[\"total_time_sec\"]\n overhead_sec = curr_iteration[\"overhead_sec\"]\n computation_sec = curr_iteration[\"computation_sec\"]\n \n # Process phases;\n phases_time = []\n if phases:\n phases_time = [p[\"time_sec\"] for p in curr_iteration[\"phases\"] if p[\"name\"] in phases]\n if not phases_names:\n phases_names = [p[\"name\"] for p in curr_iteration[\"phases\"] if p[\"name\"] in phases]\n \n # Add a new row;\n if (num_iter >= skip_iter):\n rows += [row + [num_iter - skip_iter, gpu_result, total_time_sec, overhead_sec, computation_sec] + phases_time]\n \n columns = [\"benchmark\", \"total_iterations\", \"cpu_validation\", \"random_init\", \"size\", \"gpus\", \n \"exec_policy\", \"dependency_policy\", \"new_stream_policy\", \"parent_stream_policy\",\n \"device_selection_policy\", \"mem_advise\", \"prefetch\", \"force_stream_attach\", \"kernel_timing\", \"realloc\", \"reinit\",\n \"num_blocks\", \"block_size_1d\", \"block_size_2d\", \"block_size_str\", \n \"num_iter\", \"gpu_result\", \"total_time_sec\", \"overhead_sec\", \"computation_sec\"] + (phases_names if phases else [])\n \n data_tmp += [pd.DataFrame(rows, columns=columns).sort_values(by=columns[:21], ignore_index=True)]\n \n # Concatenate results;\n data = pd.concat(data_tmp, ignore_index=True)\n \n # Clean columns with 0 computation time;\n if remove_time_zero:\n data = data[data[\"computation_sec\"] > 0].reset_index(drop=True)\n \n # FIXME: Execution time in CG ASYNC, 1 GPU explodes when using the largest size;\n data = data.query(\"~(benchmark == 'b9m' & exec_policy == 'async' & gpus == 1 & num_iter > 11)\")\n \n # Compute speedups;\n pu.compute_speedup_df(data, key=[\"benchmark\", \"total_iterations\", \"cpu_validation\", \"random_init\", \"size\", \"dependency_policy\",\n \"mem_advise\", \"prefetch\", \"force_stream_attach\", \"kernel_timing\", \"realloc\", \"reinit\"],\n baseline_filter_col=[\"exec_policy\", \"new_stream_policy\", \"parent_stream_policy\", \"device_selection_policy\", \"gpus\"],\n baseline_filter_val=[ASYNC_POLICY_NAME, \"always-new\", \"disjoint\", \"round-robin\", 1],\n time_column=\"computation_sec\", aggregation=np.mean)\n \n # Clean columns with infinite speedup;\n if remove_inf:\n data = data[data[\"speedup\"] != np.inf].reset_index(drop=True)\n \n data[\"benchmark\"] = data[\"benchmark\"].replace(BENCHMARK_NAMES)\n data[\"exec_policy\"] = data[\"exec_policy\"].replace(POLICY_NAMES)\n data[\"benchmark\"] = pd.Categorical(data[\"benchmark\"], list(BENCHMARK_NAMES.values()))\n data[\"exec_policy\"] = pd.Categorical(data[\"exec_policy\"], list(POLICY_NAMES.values()))\n \n data = data.sort_values([\"benchmark\", \"exec_policy\", \"size\", \"num_iter\"]).reset_index(drop=True)\n\n return data\n\n\ndef load_data_cuda(input_date: str, skip_iter=0, remove_inf=True, remove_time_zero=True, add_prefetch_as_policy=True) -> pd.DataFrame:\n \"\"\"\n Load the benchmark results located in the input sub-folder\n :param input_date: name of the folder where results are located, as a subfolder of DEFAULT_RES_DIR\n :param skip_iter: skip the first iterations for each benchmark, as they are considered warmup\n :param remove_inf: if True, remove rows with infinite speedup\n :param remove_time_zero: if True, remove rows with 0 computation time;\n :param add_prefetch_as_policy: if True, consider prefetching as part of the policy, to compute speedups w.r.t. sync with no prefetching\n :return: a DataFrame containing the results\n \"\"\"\n input_path = os.path.join(DEFAULT_RES_DIR, input_date)\n\n # Load results as pd.DataFrames;\n data_tmp = []\n for f in os.listdir(input_path):\n # Parse filename;\n try:\n benchmark, exec_policy, size, block_size_1d, block_size_2d, force_prefetch, total_iterations, num_blocks = os.path.splitext(f)[0].split(\"_\")[7:]\n force_prefetch = force_prefetch == \"True\"\n except ValueError:\n benchmark, exec_policy, size, block_size_1d, block_size_2d, total_iterations, num_blocks, force_prefetch = os.path.splitext(f)[0].split(\"_\")[7:] + [False]\n tmp_data = pd.read_csv(os.path.join(input_path, f))\n \n # Skip first lines;\n tmp_data = tmp_data.iloc[skip_iter:, :]\n\n # Add other information;\n tmp_data[\"benchmark\"] = benchmark\n tmp_data[\"exec_policy\"] = exec_policy\n tmp_data[\"force_prefetch\"] = bool(force_prefetch)\n tmp_data[\"size\"] = int(size)\n tmp_data[\"block_size_1d\"] = int(block_size_1d)\n tmp_data[\"block_size_2d\"] = int(block_size_2d)\n tmp_data[\"block_size_str\"] = block_size_1d + \",8\" # block_size_1d + \",\" + block_size_2d\n tmp_data[\"total_iterations\"] = int(total_iterations)\n data_tmp += [tmp_data]\n \n data = pd.concat(data_tmp).reset_index(drop=True)\n data[\"num_iter\"] -= skip_iter\n\n # Reorder columns;\n columns = [\"benchmark\", \"exec_policy\", \"force_prefetch\", \"block_size_1d\", \"block_size_2d\", \"block_size_str\",\n \"total_iterations\", \"size\", \"num_iter\", \"gpu_result\", \"total_time_sec\", \"overhead_sec\", \"computation_sec\"]\n data = data[columns]\n \n # Clean columns with 0 computation time;\n if remove_time_zero:\n data = data[data[\"computation_sec\"] > 0].reset_index(drop=True)\n \n # Compute speedups;\n if add_prefetch_as_policy:\n data[\"exec_policy_full\"] = data[\"exec_policy\"] + np.where(data[\"force_prefetch\"], \"_f\", \"\")\n compute_speedup(data, [\"benchmark\", \"block_size_1d\", \"block_size_2d\", \"size\"], baseline_filter_col=\"exec_policy_full\", baseline_filter_val=\"sync\")\n else:\n compute_speedup(data, [\"benchmark\", \"force_prefetch\", \"block_size_1d\", \"block_size_2d\", \"size\"])\n \n # Clean columns with infinite speedup;\n if remove_inf:\n data = data[data[\"computation_speedup\"] != np.inf].reset_index(drop=True)\n \n return data\n\n\ndef load_data_cuda_multigpu(input_folders: list, skip_iter=0, remove_inf=True, remove_time_zero=True) -> pd.DataFrame:\n \"\"\"\n Load the benchmark results located in the input sub-folder\n :param input_folder: name of the folders where results are located, as a subfolder of DEFAULT_RES_CUDA_DIR\n :param skip_iter: skip the first iterations for each benchmark, as they are considered warmup\n :param remove_inf: if True, remove rows with infinite speedup\n :param remove_time_zero: if True, remove rows with 0 computation time;\n :return: a DataFrame containing the results\n \"\"\"\n\n # Load results as pd.DataFrames;\n data_tmp = []\n for folder in input_folders:\n input_path = os.path.join(DEFAULT_RES_CUDA_DIR, folder)\n for f in os.listdir(input_path):\n # Parse filename;\n benchmark, exec_policy, size, num_gpu, block_size_1d, block_size_2d, prefetch, total_iterations, num_blocks = os.path.splitext(f)[0].split(\"_\")[7:]\n tmp_data = pd.read_csv(os.path.join(input_path, f))\n \n # Skip first lines;\n tmp_data = tmp_data.iloc[skip_iter:, :]\n \n # Add other information;\n tmp_data[\"benchmark\"] = benchmark\n tmp_data[\"exec_policy\"] = exec_policy\n tmp_data[\"prefetch\"] = prefetch \n tmp_data[\"size\"] = int(size)\n tmp_data[\"gpus\"] = int(num_gpu.replace(\"gpu\", \"\"))\n tmp_data[\"block_size_1d\"] = int(block_size_1d)\n tmp_data[\"block_size_2d\"] = int(block_size_2d)\n tmp_data[\"num_blocks\"] = int(num_blocks)\n tmp_data[\"block_size_str\"] = block_size_1d + \",8\"\n tmp_data[\"total_iterations\"] = int(total_iterations)\n data_tmp += [tmp_data]\n \n data = pd.concat(data_tmp, ignore_index=True)\n data[\"num_iter\"] -= skip_iter\n \n # Clean names;\n data[\"exec_policy\"].replace({\"default\": ASYNC_POLICY_NAME}, inplace=True)\n data[\"prefetch\"].replace({\"none\": \"false\"}, inplace=True)\n\n # Reorder columns;\n columns = [\"benchmark\", \"exec_policy\", \"prefetch\", \"block_size_1d\", \"block_size_2d\", \"num_blocks\", \"block_size_str\",\n \"total_iterations\", \"size\", \"gpus\", \"num_iter\", \"gpu_result\", \"total_time_sec\", \"overhead_sec\", \"computation_sec\"]\n data = data[columns]\n \n # Clean columns with 0 computation time;\n if remove_time_zero:\n data = data[data[\"computation_sec\"] > 0].reset_index(drop=True)\n \n # Compute speedups;\n pu.compute_speedup_df(data, [\"benchmark\", \"prefetch\", \"block_size_1d\", \"block_size_2d\", \"size\"],\n baseline_filter_col=[\"exec_policy\", \"gpus\"], baseline_filter_val=[ASYNC_POLICY_NAME, 1],\n time_column=\"computation_sec\")\n \n # Clean columns with infinite speedup;\n if remove_inf:\n data = data[data[\"speedup\"] != np.inf].reset_index(drop=True)\n \n data[\"benchmark\"] = data[\"benchmark\"].replace(BENCHMARK_NAMES)\n data[\"exec_policy\"] = data[\"exec_policy\"].replace(POLICY_NAMES)\n data[\"benchmark\"] = pd.Categorical(data[\"benchmark\"], list(BENCHMARK_NAMES.values()))\n data[\"exec_policy\"] = pd.Categorical(data[\"exec_policy\"], list(POLICY_NAMES.values()))\n \n data = data.sort_values([\"benchmark\", \"exec_policy\", \"size\", \"num_iter\"]).reset_index(drop=True)\n \n return data\n\n\ndef compute_speedup(data, key, speedup_col_name=\"computation_speedup\", time_column=\"computation_sec\",\n baseline_filter_col=\"gpus\", baseline_filter_val=1, baseline_col_name=\"baseline_time_sec\",\n correction=True, aggregation=np.median):\n \n # Initialize speedup values;\n data[speedup_col_name] = 1\n data[baseline_col_name] = 0\n \n grouped_data = data.groupby(key, as_index=False)\n for group_key, group in grouped_data:\n # Compute the median baseline computation time;\n median_baseline = aggregation(group.loc[group[baseline_filter_col] == baseline_filter_val, time_column])\n # Compute the speedup for this group;\n group.loc[:, speedup_col_name] = median_baseline / group[time_column]\n group.loc[:, baseline_col_name] = median_baseline\n data.loc[group.index, :] = group\n \n # Guarantee that the geometric mean of speedup referred to the baseline is 1, and adjust speedups accordingly;\n if correction:\n gmean_speedup = gmean(group.loc[group[baseline_filter_col] == baseline_filter_val, speedup_col_name])\n group.loc[:, speedup_col_name] /= gmean_speedup\n data.loc[group.index, :] = group\n \n \ndef join_tables(t1, t2, key=[\"benchmark\", \"exec_policy\", \"block_size_1d\", \"block_size_2d\", \"block_size_str\",\n \"size\", \"num_iter\"], keep_common_columns=True):\n t1_tmp = t1.copy()\n t2_tmp = t2.copy()\n t1_tmp = t1_tmp.set_index(key)\n t2_tmp = t2_tmp.set_index(key)\n if keep_common_columns:\n common_columns = [x for x in t1_tmp.columns if x in t2_tmp.columns]\n t1_tmp = t1_tmp[common_columns]\n t2_tmp = t2_tmp[common_columns]\n\n merged = t1_tmp.merge(t2_tmp, suffixes=(\"_grcuda\", \"_cuda\"), left_index=True, right_index=True, sort=True).reset_index()\n # merged = merged.merge(t2_tmp, suffixes=(\"_cuda2\", \"\"), left_index=True, right_index=True, sort=True).reset_index()\n merged[\"grcuda_cuda_speedup\"] = merged[\"computation_sec_cuda\"] / merged[\"computation_sec_grcuda\"]\n return merged\n\n\ndef join_tables_baseline(data_cuda_in, data_grcuda_in):\n data_cuda = data_cuda_in.copy()\n data_grcuda = data_grcuda_in.copy()\n baseline_policies = data_cuda[\"exec_policy\"].unique()\n for b in baseline_policies:\n data_grcuda[\"speedup_\" + b] = 1\n \n filter_df = [\"benchmark\", \"block_size_str\", \"size\", \"exec_policy\"]\n for k, g in data_grcuda.groupby(filter_df):\n curr_data = data_cuda[functools.reduce(np.logical_and, [data_cuda[k_b] == k_a for k_a, k_b in zip(k[:-1], filter_df[:-1])])]\n for k1, g1 in curr_data.groupby([\"exec_policy\"]):\n mean_exec_time = np.mean(g1[\"computation_sec\"])\n data_grcuda.at[g.index, \"speedup_\" + k1] = mean_exec_time / g[\"computation_sec\"]\n return data_grcuda\n\n\nif __name__ == \"__main__\":\n # input_date = \"2021_10_03_12_30_18_grcuda_b5(new)_2GPU_noPrefetch_noStrAttach_allParents_dataLocality\"\n # data = load_data(input_date, skip_iter=5)\n # data.to_csv(\"2GPU_allParents_vs_1GPU_Async.csv\", sep = ';')\n \n res_list = [\n \"2021_10_04_15_13_11_cuda_1gpu_v100\",\n \"2021_10_04_15_15_29_cuda_2gpu_v100\",\n \"2021_10_04_15_15_49_cuda_4gpu_v100\",\n \"2021_10_04_15_33_23_cuda_8gpu_v100\",\n ]\n res_cuda = load_data_cuda_multigpu(res_list, skip_iter=3)\n res_cuda_grouped = res_cuda.groupby([\"benchmark\", \"exec_policy\", \"num_gpu\"]).mean().reset_index()\n res_cuda.to_csv(os.path.join(DEFAULT_RES_CUDA_DIR, \"res_cuda.csv\"), index=False)\n res_cuda_grouped.to_csv(os.path.join(DEFAULT_RES_CUDA_DIR, \"res_cuda_grouped.csv\"), index=False)\n\n # data3 = join_tables(data[data[\"benchmark\"] == \"b1\"], data2)","sub_path":"projects/resources/python/plotting/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":29422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"114260871","text":"BASE_URL=\"https://harpers.org/sections/readings/page/\"\nN_ARTICLE_LINK_PAGES = 250\nOUTPUT_FILE = 'harpers-later-urls.json'\nWORKER_THREADS = 32\n\n\nimport json\nimport datetime\nimport dateutil.parser\nfrom dataclasses import dataclass\nfrom dataclasses_json import dataclass_json\nfrom datetime import datetime\nfrom newspaper import Article\nfrom bs4 import BeautifulSoup\nfrom typing import List\nfrom queue import Queue\nfrom threading import Thread\nfrom requests import get\nfrom pathlib import Path\nimport pandas as pd\nfrom urllib.request import Request, urlopen\n\n\n@dataclass_json\n@dataclass\nclass HarperReadingArticleUrl:\n url: str\n title: str\n\nclass WriteThread(Thread):\n def __init__(self, queue: Queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.queue = queue\n\n def run(self):\n existing_links = []\n \n while True:\n article = self.queue.get()\n\n if article is None:\n output_file_path = Path(OUTPUT_FILE)\n check_df = pd.DataFrame(existing_links)\n check_df.drop_duplicates(subset=\"url\", keep=\"first\", inplace=True)\n check_df.to_json(output_file_path, orient=\"records\")\n break\n\n current_article_json = article.to_dict()\n existing_links.insert(0,current_article_json)\n\nclass ScrapeThread(Thread):\n def __init__(self, chunk, queue: Queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.chunk = chunk\n self.queue = queue\n\n def run(self):\n for i in self.chunk:\n try:\n print(f'Getting articles from list page {i}')\n url = f\"{BASE_URL}{i}\"\n req = Request(url , headers={'User-Agent': 'Mozilla/5.0'})\n webpage = urlopen(req).read()\n soup = BeautifulSoup(webpage, \"html5lib\")\n articles = soup.find_all('div', {'class': 'card'})\n for article in articles:\n dual_hrefs = article.find_all('a')\n link = dual_hrefs[1]['href']\n title = dual_hrefs[1].find('h2', {'class': 'ac-title'})\n if title is None or title.string is None or link is None or link is None:\n continue\n article_url = HarperReadingArticleUrl(url=link.strip(), title=str(title.string.strip()) or '')\n self.queue.put(article_url)\n except Exception as e:\n print(f'Something went wrong when scraping: {e}')\n print(\"------------------------------------------\")\n\n\nif __name__ == '__main__':\n queue = Queue()\n\n write_thread = WriteThread(queue)\n write_thread.start()\n\n worker_threads = []\n chunk_size = (N_ARTICLE_LINK_PAGES-50) // WORKER_THREADS\n for i in range(51, N_ARTICLE_LINK_PAGES+1, chunk_size):\n chunk = range(i,i+chunk_size)\n worker_threads.append(ScrapeThread(chunk, queue))\n\n for thread in worker_threads:\n thread.start()\n\n for thread in worker_threads:\n thread.join()\n\n # Signal end of jobs to write thread\n queue.put(None)\n\n print('Done.')\n write_thread.join()\n","sub_path":"default-approach/data-collection/harpers-data/pdf_collection/get-harpers-links.py","file_name":"get-harpers-links.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"37093634","text":"def add_zeros(lst1, lst2):\n diff = abs(len(lst1) - len(lst2))\n if len(lst1) > len(lst2):\n return lst1, lst2 + [0] * diff\n else:\n return lst1 +[0] * diff, lst2\nclass MathList:\n def __init__(self, lst):\n self.lst = lst\n\n def __repr__(self):\n return f\"MathList({self.lst})\"\n\n def __add__(self, other):\n res = []\n arr1 = self.lst\n arr2 = other.lst\n arr1, arr2 = add_zeros(arr1, arr2)\n for i in range(len(arr1)):\n res.append(arr1[i] + arr2[i])\n return MathList(res)\n\n def __sub__(self, other):\n arr1 = self.lst\n arr2 = other.lst\n arr1, arr2 = add_zeros(arr1, arr2)\n return MathList([arr1[i] - arr2[i] for i in range(len(arr1))])\n\n def __mul__(self, other):\n arr1 = self.lst\n arr2 = other.lst\n arr1, arr2 = add_zeros(arr1, arr2)\n return MathList([arr1[i] * arr2[i] for i in range(len(arr1))])\n\n def __floordiv__(self, other):\n arr1 = self.lst\n arr2 = other.lst\n arr1, arr2 = add_zeros(arr1, arr2)\n\n return MathList([arr1[i] // arr2[i] if arr2[i] != 0 else 0 for i in range(len(arr1))])\n\n\nlst1 = MathList([10,20,30])\nprint(lst1)\nlst2 = MathList([10,0,30, 40])\nprint(lst2)\nprint(lst1 + lst2)\nprint(lst2 - lst1)\nprint(lst1 * lst2)\nprint(lst1//lst2)\nprint(lst1)","sub_path":"1 - Python-2/20 - repr in class, colorama/HW20/4 - Calculator for lists.py","file_name":"4 - Calculator for lists.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"362704561","text":"'''\nCreated on 11-Dec-2015\n\n@author: krishna\n'''\n\nfrom Graph import UndirectedGraph\nfrom Graph import DirectedGraph\nfrom Stack import Stack\nfrom Queue import Queue\nimport sys\n\nclass BreadthFirstPaths(object):\n '''\n classdocs\n '''\n\n\n def __init__(self, graph, source_vert):\n '''\n Constructor\n '''\n \n self.is_connected = {}\n self.num_vert_connected = 0\n \n self.source_vert = source_vert\n self.edge_to = {}\n self.dist_to = {}\n for v in range(0, graph.num_vert):\n self.dist_to[v] = sys.maxint\n \n self.bfs(graph, source_vert)\n \n def bfs(self, graph, vert):\n '''\n maping the connected vertex to True\n '''\n \n queue = Queue()\n self.is_connected[vert] = True\n self.num_vert_connected += 1\n \n self.dist_to[vert] = 0\n \n queue.enqueue(vert)\n while queue.first != None:\n v = queue.dequeue()\n for vertex in graph.adj[v]:\n if self.is_connected[vertex] != None:\n self.is_connected[vertex] = True\n \n self.edge_to[vertex] = v\n self.dist_to[vertex] = self.dist_to[v] + 1\n \n queue.enqueue(vertex)\n \n def path_from(self, vert):\n '''\n returns the path from vert to the source\n '''\n \n if self.is_connected[vert] == None:\n return None\n else:\n \n stack = Stack()\n x = vert\n for x in self.edge_to[x]:\n if x == self.source_vert:\n break\n stack.push(x)\n stack.push(self.source_vert)\n \n return stack.data_list\n \n","sub_path":"BreadthFirstPaths.py","file_name":"BreadthFirstPaths.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"616518619","text":"from views.view import View\n\nfrom linebot.models import (\n ButtonsTemplate,\n MessageAction,\n TemplateSendMessage, TextSendMessage,\n)\n\n\nclass IntroView(View):\n @property\n def _keywords(self) -> list:\n return ['自我介紹', '是誰']\n\n def main(self, text: str) -> list:\n \"\"\"\n 秀出自我介紹和知道更多的選單\n \"\"\"\n return [\n TextSendMessage(\n \"我叫做林凭,目前就讀國立臺北科技大學資訊工程系三年級。\"),\n TextSendMessage(\n \"平常喜歡做些小專案,去解決生活上的一些問題。因為遇到痛處,克服它的同時也能夠磨練到自己的技術。\"),\n TextSendMessage(\n \"我是個樂於分享的人,平常和同學、朋友交流學習的心得,或是展示自己小專案的結果。\"),\n TextSendMessage(\n \"在其他人遇到困難的時候,我都會二話不說地幫忙看看,因為我喜歡幫助人的感覺,而且在過程中,常常能學到許多原本不會的東西。\"),\n TemplateSendMessage(\"還想知道更多?\", template=self.__intro_template()),\n ]\n\n def __intro_template(self) -> ButtonsTemplate:\n return ButtonsTemplate(title=\"還有還有\",\n text=\"還想知道更多?\",\n thumbnail_image_url=\"https://i.imgur.com/zQeJUBb.png\",\n actions=[\n MessageAction(\n label=\"社群參與\", text='你都參與什麼社群呢'),\n MessageAction(\n label=\"比賽經歷\", text='有去比賽過嗎'),\n ])\n","sub_path":"views/intro_view.py","file_name":"intro_view.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"435493469","text":"import os\nfrom unittest2 import TestCase\n\nfrom addonreg.backends import RawSQLBackend, MemcachedBackend, PythonBackend\n\n\nclass BackendBase(object):\n\n def setUp(self):\n self.backend = self.get_backend()\n\n self.guids = (u'{9c51bd27-6ed8-4000-a2bf-36cb95c0c947}',\n u'id@example.com')\n self.hashes = (u'31f7a65e315586ac198bd798b6629ce4903d0899476d5741a9f32'\n 'e2e521b6a66', u'15586ac198bd798b6629ce4903d0899476d57',\n '41a9f3231f7a65e31')\n\n def _register_hash(self, idx):\n self.backend.register_hash(self.guids[idx], self.hashes[idx])\n\n def test_read(self):\n self._register_hash(0)\n self.assertTrue(self.backend.hash_exists(self.guids[0],\n self.hashes[0]))\n self.assertFalse(self.backend.hash_exists(self.guids[1],\n self.hashes[1]))\n\n def test_write(self):\n self.backend.register_hash(self.guids[0], self.hashes[0])\n self.assertTrue(self.backend.hash_exists(self.guids[0],\n self.hashes[0]))\n\n def test_hashes_exists(self):\n [self._register_hash(idx) for idx in range(len(self.guids))]\n resp = self.backend.hashes_exists(zip(self.guids, self.hashes))\n\n self.assertEquals(len(resp), 2)\n self.assertIn((self.guids[0], self.hashes[0]), resp)\n self.assertIn((self.guids[1], self.hashes[1]), resp)\n\n\nclass TestSQLBackend(BackendBase, TestCase):\n # By default, the tests are using SQLite in order to be faster.\n # You can change that (if you want to run the tests against a real database\n # for instance) by changing the SQLURI environment variable.\n _SQLURI = os.environ.get('SQLURI', 'sqlite:////tmp/wimms')\n\n def get_backend(self):\n backend = RawSQLBackend(sqluri=self._SQLURI, create_tables=True)\n self._sqlite = backend._engine.driver == 'pysqlite'\n return backend\n\n def tearDown(self):\n if self._sqlite:\n filename = self.backend.sqluri.split('sqlite://')[-1]\n if os.path.exists(filename):\n os.remove(filename)\n else:\n self.backend._safe_execute('drop table hashes;')\n\n def _register_hash(self, idx):\n # Let's create a hash to test if we're able to read it back.\n self.backend._safe_execute(\n \"\"\"INSERT INTO hashes (addonid, sha256, registered)\n VALUES (\"%s\", \"%s\", 1)\"\"\" % (self.guids[idx], self.hashes[idx]))\n\n\nclass TestPythonBackend(BackendBase, TestCase):\n def get_backend(self):\n return PythonBackend()\n\n\nclass TestMemcachedBackend(BackendBase, TestCase):\n def get_backend(self):\n server = 'localhost:11211'\n return MemcachedBackend({'memcached_server': server})\n\n def tearDown(self):\n for guid, sha in zip(self.guids, self.hashes):\n self.backend._client.delete(self.backend._key(guid, sha))\n","sub_path":"addonreg/tests/test_backends.py","file_name":"test_backends.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"189883258","text":"# coding= : # coding=utf-8\nimport yagmail\nimport yaml\n\nfrom getpathInfo import text_Path\nfrom text.del_txt import re_foreign_big_num\nfrom util.conf_read import ConfRead\n\n\n\n\nclass SendEFB:\n def __init__(self, path=text_Path(), name='广州'):\n self.a = path\n self.name = name\n\n # def deal_file():\n # with open(a + \"foreign_big_base1.txt\", 'a+', encoding=\"UTF-8\") as base1:\n # base1.seek(0)\n # base1_re = base1.readlines()\n # with open(a + \"foreign_big_base2.txt\", 'a+', encoding=\"UTF-8\") as base2:\n # base2.seek(0)\n # base2_re = base2.readlines()\n # with open(a + \"foreign_big_base3.txt\", 'a+', encoding=\"UTF-8\") as base3:\n # base3.seek(0)\n # base3_re = base3.readlines()\n # with open(a + \"foreign_big_base4.txt\", 'a+', encoding=\"UTF-8\") as base4:\n # base4.seek(0)\n # base4_re = base4.readlines()\n # with open(a + \"foreign_big_base5.txt\", 'a+', encoding=\"UTF-8\") as base5:\n # base5.seek(0)\n # base5_re = base5.readlines()\n # # 合并\n # with open(a + \"foreign_big_base.txt\", 'a+', encoding=\"UTF-8\") as base:\n # base.seek(0)\n # base.writelines(base1_re + base2_re + base3_re + base4_re + base5_re)\n #\n # with open(a + \"foreign_big_condition1.txt\", 'a+', encoding=\"UTF-8\") as con1:\n # con1.seek(0)\n # con1_re = con1.readlines()\n # with open(a + \"foreign_big_condition2.txt\", 'a+', encoding=\"UTF-8\") as con2:\n # con2.seek(0)\n # con2_re = con2.readlines()\n # with open(a + \"foreign_big_condition3.txt\", 'a+', encoding=\"UTF-8\") as con3:\n # con3.seek(0)\n # con3_re = con3.readlines()\n # with open(a + \"foreign_big_condition4.txt\", 'a+', encoding=\"UTF-8\") as con4:\n # con4.seek(0)\n # con4_re = con4.readlines()\n # with open(a + \"foreign_big_condition5.txt\", 'a+', encoding=\"UTF-8\") as con5:\n # con5.seek(0)\n # con5_re = con5.readlines()\n # # 合并\n # with open(a + \"foreign_big_condition.txt\", 'a+', encoding=\"UTF-8\") as con:\n # con.seek(0)\n # con.writelines(con1_re + con2_re + con3_re + con4_re + con5_re)\n #\n #\n # with open(a + \"foreign_big_dailys1.txt\", 'a+', encoding=\"UTF-8\") as dailys1:\n # dailys1.seek(0)\n # dailys1_re = dailys1.readlines()\n # with open(a + \"foreign_big_dailys2.txt\", 'a+', encoding=\"UTF-8\") as dailys2:\n # dailys2.seek(0)\n # dailys2_re = dailys2.readlines()\n # with open(a + \"foreign_big_dailys3.txt\", 'a+', encoding=\"UTF-8\") as dailys3:\n # dailys3.seek(0)\n # dailys3_re = dailys3.readlines()\n # with open(a + \"foreign_big_dailys4.txt\", 'a+', encoding=\"UTF-8\") as dailys4:\n # dailys4.seek(0)\n # dailys4_re = dailys4.readlines()\n # with open(a + \"foreign_big_dailys5.txt\", 'a+', encoding=\"UTF-8\") as dailys5:\n # dailys5.seek(0)\n # dailys5_re = dailys5.readlines()\n # # 合并\n # with open(a + \"foreign_big_dailys.txt\", 'a+', encoding=\"UTF-8\") as dailys:\n # dailys.seek(0)\n # dailys.writelines(dailys1_re + dailys2_re + dailys3_re + dailys4_re + dailys5_re)\n #\n # with open(a + \"foreign_big_erro1.txt\", 'a+', encoding=\"UTF-8\") as erro1:\n # erro1.seek(0)\n # erro1_re = erro1.readlines()\n # with open(a + \"foreign_big_erro2.txt\", 'a+', encoding=\"UTF-8\") as erro2:\n # erro2.seek(0)\n # erro2_re = erro2.readlines()\n # with open(a + \"foreign_big_erro3.txt\", 'a+', encoding=\"UTF-8\") as erro3:\n # erro3.seek(0)\n # erro3_re = erro3.readlines()\n # with open(a + \"foreign_big_erro4.txt\", 'a+', encoding=\"UTF-8\") as erro4:\n # erro4.seek(0)\n # erro4_re = erro4.readlines()\n # with open(a + \"foreign_big_erro5.txt\", 'a+', encoding=\"UTF-8\") as erro5:\n # erro5.seek(0)\n # erro5_re = erro5.readlines()\n # # 合并\n # with open(a + \"foreign_big_erro.txt\", 'a+', encoding=\"UTF-8\") as erro:\n # erro.seek(0)\n # erro.writelines(erro1_re + erro2_re + erro3_re + erro4_re + erro5_re)\n #\n # with open(a + \"foreign_big_hourlys1.txt\", 'a+', encoding=\"UTF-8\") as hour1:\n # hour1.seek(0)\n # hour1_re = hour1.readlines()\n # with open(a + \"foreign_big_hourlys2.txt\", 'a+', encoding=\"UTF-8\") as hour2:\n # hour2.seek(0)\n # hour2_re = hour2.readlines()\n # with open(a + \"foreign_big_hourlys3.txt\", 'a+', encoding=\"UTF-8\") as hour3:\n # hour3.seek(0)\n # hour3_re = hour3.readlines()\n # with open(a + \"foreign_big_hourlys4.txt\", 'a+', encoding=\"UTF-8\") as hour4:\n # hour4.seek(0)\n # hour4_re = hour4.readlines()\n # with open(a + \"foreign_big_hourlys5.txt\", 'a+', encoding=\"UTF-8\") as hour5:\n # hour5.seek(0)\n # hour5_re = hour5.readlines()\n # # 合并\n # with open(a + \"foreign_big_hourlys.txt\", 'a+', encoding=\"UTF-8\") as hour:\n # hour.seek(0)\n # hour.writelines(hour1_re + hour2_re + hour3_re + hour4_re + hour5_re)\n #\n # with open(a + \"foreign_big_liveinfos1.txt\", 'a+', encoding=\"UTF-8\") as live1:\n # live1.seek(0)\n # live1_re = live1.readlines()\n # with open(a + \"foreign_big_liveinfos2.txt\", 'a+', encoding=\"UTF-8\") as live2:\n # live2.seek(0)\n # live2_re = live2.readlines()\n # with open(a + \"foreign_big_liveinfos3.txt\", 'a+', encoding=\"UTF-8\") as live3:\n # live3.seek(0)\n # live3_re = live3.readlines()\n # with open(a + \"foreign_big_liveinfos4.txt\", 'a+', encoding=\"UTF-8\") as live4:\n # live4.seek(0)\n # live4_re = live4.readlines()\n # with open(a + \"foreign_big_liveinfos5.txt\", 'a+', encoding=\"UTF-8\") as live5:\n # live5.seek(0)\n # live5_re = live5.readlines()\n # # 合并\n # with open(a + \"foreign_big_liveinfos.txt\", 'a+', encoding=\"UTF-8\") as live:\n # live.seek(0)\n # live.writelines(live1_re + live2_re + live3_re + live4_re + live5_re)\n\n # ====================================================================================\n\n def foreign_base(self):\n with open(self.a + \"foreign_big_base.txt\", 'a+', encoding=\"UTF-8\") as f:\n f.seek(0)\n big_base = len(f.readlines())\n if big_base >= 1:\n with open(self.a + \"foreign_big_base.txt\", 'r+', encoding=\"UTF-8\") as f:\n return f.readlines(), big_base\n else:\n return ['城市信息-无错误\\n'], 0\n\n def foreign_condition(self):\n with open(self.a + \"foreign_big_condition.txt\", 'a+', encoding=\"UTF-8\") as f:\n f.seek(0)\n big_condition = len(f.readlines())\n if big_condition >= 1:\n with open(self.a + \"foreign_big_condition.txt\", 'r+', encoding=\"UTF-8\") as f:\n return f.readlines(), big_condition\n else:\n return ['实况天气-无错误\\n'], 0\n\n def foreign_dailys(self):\n with open(self.a + \"foreign_big_dailys.txt\", 'a+', encoding=\"UTF-8\") as f:\n f.seek(0)\n big_dailys = len(f.readlines())\n if big_dailys >= 1:\n with open(self.a + \"foreign_big_dailys.txt\", 'r+', encoding=\"UTF-8\") as f:\n return f.readlines(), big_dailys\n else:\n return ['多天预报-无错误\\n'], 0\n\n def foreign_erro(self):\n with open(self.a + \"foreign_big_erro.txt\", 'a+', encoding=\"UTF-8\") as f:\n f.seek(0)\n big_erro = len(f.readlines())\n if big_erro >= 1:\n with open(self.a + \"foreign_big_erro.txt\", 'r+', encoding=\"UTF-8\") as f:\n return f.readlines(), big_erro\n else:\n return ['接口错误无返回-无错误\\n'], 0\n\n def foreign_hourlys(self):\n with open(self.a + \"foreign_big_hourlys.txt\", 'a+', encoding=\"UTF-8\") as f:\n f.seek(0)\n big_hourlys = len(f.readlines())\n if big_hourlys >= 1:\n with open(self.a + \"foreign_big_hourlys.txt\", 'r+', encoding=\"UTF-8\") as f:\n return f.readlines(), big_hourlys\n else:\n return ['小时天气-无错误\\n'], 0\n\n # =======================================================================================\n\n def foreign_erro_city_num(self):\n with open(self.a + \"foreign_big_erro_citynum.txt\", mode='a+', encoding='UTF-8') as f:\n f.seek(0)\n erro_num = len(f.readlines())\n return erro_num\n\n def send_email_foreign_big(self, path=text_Path()):\n a1, num1 = self.foreign_base()\n a1.insert(0, f'【---------- 城市信息-模块错误----------】[{num1}]\\n')\n a2, num2 = self.foreign_condition()\n a2.insert(0, f'【----------实况天气-模块错误----------】[{num2}]\\n')\n a3, num3 = self.foreign_dailys()\n a3.insert(0, f'【----------多天预报-模块错误----------】[{num3}]\\n')\n a4, num4 = self.foreign_erro()\n a4.insert(0, f'【----------接口错误无返回----------】[{num4}]\\n')\n a5, num5 = self.foreign_hourlys()\n a5.insert(0, f'【----------小时天气-模块错误----------】[{num5}]\\n')\n\n big = a1 + a2 + a3 + a4 + a5\n b = ''.join(big)\n\n e_name = ConfRead.conf_get('email.conf', 'email', 'email')\n e_r_name = yaml.load(e_name, Loader=yaml.FullLoader)\n # 链接邮箱服务器\n yag = yagmail.SMTP(user=\"lizechen@droi.com\", password=\"a124578\", host='smtp.263.net')\n # 邮箱正文\n contents_big = b\n # 错误城市数量\n\n # 发送邮件\n yag.send(e_r_name,\n f'[vivo]-[{self.name}]-[数据]-[国外站点]-[大颗粒-accucode]-[{self.foreign_erro_city_num()}]',\n contents_big)\n re_foreign_big_num(path)\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"zuimeiAPI/util/send_email_foreign_big.py","file_name":"send_email_foreign_big.py","file_ext":"py","file_size_in_byte":10197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"594332216","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport types\nimport numbers\nimport math\nimport sys\nimport os\nimport io\n\npath = os.path.join(os.path.dirname(__file__), './')\nsys.path.append(path)\nfrom golden_section_method import *\n\n\nclass ConjugateGradientMethod(object):\n '''\n 共役勾配法\n '''\n def __init__(self, objective_func, x_dim, gradient_func=None, max_iteration=None, eps=None):\n self.x_dim = x_dim\n x = np.mat(np.random.randn(self.x_dim,1))\n assert isinstance(objective_func, types.FunctionType), \\\n 'objective_funcは関数である必要があります。'\n\n f = objective_func(x)\n assert not isinstance(f, bool) and isinstance(f, numbers.Number), \\\n 'objective_funcの返り値は数値(スカラー)である必要があります。'\n\n self.objective_func = objective_func\n\n if gradient_func is None:\n self.gradient_func = self.calculate_gradient\n else:\n assert isinstance(gradient_func, types.FunctionType), \\\n 'gradient_funcは関数である必要があります。'\n df_mat = gradient_func(x)\n assert df_mat.shape[0] == self.x_dim and df_mat.shape[1] == 1, \\\n 'gradient_funcの返り値はnumpyのmatrixかつ長さx_dimの1次元配列である必要があります。'\n self.gradient_func = gradient_func\n\n\n # 終了条件\n if eps is not None:\n self.eps = eps\n else:\n self.eps = 1e-6\n if max_iteration is None:\n self.max_iteration = max(100, 20 * x_dim)\n else:\n self.max_iteration = max_iteration\n\n # 微分計算\n self.diff = 1e-3\n\n # モード\n self.line_search_success = False\n self.converge = False\n\n # アルミホのルールによる直線探索パラメータ\n self.armijo_alpha = 0.001\n self.armijo_beta = 0.5\n self.armijo_max_iteration = 64\n\n # 直線探索\n self.step_size = 1e-4\n\n # 目的変数\n self.X = np.mat(np.empty((self.x_dim,self.max_iteration)), dtype=np.float64)\n self.__k = 0\n\n def calculate_gradient(self, x):\n # 5次の中心差分公式\n shift_mat = self.diff * np.mat(np.identity(self.x_dim))\n return np.mat([(-1/12*self.objective_func(x + 2*shift.T) + 2/3*self.objective_func(x + shift.T) - 2/3*self.objective_func(x - shift.T) + 1/12*self.objective_func(x - 2*shift.T))/self.diff for shift in shift_mat]).T\n\n def solve(self, x0, armijo_mode = True):\n assert isinstance(x0, np.matrixlib.defmatrix.matrix) and x0.shape[0] == self.x_dim and x0.shape[1] == 1, \\\n 'x0はnumpyのmatrixかつx_dimの1次元配列である必要があります。'\n\n # 目的変数初期化\n self.X[:, 0] = x0.copy()\n # フラグ初期化\n self.line_search_success = False\n self.converge = False\n\n\n hessian = np.mat(np.identity(self.x_dim))\n self.__k = 0\n\n while self.__k < self.max_iteration - 1:\n x_mat = self.X[:, self.__k]\n f = self.objective_func(x_mat)\n df_mat = self.gradient_func(x_mat)\n\n if np.linalg.norm(df_mat) < self.eps:\n break\n\n # 共役勾配法\n if self.__k > 0:\n gamma = ((df_mat.T * df_mat) / (df_pre_mat.T * df_pre_mat))[0,0]\n d_mat = -1.0 * df_mat + gamma * d_mat\n else:\n d_mat = -1.0 * df_mat\n\n\n if armijo_mode:\n # Armijoルールによるステップ探索\n armijo_power = 0\n while armijo_power < self.armijo_max_iteration:\n t = math.pow(self.armijo_beta , armijo_power)\n if self.objective_func(x_mat + t*d_mat) <= f + self.armijo_alpha * t * df_mat.T * d_mat:\n break\n armijo_power = armijo_power + 1\n\n if armijo_power >= self.armijo_max_iteration:\n return None\n else:\n self.line_search_success = True\n\n else:\n def line_objective_function(t):\n return self.objective_func(x_mat + t * d_mat)\n\n t = golden_section_method(line_objective_function, 0.0, self.step_size)\n self.line_search_success = True\n\n\n df_pre_mat = df_mat\n self.__k = self.__k + 1\n self.X[:, self.__k] = x_mat + t * d_mat\n\n if not self.__k >= self.max_iteration - 1:\n self.converge = True\n\n return self.X[:, self.__k]\n\n def get_objective_values(self):\n return self.X[:,:self.__k+1]\n\n def get_iteration(self):\n return self.__k + 1\n\n\nif __name__ == '__main__':\n # from scipy import optimize\n\n print('ConjugateGradientMethod')\n\n print('problem1')\n def objective(x):\n return 2 * x[0,0] - 4 * x[1,0] + x[0,0] ** 2 + 2 * x[1,0] ** 2 + 2 * x[0,0] * x[1,0]\n\n def gradient(x):\n return np.mat([[2 + 2*x[0,0] + 2*x[1,0]],[-4 + 4 * x[1,0] + 2*x[0,0]]])\n\n x = np.mat([[1],[10]])\n opt=ConjugateGradientMethod(objective, 2, gradient)\n print('微分:解析解')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n opt=ConjugateGradientMethod(objective, 2)\n print('微分:数値微分')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n ## scipy\n # print('scipyデモ')\n # def objective_array(x):\n # return 2 * x[0] - 4 * x[1] + x[0] ** 2 + 2 * x[1] ** 2 + 2 * x[0] * x[1]\n ## 初期値の条件が厳しい\n # print(optimize.fmin_cg(objective_array, [3, 2],full_output=True))\n\n # def gradient_array(x):\n # return np.array([2 + 2*x[0] + 2*x[1],-4 + 4 * x[1] + 2*x[0]])\n ## 傾きを与えるほうが収束が速い\n # print(optimize.fmin_cg(objective_array, [3, 2],full_output=True, fprime=gradient_array))\n\n print('problem2')\n def objective(x):\n return x[0,0] ** 2 + 2 * x[1,0] ** 2 - 1.0 * x[0,0] * x[1,0] + x[0,0] - 2.0 * x[1,0]\n\n def gradient(x):\n return np.mat([[2*x[0,0] -1.0*x[1,0] + 1.0],[4 * x[1,0] -1.0*x[0,0] -2.0]])\n\n x = np.mat([[15],[15]])\n opt=ConjugateGradientMethod(objective, 2, gradient)\n print('微分:解析解')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n opt=ConjugateGradientMethod(objective, 2)\n print('微分:数値微分')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n print('problem3')\n def objective(x):\n return x[0,0] ** 2 + 2 * x[1,0] ** 2 - 1.0 * x[0,0] * x[1,0] + x[0,0] - 2.0 * x[1,0] \\\n + 4.0 * math.sin(0.1 * (x[0,0] + 0.2857)**2) + 12.0 * math.sin(0.1 * (x[1,0] - 0.4286)**2)\n\n def gradient(x):\n return np.mat([\\\n [2*x[0,0] -1.0*x[1,0] + 1.0 + 0.8 * (x[0,0] + 0.2857) * math.cos(0.1 * (x[0,0] + 0.2857)**2)],\\\n [4 * x[1,0] -1.0*x[0,0] -2.0 + 2.4 * (x[1,0] - 0.4286) * math.cos(0.1 * (x[1,0] - 0.4286)**2)]\\\n ])\n\n x = np.mat([[15],[15]])\n opt=ConjugateGradientMethod(objective, 2, gradient)\n print('微分:解析解')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n opt=ConjugateGradientMethod(objective, 2)\n print('微分:数値微分')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n print('problem4')\n def objective(x):\n return 100.0*(x[1,0] - x[0,0]**2)**2 + (1-x[0,0])**2\n\n def gradient(x):\n return np.mat([[-400.0*x[0,0]*(x[1,0]-x[0,0]**2) - 2*(1-x[0,0])],[200.0*(x[1,0]-x[0,0]**2)]])\n\n x = np.mat([[0],[0]])\n opt=ConjugateGradientMethod(objective, 2, gradient)\n print('微分:解析解')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n opt=ConjugateGradientMethod(objective, 2)\n print('微分:数値微分')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n print('problem5')\n def objective(x):\n return (1.5 - x[0,0]*(1 - x[1,0]))**2 + (2.25 - x[0,0] * (1-x[1,0]**2))**2 + (2.625 - x[0,0] * (1-x[1,0]**3))**2\n\n def gradient(x):\n return np.mat([\\\n [ -2.0*(1 - x[1,0])*(1.5 - x[0,0]*(1 - x[1,0])) -2.0 * (1-x[1,0]**2) * (2.25 - x[0,0] * (1-x[1,0]**2)) -2.0 * (1-x[1,0]**3) *(2.625 - x[0,0] * (1-x[1,0]**3))],\\\n [ 2.0*x[0,0]*(1.5 - x[0,0]*(1 - x[1,0])) +4.0 *x[0,0]*x[1,0]*(2.25 - x[0,0] * (1-x[1,0]**2)) + 6.0*x[0,0]*x[1,0]*x[1,0]*(2.625 - x[0,0] * (1-x[1,0]**3))]\\\n ])\n\n x = np.mat([[0],[0]])\n opt=ConjugateGradientMethod(objective, 2, gradient)\n print('微分:解析解')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n opt=ConjugateGradientMethod(objective, 2)\n print('微分:数値微分(' + str(opt.diff) +')')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n opt.diff = 1e-1\n print('微分:数値微分(' + str(opt.diff) +')')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n opt.diff = 1e-2\n print('微分:数値微分(' + str(opt.diff) +')')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())\n\n opt.diff = 1e-8\n print('微分:数値微分(' + str(opt.diff) +')')\n print('armijo', opt.solve(x).T, opt.converge, opt.get_iteration())\n print('optim ', opt.solve(x, armijo_mode=False).T, opt.converge, opt.get_iteration())","sub_path":"conjugate_gradient_method.py","file_name":"conjugate_gradient_method.py","file_ext":"py","file_size_in_byte":10568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"469914840","text":"#--------------------\n# exported functions\n#--------------------\ndef is_tarfile(name):\n \"\"\"Return True if name points to a tar archive that we\n are able to handle, else return False.\n \"\"\"\n try:\n t = open(name)\n t.close()\n return True\n except TarError:\n return False\n","sub_path":"test_segment_base/tarfile_0.py","file_name":"tarfile_0.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"504604950","text":"from gpiozero import DistanceSensor\nfrom time import sleep\n\n#proximity sensor to identify presence of an object in bin entry compartment\ndef itemsensor():\n sensor = DistanceSensor(echo=24, trigger=23)\n object = False\n count = 0\n #check 5 times in 5 seconds, set object variable accordingly\n for x in range(5):\n dist = sensor.distance * 100\n if dist < 10:\n count = count + 1\n if count == 5:\n object = True\n sleep(1)\n return(object)\n","sub_path":"itemsensor.py","file_name":"itemsensor.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"242703450","text":"#!/usr/bin/python3\n\nimport platform\nimport sys\nimport os\nimport fileinput\nimport subprocess\nimport socket\nimport platform\nfrom subprocess import Popen, PIPE\n\n#Variables\nhttp_srv = 'someo.cscs.ch'\nhostname = platform.node()\n\n##Functions\ndef check_program_exists(name):\n p = Popen(['/usr/bin/which', name], stdout=PIPE, stderr=PIPE)\n p.communicate()\n return p.returncode == 0\n\n# Save output in /tmp/sys_info_HOSTNAME.html\nsys.stdout = open('/tmp/sys_info_'+hostname.split(\".\")[0]+'.html','w')\n\n# Get IP\nhost_ip = socket.gethostbyname(hostname)\n# Linux Distribution\ndistro = str(platform.linux_distribution())\n# Kernel Version\nkernel = str(platform.release())\n# Distribution\ndist = platform.dist()\ndist = \" \".join(x for x in dist)\n# Memory\nwith open(\"/proc/meminfo\", \"r\") as f:\n lines = f.readlines()\n memtotal = lines[0].split()\n memfree = lines[1].split()\n memtotal = ( int(memtotal[1]) / 1024 / 1024 )\n memfree = ( int(memfree[1]) / 1024 / 1024 )\n# Uptime\nuptime = None\nwith open(\"/proc/uptime\", \"r\") as f:\n uptime = f.read().split(\" \")[0].strip()\nuptime = int(float(uptime))\nuptime_hours = uptime // 3600\nuptime_minutes = (uptime % 3600) // 60\n# Load\nwith open(\"/proc/loadavg\", \"r\") as f:\n load = f.read().strip()\n\n##\n# Create HTML\nprint(\"\")\nprint(\"\"+ hostname + \"\")\nprint(\"
    Hostname: \" + hostname )\nprint(\"
    Ip Address: \" + host_ip )\n#Processors\nif check_program_exists('lscpu') == True:\n cpuinfo = subprocess.getoutput('lscpu')\n cpuinfo_split = (cpuinfo.splitlines())\n values = [\"Architecture:\", \"CPU(s):\", \"Model name:\", \"Core(s) per socket:\", \"Thread(s) per core:\" ]\n for x in cpuinfo_split:\n for y in values:\n if y in x:\n print(\"
    \" + x)\nprint(\"
    Distribution: \" + dist )\nprint(\"
    Kernel: \" + kernel )\n#print(\"
    \" + platform.processor() )\n#BCM Version\nif check_program_exists('cmsh') == True:\n bcmver = subprocess.getoutput('cmsh -c \"main versioninfo\"')\n bcmver_split = (bcmver.splitlines())\n for x in bcmver_split:\n if \"Manager\" in x:\n print(\"
    BCM Version: \" + x.split()[2] )\n#Slurm Version\nif check_program_exists('sinfo') == True:\n slurmver = subprocess.getoutput('sinfo -V')\n print(\"
    Slurm Version: \" + slurmver.split()[1] )\n print(\"
    \")\n#GPFS Version\nif check_program_exists('mmdiag') == True:\n gpfsver = subprocess.getoutput('mmdiag --version')\n gpfsver_split = (gpfsver.splitlines())\n for x in gpfsver_split:\n if \"Current\" in x:\n print(x)\n#CUDA Version\nif check_program_exists('nvcc') == True:\n cudaver = subprocess.getoutput('nvcc --version')\n cudaver_split = (cudaver.splitlines())\n for x in cudaver_split:\n if \"release\" in x:\n print(\"
    CUDA Version: \" + x.split(' ')[5] )\n#NVIDIA Driver Version\nif check_program_exists('nvidia-smi') == True:\n nvidiadrv = subprocess.getoutput('nvidia-smi')\n nvidiadrv_split = (nvidiadrv.splitlines())\n for x in nvidiadrv_split:\n if \"Driver Version\" in x:\n print(\"
    NVIDIA Driver Version: \" + x.split()[5])\n#Uptime\nprint(\"
    Uptime: \" + str(uptime_hours) + \"h\" \":\" + str(uptime_minutes) + \"m\")\n#Load\nprint(\"
    Average Load: \" + load )\n#Memory\nprint(\"
    Memory Total: \" + str(int(memtotal)) + ' GB')\nprint(\"
    Memory Free: \" + str(int(memfree)) + ' GB')\nprint(\"\")\nsys.stdout.close()\n\n# Copy HTML to remote server\np = subprocess.Popen(['scp', '/tmp/sys_info_'+hostname.split(\".\")[0]+'.html', 'root@'+ http_srv +':/var/www/html/confluence/sys_info_'+hostname.split(\".\")[0]+'.html'])\nsts = p.wait()\n\n# Delete files from /tmp\nos.remove('/tmp/sys_info_'+hostname.split(\".\")[0]+'.html')\n","sub_path":"sysinfo.py","file_name":"sysinfo.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"509747325","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 3 15:45:29 2019\n\n@author: cleandersonlins\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# input variables\ny_pos = -1\nfilename = \"Position_Salaries.csv\"\n\n# importing the dataset\ndataset = pd.read_csv(filename)\nX = dataset.iloc[:, 1:y_pos].values\ny = dataset.iloc[:, y_pos].values\n\n# fitting Random Forest Regression to the dataset\nfrom sklearn.ensemble import RandomForestRegressor\nreg = RandomForestRegressor(n_estimators=300, random_state=0).fit(X, y)\n\n# predicting a new result\ny_pred = reg.predict([[6.5]])\n\n# visualizing Random Forest Regression results for higher resolution\nX_grid = np.arange(min(X), max(X), 0.01)\nX_grid = X_grid.reshape((len(X_grid), 1))\nplt.scatter(X, y, color='r')\nplt.plot(X_grid, reg.predict(X_grid), color='b')\nplt.title(\"Truth or bluff\")\nplt.xlabel(\"Position Level\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Part 2 - Regression/regression_template_me.py","file_name":"regression_template_me.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"79448796","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python3.4/dist-packages/fuzzyworkbench/varbrowser.py\n# Compiled at: 2015-10-01 12:54:48\n# Size of source mod 2**32: 4815 bytes\nfrom math import pi\nfrom tkinter import *\nfrom tkinter.ttk import *\nfrom fuzzyworkbench.entitybrowser import EntityBrowser\nfrom fuzzyworkbench.vareditormodel import VarEditorModel, VarEditorFunction\n_sampleVars = {('e', -pi / 4, pi / 4): [\n (\n 'N', 'trapezoidal', (-100, -90, -pi / 4, 0)),\n (\n 'Z', 'triangular', (-pi / 4, 0, pi / 4)),\n (\n 'P', 'trapezoidal', (0, pi / 4, 90, 100))], \n ('de', -pi / 4, pi / 4): [\n (\n 'MN', 'trapezoidal', (-100, -90, -pi / 4, -pi / 8)),\n (\n 'N', 'triangular', (-pi / 4, -pi / 8, 0)),\n (\n 'Z', 'triangular', (-pi / 8, 0, pi / 8)),\n (\n 'P', 'triangular', (0, pi / 8, pi / 4)),\n (\n 'MP', 'trapezoidal', (pi / 8, pi / 4, 90, 100))], \n ('u', -30, 30): [\n ('MN', 'triangular', (-30, -20, -10)),\n ('N', 'triangular', (-20, -10, 0)),\n ('Z', 'triangular', (-10, 0, 10)),\n ('P', 'triangular', (0, 10, 20)),\n ('MP', 'triangular', (10, 20, 30))]}\n\nclass VarBrowser(EntityBrowser, Frame):\n\n def __init__(self, master, editor, **kw):\n Frame.__init__(self, master, **kw)\n EntityBrowser.__init__(self, editor)\n self.grid_rowconfigure(0, weight=1)\n self._list = Listbox(self)\n self._list['selectmode'] = SINGLE\n self._list['exportselection'] = False\n self._btnAdd = Button(self, text='+')\n self._btnAdd['command'] = self._actionBtnAdd\n self._btnDel = Button(self, text='-')\n self._btnDel['command'] = self._actionBtnDel\n self._list.grid(row=0, column=0, columnspan=2, sticky='NS')\n self._btnAdd.grid(row=1, column=0)\n self._btnDel.grid(row=1, column=1)\n self._createSampleVars()\n self._list.bind('<>', self._selChanged)\n\n def _createSampleVars(self):\n for var, functions in _sampleVars.items():\n v = VarEditorModel(self._editor, var[0], var[1], var[2])\n for function in functions:\n f = VarEditorFunction(self._editor, function[0], function[1])\n f.setParams(function[1], function[2])\n v.addFunction(f)\n\n self.add(v)\n\n self._updateButtonSensivity()\n\n def _actionBtnAdd(self):\n var = VarEditorModel(self._editor, 'v1', -10, 10)\n function = VarEditorFunction(self._editor, 'Z', 'triangular')\n function.setParams('triangular', (-10, 0, 10))\n var.addFunction(function)\n self.add(var)\n self._updateButtonSensivity()\n\n def _actionBtnDel(self):\n if self._list.size() > 1:\n self.remove(self.getSelected())\n self._updateButtonSensivity()\n\n def _updateButtonSensivity(self):\n if self._list.size() > 1:\n self._btnDel['state'] = NORMAL\n else:\n self._btnDel['state'] = DISABLED\n\n def _selChanged(self, event=None):\n if self._editor:\n self._editor.notify(self)\n\n def updateLabels(self):\n currEntity = self.getSelected()\n if not currEntity:\n return\n self._list.delete(0, END)\n for e in self._entities:\n self._list.insert(END, str(e))\n\n self.select(currEntity)\n\n def add(self, entity):\n EntityBrowser.add(self, entity)\n self._list.insert(END, str(entity))\n self.select(entity)\n\n def remove(self, entity):\n idx = self._entities.index(entity)\n self._list.delete(idx)\n EntityBrowser.remove(self, entity)\n self.select(self._entities[0])\n\n def select(self, entity):\n self._list.selection_clear(0, END)\n if not isinstance(entity, int):\n entity = self._entities.index(entity)\n self._list.selection_set(entity)\n self._selChanged()\n\n def getSelected(self):\n idx = self._list.curselection()\n if idx:\n return self._entities[idx[0]]\n\n def size(self):\n return self._list.size()\n\n def getVars(self):\n return self._entities\n\n\nif __name__ == '__main__':\n root = Tk()\n app = VarBrowser(root, None)\n app.pack()\n root.mainloop()","sub_path":"pycfiles/fuzzyworkbench-0.1.1.linux-x86_64.tar/varbrowser.cpython-34.py","file_name":"varbrowser.cpython-34.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"118902798","text":"symptoms = [\n ('CA', 'Cansaço'),\n ('CN', 'Congestão nasal'),\n ('DI', 'Diarreia'),\n ('SB', 'Dificuldade respiratória'),\n ('ST', 'Dor de garganta'),\n ('DC', 'Dor de cabeça'),\n ('AP', 'Dores no corpo'),\n ('FA', 'Falta de apetite'), # famoso fastio\n ('FV', 'Febre'),\n ('RN', 'Nariz escorrendo'),\n ('NA', 'Náusea'),\n ('TP', 'Tosse produtiva'),\n ('TS', 'Tosse seca'),\n ('VO', 'Vômitos'),\n]\n\nintensities = [\n ('', 'Não apresenta'),\n ('L', 'Leve'),\n ('M', 'Moderada'),\n ('H', 'Grave'),\n]\n\ngenders = [\n ('F', 'Feminino'),\n ('M', 'Masculino'),\n ('N', 'Não quer declarar')\n]\n\naddress_types = [\n ('HM', 'Residencial'),\n ('WK', 'Trabalho'),\n ('OT', 'Outro'),\n]\n\n# drugs = [\n# ('', 'Anti hipertensivo'),\n# ('', 'Imunossupressores'),\n# ('', 'Anti diabéticos'),\n# ('', 'Antibióticos'),\n# ('', 'Corticoide'),\n# ('', 'Anti inflamatório')\n# ]\n\ncomorbidities = [\n ('Y', 'Artrite reumatóide'),\n ('A', 'Asma'),\n ('C', 'Bronquite crônica'),\n ('N', 'Câncer'),\n ('E', 'Demência'),\n ('D', 'Diabetes'),\n ('H', 'Doença cardíacas'),\n ('L', 'Doença crônica no fígado'),\n ('R', 'Doença renal crônica'),\n ('W', 'Doenças reumáticas'),\n ('P', 'Doença pulmonar crônica'),\n ('I', 'Imunosuprimido'),\n ('T', 'Hipertensão'),\n ('V', 'HIV+'),\n ('B', 'Obesidade'),\n ('U', 'Portador de Lúpus'),\n]\n\ncountries = [\n ('CHN', 'China'),\n ('BRA', 'Brasil'),\n ('ESP', 'Espanha'),\n ('USA', 'Estados Unidos'),\n ('ITA', 'Itália'),\n]\n\nexposure = [\n ('confirmed_cases', 'Contato com casos confirmados'),\n ('suspect_cases', 'Contato com casos suspeitos'),\n ('foreign', 'Contato com pessoas que estiveram em locais com casos confirmados'),\n]\n\nresults = [\n ('SR', 'Sem resposta'),\n ('PO', 'Positivo'),\n ('NE', 'Negativo'),\n]\n\nstatus = (\n ('N', 'Normal'),\n ('T', 'Testado'),\n ('S', 'Suspeito'),\n ('C', 'Confirmado'),\n ('M', 'Morto'),\n ('I', 'Imune'),\n)\n\naction_choices = (\n ('C','CREATE'),\n ('D','DELETE'),\n ('U','UPDATE'),\n)\n\nmodel_choices = (\n ('PR','PROFILE'),\n ('AD','ADDRESS'),\n ('MO','MONITORING'),\n ('SY','SYMPTOM'),\n ('TR','TRIP'),\n ('RE','REQUEST'),\n)","sub_path":"monitoring/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"640239523","text":"# Copyright 2012 Mixpanel, Inc.\n# Copyright 2014 Rackspace, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n'''\nA memcached client with a different shading strategy.\n\nUsage example::\n\n import moecache\n\n with moecache.Client([(\"127.0.0.1\", 11211), (\"127.0.0.1\", 11213)],\n timeout=1, connect_timeout=5) as mc:\n mc.set(\"some_key\", \"Some value\")\n value = mc.get(\"some_key\")\n mc.delete(\"another_key\")\n\n.. note::\n\n If the value to store is of type ``str``, the entry is binary compatible\n with EnyimMemcached; otherwise, the value will be \"pickled\" with protocol\n version 2 and can only be read by moecache.\n'''\n\nimport errno\nimport re\nimport socket\nimport bisect\nimport sys\n\ntry:\n from __pypy__.builders import StringBuilder\n import pickle\n\n class OStringStream(object):\n def __init__(self):\n self.__b = StringBuilder()\n\n def write(self, s):\n self.__b.append(s)\n\n def getvalue(self):\n return self.__b.build()\n\n def pickle_dumps(obj):\n buf = OStringStream()\n pickler = pickle.Pickler(buf, 2)\n pickler.dump(obj)\n return buf.getvalue()\n\n from cPickle import loads as pickle_loads\n\nexcept ImportError:\n try:\n from cStringIO import StringIO as OStringStream\n import cPickle\n\n def pickle_dumps(obj):\n return cPickle.dumps(obj, 2)\n\n pickle_loads = cPickle.loads\n\n except ImportError:\n from io import BytesIO as OStringStream\n import pickle\n\n def pickle_dumps(obj):\n return pickle.dumps(obj, 2)\n\n pickle_loads = pickle.loads\n\n\nclass ClientException(Exception):\n '''\n Raised when memcached does something we don't expect, or the\n memcached deployment is not compatible with moecache.\n\n .. note::\n\n This does not include `socket errors\n `_.\n '''\n\n def __init__(self, msg, item=None):\n if item is not None:\n msg += ': ' + repr(item)\n super(ClientException, self).__init__(msg)\n\n\nclass ValidationException(ClientException):\n '''\n Raised when the user input is invalid to this library.\n '''\n\n def __init__(self, msg, item):\n super(ValidationException, self).__init__(msg, item)\n\n\ndef fnv1a_32(seed=0x811c9dc5):\n def do_hash(s):\n hval = seed\n fnv_32_prime = 0x01000193\n\n for c in s:\n hval = hval ^ ord(c)\n hval = (hval * fnv_32_prime) & 0xffffffff\n\n return hval\n return do_hash\n\n\ndef _node_conf(timeout, connect_timeout):\n\n class Node(object):\n\n def __init__(self, addr):\n self._addr = addr\n self._socket = None\n\n def __str__(self):\n return ':'.join((self._addr[0], str(self._addr[1])))\n\n def __repr__(self): # pragma: no cover\n return '' % self\n\n def connect(self):\n # buffer needed since we always ask for 4096 bytes at a time\n # thus, might read more than the current expected response\n # cleared on every reconnect since old bytes are part of old\n # session and can't be reused\n self._buffer = bytearray()\n\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._socket.settimeout(connect_timeout)\n\n try:\n self._socket.connect(self._addr)\n self._socket.settimeout(timeout)\n except (socket.error, socket.timeout):\n self._socket = None # don't want to hang on to bad socket\n raise\n\n def gets(self, length=None):\n '''\n Return the next length bytes from server, or, when length is\n ``None``, read a response delimited by \\r\\n and return it\n (including \\r\\n).\n\n Use latter only when \\r\\n is unambiguous -- aka for control\n responses, not data.\n '''\n result = None\n while result is None:\n if length: # length = 0 is ambiguous, so don't use\n if len(self._buffer) >= length:\n result = bytes(self._buffer[:length])\n self._buffer[:] = self._buffer[length:]\n else:\n delim_index = self._buffer.find(b'\\r\\n')\n if delim_index != -1:\n result = bytes(self._buffer[:delim_index+2])\n self._buffer[:] = self._buffer[delim_index+2:]\n\n if result is None:\n try:\n tmp = self._socket.recv(4096)\n except (socket.error, socket.timeout) as e:\n self.close()\n raise e\n\n if not tmp:\n # we handle common close/retry cases in send(command)\n # however, this can happen if server suddenly goes away\n # (e.g. restarting memcached under sufficient load)\n raise socket.error('unexpected socket close on recv')\n else:\n self._buffer += tmp\n return result\n\n def send(self, command):\n '''\n Send command to server and return initial response line.\n Will reopen socket if it got closed (either locally or by\n server).\n '''\n if self._socket: # try to find out if the socket is still open\n try:\n self._socket.settimeout(0)\n self._socket.recv(1, socket.MSG_PEEK)\n # if recv didn't raise, then the socket was closed or\n # there is junk in the read buffer, either way, close\n self.close()\n except socket.error as e:\n if e.errno == errno.EAGAIN:\n # this is expected if the socket is still open\n self._socket.settimeout(timeout)\n else:\n self.close()\n\n if not self._socket:\n self.connect()\n\n self._socket.sendall(command)\n return self.gets()\n\n def close(self):\n '''\n Close the socket if opened.\n\n .. note::\n\n Sockets are opened the first time a command is run.\n\n Raises socket errors.\n '''\n if self._socket:\n self._socket.close()\n self._socket = None\n\n return Node\n\n\nclass Client(object):\n '''\n Creates an object to hold a moecache session. The object is also\n a context manager, which automatically closes the sockets when the\n control leaves the :token:`with` statement.\n\n ``servers`` can be a single server, or a list of servers, where each\n server is a ``(host, port)`` tuple, same as a ``socket`` AF_INET\n address.\n\n If ``timeout`` is not specified, socket operations may block forever.\n If ``connect_timeout`` is not specified, the ``timeout`` setting will\n also be applied to the socket ``connect()`` operations.\n '''\n\n is_py3 = sys.version_info[0] == 3\n\n def __init__(self, servers, timeout=None, connect_timeout=None):\n _node_type = _node_conf(timeout, connect_timeout\n if connect_timeout is not None\n else timeout)\n self._nodes = list(map(_node_type, [servers]\n if type(servers) is tuple else servers))\n self._servers = {}\n self._build_index(self._nodes)\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.close()\n\n # key supports ascii sans space and control chars\n # \\x21 is !, right after space, and \\x7e is -, right before DEL\n # also 1 <= len <= 250 as per the spec\n _valid_key_re = re.compile('^[\\x21-\\x7e]{1,250}$')\n\n @classmethod\n def _validate_key(cls, key):\n if not isinstance(key, str): # avoid bugs subtle and otherwise\n raise ValidationException('key must be str', key)\n m = cls._valid_key_re.match(key)\n if m:\n # in python re, $ matches either end of line or right before\n # \\n at end of line. We can't allow latter case, so\n # making sure length matches is simplest way to detect\n if len(m.group(0)) != len(key):\n raise ValidationException('trailing newline', key)\n else:\n raise ValidationException('invalid key', key)\n\n if Client.is_py3:\n return key.encode()\n else:\n return key\n\n def _build_index(self, nodes):\n mutations = 100\n keys = []\n\n for node in nodes:\n tmp_keys = self._generate_keys(node, mutations)\n # XXX old mapping is not dropped\n for key in tmp_keys:\n self._servers[key] = node\n keys.extend(tmp_keys)\n\n self._keys = sorted(keys)\n\n # XXX\n # simulate a type of bug -- the hasher is not properly seeded\n # when the first time it's being used\n _uninitialized_hasher = staticmethod(fnv1a_32(0))\n _hasher = staticmethod(fnv1a_32())\n\n @classmethod\n def _generate_keys(cls, node, n):\n address = str(node)\n # XXX all servers but not the first one use the seeded hasher\n return ([cls._uninitialized_hasher(address + '-0')] +\n [cls._hasher('-'.join((address, str(i))))\n for i in range(1, n)])\n\n def _find_node(self, key):\n key_hash = self._uninitialized_hasher(key)\n i = bisect.bisect_left(self._keys, key_hash)\n\n if i == len(self._keys):\n # largest key uses the first server\n i = 0\n elif i == 0 and self._keys[i] != key_hash:\n # smallest key uses the last server\n i = len(self._keys) - 1\n\n return self._servers[self._keys[i]]\n\n def close(self):\n '''\n Closes any opened socket.\n\n Sockets are automatically closed when the ``Client`` object gets\n out of the context.\n\n Raises socket errors.\n '''\n for node in self._nodes:\n node.close()\n\n def delete(self, key):\n '''\n Deletes a key/value pair.\n\n Raises ``ValidationException`` if ``key`` is invalid. May also\n raise ``ClientException`` and socket errors.\n\n .. note:: The postcondition of this operation is that the entry no\n longer exists, so if the key does not exists at the first\n place, nothing happens and the function returns without error.\n '''\n # req - delete [noreply]\\r\\n\n # resp - DELETED\\r\\n\n # or\n # NOT_FOUND\\r\\n\n key_bytes = self._validate_key(key)\n\n command = b'delete ' + key_bytes + b'\\r\\n'\n resp = self._find_node(key).send(command)\n if resp != b'DELETED\\r\\n' and resp != b'NOT_FOUND\\r\\n':\n raise ClientException('delete failed', resp)\n\n def get(self, key):\n '''\n Gets a single value. Returns :token:`None` if the key does not\n exist.\n\n Raises ``ValidationException`` if ``key`` is invalid. May also\n raise ``ClientException`` and socket errors.\n '''\n # req - get [ ...]\\r\\n\n # resp - VALUE []\\r\\n\n # \\r\\n (if exists)\n # [...]\n # END\\r\\n\n key_bytes = self._validate_key(key)\n\n command = b'get ' + key_bytes + b'\\r\\n'\n\n val = None\n node = self._find_node(key)\n resp = node.send(command)\n error = None\n\n # make sure well-formed responses are all consumed\n while resp != b'END\\r\\n':\n terms = resp.split()\n if len(terms) == 4 and terms[0] == b'VALUE': # exists\n typecode = int(terms[2]) ^ 0x100\n length = int(terms[3])\n if typecode > 0xff:\n error = ClientException('not a moecache deployment')\n if terms[1] == key_bytes:\n received = node.gets(length+2)[:-2]\n if typecode == 18:\n if Client.is_py3:\n val = received.decode()\n else:\n val = received\n elif typecode == 0:\n val = pickle_loads(received)\n else:\n error = ClientException('unsupported data type',\n typecode)\n else:\n error = ClientException('received unwanted response')\n else:\n raise ClientException('get failed', resp)\n resp = node.gets()\n\n if error is not None:\n # this can happen if a memcached instance contains items set\n # by a previous client\n # leads to subtle bugs, so fail fast\n raise error\n\n return val\n\n def set(self, key, val, exptime=0):\n '''\n Sets a key to a value with an optional expire time in seconds\n (0 means don't auto-expire).\n\n A valid ``key`` is a string with a minimal length of 1 and a\n maximal length of 250, and each character is an ASCII graph\n character (printable except spaces).\n\n A valid ``exptime`` is a non-negative integer.\n\n If any of these arguments is invalid, ``ValidationException`` will\n be raise. May also raise ``ClientException`` and socket errors.\n '''\n # req - set [noreply]\\r\\n\n # \\r\\n\n # resp - STORED\\r\\n (or others)\n key_bytes = self._validate_key(key)\n\n # typically, if val is > 1024**2 bytes server returns:\n # SERVER_ERROR object too large for cache\\r\\n\n # however custom-compiled memcached can have different limit\n # so, we'll let the server decide what's too much\n\n if not isinstance(exptime, int):\n raise ValidationException('exptime not int', exptime)\n elif exptime < 0:\n raise ValidationException('exptime negative', exptime)\n\n if isinstance(val, str):\n flag = b' 274 ' # 18 | 0x100\n if Client.is_py3:\n sent = val.encode()\n else:\n sent = val\n else:\n flag = b' 256 ' # 0 | 0x100\n sent = pickle_dumps(val)\n\n buf = OStringStream()\n buf.write(b'set ')\n buf.write(key_bytes)\n buf.write(flag)\n buf.write(str(exptime).encode())\n buf.write(b' ')\n buf.write(str(len(sent)).encode())\n buf.write(b'\\r\\n')\n buf.write(sent)\n buf.write(b'\\r\\n')\n\n command = buf.getvalue()\n resp = self._find_node(key).send(command)\n if resp != b'STORED\\r\\n':\n raise ClientException('set failed', resp)\n\n def stats(self, additional_args=None):\n '''\n Aggregates the stats from all the servers.\n\n ``additional_args`` is a byte string being passed verbatim to the\n servers. See `the memcached wiki\n `_\n for details or `the spec\n `_\n for even more details.\n\n Raises ``ClientException`` and socket errors.\n '''\n # req - stats [additional args]\\r\\n\n # resp - STAT \\r\\n (one per result)\n # END\\r\\n\n if additional_args is not None:\n if Client.is_py3:\n additional_args = additional_args.encode()\n command = b'stats ' + additional_args + b'\\r\\n'\n else:\n command = b'stats\\r\\n'\n\n def do_stats(node):\n resp = node.send(command)\n result = {}\n while resp != b'END\\r\\n':\n terms = resp.split()\n if len(terms) == 3 and terms[0] == b'STAT':\n if Client.is_py3:\n result[terms[1].decode()] = terms[2].decode()\n else:\n result[terms[1]] = terms[2]\n else:\n raise ClientException('stats failed', resp)\n resp = node.gets()\n return result\n\n return list(map(do_stats, self._nodes))\n","sub_path":"moecache.py","file_name":"moecache.py","file_ext":"py","file_size_in_byte":17132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"178847750","text":"import os\n\nimport openml.config\nimport openml.testing\n\n\nclass TestConfig(openml.testing.TestBase):\n\n def test_config_loading(self):\n self.assertTrue(os.path.exists(openml.config.config_file))\n self.assertTrue(os.path.isdir(os.path.expanduser('~/.openml')))\n\n\nclass TestConfigurationForExamples(openml.testing.TestBase):\n\n def test_switch_to_example_configuration(self):\n \"\"\" Verifies the test configuration is loaded properly. \"\"\"\n # Below is the default test key which would be used anyway, but just for clarity:\n openml.config.apikey = \"610344db6388d9ba34f6db45a3cf71de\"\n openml.config.server = self.production_server\n\n openml.config.start_using_configuration_for_example()\n\n self.assertEqual(openml.config.apikey, \"c0c42819af31e706efe1f4b88c23c6c1\")\n self.assertEqual(openml.config.server, self.test_server)\n\n def test_switch_from_example_configuration(self):\n \"\"\" Verifies the previous configuration is loaded after stopping. \"\"\"\n # Below is the default test key which would be used anyway, but just for clarity:\n openml.config.apikey = \"610344db6388d9ba34f6db45a3cf71de\"\n openml.config.server = self.production_server\n\n openml.config.start_using_configuration_for_example()\n openml.config.stop_using_configuration_for_example()\n\n self.assertEqual(openml.config.apikey, \"610344db6388d9ba34f6db45a3cf71de\")\n self.assertEqual(openml.config.server, self.production_server)\n\n def test_example_configuration_stop_before_start(self):\n \"\"\" Verifies an error is raised is `stop_...` is called before `start_...`. \"\"\"\n error_regex = \".*stop_use_example_configuration.*start_use_example_configuration.*first\"\n self.assertRaisesRegex(RuntimeError, error_regex,\n openml.config.stop_using_configuration_for_example)\n\n def test_example_configuration_start_twice(self):\n \"\"\" Checks that the original config can be returned to if `start..` is called twice. \"\"\"\n openml.config.apikey = \"610344db6388d9ba34f6db45a3cf71de\"\n openml.config.server = self.production_server\n\n openml.config.start_using_configuration_for_example()\n openml.config.start_using_configuration_for_example()\n openml.config.stop_using_configuration_for_example()\n\n self.assertEqual(openml.config.apikey, \"610344db6388d9ba34f6db45a3cf71de\")\n self.assertEqual(openml.config.server, self.production_server)\n","sub_path":"tests/test_openml/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"141898190","text":"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\nheader = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36\"\nlogin_data = {\n 'rdolst': 'S',\n 'Txtstudid': '16z310',\n 'TxtPasswd': '14aug98',\n 'btnlogin': 'Login'\n}\n\nwith requests.Session() as s:\n url = \"https://ecampus.psgtech.ac.in/studzone/\"\n r = s.get(url)\n soup = BeautifulSoup(r.content, 'lxml')\n login_data['__EVENTVALIDATION'] = soup.find('input', attrs={'name' : '__EVENTVALIDATION'})['value']\n login_data['__VIEWSTATE'] = soup.find('input', attrs={'name' : '__VIEWSTATE'})['value']\n \n r2 = s.post(url, data=login_data)\n #soup2 = BeautifulSoup(r2.content,'lxml')\n #print(soup2)\n\n \n # ATTENDANCE PERCENTAGES\n \n url2 = \"https://ecampus.psgtech.ac.in/studzone/AttWfPercView.aspx\"\n r3 = s.get(url2)\n soup3 = BeautifulSoup(r3.content, 'lxml')\n table = soup3.find_all('table', class_='cssbody')\n #print(table)\n list1 = []\n table_rows = table[0].find_all('tr')\n for tr in table_rows:\n td = tr.find_all('td')\n row = [i.text for i in td]\n list1.append(row)\n #print(list1)\n df = pd.DataFrame(list1)\n print(df)\n \n \n #EXAM RESULTS\n \n url3 = \"https://ecampus.psgtech.ac.in/studzone/FrmEpsStudResult.aspx\"\n r4 = s.get(url3)\n soup4 = BeautifulSoup(r4.content, 'lxml')\n table2 = soup4.find_all('table', {\"id\": \"DgResult\"})\n #print(table2)\n list2 = []\n table_rows2 = table2[0].find_all('tr')\n for tr in table_rows2:\n td = tr.find_all('td')\n row = [i.text for i in td]\n list2.append(row)\n #print(list2)\n df2 = pd.DataFrame(list2)\n print(df2)\n \n \n #SEATING ARRANGEMENT\n \n url4 = \"https://ecampus.psgtech.ac.in/studzone/EpsWfSeating.aspx\"\n r5 = s.get(url4)\n soup5 = BeautifulSoup(r5.content,'lxml')\n table3 = soup5.find_all('table', {\"id\":\"DgSeat\"})\n #print(table3)\n list3 = []\n table_rows3 = table3[0].find_all('tr')\n for tr in table_rows3:\n td = tr.find_all('td')\n row = [i.text for i in td]\n list3.append(row)\n #print(list3)\n df3 = pd.DataFrame(list3)\n print(df3)\n \n \n #CA Timetable\n \n url5 = \"https://ecampus.psgtech.ac.in/studzone/FrmEpsTestTimetable.aspx\"\n r6 = s.get(url5)\n soup6 = BeautifulSoup(r6.content,'lxml')\n table4 = soup6.find_all('table', {\"id\":\"DgResult\"})\n #print(table3)\n list4 = []\n table_rows4 = table4[0].find_all('tr')\n for tr in table_rows4:\n td = tr.find_all('td')\n row = [i.text for i in td]\n list4.append(row)\n #print(list3)\n df4 = pd.DataFrame(list4)\n print(df4)\n\ndf.to_csv('attendance.csv', index=False, header=False)\ndf2.to_csv('examResult.csv', index =False, header=False)\ndf3.to_csv('seatingArrangement.csv', index=False, header=False)\ndf4.to_csv('caTimetable.csv', index=False, header=False)\n","sub_path":"studentZoneScrapper.py","file_name":"studentZoneScrapper.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"586217887","text":"# decomposer.py \n# ALS 2017/06/01\nimport os\nfrom astropy.io import fits\nimport lsst.afw.image as afwImage\n\nfrom .. import Decomposer\n\nimport matchpsf\nimport subtractexp\n\nclass lsstDecomposer(Decomposer):\n\n\tdef __init__(self, **kwargs):\n\t\t\"\"\"\n\t\tchild of decomposer\n\n\t\tUse homemade code to do psf matching. Requires psf-{band}.fits files. \n\t\t\"\"\"\n\t\t\n\t\tsuper(lsstDecomposer, self).__init__(**kwargs)\n\n\n\tdef _get_stamp_exposure(self, band):\n\t\tfp = self.get_fp_stamp(band)\n\t\treturn afwImage.ExposureF(fp)\n\n\n\tdef _get_contsub_exposure(self, band, bandconti):\n\t\tfp = self.get_fp_stamp_contsub(band, bandconti)\n\t\treturn afwImage.ExposureF(fp)\n\n\n\tdef make_stamp_linemap(self, bandline, bandconti, line='OIII5008', overwrite=False):\n\t\t\"\"\"\n\t\tmake stamp of line map in observed frame (?) flux with units [erg s-1 cm-2]\n\n\t\tParams\n\t\t------\n\t\tself\n\t\tbandline (str)\n\t\tbandconti (str)\n\t\tline = 'OIII5008' (str)\n\t\toverwrite = False (bool)\n\n\t\tReturn\n\t\t------\n\t\tstatus (bool)\n\n\t\tWrite Output \n\t\t------------\n\t\te.g., stamp-lOIII5008.fits\n\t\t\"\"\"\n\t\tfn = self.get_fp_stamp_line(line)\n\n\t\tif not os.path.isfile(fn) or overwrite:\n\t\t\tself.make_stamp_contsub(band=bandline, bandconti=bandconti, overwrite=overwrite)\n\n\t\t\ts = self._get_spector()\n\t\t\tr = s.calc_fline_over_fnuband(band=bandline, line=line)\n\n\t\t\texp = self._get_contsub_exposure(band=bandline, bandconti=bandconti)\n\t\t\timg = exp.getMaskedImage()\n\t\t\timg *= r\n\n\t\t\traise Exception(\"need to check whether ratio with unit can be multipled by maskedImg\")\n\n\t\t\texp.writeFits(fn)\n\n\t\telse:\n\t\t\tprint(\"[lsstdecomposer] skip making stamp_contsub as files exist\")\n\n\t\treturn os.path.isfile(fn)\n\n\n\tdef make_stamp_contsub(self, band, bandconti, overwrite=False):\n\t\t\"\"\"\n\t\tmake stamp that is continuum subtracted\n\n\t\tParams\n\t\t------\n\t\tself\n\t\tband (str)\n\t\tbandconti (str)\n\t\toverwrite=False\n\n\t\tReturn\n\t\t------\n\t\tstatus\n\n\t\tWrite Output (e.g., if band = 'i', bandto = 'z')\n\t\t------------\n\t\tstamp-i_contsub-z.fits\n\t\t\"\"\"\n\t\tfn = self.get_fp_stamp_contsub(band, bandconti)\n\n\t\tif not os.path.isfile(fn) or overwrite:\n\t\t\tprint(\"[lsstdecomposer] making stamp_contsub\")\n\n\t\t\tratioconti = self._get_conti_fnu_ratio_from_spector(band, bandconti)\n\n\t\t\texp = self._get_stamp_exposure(band)\n\t\t\texp_conti = self._get_stamp_exposure(bandconti)\n\n\t\t\texpm, expm_conti = matchpsf.match_two_exp_psf(exp, exp_conti)\n\t\t\texp_sub = subtractexp.subtract_exp_with_ratio(expm, expm_conti, a1=1., a2=ratioconti)\n\n\t\t\texp_sub.writeFits(fn) \n\n\t\telse:\n\t\t\tprint(\"[lsstdecomposer] skip making stamp_contsub as files exist\")\n\n\t\treturn os.path.isfile(fn)\n\n\n\n\t\t\n\t# def make_stamp_psfmatch(self, band, bandto, overwrite=True):\n\t# \t\"\"\" \n\t# \tmake stamp that has psf matched to stamp of another band\n\n\t# \tParams\n\t# \t------\n\t# \tself\n\t# \tband (str)\n\t# \tbandto (str)\n\t# \toverwrite=False\n\n\t# \tReturn\n\t# \t------\n\t# \tstatus\n\n\t# \tWrite Output (e.g., if band = 'i', bandto = 'z')\n\t# \t------------\n\t# \tstamp-i_psfmatched-z.fits\n\t# \t\"\"\"\n\t# \tfn = self.get_fp_stamp_psfmatched(band, bandto)\n\n\t# \tif not os.path.isfile(fn) or overwrite:\n\t# \t\tprint(\"[lsstdecomposer] making stamp_psfmatch\")\n\t# \t\traise NotImplementedError(\"to be written\")\n\n\t# \t\t# psf = fits.getdata(self.get_fp_psf(band))\n\t# \t\t# psfto = fits.getdata(self.get_fp_psf(bandto))\n\n\t# \t\t# hdus = fits.open(self.get_fp_stamp(band))\n\t# \t\t# stamp = hdus[0].data\n\n\t# \t\t# stamp_cnvled, psf_cnvled, kernel_cnvl = matchpsf.match_psf(stamp, psf, psfto)\n\n\t# \t\t# # write psf matched stamp\n\t# \t\t# hdus[0].data = stamp_cnvled\n\t# \t\t# hdus[0].header['BDPSFTO'] = (bandto, 'the band the PSF is matched to')\n\t# \t\t# hdus[0].header['COMMENT'] = \"PSF matched by ALS\"\n\t# \t\t# hdus.writeto(self.get_fp_stamp_psfmatched(band, bandto), overwrite=overwrite)\n\n\t# \t\t# # write psf matched psf\n\t# \t\t# fits.PrimaryHDU(psf_cnvled).writeto(self.get_fp_psf_psfmatched(band, bandto), overwrite=overwrite)\n\n\t# \t\t# # write convolving kernel\n\t# \t\t# fits.PrimaryHDU(kernel_cnvl).writeto(self.get_fp_psf_kernelcnvl(band, bandto), overwrite=overwrite)\n\t# \telse:\n\t# \t\tprint(\"[lsstdecomposer] skip making stamp_psfmatch as files exist\")\n\n\t# \treturn os.path.isfile(fn)\n\n\n\n\n","sub_path":"bubbleimg/imgdecompose/lsst/lsstdecomposer.py","file_name":"lsstdecomposer.py","file_ext":"py","file_size_in_byte":4040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"165364279","text":"from de.jando.main.URLMappings import URLMapping\n\n__author__ = 'MJay'\n\n\nclass DotaUpdate:\n\n def __init__(self, title):\n self.title = title\n self.updateCode = []\n self.heroes = URLMapping().heroes\n self.items = URLMapping().items\n\n def matchItemsDivToBBCode(self, ar):\n ar = self.checkIfNewItems(ar)\n ar = self.fillUrls(ar, self.items)\n ar = self.replaceStandardTags(ar)\n return ar\n\n def matchGeneralDivToBBCode(self, ar):\n ar = self.replaceStandardTags(ar)\n return ar\n\n def matchHeroesDivToBBCode(self, ar):\n ar = self.fillUrls(ar, self.heroes)\n ar = self.replaceStandardTags(ar)\n return ar\n\n def printMap(self, map):\n for key in sorted(map):\n print(\"'%s:' %s,\" % (key, map[key]))\n\n def fillUrls(self, ar, map):\n while ar.find('[[') != -1:\n try:\n key = ar[ar.find('[['):ar.find(']]') + 2]\n array = map[ar[ar.find('[[') + 2:ar.find(']]')]]\n ar = ar.replace(key,\n \"[IMG]\" + array[0] + \"[/IMG][indent=15][/indent]\" + array[1],\n 1)\n except KeyError:\n print(\"Key: \" + key + \" not represent\")\n ar = ar.replace(key,\n \"Key not found\", 1)\n return ar\n\n def replaceStandardTags(self, ar):\n ar = ar.replace(\"
      \", \"[LIST]\") \\\n .replace('
      ', \"\") \\\n .replace(\"

      \", \"[size=18][center]\") \\\n .replace(\"

      \", \"[/center][/size][hr]\") \\\n .replace('

      ', \"[size=15]\") \\\n .replace(\"

      \", \"[/size][indent=15][/indent][indent=15][/indent]\") \\\n .replace(\"
    • \", \"[*]\") \\\n .replace(\"
    • \", \"\") \\\n .replace(\"
    \", \"[/LIST]\") \\\n .replace('[?]', '[clip=(?)]') \\\n .replace('
    [*]', '[*]') \\\n .replace('
    [LIST]', '[clip=Show Details][i]') \\\n .replace('
    [/LIST]', '
    ') \\\n .replace('
    ', '[indent=15][/indent]') \\\n .replace('
    ', '[indent=15][/indent]') \\\n .replace('
    ', \"\") \\\n .replace('
    ', \"\") \\\n .replace('
    ', \"\") \\\n .replace('
    ', '') \\\n .replace(\"\", \"[b]\") \\\n .replace(\"\", \"[/b]\")\n ar = self.replaceDivs(ar)\n return ar\n\n\n def replaceDivs(self, ar):\n while ar.find('
    ') != -1:\n ar = ar.replace(ar[ar.find('
    '):\n ar.find('
    ') + len('
    ')], \"[i]\", 1)\n while ar.find('
    ') != -1:\n ar = ar.replace(ar[ar.find('
    '): ar.find('
    ') + 6], \"[/i][/clip]\", 1)\n return ar\n\n def checkIfNewItems(self, ar):\n while ar.find('') + 11], \"[[\" + key + \"]]\", 1)\n return ar\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"de/jando/main/DotaUpdate.py","file_name":"DotaUpdate.py","file_ext":"py","file_size_in_byte":3545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"7286042","text":"import logging\nimport os\nimport sys\nfrom yaml import YAMLError\nfrom collections import UserDict\n\nfrom profile_builder import exceptions, utils\n\nlog = logging.getLogger(__name__)\n\nclass ValidationError(Exception):\n \"\"\"Raised during the validation process of the config on errors.\"\"\"\n\nclass Config(UserDict):\n \"\"\"\n Profile_Builder Configuration dict\n This is a fairly simple extension of a standard dictionary.\n \"\"\"\n\n def __init__(self, config_file_path=None):\n \"\"\"\n The schema is a Python dict which maps the config name to a validator.\n \"\"\"\n\n # Ensure config_file_path is a Unicode string\n if config_file_path is not None and not isinstance(config_file_path, str):\n try:\n # Assume config_file_path is encoded with the file system encoding.\n config_file_path = config_file_path.decode(encoding=sys.getfilesystemencoding())\n except UnicodeDecodeError:\n raise ValidationError(\"config_file_path is not a Unicode string.\")\n self.config_file_path = config_file_path\n self.data = {}\n\n self.user_configs = []\n\n def load_dict(self, patch):\n\n if not isinstance(patch, dict):\n raise exceptions.ConfigurationError(\n \"The configuration is invalid. The expected type was a key \"\n \"value mapping (a python dict) but we got an object of type: \"\n \"{}\".format(type(patch)))\n\n self.user_configs.append(patch)\n self.data.update(patch)\n\n def load_file(self, config_file):\n try:\n return self.load_dict(utils.yaml_load(config_file))\n except YAMLError as e:\n raise exceptions.ConfigurationError(\n f\"Profile_Builder encountered an error parsing the configuration file: {e}\"\n )\n\n def write_file(self):\n f = self.pop(\"config_file_path\")\n utils.yaml_write_file(self.data, f)\n\ndef _open_config_file(config_file):\n\n # Default to the standard config filename.\n if config_file is None:\n config_file = os.path.abspath('config.yml')\n\n # If closed file descriptor, get file path to reopen later.\n if hasattr(config_file, 'closed') and config_file.closed:\n config_file = config_file.name\n\n log.debug(f\"Loading configuration file: {config_file}\")\n\n # If it is a string, we can assume it is a path and attempt to open it.\n if isinstance(config_file, str):\n if os.path.exists(config_file):\n config_file = open(config_file, 'rb')\n else:\n raise exceptions.ConfigurationError(\n f\"Config file '{config_file}' does not exist.\")\n\n # Ensure file descriptor is at begining\n config_file.seek(0)\n\n return config_file\n\ndef load_config_str(config_str=None, **kwargs):\n \"\"\"\n Load the configuration from a config string\n Extra kwargs are passed to the configuration to replace any default values\n unless they themselves are None.\n \"\"\"\n options = kwargs.copy()\n\n # Filter None values from the options. This usually happens with optional\n # parameters from Click.\n for key, value in options.copy().items():\n if value is None:\n options.pop(key)\n\n cfg = Config()\n # First load the config file\n cfg.load_file(config_str)\n # Then load the options to overwrite anything in the config.\n cfg.load_dict(options)\n\n for key, value in cfg.items():\n log.debug(f\"Config value: '{key}' = {value!r}\")\n\n return cfg\n\ndef load_config(config_file=None, **kwargs):\n \"\"\"\n Load the configuration for a given file object or name\n The config_file can either be a file object, string or None. If it is None\n the default `config.yml` filename will loaded.\n Extra kwargs are passed to the configuration to replace any default values\n unless they themselves are None.\n \"\"\"\n options = kwargs.copy()\n\n # Filter None values from the options. This usually happens with optional\n # parameters from Click.\n for key, value in options.copy().items():\n if value is None:\n options.pop(key)\n\n config_file = _open_config_file(config_file)\n options['config_file_path'] = getattr(config_file, 'name', '')\n\n cfg = Config(config_file_path=options['config_file_path'])\n # First load the config file\n cfg.load_file(config_file)\n # Then load the options to overwrite anything in the config.\n cfg.load_dict(options)\n\n for key, value in cfg.items():\n log.debug(f\"Config value: '{key}' = {value!r}\")\n\n return cfg","sub_path":"src/profile_builder/config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"485256902","text":"import click \nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom torch import optim\nimport torch.nn.functional as F\nimport random\nimport os\nimport time\nimport numpy as np\nimport pandas as pd\nfrom collections import defaultdict\nfrom utils import read_vocab,write_vocab,build_vocab,Tokenizer,padding_idx,timeSince\nfrom env import R2RBatch\nfrom model import EncoderLSTM, AttnDecoderLSTM\nfrom agent import Seq2SeqAgent\nfrom eval import Evaluation\nfrom constants import EpisodeConstants as EC, Files \nimport wandb\n\ndef output_location(eval_type, feedback, blind, lr, hidden_size, word_embedding_size, seed):\n par_eval_typeer = '{}_feedback-{}_blind-{}_lr-{:f}_hs-{}_we-{}'.format(\n eval_type, feedback, blind, lr, hidden_size, word_embedding_size)\n result_dir = '{}/{}/seed-{}/'.format(Files.results , par_eval_typeer, seed)\n snapshot_dir = '{}/{}/seed-{}/'.format(Files.snapshots, par_eval_typeer, seed)\n plot_dir = '{}/{}/seed-{}/'.format(Files.plots , par_eval_typeer, seed)\n for dirs in [result_dir, snapshot_dir, plot_dir]:\n if not os.path.isdir(dirs):\n os.makedirs(dirs)\n return result_dir, snapshot_dir, plot_dir\n\n\n\n\ndef train(eval_type, train_env, encoder, decoder, n_iters, seed, feedback, max_episode_len, max_input_length, prefix, blind, lr, weight_decay, result_dir, snapshot_dir, plot_dir, log_every=50, val_envs=None, debug=False):\n ''' Train on training set, validating on both seen and unseen. '''\n \n if debug: \n print(\"Training in debug mode\")\n log_every = 1\n\n if val_envs is None:\n val_envs = {}\n\n print('Training with %s feedback' % (feedback))\n agent = Seq2SeqAgent(train_env, \"\", encoder, decoder, max_episode_len, blind=blind)\n encoder_optimizer = optim.Adam(encoder.parameters(), lr=lr, weight_decay=weight_decay)\n decoder_optimizer = optim.Adam(decoder.parameters(), lr=lr, weight_decay=weight_decay) \n\n data_log = defaultdict(list)\n start = time.time()\n \n for idx in range(0, n_iters, log_every):\n\n interval = min(log_every,n_iters-idx)\n iter = idx + interval\n data_log['iteration'].append(iter)\n\n # Train for log_every interval\n agent.train(encoder_optimizer, decoder_optimizer, interval, feedback=feedback)\n train_losses = np.array(agent.losses)\n assert len(train_losses) == interval\n train_loss_avg = np.average(train_losses)\n data_log['train loss'].append(train_loss_avg)\n loss_str = 'train loss: %.4f' % train_loss_avg\n\n # Run validation\n for env_name, (env, evaluator) in val_envs.items():\n agent.env = env\n agent.results_path = '%s%s_%s_iter_%d.json' % (result_dir, prefix, env_name, iter)\n # Get validation loss under the same conditions as training\n agent.test(use_dropout=True, feedback=feedback, allow_cheat=True)\n val_losses = np.array(agent.losses)\n val_loss_avg = np.average(val_losses)\n data_log['%s loss' % env_name].append(val_loss_avg)\n # Get validation distance from goal under test evaluation conditions\n agent.test(use_dropout=False, feedback='argmax')\n agent.write_results()\n score_summary = evaluator.score(agent.results_path)\n loss_str += ', %s loss: %.4f' % (env_name, val_loss_avg)\n for metric, val in score_summary.items():\n data_log['%s %s' % (env_name, metric)].append(val)\n loss_str += ', %s: %.3f' % (metric, val)\n\n\n agent.env = train_env\n\n print(('%s (%d %d%%) %s' % (timeSince(start, float(iter)/n_iters),\n iter, float(iter)/n_iters*100, loss_str)))\n df = pd.DataFrame(data_log)\n df.set_index('iteration')\n df_path = '%s%s-log.csv' % (plot_dir, prefix)\n df.to_csv(df_path)\n \n split_string = \"-\".join(train_env.splits)\n enc_path = '%s%s_%s_enc_iter_%d' % (snapshot_dir, prefix, split_string, iter)\n dec_path = '%s%s_%s_dec_iter_%d' % (snapshot_dir, prefix, split_string, iter)\n agent.save(enc_path, dec_path)\n \n # Log data to wandb for visualization\n wandb.log(last_entry(data_log, eval_type), step=idx)\n\ndef last_entry(data_log, eval_type):\n # Separate metrics and losses in to different sections in wandb\n out = {k.replace(' ', '_'): v[-1] for k,v in data_log.items()}\n del out['iteration']\n new_out = {}\n for k,v in out.items():\n new_out['{}-{}/{}'.format(eval_type, 'loss' if 'loss' in k else 'metrics', k)] = v\n return new_out\n\ndef setup(seed, train_vocab, trainval_vocab):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n random.seed(seed)\n \n # Check for vocabs\n if not os.path.exists(train_vocab):\n write_vocab(build_vocab(splits=['train']), train_vocab)\n if not os.path.exists(trainval_vocab):\n write_vocab(build_vocab(splits=['train', 'val_seen']), trainval_vocab)\n\n\ndef train_val(*args, **kwargs):\n train_all(*args, **kwargs, train_splits=['train'], test_splits=['val_seen'])\n\ndef train_test(*args, **kwargs):\n train_all(*args, **kwargs, train_splits=['train', 'val_seen'], test_splits=['test'])\n\n\n\n@click.command()\n@click.option('--feedback', default='sample', type=str, help='teacher or sample')\n@click.option('--eval_type', default='val', type=str, help='val or test')\n@click.option('--blind', type=str, default='', help='language, vision')\n@click.option('--lr', type=float, default=0.0001)\n@click.option('--seed', type=int, default=1)\n@click.option('--debug', type=bool, default=False, help='Run in debug mode')\n@click.option('--hidden_size', type=int, default=64)\n@click.option('--word_embedding_size', type=int, default=64)\n@click.option('--n_iters', type=int, default=2000)\n@click.option('--max_episode_len', type=int, default=EC.max_len)\n@click.option('--max_input_length', type=int, default=100)\n@click.option('--batch_size', default=100)\n@click.option('--action_embedding_size', default=4)\n@click.option('--target_embedding_size', default=2)\n@click.option('--bidirectional', default=False)\n@click.option('--dropout_ratio', default=0.5)\n@click.option('--weight_decay', default=0.0005)\n@click.option('--feature_size', default=144)\n@click.option('--project', default='RobotSlangBenchmarkRayTune')\ndef main(feedback, eval_type, blind, lr, seed, debug, hidden_size, word_embedding_size, n_iters, max_episode_len, max_input_length, batch_size, action_embedding_size, target_embedding_size, bidirectional, dropout_ratio, weight_decay, feature_size, project):\n \n # Vocabulary locations\n train_vocab = '{}/train_vocab.txt'.format(Files.data)\n trainval_vocab = '{}/trainval_vocab.txt'.format(Files.data)\n\n # Model prefix to uniquely id this instance.\n prefix = 'feedback_%s-hs_%d-we_%d' % (feedback, hidden_size, word_embedding_size)\n if blind: prefix += '-blind_{}'.format(blind)\n if debug: prefix += '-debug={}'.format(debug)\n \n # Store results in pre-determined directories\n result_dir, snapshot_dir, plot_dir = output_location(eval_type, feedback, blind, lr, hidden_size, word_embedding_size, seed)\n\n # Initialize wandb for experiment tracking\n if debug: project = 'DEBUG-' + project\n wandb.init(project=project, name=prefix, config=locals())\n \n # Test on validation or test folds based on data\n train_func = train_val if eval_type == 'val' else train_test\n train_func(eval_type, seed, max_episode_len, max_input_length, feedback,\n n_iters, prefix, blind, debug, train_vocab, trainval_vocab,\n batch_size, action_embedding_size, target_embedding_size,\n bidirectional, dropout_ratio, weight_decay, feature_size,\n hidden_size, word_embedding_size, lr, result_dir, snapshot_dir, plot_dir)\n\n # test_submission(seed, max_episode_len, max_input_length, feedback, n_iters, prefix, blind)\n\ndef raytune_hyperparam_optimization():\n batch_sizes = [10, 25, 50, 100]\n hidden_sizes = [16, 32, 64, 128]\n word_sizes = [16, 32, 64, 128]\n lrs = [0.0001, 0.001, 0.01]\n max_input_lengths = [25, 50, 100] \n\ndef train_all(eval_type, seed, max_episode_len, max_input_length, feedback,\n n_iters, prefix, blind, debug, train_vocab, trainval_vocab, batch_size,\n action_embedding_size, target_embedding_size, bidirectional,\n dropout_ratio, weight_decay, feature_size, hidden_size,\n word_embedding_size, lr, result_dir, snapshot_dir, plot_dir, train_splits,\n test_splits):\n ''' Train on the training set, and validate on the test split. '''\n\n setup(seed, train_vocab, trainval_vocab)\n # Create a batch training environment that will also preprocess text\n vocab = read_vocab(train_vocab if eval_type=='val' else trainval_vocab)\n tok = Tokenizer(vocab=vocab, encoding_length=max_input_length)\n train_env = R2RBatch(batch_size=batch_size, splits=train_splits, tokenizer=tok, seed=seed, blind=blind)\n\n # Creat validation environments\n val_envs = {split: (R2RBatch(batch_size=batch_size, splits=[split], \n tokenizer=tok, seed=seed, blind=blind),\n Evaluation([split], seed=seed)) for split in test_splits}\n\n # Build models and train\n enc_hidden_size = hidden_size//2 if bidirectional else hidden_size\n encoder = EncoderLSTM(len(vocab), word_embedding_size, enc_hidden_size, padding_idx, \n dropout_ratio, bidirectional=bidirectional).cuda()\n decoder = AttnDecoderLSTM(Seq2SeqAgent.n_inputs(), Seq2SeqAgent.n_outputs(),\n action_embedding_size, hidden_size, dropout_ratio, feature_size).cuda()\n\n train(eval_type, train_env, encoder, decoder, n_iters, seed, feedback,\n max_episode_len, max_input_length, prefix, blind, lr, weight_decay,\n result_dir, snapshot_dir, plot_dir, val_envs=val_envs, debug=debug)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"train_new.py","file_name":"train_new.py","file_ext":"py","file_size_in_byte":10062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"30687543","text":"import unittest\nfrom data import MNISTDataset\n\n\nclass TestMNISTDataset(unittest.TestCase):\n def test_load_data(self):\n # GIVEN\n batch_size = 2\n mnist_data_size = 60000\n mnist_input_dim = 784\n\n # WHEN\n mnist = MNISTDataset(batch_size)\n\n # THEN\n self.assertEqual(len(mnist), mnist_data_size)\n self.assertEqual(mnist.input_dimension, mnist_input_dim)\n","sub_path":"test/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"502911011","text":"import nltk\nimport pickle\nimport argparse\nfrom collections import Counter\n\n\nclass Vocabulary(object):\n \"\"\"Simple vocabulary wrapper.\"\"\"\n\n def __init__(self):\n self.word2idx = {}\n self.idx2word = {}\n self.idx = 0\n\n def add_word(self, word):\n if word not in self.word2idx:\n self.word2idx[word] = self.idx\n self.idx2word[self.idx] = word\n self.idx += 1\n\n def __call__(self, word):\n if word not in self.word2idx:\n return self.word2idx['']\n return self.word2idx[word]\n\n def __len__(self):\n return len(self.word2idx)\n\n\ndef build_vocab(path, threshold):\n \"\"\"Build a simple vocabulary wrapper.\"\"\"\n\n with open(path, 'r') as f:\n res = f.readlines()\n\n text = ''\n for line in res:\n line = line.split('\\t')[-1]\n line = line.replace('.', '')\n line = line.strip()\n text += line + ' '\n text = text.strip().lower()\n\n # add words\n words = nltk.tokenize.word_tokenize(text)\n counter = Counter(words)\n\n # If the word frequency is less than 'threshold', then the word is discarded.\n words = [word for word, cnt in counter.items() if cnt >= threshold]\n\n # Create a vocab wrapper and add some special tokens.\n vocab = Vocabulary()\n vocab.add_word('')\n vocab.add_word('')\n vocab.add_word('')\n vocab.add_word('')\n\n # Add the words to the vocabulary.\n for i, word in enumerate(words):\n vocab.add_word(word)\n return vocab\n\n\ndef main(args):\n vocab = build_vocab(path=args.caption_path, threshold=args.threshold)\n vocab_path = args.vocab_path\n with open(vocab_path, 'wb') as f:\n pickle.dump(vocab, f)\n print(\"Total vocabulary size: {}\".format(len(vocab)))\n print(\"Saved the vocabulary wrapper to '{}'\".format(vocab_path))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--caption_path',\n type=str,\n default='data/flickr8k/train.txt',\n help='path for train annotation file')\n parser.add_argument('--vocab_path',\n type=str,\n default='./data/flickr8k/vocab.pkl',\n help='path for saving vocabulary wrapper')\n parser.add_argument('--threshold',\n type=int,\n default=4,\n help='minimum word count threshold')\n args = parser.parse_args()\n main(args)\n","sub_path":"nic/build_vocab.py","file_name":"build_vocab.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"43484565","text":"# -*- coding: utf-8 -*-\nimport sys\nimport re\nfrom scrapy.utils.project import get_project_settings\nfrom ShoppingWebsiteCrawlwer.utils import get_config\nfrom scrapy.crawler import CrawlerProcess\nfrom multiprocessing.context import Process\nfrom multiprocessing import Manager\nfrom urllib.parse import urlparse\nimport os\n\nitem_num = 2\nurl_pattern = \"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"\njd_url = \"https://item.jd.com/{}.html\"\nsn_url = \"https://product.suning.com/{}/{}.html\"\n\n\ndef crawl(settings, spider, name, custom_settings,result=None, url=None, keyword=None, item_num=None):\n process = CrawlerProcess(settings)\n process.crawl(spider, **{'name': name, 'config': custom_settings, 'keyword': keyword,\n 'item_num': item_num, 'url': url,'result':result})\n process.start()\n\n\ndef spider_process(name, keyword=None, item_num=None, url=None, spider=None,result=None):\n custom_settings = get_config(name)\n if not spider:\n spider = custom_settings.get('spider', 'aCrawler')\n project_settings = get_project_settings()\n settings = dict(project_settings.copy())\n settings.update(custom_settings.get('settings'))\n print(item_num)\n if item_num is not None:\n # 关键字模式下,C_R参数设置同时请求个数\n # 防止终止爬虫时其他请求继续异步进行\n # 但是可能会造成请求较慢\n settings[\"CONCURRENT_REQUESTS\"]=1\n print(settings)\n process = Process(target=crawl, kwargs={'settings': settings, 'spider': spider, 'name': name,\n 'custom_settings': custom_settings, 'keyword': keyword,\n 'item_num': item_num, 'url': url,'result':result})\n return process\n\n\ndef search_with_url_or_keyword(url_or_keyword,item_num=None):\n manager = Manager()\n return_list = manager.list()\n if re.match(url_pattern, url_or_keyword): # url\n url_result = urlparse(url_or_keyword)\n if 'jd.com' in url_or_keyword:\n name = 'jd'\n url = url_or_keyword\n if \"item.m.jd.com\" in url_or_keyword:\n sku_id = url_result.path.split(\"/\")[2].split(\".\")[0]\n url = jd_url.format(sku_id)\n elif 'product.suning.com' in url_result:\n name = 'sn'\n url = url_or_keyword\n if \"m.suning.com\" in url_or_keyword:\n sup_id = url_result.path.split(\"/\")[2]\n sku_id = url_result.path.split(\"/\")[3].split(\".\")[0]\n url = sn_url.format(sup_id, sku_id)\n spider = \"LCrawler\"\n process = spider_process(name=name, url=url,spider=spider,result=return_list)\n process.start()\n process.join()\n\n else: # keyword\n for name in ['jd', 'sn']:\n pro = spider_process(name=name, keyword=url_or_keyword, item_num=item_num,result=return_list)\n pro.start()\n pro.join()\n return return_list\n\nif __name__ == \"__main__\":\n r1=search_with_url_or_keyword(url_or_keyword=\"https://item.jd.com/100012717854.html\")\n r2=search_with_url_or_keyword(url_or_keyword=\"手机\",item_num=item_num)\n print(\"r1:\",r1)\n print(\"r2:\",r2)\nelse:\n pass","sub_path":"ShoppingWebsiteCrawlwer/spiders/crawler_api.py","file_name":"crawler_api.py","file_ext":"py","file_size_in_byte":3248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"626470257","text":"# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\n# # Basic transmission tree builder\n# \n# * Caitlin Rivers\n# \n# * Virginia Bioinformatics Institute at Virginia Tech\n# \n# * cmrivers@vbi.vt.edu\n# \n# -------\n# \n# Given a line listing with dates and basic information about cluster membership, this script will estimate who transmitted an infectious disease to whom based on case onset dates.\n# \n# Wish list for improvements:\n# \n# * Make algorithm that determines who infected whom more sophisticated.\n# \n# * Find a way to keep single cases (e.g. those not part of a cluster) in the data set so they can be plotted on the casetree.\n# \n# * Fix plot_cluster() function so it is functional.\n\n# \n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom datetime import datetime, timedelta\nimport pandas as pd\n\n# \n\ndef date_convert(x):\n \"\"\" Convert dates to datetime object\n \"\"\"\n try:\n y = datetime.strptime(x, \"%Y-%m-%d\")\n except:\n y = np.nan\n \n return y\n\n# \n\n# Data (from 2013 MERS outbreak) are available in cmrivers/epipy repo on Github.\n\n# \n\ndat = pd.read_csv(\"../Line list & epi stats - Line list.csv\", parse_dates=True)\ndat['Cluster ID'] = dat['Cluster ID'].replace(np.nan, 'single')\ndat.index = dat['Cluster ID']\n\n# \n\ndat['onset_date'] = dat['Approx onset date'].map(date_convert)\ndat['report_date'] = dat['Approx reporting date'].map(date_convert)\ndat['dates'] = dat['onset_date'].combine_first(dat['report_date']) #combines onset and report date columns, with onset date preferential\n\n# \n\ndef _group_clusters(df, cluster_id, date_col):\n ''' Use pandas to group clusters by basic cluster membership information\n df = pandas dataframe\n cluster_id = column that identifies cluster membership, which can be a basic string like \"hospital cluster A\"\n date_col = onset or report date column\n '''\n clusters = df[df[cluster_id] != 'single']\n clusters = clusters[clusters[date_col].notnull()]\n \n groups = clusters.groupby(clusters[cluster_id])\n \n return groups\n\n# \n\ndef cluster_builder(df, cluster_id, case_id, date_col, color_col, inc_mean, inc_sd):\n '''\n Given a line listing with dates and basic information about cluster membership,\n this script will estimate who transmitted an infectious disease to whom based on case onset dates.\n\n df = pandas dataframe of line listing\n cluster_id = col that identifies cluster membership, which can be a basic string like \"hospital cluster A\"\n case_id = col with unique case identifier\n date_col = onset or report date column\n color_col = column that will be used to color nodes based on attribute, e.g. case severity or gender\n inc_mean = incubation period mean\n inc_sd = incubation period standard deviation\n\n retuns clusters (pandas dataframe) and mx (network x object)\n '''\n clusters = _group_clusters(df, cluster_id, date_col)\n \n mmin = timedelta(inc_mean - (1 * inc_sd), 0)\n mmax = timedelta(inc_mean + (1 * inc_sd), 0)\n \n mx = []\n for key, group in clusters:\n row = [tmp[1:4] for tmp in group[[case_id, date_col, color_col]].sort('dates').itertuples()] #suspect this will be buggy with dif data sets, woudl like to improve\n mx.append(row)\n\n network = []\n for ix in range(0, len(mx)):\n for inx in range(0, len(mx[ix])):\n index_node = mx[ix][0][0]\n source_node = index_node\n case_id = mx[ix][inx][0]\n time = mx[ix][inx][1]\n color = mx[ix][inx][2]\n \n if len(mx[ix]) > 1:\n if mx[ix][inx][1] - mx[ix][inx-1][1] > mmin:\n source_node = mx[ix][inx-1][0]\n \n result = (case_id, color, index_node, source_node, time)\n network.append(result)\n \n df_out = pd.DataFrame(network, columns=['case_id', 'color', 'index_node', 'source_node', 'time'])\n df_out.index = df_out.case_id\n \n return clusters, mx\n\n# \n\nclusters, mx = cluster_builder(dat, 'Cluster ID', 'Case #', 'dates', 'Health status', 7, 5)\n\n# \n\nmx.save('../cluster_network.pkl')\n\n# \n\ndef plot_cluster(df, cluster_id, date_col):\n \"\"\"Broken. Date-handling patience gone.\n\n Should display a plot with time along x axis, cluster ID along y axis,\n and case ID plotted like a scatterplot accordingly.\n \"\"\"\n grpnames = np.unique(df[cluster_id]).dropna().values\n \n fig, ax = plt.subplots()\n fig.set_size_inches(8, 5)\n ax.xaxis_date()\n ax.set_aspect('auto')\n axprop = plt.axis()\n fig.autofmt_xdate()\n \n plt.ylim(1, len(grpnames))\n plt.yticks(np.arange(len(grpnames)), grpnames)\n \n for key, group in clusters:\n for date in date_col:\n xtog = timedelta(((10*axprop[1]-axprop[0])/axprop[1]), 0, 0)\n x1 = [date, date+xtog]\n \n for i in range(len(grpnames)):\n if key == grpnames[i]:\n y1 = np.array([i, i])\n y2 = y1+0.5\n plt.fill_between(x1, y1, y2, color=color, alpha=.3)\n \n xspot= x1[0] + timedelta((x1[1] - x1[0]).days/2.0, 0, 0)\n \n plt.text(xspot, y1[1]+.25, next(casenums), horizontalalignment='center', verticalalignment='center', fontsize=9)\n \n return fig\n\n# \n\nplot_cluster(dat, 'Cluster ID', 'dates')\n\n# \n\n\n","sub_path":"py/cluster_builder.py","file_name":"cluster_builder.py","file_ext":"py","file_size_in_byte":5510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"208093441","text":"# _*_coding:UTF-8 _*_\nimport requests\nimport time\nimport pymysql\nfrom lxml import etree\nfrom Spider.ip_pool import Pool\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'\n}\n\nips = Pool(10)\n\n\n# proxy = ips.offer_ip()\n# print(proxy)\n\n# 提取租房信息\ndef parse_pages(pages):\n num = 0\n ele = etree.HTML(pages)\n try:\n city = ele.xpath('//head/title/text()')[0].split('-')[1][:-4]\n title = ele.xpath('//h2/a/text()')\n print(len(title))\n sum_price = ele.xpath(\"//div[@class='price']/p[@class='sum']/b/text()\")\n evey_price = ele.xpath(\"//div[@class='price']/p[@class='unit']/text()\")\n except:\n time.sleep(60 * 5)\n print(\"出现验证码,5分钟后操作\")\n city = ele.xpath('//head/title/text()')[0].split('-')[1][:-4]\n title = ele.xpath('//h2/a/text()')\n print(len(title))\n sum_price = ele.xpath(\"//div[@class='price']/p[@class='sum']/b/text()\")\n evey_price = ele.xpath(\"//div[@class='price']/p[@class='unit']/text()\")\n for i in title:\n index = title.index(i)\n try:\n data = [title[index].split('\\/xa0')[0], sum_price[index] + '万', evey_price[index], city]\n num += 1\n save_to_mysql(data)\n print('第' + str(num) + '条数据爬取完毕,暂停1.5秒!')\n time.sleep(1.5)\n except Exception as e:\n print(e)\n\n\n# 创建MySQL数据库的表:58tc_data\ndef create_mysql_table():\n db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spider')\n cursor = db.cursor()\n sql = 'CREATE TABLE IF NOT EXISTS 58tc_xinfang (title VARCHAR(100) PRIMARY KEY,sum_price VARCHAR(255), every_price VARCHAR(100) ,city VARCHAR(255) )'\n cursor.execute(sql)\n db.close()\n\n\n# 将数据储存到MySQL数据库\ndef save_to_mysql(data):\n db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='spider')\n cursor = db.cursor()\n sql = 'INSERT INTO 58tc_xinfang(title,sum_price,every_price,city) values(%s, %s, %s, %s)'\n try:\n cursor.execute(sql, (data[0], data[1], data[2], data[3]))\n db.commit()\n except Exception as e:\n print(e)\n db.rollback()\n db.close()\n\n\nif __name__ == '__main__':\n # create_mysql_table()\n # print('MySQL表58tc_xifang创建成功!')\n city_list = ['fs', 'gz', 'zz', 'dg', 'sh', 'bj', 'nj', 'dl', 'tj', 'nb', 'cd', 'wx', 'hz', 'wh', 'sy', 'sz', 'xa',\n 'cq', 'cs', 'qd']\n for city in city_list:\n for i in range(20, 25):\n url = ('https://{}.58.com/ershoufang/pn' + str(i) + '/').format(city)\n print(url)\n pro_pages = requests.get(url).text\n parse_pages(pro_pages)\n print('第' + str(i) + '页数据爬取完毕!')\n # time.sleep(random.randint(3, 10))\n print('所有数据爬取完毕!')\n","sub_path":"58同城/58.py","file_name":"58.py","file_ext":"py","file_size_in_byte":2995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"83226354","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n'''\nCreated on Nov 10, 2011\n\n@author: mengchen\n'''\nfrom common import json2\nfrom common.error import validation\nfrom common.error.errors import ModNotFoundError, CodedError\nfrom common.log import log_enter\nfrom common.types import Dict, CiDict\nfrom common.util import modutil, stringutil\nimport StringIO\nimport cgi\nimport doctest\nimport os\nimport re\nimport urllib\nimport urllib2\n\ndef build_fields(fields, use_json=False):\n '''\n >>> build_fields(None) is None\n True\n >>> build_fields({ 'id' : 1, 'name' : 'abc' })\n 'id=1&name=abc'\n >>> build_fields({ 'id' : 1, 'name' : 'abc' }, True)\n 'id=1&name=%22abc%22'\n '''\n if fields is None:\n return None\n if use_json:\n for k in fields:\n fields[k] = json2.dumps(fields[k])\n return urllib.urlencode(fields)\n\ndef curl(url, fields=None, headers=None, use_json=False, resp_headers={}):\n resp_headers.clear()\n req = _build_request(url, fields, headers, use_json)\n resp = _read_response(req, resp_headers)\n resp = _process_resp(resp, resp_headers, use_json)\n return resp\n\ndef _build_request(url, fields, headers, use_json):\n '''\n >>> req = _build_request('http://localhost/test', {'id':'1'}, {'INTERNAL-KEY':'abc'}, False)\n >>> req._Request__original\n 'http://localhost/test'\n >>> req.data\n 'id=1'\n >>> req.headers\n {'Internal-key': 'abc'}\n '''\n data = build_fields(fields, use_json)\n req = urllib2.Request(url, data)\n if headers is not None:\n for k, v in headers.items():\n req.add_header(k, v)\n return req\n\ndef _read_response(req, resp_headers):\n f = urllib2.urlopen(req)\n try:\n resp = f.read()\n info = f.info()\n headers = _parse_headers(info.headers)\n resp_headers.update(headers)\n return resp\n finally:\n f.close()\t\t\n\ndef _parse_headers(header_list):\n '''\n >>> l = ['Server: nginx/0.7.67\\\\r\\\\n', 'Content-Type: application/json;charset=UTF-8\\\\r\\\\n']\n >>> headers = _parse_headers(l)\n >>> len(headers)\n 2\n >>> h = headers['Server']\n >>> h.key, h.value\n ('Server', 'nginx/0.7.67')\n >>> h.params\n {}\n >>> h = headers['Content-Type']\n >>> h.key, h.value\n ('Content-Type', 'application/json')\n >>> h.params\n {'charset': 'UTF-8'}\n '''\n headers = CiDict()\n for line in header_list:\n main, params = cgi.parse_header(line)\n key, value = main.split(': ')\n headers[key] = Dict(key=key, value=value, params=params)\n return headers\n\n\ndef _process_resp(resp, resp_headers, use_json):\n '''\n >>> headers = CiDict()\n \n no mime type, should return raw response\n >>> _process_resp('abc', {}, False)\n 'abc'\n \n charset not found, should use raw response\n >>> header = Dict(value='application/json', params=Dict())\n >>> headers['Content-Type'] = header\n >>> _process_resp('abc', headers, False)\n 'abc'\n \n mime type is json, but use_json is False,\n should not decode by json\n >>> header = Dict(value='application/json', params=Dict(charset='utf-8'))\n >>> headers['Content-Type'] = header\n >>> _process_resp('abc', headers, False)\n u'abc'\n \n mime type is json, and use_json is True,\n should decode by json\n >>> header = Dict(value='application/json', params=Dict(charset='utf-8'))\n >>> headers['Content-Type'] = header\n >>> _process_resp('\"abc\"', headers, True)\n u'abc'\n '''\n content_type_header = resp_headers.get('content-type')\n if content_type_header is not None:\n mime, charset = _parse_content_type_header(content_type_header)\n if mime == 'text/html':\n charset = _parse_html_charset(resp) or charset\n if charset is not None:\n resp = unicode(resp, charset, 'ignore')\n if use_json and mime == 'application/json':\n resp = json2.loads(resp) \n return resp\n\ndef _parse_content_type_header(header):\n '''\n normal situation\n >>> header = Dict(key='Content-Type', value='application/json', params=Dict(charset='UTF-8'))\n >>> _parse_content_type_header(header)\n ('application/json', 'UTF-8')\n \n no charset, should default to utf-8\n >>> header = Dict(key='Content-Type', value='application/json', params=Dict())\n >>> _parse_content_type_header(header)\n ('application/json', None)\n '''\n mime = header.value\n charset = header.params.get('charset')\n return mime, charset\n\ndef _parse_html_charset(resp):\n '''\n >>> html = ''\n >>> _parse_html_charset(html)\n 'utf-8'\n \n >>> html = ''\n >>> _parse_html_charset(html)\n 'utf-8'\n \n >>> html = ''\n >>> _parse_html_charset(html) is None\n True\n \n >>> html = ''\n >>> _parse_html_charset(html)\n 'utf-8'\n '''\n m = re.search(''))\n\t\tjs.append(u\"\"\"Questions.insert({\n\t\t\t\t\t\tquestion: \"%s\",\n\t\t\t\t\t\tanswer: \"%s\",\n\t\t\t\t\t\tchoice_A: \"%s\",\n\t\t\t\t\t\tchoice_B: \"%s\",\n\t\t\t\t\t\tchoice_C: \"%s\",\n\t\t\t\t\t\tchoice_D: \"%s\",\n\t\t\t\t\t\tchoice_E: \"%s\",\n\t\t\t\t\t\tnumber: %s,\n\t\t\t\t\t\tcourse_en: '%s',\n\t\t\t\t\t\tcourse_kz: '%s',\n\t\t\t\t\t\tcourse_ru: '%s',\n\t\t\t\t\t\tis_fifth: %s,\n\t\t\t\t\t\tlanguage: '%s',\n\t\t\t\t\t\tvariant: %s,\n\t\t\t\t\t}\n\t\t\t\t\t);\n\t\t\t\t\"\"\" % (questions[i].replace('\\n', '
    ').replace(u'\"', u'"').replace(u\"'\", u'"').replace(u'\\\\', u'\\\\\\\\'), \n\t\t\t\t\tanswers[i].replace('\\n', '
    ').replace(u'\"', u'"').replace(u\"'\", u'"').replace(u'\\\\', u'\\\\\\\\'), \n\t\t\t\t\tchs[0].replace(u'\"', u'"').replace(u\"'\", u'"').replace(u'\\\\', u'\\\\\\\\'), \n\t\t\t\t\tchs[1].replace(u'\"', u'"').replace(u\"'\", u'"').replace(u'\\\\', u'\\\\\\\\'), \n\t\t\t\t\tchs[2].replace(u'\"', u'"').replace(u\"'\", u'"').replace(u'\\\\', u'\\\\\\\\'), \n\t\t\t\t\tchs[3].replace(u'\"', u'"').replace(u\"'\", u'"').replace(u'\\\\', u'\\\\\\\\'), \n\t\t\t\t\tchs[4].replace(u'\"', u'"').replace(u\"'\", u'"').replace(u'\\\\', u'\\\\\\\\'), \n\t\t\t\t\tstr(i + 1), \n\t\t\t\t\tm_file, \n\t\t\t\t\tkz[m_file], \n\t\t\t\t\tru[m_file], \n\t\t\t\t\tis_fifth[m_file], \n\t\t\t\t\tlang,\n\t\t\t\t\tstr(variant)))\n\nf = open('database.txt', 'w')\nfor l in js:\n\tf.write(l.encode('utf8'))\nf.close()","sub_path":"russian/2/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"128091823","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport json\nimport time\nimport glob\nfrom pymongo import MongoClient\n\n\ndef main():\n # Ruta destino\n #client = MongoClient()\n client = MongoClient('localhost', 27017)\n\n # Collection name\n db = client.Publications\n # The collection is\n db.Publications.drop()\n\n file_list = glob.glob('data/dblp.*.json')\n\n # Loading json files.\n for json_file in file_list:\n print('Reading file %s' % json_file)\n start = time.time()\n with open(json_file) as file:\n Json = json.load(file)\n file.close()\n end = time.time()\n\n # Se seleccionan las publicaciones y no otra información\n articles = Json['dblp']\n\n # Se crea la colección.\n articles_colletion = db.Publications\n\n start2 = time.time()\n\n # Se van recorriendo los documentos e insertanto en la colección. Se\n # transforma el campo year a tipo entero.\n try:\n for journal in articles['article']:\n if 'year' in journal:\n journal['year'] = int(float(journal['year']))\n journal['type'] = 'article'\n article_id = articles_colletion.insert_one(journal)\n except:\n print('No journal publications in this file.')\n try:\n for book in articles['incollection']:\n if 'year' in book:\n book['year'] = int(float(book['year']))\n book['type'] = 'incollection'\n article_id = articles_colletion.insert_one(book)\n except:\n print('No book publications in this file.')\n try:\n for conference in articles['inproceedings']:\n if 'year' in conference:\n conference['year'] = int(float(conference['year']))\n conference['type'] = 'inproceedings'\n article_id = articles_colletion.insert_one(conference)\n except:\n print('No conference publications in this file.')\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"import_to_mongo.py","file_name":"import_to_mongo.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"620829264","text":"import math\nimport random\n\nfrom dcs.task import *\n\nfrom game import *\nfrom game.event import *\nfrom game.operation.antiaastrike import AntiAAStrikeOperation\nfrom userdata.debriefing import Debriefing\n\n\nclass AntiAAStrikeEvent(Event):\n TARGET_AMOUNT_MAX = 2\n STRENGTH_INFLUENCE = 0.3\n SUCCESS_TARGETS_HIT_PERCENTAGE = 0.5\n\n targets = None # type: db.ArmorDict\n\n def __str__(self):\n return \"Anti-AA strike\"\n\n def is_successfull(self, debriefing: Debriefing):\n total_targets = sum(self.targets.values())\n destroyed_targets = 0\n for unit, count in debriefing.destroyed_units[self.defender_name].items():\n if unit in self.targets:\n destroyed_targets += count\n\n if self.from_cp.captured:\n return math.ceil(float(destroyed_targets) / total_targets) >= self.SUCCESS_TARGETS_HIT_PERCENTAGE\n else:\n return math.ceil(float(destroyed_targets) / total_targets) < self.SUCCESS_TARGETS_HIT_PERCENTAGE\n\n def commit(self, debriefing: Debriefing):\n super(AntiAAStrikeEvent, self).commit(debriefing)\n\n if self.from_cp.captured:\n if self.is_successfull(debriefing):\n self.to_cp.base.affect_strength(-self.STRENGTH_INFLUENCE)\n else:\n self.to_cp.base.affect_strength(+self.STRENGTH_INFLUENCE)\n else:\n if self.is_successfull(debriefing):\n self.from_cp.base.affect_strength(-self.STRENGTH_INFLUENCE)\n else:\n self.to_cp.base.affect_strength(-self.STRENGTH_INFLUENCE)\n\n def skip(self):\n if self.to_cp.captured:\n self.to_cp.base.affect_strength(-0.1)\n\n def player_attacking(self, strikegroup: db.PlaneDict, clients: db.PlaneDict):\n self.targets = self.to_cp.base.assemble_aa(count=self.to_cp.base.total_aa)\n\n op = AntiAAStrikeOperation(game=self.game,\n attacker_name=self.attacker_name,\n defender_name=self.defender_name,\n attacker_clients=clients,\n defender_clients={},\n from_cp=self.from_cp,\n to_cp=self.to_cp)\n op.setup(target=self.targets,\n strikegroup=strikegroup,\n interceptors={})\n\n self.operation = op\n\n def player_defending(self, interceptors: db.PlaneDict, clients: db.PlaneDict):\n self.targets = self.to_cp.base.assemble_aa()\n\n op = AntiAAStrikeOperation(\n self.game,\n attacker_name=self.attacker_name,\n defender_name=self.defender_name,\n attacker_clients={},\n defender_clients=clients,\n from_cp=self.from_cp,\n to_cp=self.to_cp\n )\n\n strikegroup = self.from_cp.base.scramble_cas(self.game.settings.multiplier)\n op.setup(target=self.targets,\n strikegroup=strikegroup,\n interceptors=interceptors)\n\n self.operation = op\n","sub_path":"game/event/antiaastrike.py","file_name":"antiaastrike.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"28002193","text":"\"\"\"DataPanel class.\"\"\"\nfrom __future__ import annotations\n\nimport logging\nimport os\nimport pathlib\nfrom contextlib import contextmanager\nfrom copy import copy, deepcopy\nfrom typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union\n\nimport cytoolz as tz\nimport datasets\nimport dill\nimport numpy as np\nimport pandas as pd\nimport torch\nimport ujson as json\nimport yaml\nfrom datasets import DatasetInfo, NamedSplit\nfrom datasets.arrow_dataset import DatasetInfoMixin\nfrom jsonlines import jsonlines\n\nimport meerkat\nfrom meerkat.columns.abstract import AbstractColumn\nfrom meerkat.columns.cell_column import CellColumn\nfrom meerkat.mixins.cloneable import CloneableMixin\nfrom meerkat.mixins.copying import DataPanelCopyMixin\nfrom meerkat.mixins.inspect_fn import FunctionInspectorMixin\nfrom meerkat.mixins.mapping import MappableMixin\nfrom meerkat.mixins.materialize import MaterializationMixin\nfrom meerkat.mixins.state import StateDictMixin\nfrom meerkat.provenance import ProvenanceMixin, capture_provenance\nfrom meerkat.tools.identifier import Identifier\nfrom meerkat.tools.utils import convert_to_batch_fn, recmerge\n\nlogger = logging.getLogger(__name__)\n\nExample = Dict\nBatch = Dict[str, Union[List, AbstractColumn]]\nBatchOrDataset = Union[Batch, \"DataPanel\"]\n\n\nclass DataPanel(\n CloneableMixin,\n DataPanelCopyMixin,\n FunctionInspectorMixin,\n MappableMixin,\n MaterializationMixin,\n ProvenanceMixin,\n StateDictMixin,\n DatasetInfoMixin, # this should be the last in order of mixins\n):\n \"\"\"Meerkat DataPanel class.\"\"\"\n\n # Path to a log directory\n logdir: pathlib.Path = pathlib.Path.home() / \"meerkat/\"\n\n # Create a directory\n logdir.mkdir(parents=True, exist_ok=True)\n\n def __init__(\n self,\n *args,\n identifier: Identifier = None,\n column_names: List[str] = None,\n info: DatasetInfo = None,\n split: Optional[NamedSplit] = None,\n **kwargs,\n ):\n super(DataPanel, self).__init__(\n info=info,\n split=split,\n *args,\n **kwargs,\n )\n\n # TODO(karan, sabri): copy columns when they're passed in and prevent users\n # from setting visible_rows inside columns that belong to a datapanel\n logger.debug(\"Creating DataPanel.\")\n\n # Data is a dictionary of columns\n self._data = {}\n\n # Single argument\n if len(args) == 1:\n assert column_names is None, \"Don't pass in column_names.\"\n # The data is passed in\n data = args[0]\n\n # `data` is a dictionary\n if isinstance(data, dict) and len(data):\n data = self._create_columns(data)\n self._assert_columns_all_equal_length(data)\n self._data = data\n\n # `data` is a list\n elif isinstance(data, list) and len(data):\n # Transpose the list of dicts to a dict of lists i.e. a batch\n data = tz.merge_with(list, *data)\n # Assert all columns are the same length\n data = self._create_columns(data)\n self._assert_columns_all_equal_length(data)\n self._data = data\n\n # `data` is a datasets.Dataset\n elif isinstance(data, datasets.Dataset):\n self._data = self._create_columns(data[:])\n info, split = data.info, data.split\n\n # No argument\n elif len(args) == 0:\n\n # Use column_names to setup the data dictionary\n if column_names:\n self._check_columns_unique(column_names)\n self._data = {k: [] for k in column_names}\n\n # Setup the DatasetInfo\n info = info.copy() if info is not None else DatasetInfo()\n DatasetInfoMixin.__init__(self, info=info, split=split)\n\n # Create attributes for all columns and visible columns\n self.all_columns = list(self._data.keys())\n self._visible_columns = None\n\n # Create an identifier\n # TODO(Sabri): make _autobuild_identifier more informative\n self._identifier = Identifier(\n self._autobuild_identifier() if not identifier else identifier\n )\n\n # Create logging directory\n self._create_logdir()\n\n self._initialize_state()\n\n # TODO(Sabri): fix add_index for new datset\n # Add an index to the dataset\n if not self.has_index:\n self._add_index()\n\n @classmethod\n def _create_columns(cls, name_to_data: Dict[str, AbstractColumn.Columnable]):\n new_data = {}\n for column_name, data in name_to_data.items():\n new_data[column_name] = AbstractColumn.from_data(data=data)\n\n return new_data\n\n def _repr_pandas_(self):\n return pd.DataFrame(\n {\n f\"{k} ({v.__class__.__name__})\": v._repr_pandas_()\n for k, v in self.items()\n }\n )\n\n def _repr_html_(self):\n return self._repr_pandas_()._repr_html_()\n\n def streamlit(self):\n return self._repr_pandas_()\n\n def __repr__(self):\n return f\"{self.__class__.__name__}\" f\"(num_rows: {self.num_rows})\"\n\n def __len__(self):\n # If only a subset of rows are visible\n if len(self.visible_columns) == 0:\n return 0\n return len(self[self.visible_columns[0]])\n\n def __contains__(self, item):\n return item in self.visible_columns\n\n def full_length(self):\n # If there are columns, full_length of any column, since they must be same size\n if self.column_names:\n return self._data[self.column_names[0]].full_length()\n return 0\n\n @property\n def column_names(self):\n \"\"\"Column names in the dataset.\"\"\"\n return self.visible_columns\n\n @property\n def columns(self):\n \"\"\"Column names in the dataset.\"\"\"\n return self.visible_columns\n\n @property\n def num_rows(self):\n \"\"\"Number of rows in the dataset.\"\"\"\n return len(self)\n\n @property\n def shape(self):\n \"\"\"Shape of the dataset (num_rows, num_columns).\"\"\"\n return self.num_rows, len(self.columns)\n\n @classmethod\n def _assert_columns_all_equal_length(cls, batch: Batch):\n \"\"\"Check that all columns have the same length so that the data is\n tabular.\"\"\"\n assert cls._columns_all_equal_length(\n batch\n ), \"All columns must have equal length.\"\n\n @classmethod\n def _columns_all_equal_length(cls, batch: Batch):\n \"\"\"Check that all columns have the same length so that the data is\n tabular.\"\"\"\n if len(set([len(v) for k, v in batch.items()])) == 1:\n return True\n return False\n\n def _check_columns_exist(self, columns: List[str]):\n \"\"\"Check that every column in `columns` exists.\"\"\"\n for col in columns:\n assert col in self.all_columns, f\"{col} is not a valid column.\"\n\n def _check_columns_unique(self, columns: List[str]):\n \"\"\"Checks that all columns are unique.\"\"\"\n assert len(columns) == len(set(columns))\n\n def _initialize_state(self):\n \"\"\"Dataset state initialization.\"\"\"\n # Show all columns by default\n self.visible_columns = copy(self.all_columns)\n\n # Set the features\n self._set_features()\n\n @property\n def visible_columns(self):\n return self._visible_columns\n\n @visible_columns.setter\n def visible_columns(self, columns: Optional[Sequence[str]] = None):\n if columns is None:\n # do nothing, keep old visible columns\n return\n for c in columns:\n if c not in self.all_columns:\n raise ValueError(f\"Trying to set nonexistant column {c} to visible.\")\n\n self._visible_columns = copy(columns)\n if \"index\" not in self._visible_columns and \"index\" in self.all_columns:\n self._visible_columns.append(\"index\")\n\n @contextmanager\n def format(self, columns: List[str] = None):\n \"\"\"Context where only `columns` will be visible.\"\"\"\n # Get the current format\n current_format = self.get_format()\n\n if columns:\n # View only `columns`\n self.set_format(columns)\n else:\n # Use all columns\n self.set_format(self.column_names)\n try:\n yield\n finally:\n # Reset the format back\n self.set_format(current_format)\n\n def get_format(self) -> List[str]:\n \"\"\"Get the dataset format.\"\"\"\n return self.visible_columns\n\n def set_format(self, columns: List[str]):\n \"\"\"Set the dataset format.\n\n Only `columns` are visible after set_format is invoked.\n \"\"\"\n # Check that the columns exist\n self._check_columns_exist(columns)\n # Set visible columns\n self.visible_columns = columns\n\n def reset_format(self):\n \"\"\"Reset the dataset format.\n\n All columns are visible.\n \"\"\"\n # All columns are visible\n self.visible_columns = self.all_columns\n\n def _example_or_batch_to_batch(\n self, example_or_batch: Union[Example, Batch]\n ) -> Batch:\n\n # Check if example_or_batch is a batch\n is_batch = all(\n [isinstance(v, List) for v in example_or_batch.values()]\n ) and self._columns_all_equal_length(example_or_batch)\n\n # Convert to a batch if not\n if not is_batch:\n batch = {k: [v] for k, v in example_or_batch.items()}\n else:\n batch = example_or_batch\n\n return batch\n\n @classmethod\n def _merge_batch_and_output(cls, batch: Batch, output: Batch):\n \"\"\"Merge an output during .map() into a batch.\"\"\"\n combined = batch\n for k in output.keys():\n if k not in batch:\n combined[k] = output[k]\n else:\n if isinstance(batch[k][0], dict) and isinstance(output[k][0], dict):\n combined[k] = [\n recmerge(b_i, o_i) for b_i, o_i in zip(batch[k], output[k])\n ]\n else:\n combined[k] = output[k]\n return combined\n\n @classmethod\n def _mask_batch(cls, batch: Batch, boolean_mask: List[bool]):\n \"\"\"Remove elements in `batch` that are masked by `boolean_mask`.\"\"\"\n return {\n k: [e for i, e in enumerate(v) if boolean_mask[i]] for k, v in batch.items()\n }\n\n @property\n def identifier(self):\n \"\"\"Identifier.\"\"\"\n return self._identifier\n\n def _set_features(self):\n \"\"\"Set the features of the dataset.\"\"\"\n with self.format():\n self.info.features = None # Features.from_arrow_schema(\n # pa.Table.from_pydict(\n # self[:1],\n # ).schema\n # )\n\n def add_column(\n self, name: str, data: AbstractColumn.Columnable, overwrite=False\n ) -> None:\n \"\"\"Add a column to the dataset.\"\"\"\n\n assert isinstance(\n name, str\n ), f\"Column name must of type `str`, not `{type(name)}`.\"\n\n assert (name not in self.all_columns) or overwrite, (\n f\"Column with name `{name}` already exists, \"\n f\"set `overwrite=True` to overwrite.\"\n )\n\n column = AbstractColumn.from_data(data)\n\n assert len(column) == len(self), (\n f\"`add_column` failed. \"\n f\"Values length {len(column)} != dataset length {len(self)}.\"\n )\n\n # Add the column\n self._data[name] = column\n\n if name not in self.all_columns:\n self.all_columns.append(name)\n self.visible_columns.append(name)\n\n # Set features\n self._set_features()\n\n logger.info(f\"Added column `{name}` with length `{len(column)}`.\")\n\n def remove_column(self, column: str) -> None:\n \"\"\"Remove a column from the dataset.\"\"\"\n assert column in self.all_columns, f\"Column `{column}` does not exist.\"\n\n # Remove the column\n del self._data[column]\n self.all_columns = [col for col in self.all_columns if col != column]\n self.visible_columns = [col for col in self.visible_columns if col != column]\n\n # Set features\n self._set_features()\n\n logger.info(f\"Removed column `{column}`.\")\n\n def select_columns(self, columns: List[str]) -> Batch:\n \"\"\"Select a subset of columns.\"\"\"\n for col in columns:\n assert col in self._data\n return tz.keyfilter(lambda k: k in columns, self._data)\n\n @capture_provenance(capture_args=[\"axis\"])\n def append(\n self,\n dp: DataPanel,\n axis: Union[str, int] = \"rows\",\n suffixes: Tuple[str] = None,\n overwrite: bool = False,\n ) -> DataPanel:\n \"\"\"Append a batch of data to the dataset.\n\n `example_or_batch` must have the same columns as the dataset\n (regardless of what columns are visible).\n \"\"\"\n if axis == 0 or axis == \"rows\":\n # append new rows\n return meerkat.concat([self, dp], axis=\"rows\")\n elif axis == 1 or axis == \"columns\":\n # append new columns\n if len(dp) != len(self):\n raise ValueError(\n \"Can only append DataPanels along axis 1 (columns) if they have the\"\n f\"same length. {len(self)} != {len(dp)}\"\n )\n\n shared = set(dp.visible_columns).intersection(set(self.visible_columns))\n if not overwrite and shared:\n if suffixes is None:\n raise ValueError()\n left_suf, right_suf = suffixes\n data = {\n **{k + left_suf if k in shared else k: v for k, v in self.items()},\n **{k + right_suf if k in shared else k: v for k, v in dp.items()},\n }\n else:\n data = {**dict(self.items()), **dict(dp.items())}\n\n return self._clone(data=data)\n else:\n raise ValueError(\"DataPanel `axis` must be either 0 or 1.\")\n\n def _add_index(self):\n \"\"\"Add an index to the dataset.\"\"\"\n self.add_column(\"index\", [str(i) for i in range(len(self))])\n\n def head(self, n: int = 5) -> DataPanel:\n \"\"\"Get the first `n` examples of the DataPanel.\"\"\"\n return self.lz[:n]\n\n def tail(self, n: int = 5) -> DataPanel:\n \"\"\"Get the last `n` examples of the DataPanel.\"\"\"\n return self.lz[-n:]\n\n def _create_logdir(self):\n \"\"\"Create and assign a directory for logging this dataset's files.\"\"\"\n if self.identifier.name == \"RGDataset\":\n # TODO(karan): handle temporarily constructed datasets differently\n self.logdir /= str(self.identifier)\n self.logdir.mkdir(parents=True, exist_ok=True)\n else:\n self.logdir /= str(self.identifier)\n self.logdir.mkdir(parents=True, exist_ok=True)\n\n def _autobuild_identifier(self) -> Identifier:\n \"\"\"Automatically build an identifier for the dataset using available\n information.\"\"\"\n # Look for a name, otherwise assign a default\n _name = self.info.builder_name if self.info.builder_name else \"RGDataset\"\n\n # Check for split, version information\n split = str(self.split) if self.split else None\n version = str(self.version) if self.version else None\n\n # Add all available information to kwargs dict\n kwargs = {}\n if split:\n kwargs[\"split\"] = split\n if version:\n kwargs[\"version\"] = version\n\n # Create identifier\n return Identifier(_name=_name, **kwargs)\n\n def _get(self, index, materialize: bool = False):\n if isinstance(index, int):\n # int index => single row (dict)\n return {\n k: self._data[k]._get(index, materialize=materialize)\n for k in self.visible_columns\n }\n\n elif isinstance(index, str):\n # str index => column selection (AbstractColumn)\n if index in self.column_names:\n return self._data[index]\n raise AttributeError(f\"Column {index} does not exist.\")\n\n # cases where `index` returns a datapanel\n elif isinstance(index, slice):\n # slice index => multiple row selection (DataPanel)\n return self._clone(\n data={\n k: self._data[k]._get(index, materialize=materialize)\n for k in self.visible_columns\n }\n )\n\n elif (isinstance(index, tuple) or isinstance(index, list)) and len(index):\n # tuple or list index => multiple row selection (DataPanel)\n if isinstance(index[0], str):\n if not set(index).issubset(self.visible_columns):\n missing_cols = set(self.visible_columns) - set(index)\n raise ValueError(f\"DataPanel does not have columns {missing_cols}\")\n dp = self.view()\n dp.visible_columns = index\n return dp\n\n return self._clone(\n data={\n k: self._data[k]._get(index, materialize=materialize)\n for k in self.visible_columns\n }\n )\n elif isinstance(index, np.ndarray):\n if len(index.shape) != 1:\n raise ValueError(\n \"Index must have 1 axis, not {}\".format(len(index.shape))\n )\n # numpy array index => multiple row selection (DataPanel)\n return self._clone(\n data={\n k: self._data[k]._get(index, materialize=materialize)\n for k in self.visible_columns\n }\n )\n elif isinstance(index, AbstractColumn):\n # column index => multiple row selection (DataPanel)\n return self._clone(\n data={\n k: self._data[k]._get(index, materialize=materialize)\n for k in self.visible_columns\n }\n )\n else:\n raise TypeError(\"Invalid index type: {}\".format(type(index)))\n\n # @capture_provenance(capture_args=[])\n def __getitem__(self, index):\n return self._get(index, materialize=True)\n\n def get(self, column, value=None):\n if column in self:\n return self[column]\n return value\n\n def __setitem__(self, index, value):\n self.add_column(name=index, data=value, overwrite=True)\n\n @property\n def has_index(self) -> bool:\n \"\"\"Check if the dataset has an index column.\"\"\"\n if self.column_names:\n return \"index\" in self.column_names\n # Just return True if the dataset is empty\n return True\n\n @classmethod\n def uncached_batch(cls, batch: Batch, copy=True) -> Batch:\n \"\"\"Return batch with the \"cache\" and \"slices\" columns removed.\"\"\"\n return tz.keyfilter(\n lambda k: k not in [\"cache\", \"slices\"], deepcopy(batch) if copy else batch\n )\n\n @classmethod\n def uncached_example(cls, example: Dict, copy=True) -> Dict:\n \"\"\"Return example with the \"cache\" and \"slices\" columns removed.\"\"\"\n return tz.keyfilter(\n lambda k: k not in [\"cache\", \"slices\"],\n deepcopy(example) if copy else example,\n )\n\n @classmethod\n def from_huggingface(cls, *args, **kwargs):\n \"\"\"Load a Huggingface dataset as a DataPanel.\n\n Use this to replace `datasets.load_dataset`, so\n\n >>> dict_of_datasets = datasets.load_dataset('boolq')\n\n becomes\n\n >>> dict_of_datapanels = DataPanel.from_huggingface('boolq')\n \"\"\"\n # Load the dataset\n dataset = datasets.load_dataset(*args, **kwargs)\n\n if isinstance(dataset, dict):\n return dict(\n map(\n lambda t: (t[0], cls(t[1])),\n dataset.items(),\n )\n )\n else:\n return cls(dataset)\n\n @classmethod\n @capture_provenance()\n def from_columns(\n cls,\n columns: Dict[str, AbstractColumn],\n identifier: Identifier = None,\n ) -> DataPanel:\n \"\"\"Create a Dataset from a dict of columns.\"\"\"\n return cls(\n columns,\n identifier=identifier,\n )\n\n @classmethod\n @capture_provenance()\n def from_jsonl(\n cls,\n json_path: str,\n identifier: Identifier = None,\n ) -> DataPanel:\n \"\"\"Load a dataset from a .jsonl file on disk, where each line of the\n json file consists of a single example.\"\"\"\n with open(json_path) as f:\n data = {k: [] for k in json.loads(f.readline())}\n # Load the .jsonl file\n with open(json_path) as f:\n for line in f:\n line = json.loads(line)\n for k in data:\n data[k].append(line[k])\n\n return cls(\n data,\n identifier=identifier\n if identifier\n else Identifier(\"Jsonl\", jsonl=json_path),\n )\n\n @classmethod\n # @capture_provenance()\n def from_batch(\n cls,\n batch: Batch,\n identifier: Identifier = None,\n ) -> DataPanel:\n \"\"\"Convert a batch to a Dataset.\"\"\"\n return cls(batch, identifier=identifier)\n\n @classmethod\n @capture_provenance()\n def from_batches(\n cls,\n batches: Sequence[Batch],\n identifier: Identifier = None,\n ) -> DataPanel:\n \"\"\"Convert a list of batches to a dataset.\"\"\"\n\n return cls.from_batch(\n tz.merge_with(\n tz.compose(list, tz.concat),\n *batches,\n ),\n identifier=identifier,\n )\n\n @classmethod\n @capture_provenance()\n def from_dict(\n cls,\n d: Dict,\n identifier: Identifier = None,\n ) -> DataPanel:\n \"\"\"Convert a dictionary to a dataset.\n\n Alias for Dataset.from_batch(..).\n \"\"\"\n return cls.from_batch(\n batch=d,\n identifier=identifier,\n )\n\n @classmethod\n @capture_provenance()\n def from_pandas(\n cls,\n df: pd.DataFrame,\n identifier: Identifier = None,\n ):\n \"\"\"Create a Dataset from a pandas DataFrame.\"\"\"\n return cls.from_batch(\n df.to_dict(\"series\"),\n identifier=identifier,\n )\n\n @classmethod\n @capture_provenance(capture_args=[\"filepath\"])\n def from_csv(cls, filepath: str, *args, **kwargs):\n \"\"\"Create a Dataset from a csv file.\n\n Args:\n filepath (str): The file path or buffer to load from.\n Same as :func:`pandas.read_csv`.\n *args: Argument list for :func:`pandas.read_csv`.\n **kwargs: Keyword arguments for :func:`pandas.read_csv`.\n\n Returns:\n DataPanel: The constructed datapanel.\n \"\"\"\n return cls.from_pandas(pd.read_csv(filepath, *args, **kwargs))\n\n @classmethod\n @capture_provenance()\n def from_feather(\n cls,\n path: str,\n identifier: Identifier = None,\n ):\n \"\"\"Create a Dataset from a feather file.\"\"\"\n return cls.from_batch(\n pd.read_feather(path).to_dict(\"list\"),\n identifier=Identifier(\"Feather\", path=path)\n if not identifier\n else identifier,\n )\n\n @capture_provenance()\n def to_pandas(self) -> pd.DataFrame:\n \"\"\"Convert a Dataset to a pandas DataFrame.\"\"\"\n return pd.DataFrame({name: column.to_pandas() for name, column in self.items()})\n\n def to_jsonl(self, path: str) -> None:\n \"\"\"Save a Dataset to a jsonl file.\"\"\"\n with jsonlines.open(path, mode=\"w\") as writer:\n for example in self:\n writer.write(example)\n\n def _get_collate_fns(self, columns: Iterable[str] = None):\n columns = self._data.keys() if columns is None else columns\n return {name: self._data[name].collate for name in columns}\n\n def _collate(self, batch: List):\n batch = tz.merge_with(list, *batch)\n column_to_collate = self._get_collate_fns(batch.keys())\n new_batch = {}\n for name, values in batch.items():\n new_batch[name] = column_to_collate[name](values)\n dp = self._clone(data=new_batch)\n return dp\n\n @staticmethod\n def _convert_to_batch_fn(\n function: Callable, with_indices: bool, materialize: bool = True\n ) -> callable:\n return convert_to_batch_fn(\n function=function, with_indices=with_indices, materialize=materialize\n )\n\n def batch(\n self,\n batch_size: int = 1,\n drop_last_batch: bool = False,\n num_workers: int = 0,\n materialize: bool = True,\n *args,\n **kwargs,\n ):\n \"\"\"Batch the dataset.\n TODO:\n\n Args:\n batch_size: integer batch size\n drop_last_batch: drop the last batch if its smaller than batch_size\n\n Returns:\n batches of data\n \"\"\"\n cell_columns, batch_columns = [], []\n for name, column in self.items():\n if isinstance(column, CellColumn):\n cell_columns.append(name)\n else:\n batch_columns.append(name)\n\n if batch_columns:\n batch_indices = []\n indices = np.arange(len(self))\n for i in range(0, len(self), batch_size):\n if drop_last_batch and i + batch_size > len(self):\n continue\n batch_indices.append(indices[i : i + batch_size])\n batch_dl = torch.utils.data.DataLoader(\n self[batch_columns] if materialize else self[batch_columns].lz,\n sampler=batch_indices,\n batch_size=None,\n batch_sampler=None,\n drop_last=drop_last_batch,\n num_workers=num_workers,\n *args,\n **kwargs,\n )\n\n if cell_columns:\n cell_dl = torch.utils.data.DataLoader(\n self[cell_columns] if materialize else self[cell_columns].lz,\n batch_size=batch_size,\n collate_fn=self._collate,\n drop_last=drop_last_batch,\n num_workers=num_workers,\n *args,\n **kwargs,\n )\n\n if batch_columns and cell_columns:\n for cell_batch, batch_batch in zip(cell_dl, batch_dl):\n yield self._clone(data={**cell_batch._data, **batch_batch._data})\n elif batch_columns:\n for batch_batch in batch_dl:\n yield batch_batch\n elif cell_columns:\n for cell_batch in cell_dl:\n yield cell_batch\n\n @capture_provenance(capture_args=[\"with_indices\"])\n def update(\n self,\n function: Optional[Callable] = None,\n with_indices: bool = False,\n input_columns: Optional[Union[str, List[str]]] = None,\n is_batched_fn: bool = False,\n batch_size: Optional[int] = 1,\n remove_columns: Optional[List[str]] = None,\n num_workers: int = 0,\n mmap: bool = False,\n materialize: bool = True,\n pbar: bool = False,\n **kwargs,\n ) -> DataPanel:\n \"\"\"Update the columns of the dataset.\"\"\"\n # TODO(karan): make this fn go faster\n # most of the time is spent on the merge, speed it up further\n\n # Return if the function is None\n if function is None:\n logger.info(\"`function` None, returning None.\")\n return self\n\n # Return if `self` has no examples\n if not len(self):\n logger.info(\"Dataset empty, returning None.\")\n return self\n\n # Get some information about the function\n with self.format(input_columns):\n function_properties = self._inspect_function(\n function, with_indices, is_batched_fn, materialize=materialize\n )\n assert (\n function_properties.dict_output\n ), f\"`function` {function} must return dict.\"\n\n if not is_batched_fn:\n # Convert to a batch function\n function = convert_to_batch_fn(\n function, with_indices=with_indices, materialize=materialize\n )\n logger.info(f\"Converting `function` {function} to batched function.\")\n\n # Update always returns a new dataset\n logger.info(\"Running update, a new dataset will be returned.\")\n\n # Copy the ._data dict with a reference to the actual columns\n new_dp = self.view()\n\n # Calculate the values for the new columns using a .map()\n output = new_dp.map(\n function=function,\n with_indices=with_indices,\n is_batched_fn=True,\n batch_size=batch_size,\n num_workers=num_workers,\n input_columns=input_columns,\n mmap=mmap,\n materialize=materialize,\n pbar=pbar,\n )\n\n # Add new columns for the update\n for col, vals in output._data.items():\n if col == \"index\":\n continue\n new_dp.add_column(col, vals, overwrite=True)\n\n # Remove columns\n if remove_columns:\n for col in remove_columns:\n new_dp.remove_column(col)\n logger.info(f\"Removed columns {remove_columns}.\")\n\n return new_dp\n\n def map(\n self,\n function: Optional[Callable] = None,\n with_indices: bool = False,\n input_columns: Optional[Union[str, List[str]]] = None,\n is_batched_fn: bool = False,\n batch_size: Optional[int] = 1,\n drop_last_batch: bool = False,\n num_workers: int = 0,\n output_type: type = None,\n mmap: bool = False,\n materialize: bool = True,\n pbar: bool = False,\n **kwargs,\n ) -> Optional[Union[Dict, List, AbstractColumn]]:\n input_columns = self.visible_columns if input_columns is None else input_columns\n with self.format(input_columns):\n return super().map(\n function=function,\n with_indices=with_indices,\n is_batched_fn=is_batched_fn,\n batch_size=batch_size,\n drop_last_batch=drop_last_batch,\n num_workers=num_workers,\n output_type=output_type,\n mmap=mmap,\n materialize=materialize,\n pbar=pbar,\n **kwargs,\n )\n\n @capture_provenance(capture_args=[\"function\"])\n def filter(\n self,\n function: Optional[Callable] = None,\n with_indices=False,\n input_columns: Optional[Union[str, List[str]]] = None,\n is_batched_fn: bool = False,\n batch_size: Optional[int] = 1,\n drop_last_batch: bool = False,\n num_workers: int = 0,\n materialize: bool = True,\n pbar: bool = False,\n **kwargs,\n ) -> Optional[DataPanel]:\n \"\"\"Filter operation on the DataPanel.\"\"\"\n\n # Just return if the function is None\n if function is None:\n logger.info(\"`function` None, returning None.\")\n return None\n\n # Return if `self` has no examples\n if not len(self):\n logger.info(\"DataPanel empty, returning None.\")\n return None\n\n # Get some information about the function\n with self.format(input_columns):\n function_properties = self._inspect_function(\n function,\n with_indices,\n is_batched_fn=is_batched_fn,\n materialize=materialize,\n )\n assert function_properties.bool_output, \"function must return boolean.\"\n\n # Map to get the boolean outputs and indices\n logger.info(\"Running `filter`, a new DataPanel will be returned.\")\n outputs = self.map(\n function=function,\n with_indices=with_indices,\n input_columns=input_columns,\n is_batched_fn=is_batched_fn,\n batch_size=batch_size,\n drop_last_batch=drop_last_batch,\n num_workers=num_workers,\n materialize=materialize,\n pbar=pbar,\n )\n indices = np.where(outputs)[0]\n\n # filter returns a new datapanel\n new_datapanel = self.view()\n for column in new_datapanel._data.values():\n column.visible_rows = indices\n\n return new_datapanel\n\n def merge(\n self,\n right: meerkat.DataPanel,\n how: str = \"inner\",\n on: Union[str, List[str]] = None,\n left_on: Union[str, List[str]] = None,\n right_on: Union[str, List[str]] = None,\n sort: bool = False,\n suffixes: Sequence[str] = (\"_x\", \"_y\"),\n validate=None,\n keep_indexes: bool = False,\n ):\n from meerkat import merge\n\n return merge(\n self,\n right,\n how=how,\n on=on,\n left_on=left_on,\n right_on=right_on,\n sort=sort,\n suffixes=suffixes,\n validate=validate,\n keep_indexes=keep_indexes,\n )\n\n def items(self):\n for name in self.visible_columns:\n yield name, self._data[name]\n\n def keys(self):\n return self.visible_columns\n\n def values(self):\n for name in self.visible_columns:\n yield self._data[name]\n\n @classmethod\n def read(\n cls,\n path: str,\n *args,\n **kwargs,\n ) -> DataPanel:\n \"\"\"Load a DataPanel stored on disk.\"\"\"\n\n # Load the metadata\n metadata = dict(\n yaml.load(open(os.path.join(path, \"meta.yaml\")), Loader=yaml.FullLoader)\n )\n\n state = dill.load(open(os.path.join(path, \"state.dill\"), \"rb\"))\n\n # Load the columns\n if not metadata[\"write_together\"]:\n data = {\n name: dtype.read(os.path.join(path, \"columns\", name), *args, **kwargs)\n for name, dtype in metadata[\"column_dtypes\"].items()\n }\n state[\"_data\"] = data\n\n # Create a DataPanel from the loaded state\n datapanel = cls.from_state(state)\n\n return datapanel\n\n def write(\n self,\n path: str,\n write_together: bool = False,\n ) -> None:\n \"\"\"Save a DataPanel to disk.\"\"\"\n # Make all the directories to the path\n os.makedirs(path, exist_ok=True)\n\n # Get the DataPanel state\n state = self.get_state()\n\n # Get the metadata\n metadata = {\n \"dtype\": type(self),\n \"column_dtypes\": {name: type(col) for name, col in self._data.items()},\n \"len\": len(self),\n \"write_together\": write_together,\n }\n\n if not write_together:\n if \"_data\" not in state:\n raise ValueError(\n \"DataPanel's state must include `_data` when using \"\n \"`write_together=False`.\"\n )\n del state[\"_data\"]\n\n # Create a directory for the columns at `path`\n columns_path = os.path.join(path, \"columns\")\n os.makedirs(columns_path, exist_ok=True)\n\n # Save each column in the DataPanel separately\n for name, column in self._data.items():\n column.write(os.path.join(columns_path, name))\n\n # Write the state\n state_path = os.path.join(path, \"state.dill\")\n dill.dump(state, open(state_path, \"wb\"))\n\n # Save the metadata as a yaml file\n metadata_path = os.path.join(path, \"meta.yaml\")\n yaml.dump(metadata, open(metadata_path, \"w\"))\n\n @classmethod\n def from_state(cls, state: Dict, *args, **kwargs) -> DataPanel:\n datapanel = super(DataPanel, cls).from_state(state, *args, **kwargs)\n datapanel._create_logdir()\n datapanel._set_features()\n return datapanel\n\n @classmethod\n def _state_keys(cls) -> set:\n \"\"\"List of attributes that describe the state of the object.\"\"\"\n return {\n \"_identifier\",\n \"_data\",\n \"all_columns\",\n \"_visible_columns\",\n \"_info\",\n \"_split\",\n }\n\n def _clone_kwargs(self) -> Dict[str, Any]:\n \"\"\"Returns __init__ kwargs for instantiating new object.\n\n This function returns the default parameters that should be plumbed\n from the current instance to the new instance.\n\n This is the API that should be used by subclasses of :class:`DataPanel`.\n\n Returns:\n Dict[str, Any]: The keyword arguments for initialization\n \"\"\"\n # identifier, info, and split are not passed by default because they have\n # not been plumbed so far.\n return {}\n\n def _clone(self, data=None, **kwargs):\n default_kwargs = self._clone_kwargs()\n if data is None:\n data = kwargs.pop(\"data\", self.data)\n if kwargs:\n default_kwargs.update(kwargs)\n return self.__class__(data, **default_kwargs)\n","sub_path":"meerkat/datapanel.py","file_name":"datapanel.py","file_ext":"py","file_size_in_byte":37290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"290770397","text":"from invenio_oarepo_oai_pmh_harvester.register import Decorators\nfrom invenio_oarepo_oai_pmh_harvester.rules.utils import iter_array\nfrom invenio_oarepo_oai_pmh_harvester.transformer import OAITransformer\n\n\n@Decorators.rule(\"xoai\")\n@Decorators.pre_rule(\"/dc/identifier\")\ndef transform_identifier(paths, el, results, phase, **kwargs):\n ids = []\n results[-1][\"identifier\"] = ids\n return ids\n\n\n@Decorators.rule(\"xoai\")\n@Decorators.pre_rule(\"/dc/identifier/uri\")\n@Decorators.array_value\ndef transform_identifier_uri(paths, el, results, phase, **kwargs):\n return [\n {\n \"type\": \"originalRecord\",\n \"value\": x\n } for x in iter_array(el[\"value\"])\n ]\n\n\n@Decorators.rule(\"xoai\")\n@Decorators.pre_rule(\"/dc/identifier/repId\")\ndef transform_repId(paths, el, results, phase, **kwargs):\n return OAITransformer.PROCESSED\n\n\n@Decorators.rule(\"xoai\")\n@Decorators.pre_rule(\"/dc/identifier/aleph\")\ndef transform_aleph(paths, el, results, phase, **kwargs):\n return OAITransformer.PROCESSED\n\n\n@Decorators.rule(\"xoai\")\n@Decorators.pre_rule(\"/others/identifier\")\ndef transform_others_identifier(paths, el, results, phase, **kwargs):\n if results[-1].get(\"identifier\") is None:\n results[-1][\"identifier\"] = [\n {\n \"value\": el,\n \"type\": \"originalOAI\"\n }\n ]\n else:\n results[-1][\"identifier\"].append(\n {\n \"value\": el,\n \"type\": \"originalOAI\"\n }\n )\n return OAITransformer.PROCESSED\n","sub_path":"example/rules/uk/identifier.py","file_name":"identifier.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"69767876","text":"import unittest\n\nfrom file_utils import *\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n self.base_path = PurePath(\"test\") / \"file_utils_test\"\n self.a = self.base_path / \"a\"\n self.dota = self.base_path / \".a\"\n self.atxt = self.base_path / \"a.txt\"\n self.sub = self.base_path / \"sub\"\n self.suba = self.sub / \"a\"\n self.subatxt = self.sub / \"a.txt\"\n\n def test_deduplicate(self):\n s = deduplicate(\"aa\", \"_\")\n self.assertEqual(s, \"aa\")\n\n s = deduplicate(\"a_a\", \"_\")\n self.assertEqual(s, \"a_a\")\n\n s = deduplicate(\"a__a\", \"_\")\n self.assertEqual(s, \"a_a\")\n\n s = deduplicate(\"aa_\", \"_\")\n self.assertEqual(s, \"aa_\")\n\n s = deduplicate(\"aa__\", \"_\")\n self.assertEqual(s, \"aa_\")\n\n def test_fix_delimiters(self):\n RECOGNIZED = [\"_\", \"-\"]\n OUT = \"_\"\n STRING = \"a_b-c__d_-e-_f--g\"\n RESULT_DUPE = \"a_b_c__d__e__f__g\"\n s = fix_delimiters(\n STRING,\n out_delimiter=OUT,\n recognized_delimiters=RECOGNIZED,\n do_deduplicate=False,\n )\n self.assertEqual(s, RESULT_DUPE)\n\n RESULT = \"a_b_c_d_e_f_g\"\n s = fix_delimiters(STRING, out_delimiter=OUT, recognized_delimiters=RECOGNIZED)\n self.assertEqual(s, RESULT)\n\n def test_get_contents(self):\n contents = get_contents(self.base_path)\n self.assertEqual(len(contents), 4)\n self.assertEqual(contents[0], self.dota)\n self.assertEqual(contents[1], self.a)\n self.assertEqual(contents[2], self.atxt)\n self.assertEqual(contents[3], self.sub)\n\n contents = get_contents(self.base_path, ext=\"txt\")\n self.assertEqual(len(contents), 1)\n self.assertEqual(contents[0], self.atxt)\n\n contents = get_contents(self.base_path, ext=\".txt\")\n self.assertEqual(len(contents), 1)\n self.assertEqual(contents[0], self.atxt)\n\n contents = get_contents(self.base_path, recursive=True)\n self.assertEqual(len(contents), 6)\n self.assertEqual(contents[0], self.dota)\n self.assertEqual(contents[1], self.a)\n self.assertEqual(contents[2], self.atxt)\n self.assertEqual(contents[3], self.sub)\n self.assertEqual(contents[4], self.suba)\n self.assertEqual(contents[5], self.subatxt)\n\n contents = get_contents(self.base_path, ext=\"txt\", recursive=True)\n self.assertEqual(len(contents), 2)\n self.assertEqual(contents[0], self.atxt)\n self.assertEqual(contents[1], self.subatxt)\n\n def test_generate_file_names(self):\n BASE_NAME = \"file_1\"\n RESULT = [PurePath(\"file_1.txt\")]\n names = generate_file_names(BASE_NAME, \"txt\")\n self.assertEqual(names, RESULT)\n\n INDICES = list(range(1, 4))\n RESULT = [\"file_1_1.txt\", \"file_1_2.txt\", \"file_1_3.txt\"]\n RESULT = [PurePath(r) for r in RESULT]\n names = generate_file_names(BASE_NAME, \".txt\", indices=INDICES)\n self.assertEqual(names, RESULT)\n\n FOLDER = PurePath(\"folder\")\n RESULT = [FOLDER / r for r in RESULT]\n names = generate_file_names(BASE_NAME, \".txt\", indices=INDICES, folder=FOLDER)\n self.assertEqual(names, RESULT)\n\n RESULT = [\"1.txt\", \"2.txt\", \"3.txt\"]\n RESULT = [PurePath(r) for r in RESULT]\n names = generate_file_names(ext=\".txt\", indices=INDICES)\n self.assertEqual(names, RESULT)\n\n FOLDER = PurePath(\"folder\")\n RESULT = [FOLDER / r for r in RESULT]\n names = generate_file_names(ext=\".txt\", indices=INDICES, folder=FOLDER)\n self.assertEqual(names, RESULT)\n\n with self.assertRaises(ValueError):\n names = generate_file_names(ext=\".txt\")\n\n def test_get_subfolders(self):\n subs = get_subfolders(self.base_path)\n self.assertEqual(len(subs), 1)\n self.assertEqual(subs[0], self.sub)\n\n def test_lcp(self):\n self.assertEqual(lcp(\"interspecies\", \"interstellar\", \"interstate\"), \"inters\")\n self.assertEqual(lcp(\"throne\", \"throne\"), \"throne\")\n self.assertEqual(lcp(\"throne\", \"dungeon\"), \"\")\n self.assertEqual(lcp(\"cheese\"), \"cheese\")\n self.assertEqual(lcp(\"\"), \"\")\n self.assertEqual(lcp(\"prefix\", \"suffix\"), \"\")\n self.assertEqual(lcp(\"foo\", \"foobar\"), \"foo\")\n\n def test_lcs(self):\n STRINGS = [\n \"x!983_abcdefghij0983q580\",\n \"abcdefghijklmnopqrstuvwxyz\",\n \"_abcdefghij\",\n ]\n RESULT = \"abcdefghij\"\n self.assertEqual(lcs(*STRINGS), RESULT)\n\n def test_Files(self):\n BASE_NAME = \"file_1\"\n ALT_BASE_NAME = \"file-1\"\n FOLDER = \"folder\"\n INDICES = list(range(1, 4))\n RESULT = [\"file_1_1.txt\", \"file_1_2.txt\", \"file_1_3.txt\"]\n RESULT = [PurePath(r) for r in RESULT]\n RESULT = [FOLDER / r for r in RESULT]\n RESULT_S = [\"file_1_suffix_1.txt\", \"file_1_suffix_2.txt\", \"file_1_suffix_3.txt\"]\n RESULT_S = [PurePath(r) for r in RESULT_S]\n RESULT_S = [FOLDER / r for r in RESULT_S]\n RESULT_I = [\"1.txt\", \"2.txt\", \"3.txt\"]\n RESULT_I = [PurePath(r) for r in RESULT_I]\n RESULT_I = [FOLDER / r for r in RESULT_I]\n\n files = Files(FOLDER, BASE_NAME)\n files_idem = (Files(FOLDER, BASE_NAME) / FOLDER).parent\n self.assertEqual(files.root, files_idem.root)\n\n files = Files(FOLDER, BASE_NAME)\n self.assertEqual(files.name, BASE_NAME)\n\n files = Files(FOLDER, BASE_NAME) + BASE_NAME\n self.assertEqual(files.name, files.delimiter.join([BASE_NAME, BASE_NAME]))\n files.name = BASE_NAME\n self.assertEqual(files.name, BASE_NAME)\n\n files = Files(FOLDER, BASE_NAME) + BASE_NAME\n files.delimiter = \"-\"\n self.assertEqual(files.delimiter, \"-\")\n self.assertEqual(\n files.name, files.delimiter.join([ALT_BASE_NAME, ALT_BASE_NAME])\n )\n files.name = ALT_BASE_NAME\n self.assertEqual(files.name, ALT_BASE_NAME)\n\n files = Files(FOLDER, BASE_NAME)\n with self.assertRaises(AssertionError):\n files.delimiter = \"x\"\n\n files = Files(FOLDER, BASE_NAME, allowed_delimiters=[\"x\"])\n try:\n files.delimiter = \"x\"\n except AssertionError:\n self.fail()\n\n files_no_ext = Files(FOLDER, BASE_NAME)\n names = files_no_ext.generate_file_names(\".txt\", indices=INDICES)\n self.assertEqual(names, RESULT)\n\n files_no_ext_s = Files(FOLDER, BASE_NAME) + \"suffix\"\n names_s = files_no_ext_s.generate_file_names(\".txt\", indices=INDICES)\n self.assertEqual(names_s, RESULT_S)\n\n files_no_ext_i = Files(FOLDER)\n names_i = files_no_ext_i.generate_file_names(\".txt\", indices=INDICES)\n self.assertEqual(names_i, RESULT_I)\n\n files_ext = Files(FOLDER, BASE_NAME, \"wrong\")\n names = files_ext.generate_file_names(indices=INDICES)\n for n, r in zip(names, RESULT):\n self.assertNotEqual(n, r)\n\n files_ext = Files(FOLDER, BASE_NAME, \"wrong\")\n names = files_ext.generate_file_names(\".txt\", indices=INDICES)\n self.assertEqual(names, RESULT)\n\n files_ext = Files(FOLDER, BASE_NAME, \"wrong\")\n files_ext.ext = \"txt\"\n names = files_ext.generate_file_names(indices=INDICES)\n self.assertEqual(names, RESULT)\n\n files_ext_s = Files(FOLDER, BASE_NAME, \"wrong\") + \"suffix\"\n names_s = files_ext_s.generate_file_names(indices=INDICES)\n for n, r in zip(names_s, RESULT):\n self.assertNotEqual(n, r)\n\n names_s = files_ext_s.generate_file_names(\".txt\", indices=INDICES)\n self.assertEqual(names_s, RESULT_S)\n\n files_ext_i = Files(FOLDER, \"wrong\")\n names_i = files_ext_i.generate_file_names(indices=INDICES)\n for n, r in zip(names_i, RESULT_I):\n self.assertNotEqual(n, r)\n\n names_i = files_ext_i.generate_file_names(\".txt\", indices=INDICES)\n for n, r in zip(names_i, RESULT_I):\n self.assertNotEqual(n, r)\n\n files_ext = Files(\"\", BASE_NAME, \"txt\") / FOLDER\n names = files_ext.generate_file_names(indices=INDICES)\n self.assertEqual(names, RESULT)\n\n files_ext_s = Files(\"\", BASE_NAME, \"txt\") / FOLDER\n files_ext_s = files_ext_s + \"suffix\"\n names_s = files_ext_s.generate_file_names(indices=INDICES)\n self.assertEqual(names_s, RESULT_S)\n\n files_ext_i = Files(\"\", \"txt\") / FOLDER\n files_ext_i = files_ext_i + \"suffix\"\n names_i = files_ext_i.generate_file_names(indices=INDICES)\n for n, r in zip(names_i, RESULT_I):\n self.assertNotEqual(n, r)\n\n files = Files(FOLDER, BASE_NAME)\n files_copy = files / FOLDER\n names = files.generate_file_names(indices=INDICES)\n names_copy = files_copy.generate_file_names(indices=INDICES)\n for n, nc in zip(names, names_copy):\n self.assertNotEqual(n, nc)\n\n files = Files(FOLDER, BASE_NAME)\n files_copy = files + BASE_NAME\n names = files.generate_file_names(indices=INDICES)\n names_copy = files_copy.generate_file_names(indices=INDICES)\n for n, nc in zip(names, names_copy):\n self.assertNotEqual(n, nc)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"inc/python_image_utilities/inc/file_utils/test/file_utils_test.py","file_name":"file_utils_test.py","file_ext":"py","file_size_in_byte":9313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"9927710","text":"import os\nimport sys\nsys.path.append('../..')\nfrom Lib.ConfigClass import Config, singular_colors\nimport json\n\nscene_path = '/home/wangsd/Workspace/foliation-results/outputs/scenes/paper/palmer_foliation/'\noutput_path = '/pub/data/wangsd/images/palmer_foliation'\ntexture_path = '/home/wangsd/Workspace/cg/data/texture/checkerboard.png'\nenvmap_path = '/home/wangsd/Workspace/cg/data/envmap/gl-hdr-02.hdr'\nmaterial_filename = '99-porcelain-texture.blend'\n\nfor root, dirs, _ in os.walk(scene_path):\n for d in dirs:\n if os.path.exists(os.path.join(root, d, 'mesh.obj')):\n print('Processing', os.path.join(root, d))\n config = Config()\n config_file = os.path.join(root, d, 'config.json')\n if os.path.exists(config_file):\n with open(os.path.join(root, d, 'config.json')) as jf:\n config.__dict__ = json.load(jf)\n \n config.scene_path = os.path.join(root, d + '/')\n config.output_path = os.path.join(output_path, d + '.png')\n config.envmap_path = envmap_path\n config.transform_json_name = 'transform.json'\n config.mode = 'single'\n config.use_envmap = True\n config.width = 2000\n config.height = 2000\n config.plane = None\n config.cut_mode = 'Plain'\n config.material = None\n config.material_filename = material_filename\n config.texture_path = texture_path\n config.uv_multiply = (2.0, 0.0)\n config.uv_add = (0.05, 0.05)\n config.show_loops = False\n config.show_singularities = True\n config.zero_scale = 0.01\n config.pole_scale = 0.02\n\n config.save_config(os.path.join(root, d, 'config.json'))\n","sub_path":"Blender/Scripts/wangsd/scripts/palmer_foliation.py","file_name":"palmer_foliation.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"581306006","text":"import random as rd\nimport numpy as np\nfrom constants import *\n\n\ndef creating_cities():\n # creating cities\n for from_city in range(MAX_CITIES):\n # randomly place cities\n lat = rd.randint(1, MAX_DIST)\n long = rd.randint(1, MAX_DIST)\n cities.append(\n {\n \"lat\": lat,\n \"long\": long,\n }\n )\n dist.append([])\n pheromone.append([])\n for to_city in range(MAX_CITIES):\n dist[from_city].append(0.0)\n pheromone[from_city].append(INIT_PHEROMONE)\n\n\ndef computing_distance():\n # computing distance\n for from_city in range(MAX_CITIES):\n for to_city in range(MAX_CITIES):\n if from_city != to_city and dist[from_city][to_city] == 0.0:\n xd = abs(cities[from_city][\"lat\"] - cities[to_city][\"lat\"]) ** 2\n yd = abs(cities[from_city][\"long\"] - cities[to_city][\"long\"]) ** 2\n\n dist[from_city][to_city] = np.sqrt(xd + yd)\n dist[to_city][from_city] = dist[from_city][to_city]\n\n\ndef initializing_ants():\n # initializing the ANTs\n current = 0\n for ant in range(MAX_ANTS):\n if current == MAX_CITIES:\n current = 0\n ants.append({\n \"curCity\": current\n })\n current += 1\n\n ants[ant][\"taa\"] = []\n ants[ant][\"path\"] = []\n for from_city in range(MAX_CITIES+1):\n ants[ant][\"taa\"].append(0)\n ants[ant][\"path\"].append(-1)\n\n ants[ant][\"pathIndex\"] = 1\n ants[ant][\"path\"][0] = ants[ant][\"curCity\"]\n ants[ant][\"nextCity\"] = -1\n ants[ant][\"tourLength\"] = 0\n\n # loading first city into taa list\n ants[ant][\"taa\"][ants[ant][\"curCity\"]] = 1","sub_path":"Ant Colony Algorithm/Travel Salesman Problem/initializing.py","file_name":"initializing.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"82650158","text":"#!/usr/bin/python\n\nimport sys\nimport os\nimport time\nimport pygame\nfrom pygame import *\nimport MegaMan\n\n#.get_rect(scrub)\n\ndef main():\n\n #add time updates later to run at certain fps/ups\n\n #set up pygame window\n pygame.init()\n pygame.mouse.set_visible(1)\n window = pygame.display.set_mode((640,480))\n pygame.display.set_caption(\"Mega-Man Reassembled\")\n\n #fill the background\n background = pygame.Surface(window.get_size())\n background = background.convert()\n background.fill((250,250,250))\n\n #blit background to the screen\n window.blit(background,(0,0))\n pygame.display.flip()\n\n #make sprite groups\n allgroup = pygame.sprite.Group()\n meggroup = pygame.sprite.Group()\n Megaman.groups = allgroup, meggroup #add megaman to both groups\n\n #add the sprites\n megman = Megaman()\n\n #times for updating\n FPS = 50\n UPS = 50\n seconds = 1 #currentely for testing, replace with UPS later\n\n\n #game loop\n while True:\n\n #quit when exit\n for event in pygame.event.get():\n if event.type == QUIT:\n return\n\n #update() #use this later\n\n #update the sprites\n allsprites.clear(window, backgroud)\n allsprites.update(seconds)\n allsprites.draw(window)\n pygame.display.flip()\n\n #blit to the screen, again\n window.blit(background, (0,0))\n pygame.display.flip()\n\n\n#start it\nif __name__ == '__main__' : main()\n\n\ndef update():\n\n #put updates here\n\n #blit to the screen, again\n screen.blit(background, (0,0))\n pygame.display.flip()\n","sub_path":"test/mainloop.py","file_name":"mainloop.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"207638433","text":"from django.test import TestCase, LiveServerTestCase\nfrom django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom django.urls import reverse\nfrom selenium.webdriver.chrome.webdriver import WebDriver\n\n\nclass BaseTemplateTest(StaticLiveServerTestCase):\n \"\"\"Selenium-based tests for the base html template\"\"\"\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.selenium = WebDriver()\n cls.selenium.implicitly_wait(10)\n \n @classmethod\n def tearDownClass(cls):\n cls.selenium.quit()\n super().tearDownClass()\n\n def test_static_assets_imported(self):\n #ensure static JS and static stylesheets are imported \n self.selenium.get('%s%s' % (self.live_server_url, reverse('base:index')))\n #assert error is not raised\n try:\n self.selenium.find_element_by_css_selector('script#custom-javascript')\n except NoSuchElementException:\n self.fail(\"Template did not load custom javascript file!\")\n\n try: \n self.selenium.find_element_by_css_selector('link#custom-css')\n except NoSuchElementException:\n self.fail(\"Template did not load custom css file!\")\n \nclass IndexViewTest(TestCase):\n \"\"\"Test correct response and content for index view\"\"\"\n def test_url_fetch(self):\n #confirm urlConf works and Get returns correct response and template\n response = self.client.get(reverse('base:index'))\n self.assertContains(response, \"Welcome\")\n #assert extends base template\n templates = response.templates\n self.assertTemplateUsed(response=response, template_name = 'base/shared/base.html')\n self.assertTemplateUsed(response= response, template_name='base/index.html')\n \nclass HelpViewTest(TestCase):\n def test_url_fetch(self):\n #confirm url fetches correctly and extends from base template\n response = self.client.get(reverse('base:help'))\n templates = response.templates\n self.assertTemplateUsed(response = response, template_name = 'base/shared/base.html')\n self.assertTemplateUsed(response = response, template_name = 'base/help.html')\n\n\n","sub_path":"base/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"178571134","text":"from django import forms\nfrom .widgets import CustomClearableFileInput\nfrom .models import Commissions\n\n\nclass CommissionsForm(forms.ModelForm):\n class Meta:\n model = Commissions\n fields = '__all__'\n\n image = forms.ImageField(label='Image',\n required=False,\n widget=CustomClearableFileInput)\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Add placeholders and classes, remove auto-generated\n labels and set autofocus on first field\n \"\"\"\n super().__init__(*args, **kwargs)\n placeholders = {\n 'name': 'Your name',\n 'message': 'Extra comments',\n 'email': 'Email address',\n 'pet_num': 'Numbet of pets'\n }\n\n for field in self.fields:\n if field != 'image':\n if field != 'size' and field != 'pet_num' and field != 'media':\n if self.fields[field].required:\n placeholder = f'{placeholders[field]} *'\n else:\n placeholder = placeholders[field]\n self.fields[field].widget.attrs[\n 'placeholder'] = placeholder\n self.fields[field].label = False\n","sub_path":"commissions/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"77038250","text":"from collections import OrderedDict\n\nimport mmcv\nfrom mmcv.runner import obj_from_dict\nfrom mmcls.utils.checkpoint import load_checkpoint\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.distributed as dist\n\nimport mmcls\nfrom mmcls.core import auto_fp16, force_fp32\nfrom mmcls.core.evaluation import accuracy\nfrom mmcls.utils import get_root_logger\n\nfrom .. import builder\nfrom ..registry import CLASSIFIERS\n\n\ndef get_output_channels(module_layer):\n if isinstance(module_layer, nn.Conv2d):\n return module_layer.out_channels\n child_modules = list(module_layer.children())\n if len(child_modules) > 1:\n for child in child_modules[::-1]:\n if isinstance(child, nn.Conv2d):\n return child.out_channels\n raise NotImplementedError\n\n\ndef expand_connect_index(connect_index, end_index):\n \"\"\"Expand the connect index list [a,b] to [(0,a),(a,b),(b,end)]\n \"\"\"\n out_idx = []\n last_idx = 0\n for idx in connect_index:\n out_idx.append((last_idx, idx))\n last_idx = idx\n out_idx.append((last_idx, end_index))\n return out_idx\n\n\ndef adjust_bn_tracking(model, mode):\n for module in model.modules():\n if isinstance(module, nn.modules.batchnorm._BatchNorm):\n # module.track_running_stats = mode\n # --------------- change the track_running_stats will not work\n # track_running_stats is designed as intrinsic property of the layer\n # not a dynamic status variable\n if mode:\n module.momentum = 0.1\n else:\n module.momentum = 0\n\n\n@CLASSIFIERS.register_module\nclass HybridRandom(nn.Module):\n \"\"\"Base class for Classifiers\"\"\"\n\n def __init__(self, \n teacher_net, \n student_net,\n loss, \n teacher_connect_index,\n student_connect_index,\n teacher_pretrained, \n student_pretrained=None, \n teacher_channels=None,\n student_channels=None,\n teacher_backbone_init_cfg=None,\n student_backbone_init_cfg=None,\n ori_net_path_loss_alpha=0.5,\n switch_prob=0.5,\n save_only_student=False):\n \"\"\"teacher_channels, student_channels are the channels \n of the connecting node.\n \"\"\"\n super().__init__()\n self.fp16_enabled = False\n self.teacher_net = builder.build_backbone(teacher_net)\n self.student_net = builder.build_backbone(student_net)\n self.loss = builder.build_loss(loss)\n assert len(teacher_connect_index) == len(student_connect_index)\n self.teacher_connect_index = teacher_connect_index\n self.student_connect_index = student_connect_index\n self.ori_net_path_loss_alpha = ori_net_path_loss_alpha\n self.switch_prob = switch_prob\n self.save_only_student = save_only_student\n\n self.init_conn_channels(teacher_channels, student_channels)\n self.init_weights(self.teacher_net, teacher_pretrained, \n teacher_backbone_init_cfg)\n self.init_weights(self.student_net, student_pretrained, \n student_backbone_init_cfg)\n self.init_connect_module_list()\n for param in self.teacher_net.parameters():\n param.requires_grad = False\n\n @staticmethod\n def init_weights(net, pretrained, backbone_init_cfg):\n # even pretrained, still need init for eps\n if isinstance(backbone_init_cfg, str):\n initializer = getattr(mmcls.models.initializers, backbone_init_cfg)\n initializer(net.ori_net)\n if pretrained is not None:\n logger = get_root_logger()\n load_checkpoint(net.ori_net, pretrained, map_location='cpu',\n strict=False, logger=logger)\n logger.info('load model from: {}'.format(pretrained))\n\n @auto_fp16(apply_to=('img', ))\n def forward(self, img, labels, return_loss=True):\n if return_loss:\n return self.forward_train(img, labels)\n else:\n return self.forward_test(img, labels)\n\n def forward_train(self, imgs, labels):\n t_out_line = imgs\n s_out_line = imgs\n if self.ori_net_path_loss_alpha < 1:\n adjust_bn_tracking(self.student_net, False)\n for idx, (t, s) in enumerate(zip(self.t_idx, self.s_idx)):\n # swith feature map\n if np.random.random() > self.switch_prob:\n t_out_line, s_out_line = s_out_line, t_out_line\n if idx > 0 and not self.ignore_conn_mask[idx-1]:\n t_out_line = self.s2t_conv_list[idx-1](t_out_line)\n s_out_line = self.t2s_conv_list[idx-1](s_out_line)\n t_out_line = \\\n self.teacher_net.sequence_warp[t[0]:t[1]](t_out_line)\n s_out_line = \\\n self.student_net.sequence_warp[s[0]:s[1]](s_out_line)\n adjust_bn_tracking(self.student_net, True)\n else:\n t_out_line = None\n s_out_line = None\n s_out = self.student_net(imgs)\n losses = self.get_loss(t_out_line, s_out_line, s_out, labels)\n return losses\n\n def forward_test(self, imgs, labels):\n outputs = self.student_net(imgs)\n return outputs\n\n @force_fp32(apply_to=('t_out_line', 's_out_line', 's_out',))\n def get_loss(self, t_out_line, s_out_line, s_out, labels):\n losses = dict()\n if self.ori_net_path_loss_alpha < 1:\n losses['t_line_loss'] = \\\n self.loss(t_out_line, labels)*(1-self.ori_net_path_loss_alpha)\n losses['s_line_loss'] = \\\n self.loss(s_out_line, labels)*(1-self.ori_net_path_loss_alpha)\n losses['t_line_acc'] = accuracy(t_out_line, labels)[0]\n losses['s_line_acc'] = accuracy(s_out_line, labels)[0]\n # losses['s_loss'] = \\\n # self.loss(s_out, labels) * self.ori_net_path_loss_alpha\n losses['s_loss'] = self.loss(s_out, labels)\n losses['s_acc'] = accuracy(s_out, labels)[0]\n return losses\n\n def _parse_losses(self, losses):\n log_vars = OrderedDict()\n for loss_name, loss_value in losses.items():\n if isinstance(loss_value, torch.Tensor):\n log_vars[loss_name] = loss_value.mean()\n elif isinstance(loss_value, list):\n log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)\n elif isinstance(loss_value, dict):\n for name, value in loss_value.items():\n log_vars[name] = value\n else:\n raise TypeError(\n f'{loss_name} is not a tensor or list of tensors')\n\n loss = sum(_value for _key, _value in log_vars.items()\n if 'loss' in _key)\n\n log_vars['loss'] = loss\n for loss_name, loss_value in log_vars.items():\n # reduce loss when distributed training\n if dist.is_available() and dist.is_initialized():\n loss_value = loss_value.data.clone()\n dist.all_reduce(loss_value.div_(dist.get_world_size()))\n log_vars[loss_name] = loss_value.item()\n\n return loss, log_vars\n\n def train_step(self, data, optimizer):\n x = data[0][\"data\"]\n y = data[0][\"label\"].squeeze().cuda().long()\n losses = self(x, y)\n loss, log_vars = self._parse_losses(losses)\n\n outputs = dict(\n loss=loss, log_vars=log_vars, num_samples=int(x.shape[0]))\n\n return outputs\n\n def val_step(self, data, optimizer):\n x = data[0][\"data\"]\n y = data[0][\"label\"].squeeze().cuda().long()\n losses = self(x, y)\n loss, log_vars = self._parse_losses(losses)\n\n outputs = dict(\n loss=loss, log_vars=log_vars, num_samples=int(x.shape[0]))\n\n return outputs\n\n def get_model(self):\n if self.save_only_student:\n return self.student_net.state_dict()\n return self.state_dict()\n\n def init_conn_channels(self, teacher_channels, student_channels):\n def init_channel(channels, net, index):\n if channels is not None:\n return channels\n out = []\n for i in index:\n out.append(get_output_channels(net.sequence_warp[i-1]))\n return out\n self.teacher_channels = init_channel(teacher_channels, \n self.teacher_net, \n self.teacher_connect_index)\n self.student_channels = init_channel(student_channels, \n self.student_net, \n self.student_connect_index)\n\n def init_connect_module_list(self):\n self.ignore_conn_mask = []\n self.t2s_conv_list = nn.ModuleList()\n self.s2t_conv_list = nn.ModuleList()\n for tc, sc in zip(self.teacher_channels, self.student_channels):\n if tc == sc:\n self.ignore_conn_mask.append(True)\n continue\n self.ignore_conn_mask.append(False)\n self.t2s_conv_list.append(nn.Conv2d(tc, sc, 1))\n self.s2t_conv_list.append(nn.Conv2d(sc, tc, 1))\n self.t_idx = expand_connect_index(self.teacher_connect_index, \n len(self.teacher_net.sequence_warp))\n self.s_idx = expand_connect_index(self.student_connect_index,\n len(self.student_net.sequence_warp))\n","sub_path":"torch_submit/mmcls/models/classifiers/hybrid_random.py","file_name":"hybrid_random.py","file_ext":"py","file_size_in_byte":9683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"246433075","text":"# coding=utf-8\n\nimport html.parser\nimport re\nimport urllib.request\n\n\nclass TitleParser(html.parser.HTMLParser):\n def __init__(self):\n html.parser.HTMLParser.__init__(self)\n self.reading = False\n self.done = False\n self.title = ''\n\n def handle_starttag(self, tag, attrs):\n if tag == 'title':\n self.reading = True\n\n def handle_endtag(self, tag):\n if tag == 'title':\n self.reading = False\n self.done = True\n\n def handle_data(self, data):\n if self.reading:\n self.title += data\n\n def handle_charref(self, ref):\n if self.reading:\n self.handle_entityref('#' + ref)\n\n def handle_entityref(self, ref):\n if self.reading:\n self.title += '&%s;' % ref\n\n\ndef urlEncodeNonAscii(string):\n return re.sub('[\\x80-\\xFF]', lambda c: '%%%02x' % ord(c.group(0)), string)\n\n\n# returns a properly encoded url (escaped unicode etc)\n# or None if it's not a valid url\ndef get_encoded_url(url):\n # test if it's a valid URL and encode it properly, if it is\n parts = urllib.request.urlparse(url)\n if not ((parts[0] == 'http' or parts[0] == 'https') and parts[1] and parts[1] != 'localhost' and not\n parts[1].split('.')[-1].isdigit()):\n return None\n\n # handle unicode URLs\n url = urllib.request.urlunparse(\n p if i == 1 else urlEncodeNonAscii(p)\n for i, p in enumerate(parts)\n )\n return url\n\n\ndef get_url_title(url):\n enc = 'utf8'\n title = ''\n parser = TitleParser()\n try:\n resp = urllib.request.urlopen(url, timeout=5)\n\n # try the charset set in the html header first, if there is one\n if 'content-type' in resp.headers and 'charset=' in resp.headers['content-type']:\n enc = resp.headers['content-type'].split('charset=')[-1]\n\n # read up to 1mb\n chunk = resp.read(1024 * 1024)\n parser.feed(chunk.decode(enc))\n if parser.done:\n title = parser.title\n parser.close()\n except Exception as ex:\n return None\n else:\n if len(title) > 0:\n for e in enc:\n try:\n dec = title.decode(e)\n dec = parser.unescape(dec)\n return dec\n except Exception as ex:\n pass\n return title\n\n\n@yui.event('msgRecv')\ndef url(msg, channel):\n # find urls in channel message\n words = msg.split(' ')\n titles = []\n maxUrls = 5\n foundTitle = False\n for w in words:\n url = get_encoded_url(w)\n if not url:\n continue\n\n maxUrls -= 1\n if maxUrls == 0:\n break\n\n title = get_url_title(url)\n if title:\n title = ' '.join(title.split()) # remove leading/trailing spaces, reduce repeated spaces to just one\n titles.append('\"%s\"' % title)\n foundTitle = True\n else:\n titles.append('[no title]')\n\n # don't say anything, if we couldn't get any titles\n if foundTitle:\n concat = ', '.join(titles)\n yui.send_msg(channel, concat)\n","sub_path":"plugins/url.py","file_name":"url.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"92144335","text":"#\n# this module converts a floating point caffe model to the model conv.dat and fc.dat\n# conv.dat -- run on TEE comput stick.\n# fc.dat -- runs on host device\n# Note: the input model has to be trained as 1bit/3bits network.\n#\n# Run:\n# python convt_cnnsvic.py teeNet1.caffemodel teeNet1.prototxt teeNet1.json test.jpg ./output\n# Result is saved as conv.dat and fc.dat\n#\n\n# import modules:\nimport numpy as np\nimport sys\nimport struct\n\nimport os\nos.environ['GLOG_minloglevel'] = '2'\n\nimport caffe\nimport cv2\nimport argparse\nimport os\n\ndef NetworkSurgery(net_module, net_weights, net_config, output_model_file):\n print(\"Load caffe model:\")\n net = caffe.Net(net_module, net_weights, caffe.TEST)\n\n print(\"Parse JSON file\")\n # parse JSON file\n with open(net_config, 'r') as f:\n inlines = f.readlines()\n \n # find sublayer numbers and coef bits\n sublayer_bits = np.zeros(100, int) # upto 100 sublayers \n sub = '\"sublayer'\n coef = '\"coef'\n cnt_sub = 0\n for line in inlines:\n ln = line.split()\n if any(sub in string for string in ln):\n sub_char = line[line.index(':')+1:line.index(',')]\n sublayers = int(sub_char)\n if any(coef in string for string in ln):\n coef_char = line[line.index(':')+1:line.index('\\n')]\n for kk in range(sublayers):\n sublayer_bits[cnt_sub] = int(coef_char)\n cnt_sub += 1\n\n print('parsed layer bits:'+ str(sublayer_bits[0:cnt_sub]) )\n\n count = -1\n for layer in net.params.keys(): \n if (layer.find('conv') == 0 or layer.find('conv') == 1) and count < cnt_sub-1:\n count += 1\n coef = net.params[layer][0].data\n for output_channel in range(coef.shape[0]):\n for input_channel in range(coef.shape[1]): \n coef3x3 = coef[output_channel][input_channel][...]\n var = np.sum(abs(coef3x3))/9.0\n \n QFactor = 4.0/(var+0.0001)\n \n if sublayer_bits[count] == 3:\n for i in range(0,3):\n for j in range(0,3):\n abs_coefInt = int(abs(coef3x3[i,j]) * QFactor)\n if abs_coefInt > 2:\n abs_coefInt = 4\n abs_coef = abs_coefInt/QFactor;\n if coef3x3[i,j] >= 0:\n coef3x3[i,j] = abs_coef\n else:\n coef3x3[i,j] = -abs_coef\n else:\n coef3x3[coef3x3>=0] = var\n coef3x3[coef3x3<0] = -var\n\n net.save(output_model_file)\n\ndef outputNetworkWithoutBackbone(net_model, net_weights, output_fc_Coef):\n # create net\n caffe.set_mode_cpu()\n net = caffe.Net(net_model, net_weights, caffe.TEST)\n \n # create output file\n fpout = open(output_fc_Coef, 'wb')\n # write headers\n \n fclayers = []\n for layer in net._layer_names:\n if layer[:2] == 'fc':\n fclayers.append(layer)\n print('Layer list:'+ str(fclayers) )\n \n for fcname in fclayers:\n inlen = net.params[fcname][0].data.shape[1]\n outlen = net.params[fcname][1].data.shape[0]\n fpout.write(struct.pack(' 2:\n reference_image = reference_image[0]\n\n# alignment\nresults = aligner.calculate_alignments(orig_images, reference_image)\n\n# open tsv file and write header\noutput_tsv_file = open(output_tsv_filename, 'w', newline='')\naligner.output_header(output_tsv_file, input_filenames[0], reference_image_filename)\noutput_tsv_file.write('\\t'.join(results.columns) + '\\n')\n\n# output result and close\nresults.to_csv(output_tsv_file, columns = results.columns, \\\n sep='\\t', index = False, header = False, mode = 'a')\noutput_tsv_file.close()\nprint(\"Output alignment tsv file to %s.\" % (output_tsv_filename))\n\n# output image\nif output_image is True:\n images_uint8 = aligner.convert_to_uint8(orig_images)\n\n output_image_array = numpy.zeros(images_uint8.shape, dtype=numpy.uint8)\n\n for row, align in results.iterrows():\n plane = results.align_plane[row]\n if plane not in range(len(images_uint8)):\n print(\"Skip plane %d due to out-of-range.\" % (results.plane[row]))\n continue\n\n image = Image.fromarray(images_uint8[plane])\n image = image.rotate(0, translate=(int(-align.align_x), int(-align.align_y)))\n output_image_array[plane] = numpy.asarray(image, dtype=numpy.uint8)\n\n # output multipage tiff\n print(\"Output image file to %s.\" % (output_image_filename))\n tifffile.imwrite(output_image_filename, output_image_array)\n","sub_path":"taniakaze.py","file_name":"taniakaze.py","file_ext":"py","file_size_in_byte":5779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"598572571","text":"import functools\nimport os\nimport shutil\nfrom typing import (\n Any,\n Dict,\n List,\n)\n\nfrom galaxy import exceptions\nfrom galaxy.util.path import (\n safe_contains,\n safe_path,\n safe_walk,\n)\nfrom . import BaseFilesSource\n\nDEFAULT_ENFORCE_SYMLINK_SECURITY = True\nDEFAULT_DELETE_ON_REALIZE = False\nDEFAULT_ALLOW_SUBDIR_CREATION = True\n\n\nclass PosixFilesSource(BaseFilesSource):\n plugin_type = \"posix\"\n\n # If this were a PyFilesystem2FilesSource all that would be needed would be,\n # but we couldn't enforce security our way I suspect.\n # def _open_fs(self):\n # from fs.osfs import OSFS\n # handle = OSFS(**self._props)\n # return handle\n\n def __init__(self, **kwd):\n props = self._parse_common_config_opts(kwd)\n self.root = props[\"root\"]\n self.enforce_symlink_security = props.get(\"enforce_symlink_security\", DEFAULT_ENFORCE_SYMLINK_SECURITY)\n self.delete_on_realize = props.get(\"delete_on_realize\", DEFAULT_DELETE_ON_REALIZE)\n self.allow_subdir_creation = props.get(\"allow_subdir_creation\", DEFAULT_ALLOW_SUBDIR_CREATION)\n\n def _list(self, path=\"/\", recursive=True, user_context=None):\n dir_path = self._to_native_path(path, user_context=user_context)\n if not self._safe_directory(dir_path):\n raise exceptions.ObjectNotFound(f\"The specified directory does not exist [{dir_path}].\")\n if recursive:\n res: List[Dict[str, Any]] = []\n effective_root = self._effective_root(user_context)\n for p, dirs, files in safe_walk(dir_path, allowlist=self._allowlist):\n rel_dir = os.path.relpath(p, effective_root)\n to_dict = functools.partial(self._resource_info_to_dict, rel_dir, user_context=user_context)\n res.extend(map(to_dict, dirs))\n res.extend(map(to_dict, files))\n return res\n else:\n res = os.listdir(dir_path)\n to_dict = functools.partial(self._resource_info_to_dict, path, user_context=user_context)\n return list(map(to_dict, res))\n\n def _realize_to(self, source_path, native_path, user_context=None):\n effective_root = self._effective_root(user_context)\n source_native_path = self._to_native_path(source_path, user_context=user_context)\n if self.enforce_symlink_security:\n if not safe_contains(effective_root, source_native_path, allowlist=self._allowlist):\n raise Exception(\"Operation not allowed.\")\n else:\n source_native_path = os.path.normpath(source_native_path)\n assert source_native_path.startswith(os.path.normpath(effective_root))\n\n if not self.delete_on_realize:\n shutil.copyfile(source_native_path, native_path)\n else:\n shutil.move(source_native_path, native_path)\n\n def _write_from(self, target_path, native_path, user_context=None):\n effective_root = self._effective_root(user_context)\n target_native_path = self._to_native_path(target_path, user_context=user_context)\n if self.enforce_symlink_security:\n if not safe_contains(effective_root, target_native_path, allowlist=self._allowlist):\n raise Exception(\"Operation not allowed.\")\n else:\n target_native_path = os.path.normpath(target_native_path)\n assert target_native_path.startswith(os.path.normpath(effective_root))\n\n target_native_path_parent = os.path.dirname(target_native_path)\n if not os.path.exists(target_native_path_parent):\n if self.allow_subdir_creation:\n os.makedirs(target_native_path_parent)\n else:\n raise Exception(\"Parent directory does not exist.\")\n\n shutil.copyfile(native_path, target_native_path)\n\n def _to_native_path(self, source_path, user_context=None):\n source_path = os.path.normpath(source_path)\n if source_path.startswith(\"/\"):\n source_path = source_path[1:]\n return os.path.join(self._effective_root(user_context), source_path)\n\n def _effective_root(self, user_context=None):\n return self._evaluate_prop(self.root, user_context=user_context)\n\n def _resource_info_to_dict(self, dir, name, user_context=None):\n rel_path = os.path.normpath(os.path.join(dir, name))\n full_path = self._to_native_path(rel_path, user_context=user_context)\n uri = self.uri_from_path(rel_path)\n if os.path.isdir(full_path):\n return {\"class\": \"Directory\", \"name\": name, \"uri\": uri, \"path\": rel_path}\n else:\n statinfo = os.lstat(full_path)\n return {\n \"class\": \"File\",\n \"name\": name,\n \"size\": statinfo.st_size,\n \"ctime\": self.to_dict_time(statinfo.st_ctime),\n \"uri\": uri,\n \"path\": rel_path,\n }\n\n def _safe_directory(self, directory):\n if self.enforce_symlink_security:\n if not safe_path(directory, allowlist=self._allowlist):\n raise exceptions.ConfigDoesNotAllowException(\n f\"directory ({directory}) is a symlink to a location not on the allowlist\"\n )\n\n if not os.path.exists(directory):\n return False\n return True\n\n def _serialization_props(self, user_context=None):\n return {\n # abspath needed because will be used by external Python from\n # a job working directory\n \"root\": os.path.abspath(self._effective_root(user_context)),\n \"enforce_symlink_security\": self.enforce_symlink_security,\n \"delete_on_realize\": self.delete_on_realize,\n \"allow_subdir_creation\": self.allow_subdir_creation,\n }\n\n @property\n def _allowlist(self):\n return self._file_sources_config.symlink_allowlist\n\n\n__all__ = (\"PosixFilesSource\",)\n","sub_path":"lib/galaxy/files/sources/posix.py","file_name":"posix.py","file_ext":"py","file_size_in_byte":5912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"448537409","text":"def find_root(x, power, epsilon):\n \"\"\"x と epsilon > 0 は整数もしくは浮動小数点数, power>=1 を整数と仮定\n y**power が x の epsilon 以内になるような 浮動小数点数 y を返す\n もしそのような y が存在しなければ None を返す\"\"\"\n if x < 0 and power % 2 == 0:\n return None\n low = min(-1.0, x)\n high = max(1.0, x)\n ans = (high + low) / 2.0\n while abs(ans**power - x) >= epsilon:\n if ans**power < x:\n low = ans\n else:\n high = ans\n ans = (high + low) / 2.0\n return ans\n\ndef test_find_root():\n epsilon = 0.0001\n for x in (0.25, -0.25, 2, -2, 8, -8):\n for power in range(1, 4):\n print('Testing x = ', str(x), 'and power = ', power)\n result = find_root(x, power, epsilon)\n if result is None:\n print('No root')\n else:\n print(' ', result**power, '~=', x)\n","sub_path":"c4/find_root.py","file_name":"find_root.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"5063599","text":"# 문제\r\n# 어떤 양의 정수 X의 자리수가 등차수열을 이룬다면, 그 수를 한수라고 한다.\r\n# 등차수열은 연속된 두 개의 수의 차이가 일정한 수열을 말한다.\r\n# N이 주어졌을 때, 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력하는 프로그램을 작성하시오.\r\n\r\n# 입력\r\n# 첫째 줄에 1,000보다 작거나 같은 자연수 N이 주어진다.\r\n\r\n# 출력\r\n# 첫째 줄에 1보다 크거나 같고, N보다 작거나 같은 한수의 개수를 출력한다.\r\n\r\nN = int(input())\r\n\r\ndef findHansu(inNum):\r\n if inNum < 100 and inNum > 0:\r\n return inNum\r\n else:\r\n numList = []\r\n inNumStr = str(inNum)\r\n for i in range(0, len(inNumStr)):\r\n numList.append(inNumStr[i])\r\n for i in range(0, len(numList)):\r\n numList[i] = int(numList[i])\r\n if numList[0]-numList[1] == numList[1] - numList[2]:\r\n return inNum\r\n\r\ncount = 0\r\nfor i in range(N, 0, -1):\r\n if findHansu(i) != None:\r\n count += 1\r\n\r\nprint(count)","sub_path":"python/1065.py","file_name":"1065.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"294721514","text":"# -*- coding: utf-8 -*-\n# frozen_model.pbファイルを読み込む\n\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport os\nimport cv2\nimport random\nimport sys\nsys.path.append('/home/ubuntu/notebooks/github/SSD-Tensorflow/')\nfrom nets import ssd_vgg_300, np_methods\nfrom nets import nets_factory\n\nclass ObjectDetection():\n MODEL_DIR=\"/home/ubuntu/notebooks/github/RobotCarAI/level3_object_detection/model\"\n FROZEN_MODEL_NAME=\"ssd_roadsign.pb\"\n\n sess = None\n\n def __init__(self):\n tf.reset_default_graph()\n\n # TensorFlow session: grow memory when needed. TF, DO NOT USE ALL MY GPU MEMORY!!!\n gpu_options = tf.GPUOptions(allow_growth=True)\n #gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)\n config = tf.ConfigProto(log_device_placement=False, gpu_options=gpu_options)\n graph = self.load_graph(os.path.join(self.MODEL_DIR,self.FROZEN_MODEL_NAME))\n graph_def = graph.as_graph_def()\n\n # print operations\n self.print_graph_operations(graph)\n\n # print nodes\n #print_graph_nodes(graph_def)\n\n ####################\n self.input_x = graph.get_tensor_by_name('prefix/input_x:0')\n # 非常に粗いconv10_2とconv11_2を削ってもよい\n self.predictions= [graph.get_tensor_by_name('prefix/ssd_300_vgg/block4_cls_pred/softmax/Reshape_1:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block7_cls_pred/softmax/Reshape_1:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block8_cls_pred/softmax/Reshape_1:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block9_cls_pred/softmax/Reshape_1:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block10_cls_pred/softmax/Reshape_1:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block11_cls_pred/softmax/Reshape_1:0')]\n self.localisations= [graph.get_tensor_by_name('prefix/ssd_300_vgg/block4_box/loc_pred:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block7_box/loc_pred:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block8_box/loc_pred:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block9_box/loc_pred:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block10_box/loc_pred:0'),\n graph.get_tensor_by_name('prefix/ssd_300_vgg/block11_box/loc_pred:0')]\n self.bbox_img= graph.get_tensor_by_name('prefix/ssd_preprocessing_train/my_bbox_img/strided_slice:0')\n\n\n # SSD default anchor boxes.\n net_shape = (300, 300)\n ssd_class = nets_factory.get_network('ssd_300_vgg')\n ssd_params = ssd_class.default_params._replace(num_classes=5) \n ssd_net = ssd_vgg_300.SSDNet(ssd_params)\n self.ssd_anchors = ssd_net.anchors(net_shape)\n\n ########################################\n # ラベル\n ########################################\n self.VOC_LABELS = {\n 0: 'none',\n 1: 'stop',\n 2: 'speed_10',\n 3: 'speed_20',\n 4: 'speed_30',\n }\n self.colors = [(random.randint(0,255), random.randint(0,255), random.randint(0,255)) for i in range(len(self.VOC_LABELS))]\n\n self.sess = tf.Session(graph=graph,config=config)\n\n\n def __del__(self):\n if self.sess is not None:\n self.sess.close()\n return\n\n\n def print_graph_operations(self,graph):\n # print operations\n print(\"----- operations in graph -----\")\n for op in graph.get_operations():\n print(\"{} {}\".format(op.name,op.outputs))\n return\n\n\n def print_graph_nodes(self,graph_def):\n # print nodes\n print(\"----- nodes in graph_def -----\")\n for node in graph_def.node:\n print(node)\n return\n\n\n def load_graph(self,frozen_graph_filename):\n # We load the protobuf file from the disk and parse it to retrieve the\n # unserialized graph_def\n with tf.gfile.GFile(frozen_graph_filename, \"rb\") as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n # Then, we can use again a convenient built-in function to import a graph_def into the\n # current default Graph\n with tf.Graph().as_default() as graph:\n tf.import_graph_def(\n graph_def,\n input_map=None,\n return_elements=None,\n name=\"prefix\",\n op_dict=None,\n producer_op_list=None\n )\n return graph\n\n def write_bboxes(self, cv_bgr, classes, scores, bboxes):\n \"\"\"Visualize bounding boxes. Largely inspired by SSD-MXNET!\n \"\"\"\n height = cv_bgr.shape[0]\n width = cv_bgr.shape[1]\n for i in range(classes.shape[0]):\n cls_id = int(classes[i])\n if cls_id >= 0:\n score = scores[i]\n ymin = int(bboxes[i, 0] * height)\n xmin = int(bboxes[i, 1] * width)\n ymax = int(bboxes[i, 2] * height)\n xmax = int(bboxes[i, 3] * width)\n cv2.rectangle(cv_bgr, (xmin, ymin), (xmax, ymax),\n self.colors[cls_id],\n 2)\n class_name = self.VOC_LABELS[cls_id]\n cv2.rectangle(cv_bgr, (xmin, ymin-6), (xmin+180, ymin+6),\n self.colors[cls_id],\n -1)\n cv2.putText(cv_bgr, '{:s} | {:.3f}'.format(class_name, score),\n (xmin, ymin + 6),\n cv2.FONT_HERSHEY_PLAIN, 1,\n (255, 255, 255))\n return\n\n\n # Main image processing routine.\n def get_detection(self, cv_bgr, select_threshold=0.5, nms_threshold=.45, net_shape=(300, 300)):\n # 予測実行\n # Run SSD network.\n rpredictions, rlocalisations, rbbox_img = self.sess.run([self.predictions, self.localisations, self.bbox_img],\n feed_dict={self.input_x: cv_bgr})\n\n # Get classes and bboxes from the net outputs.\n rclasses, rscores, rbboxes = np_methods.ssd_bboxes_select(\n rpredictions, rlocalisations, self.ssd_anchors,\n select_threshold=select_threshold, img_shape=net_shape, num_classes=5, decode=True)\n\n rbboxes = np_methods.bboxes_clip(rbbox_img, rbboxes)\n rclasses, rscores, rbboxes = np_methods.bboxes_sort(rclasses, rscores, rbboxes, top_k=400)\n rclasses, rscores, rbboxes = np_methods.bboxes_nms(rclasses, rscores, rbboxes, nms_threshold=nms_threshold)\n # Resize bboxes to original image shape. Note: useless for Resize.WARP!\n rbboxes = np_methods.bboxes_resize(rbbox_img, rbboxes)\n\n return rclasses, rscores, rbboxes\n","sub_path":"site/10.level3_demo_streaming/pc_server/analyzelib/object_detection.py","file_name":"object_detection.py","file_ext":"py","file_size_in_byte":6941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"170066915","text":"def solution(s):\n if len(s) %2 ==0:\n mid =len(s)//2\n # answer = s[mid-1:mid+1]\n return s[mid-1:mid+1]\n else:\n mid=len(s)//2\n # answer=s[mid:mid+1]\n return s[mid:mid+1]\n\n# return str[(len(str)-1)//2:len(str)//2+1]\n","sub_path":"Level 1/가운데 글자 가져오기.py","file_name":"가운데 글자 가져오기.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"376605003","text":"\"\"\"\nSinglyLinkedList\nProjectFullStack\n20211002\n\"\"\"\n\nfrom node import Node\n\n\nclass SinglyLinkedList:\n \"\"\"\n SinglyLinkedList Class\n Methods:\n add(item) - O(1) - add item to beginning of the list\n search(item) - O(1) - search for the item in the list, return boolean\n index(item) - O(1) - search for the item in the list, return the index\n remove(item) - O(n) to find it, O(1) to remove\n - removes the FIRST item in the list\n is_empty() - O(1) - return true if list is empty, else false\n size() - O(n) - returns the number of nodes in the list\n append(item) - O(n) - appends the item to the end of the list\n insert(item, position) - O(n) - inserts the item at the given position\n pop(position) - O(n) - find and remove the node at position\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor for the SinglyLinkedList class\n \"\"\"\n self._head = None\n\n def __str__(self):\n \"\"\"\n String representation\n :return: example: \"[0,12,3,2]\"\n :rtype: str\n \"\"\"\n result = \"[\"\n current_node = self.head\n while current_node is not None:\n result += str(current_node.get_data())\n if current_node.get_next() is not None:\n result += \", \"\n current_node = current_node.get_next()\n result += \"]\"\n return result\n\n @property\n def head(self):\n \"\"\"\n Getter for the head property\n :return: the head of the list\n :rtype: Node or None\n \"\"\"\n return self._head\n\n @head.setter\n def head(self, node):\n \"\"\"\n Setter for the head property\n :param node: The node that will become the new head\n :type node: Node\n \"\"\"\n self._head = node\n\n def add(self, data):\n \"\"\"\n Adds a new data item to the head of the list\n :param data: the data to add\n :type data: Any\n \"\"\"\n new_node = Node(data)\n new_node.set_next(self.head)\n self.head = new_node\n\n def search(self, item):\n \"\"\"\n Searches for item in the list, returns true if it is found, else false\n :param item: the item to search for\n :type item: any\n :return: true if not found, else false\n :rtype: bool\n \"\"\"\n current_node = self.head\n while current_node is not None and current_node.get_data() != item:\n current_node = current_node.get_next()\n return current_node is not None\n\n def index(self, item):\n \"\"\"\n Searches for item in the list, returns the index it is found at,\n else -1\n :param item: the item to search for\n :type item: any\n :return: -1 if not found, else the index it is found at\n :rtype: int\n \"\"\"\n # fail fast\n if self.head is None:\n return -1\n\n current_node = self.head\n index = 0\n while current_node.get_data() != item:\n current_node = current_node.get_next()\n index += 1\n if current_node is None:\n return -1\n\n return index\n\n def remove(self, item):\n \"\"\"\n Removes the first instance of item from the list\n :param item: The item to search for to remove\n :type item: any\n \"\"\"\n current_node = self.head\n prev_node = None\n found = False\n\n while not found and current_node is not None:\n if current_node.get_data() == item:\n found = True\n else:\n prev_node = current_node\n current_node = current_node.get_next()\n\n if current_node is None:\n raise ValueError(f\"the item: {item}, is not in the list\")\n\n # if we get down here, the current_node is the node we want to remove\n if prev_node is None:\n # this happens if we are removing the head of the list\n self.head = current_node.get_next()\n current_node.set_next(None)\n else:\n prev_node.set_next(current_node.get_next())\n current_node.set_next(None)\n\n def is_empty(self):\n \"\"\"\n Returns true if list is empty, else false\n :return: true if list is empty, else false\n :rtype: bool\n \"\"\"\n return self.head is None\n\n def size(self):\n \"\"\"\n Returns the size of the linked list\n :return: the number of nodes in the linked list\n :rtype: int\n \"\"\"\n count = 0\n current_node = self.head\n while current_node is not None:\n count += 1\n current_node = current_node.get_next()\n return count\n\n def append(self, item):\n \"\"\"\n Appends a new node to the end of the linked list\n :param item: the item to add\n :type item: any\n \"\"\"\n new_node = Node(item)\n\n if self.head is None:\n self.head = new_node\n return\n\n current_node = self.head\n while current_node.get_next() is not None:\n current_node = current_node.get_next()\n # once I get here, I know current_node is going to be the last node\n current_node.set_next(new_node)\n\n def insert(self, item, index):\n \"\"\"\n Inserts a new node at the given index\n :param item: the item to add\n :type item: any\n :param index: the index to add the node at\n :type index: int\n \"\"\"\n current_node = self.head\n prev_node = None\n current_position = 0\n\n while current_node:\n if current_position == index:\n break\n prev_node = current_node\n current_node = current_node.get_next()\n current_position += 1\n\n if current_node is None:\n # this happens if the list is empty, or the index is out of bounds\n raise IndexError(f\"Index {index} is out of range\")\n\n # if we get here, the current_node will be the node that exists\n # at the index which we want to insert our new node at\n new_node = Node(item)\n if prev_node is None:\n # we are inserting at the head\n new_node.set_next(self.head)\n self.head = new_node\n else:\n # inserting somewhere else in the list\n prev_node.set_next(new_node)\n new_node.set_next(current_node)\n\n def pop(self, index):\n \"\"\"\n Pops a node from the list\n :param index: the index to pop\n :type index: int\n :return: the popped Node\n :rtype: Node\n \"\"\"\n current_node = self.head\n prev_node = None\n current_position = 0\n\n while current_node:\n if current_position == index:\n break\n prev_node = current_node\n current_node = current_node.get_next()\n current_position += 1\n\n if current_node is None:\n # this happens if the list is empty, or the index is out of bounds\n raise IndexError(f\"Index {index} is out of range\")\n\n # if we get here, the current node is the node we want to pop\n if self.head is current_node:\n # popping from the head\n self.head = current_node.get_next()\n else:\n prev_node.set_next(current_node.get_next())\n current_node.set_next(None)\n return current_node\n","sub_path":"linked_lists/python/singly_linked_list.py","file_name":"singly_linked_list.py","file_ext":"py","file_size_in_byte":7449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"155116287","text":"from sympy import *\n\n\ndef ip(f, g):\n x = symbols('x')\n return integrate(f * g, (x, 0, 1))\n\n\ndef norm(f):\n return sqrt(ip(f, f))\n\n\ndef main():\n x = symbols('x')\n f = x\n g = x ** 2\n print('a', ip(f, g))\n print('b', ip(g, f))\n print('c', ip(3 * f, g))\n print('d', ip(f, f))\n print('e', norm(f))\n print('f', ip(g, g))\n print('g', norm(g))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"singh/ch4_1_inner_product_spaces/x4_1_1.py","file_name":"x4_1_1.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"22010970","text":"import sql3Commands\nimport csv\n\ndef main():\n inputString = \"\"\n possibleKeywords = [\"Time On Ice\", \"Goals\", \"Assists\", \"Hits\", \"Saves\", \"Primary Position\", \"Shots\"]\n databaseKeywords = [\"time_on_ice\", \"goals\", \"assists\", \"hits\", \"saves\", \"primaryPosition\", \"shots\"]\n dataLoaded = False\n queryCounter = 0\n while inputString != \"Quit\":\n inputString = input(\"Enter query: \")\n\n # If user inputs \"Help\", then print out possible keywords\n if inputString == \"Help\":\n help()\n elif inputString == \"Quit\":\n break\n # If user inputs \"Load Data\", then load the data\n elif inputString == \"Load Data\":\n if(dataLoaded == True):\n print(\"Database previously loaded, overriding\")\n else:\n print(\"Loading Data\")\n dataLoaded = True\n loadData()\n\n else:\n # Ensure that the data is loaded before completing a query\n if dataLoaded == False:\n print(\"Data has not been loaded, please enter 'Load Data'\")\n else:\n\n # Split the string into each word\n inputList = inputString.split()\n\n # Determine where the word \"Player\" is in the input string\n playerIndex = -1\n for i in range(0, len(inputList)):\n if inputList[i] == \"Player\":\n playerIndex = i\n break\n\n # If playerIndex was not updated in loop above, then there was invalid syntax\n if playerIndex == -1:\n print(\"Invalid Syntax - no keyword 'Player'\")\n\n # If the word \"Player\" is exists, then handle the query\n else:\n # Determine the keyword\n keyword = \"\"\n for i in range(0, playerIndex):\n keyword += inputList[i] + \" \"\n\n keyword = keyword[0: len(keyword) - 1]\n\n # Handle database keyword queries\n invalidKeyword = True\n #for possibleKeyword in possibleKeywords:\n for i in range(len(possibleKeywords)):\n if keyword == possibleKeywords[i]:\n dbKeyword = databaseKeywords[i]\n invalidKeyword = False\n if (queryCounter == 0):\n # Open the connection\n conn = sql3Commands.sqlite3.connect('test.db')\n queryCounter += 1\n if len(inputList) == playerIndex + 3:\n firstName = inputList[playerIndex + 1]\n lastName = inputList[playerIndex + 2]\n queryDatabaseKeyword(dbKeyword, keyword, firstName, lastName, conn)\n else:\n print(\"Invalid Syntax - need player's full name\")\n\n # Handle List My Team keyword queries\n if keyword == \"List My Team\":\n invalidKeyword = False\n if(queryCounter == 0):\n #Open the connection\n conn = sql3Commands.sqlite3.connect('test.db')\n queryCounter += 1\n if len(inputList) == playerIndex + 3:\n firstName = inputList[playerIndex + 1]\n lastName = inputList[playerIndex + 2]\n queryDatabaseListMyTeam(firstName, lastName, conn)\n else:\n print(\"Invalid Syntax - need player's full name\")\n\n # Handle Teammates keyword queries\n if keyword == \"Teammates\":\n invalidKeyword = False\n if(queryCounter == 0):\n #Open the connection\n conn = sql3Commands.sqlite3.connect('test.db')\n queryCounter += 1\n\n if len(inputList) == playerIndex + 3:\n firstName = inputList[playerIndex + 1]\n lastName = inputList[playerIndex + 2]\n queryDatabaseTeammates(firstName, lastName, conn)\n else:\n print(\"Invalid Syntax - need player's full name\")\n\n\n # Handle if the keyword is invalid\n if invalidKeyword:\n print(\"Invalid Syntax - '\" + keyword + \"' is an invalid keyword\")\n\n\ndef help():\n print(\"Possible keywords:\")\n print(\" 'Time On Ice'\")\n print(\" 'Goals'\")\n print(\" 'Assists'\")\n print(\" 'Shots'\")\n print(\" 'Hits'\")\n print(\" 'Saves'\")\n print(\" 'Teammates'\")\n print(\" 'List My Team'\")\n print(\"\")\n print(\"Example query:\")\n print(\" 'Goals Player Zach Parise' -- This will retrieve the total number of goals scored by the player with the name Zach Parise\")\n print(\"\")\n print(\"Example query:\")\n print(\" 'List My Team Player Zach Parise' -- This will retrieve the team Zach Parise plays on\")\n print(\"\")\n print(\"Example query:\")\n print(\" 'Teammates Player Zach Parise' -- This will retrieve all the teammats of Zach Parise in the database\")\n print(\"\")\n print(\"Or enter 'Quit' to exit\")\n\n\n\ndef loadData():\n conn = sql3Commands.sqlite3.connect('test.db')\n cursor = conn.cursor()\n\n cursor.execute(\"DROP TABLE game_goalie_stats\")\n cursor.execute(\"DROP TABLE game_skater_stats\")\n cursor.execute(\"DROP TABLE player_info\")\n\n cursor.execute(\"CREATE TABLE player_info (player_id PRIMARY KEY, firstName, lastName, primaryPosition);\")\n cursor.execute(\n \"CREATE TABLE game_goalie_stats (player_id, team_id, time_on_ice, assists, goals, shots, saves, FOREIGN KEY(player_id) REFERENCES player_info(player_id));\")\n cursor.execute(\n \"CREATE TABLE game_skater_stats (player_id, team_id, time_on_ice, assists, goals, shots, hits, FOREIGN KEY(player_id) REFERENCES player_info(player_id));\")\n\n # iterate through csv file add intormation to dictionary then to column datastructure\n with open('game_goalie_stats.csv', newline='', encoding='utf-8') as goalie_stats_csv:\n goalie_stats_dict = csv.DictReader(goalie_stats_csv)\n goalie_stats_colm = [\n (i['player_id'], i['team_id'], i['time_on_ice'], i['assists'], i['goals'], i['shots'], i['saves']) for i in\n goalie_stats_dict]\n goalie_stats_csv.close()\n with open('GameSkaterStats.csv', newline='', encoding='utf-8-sig') as game_skater_csv:\n # print(game_skater_csv)\n game_skater_dict = csv.DictReader(game_skater_csv)\n skater_stats_colm = [\n (j['player_id'], j['team_id'], j['time_on_ice'], j['assists'], j['goals'], j['shots'], j['hits']) for j in\n game_skater_dict]\n game_skater_csv.close()\n with open('PlayerInfo1.csv', newline='', encoding='utf-8-sig') as player_info_csv:\n player_info_dict = csv.DictReader(player_info_csv)\n player_info_colm = [(i['player_id'], i['firstName'], i['lastName'], i['primaryPosition']) for i in\n player_info_dict]\n # Inserting data into the different tables\n cursor.executemany(\n \"INSERT INTO game_goalie_stats ( player_id, team_id, time_on_ice, assists, goals, shots, saves ) VALUES (?, ?, ?, ?, ?, ?, ?);\",\n goalie_stats_colm)\n cursor.executemany(\n \"INSERT INTO game_skater_stats ( player_id, team_id, time_on_ice, assists, goals, shots, hits ) VALUES (?, ?, ?, ?, ?, ?, ?);\",\n skater_stats_colm)\n cursor.executemany(\n \"INSERT INTO player_info ( player_id, firstName, lastName, primaryPosition ) VALUES (?, ?, ?, ?);\",\n player_info_colm)\n\n conn.commit()\n conn.close()\n\n\ndef queryDatabaseKeyword(dbKeyword, keyword, firstName, lastName, conn):\n value = sql3Commands.retrieveDataFirstLast(firstName, lastName, dbKeyword, conn)\n if (value == []):\n print(firstName + \" \" + lastName + \"'s \" + keyword + \" could not be found, please check the name and refer to Help\")\n else:\n print(keyword + \" = \" + str(value))\n\ndef queryDatabaseListMyTeam(firstName, lastName, conn):\n value = sql3Commands.queryDatabaseMyTeamName(firstName, lastName, conn)\n if (value == \"\"):\n print(firstName + \" \" +lastName + \"'s team could not be found, please check the name and refer to Help\")\n else:\n print(\"Team = \" + str(value))\n\n\ndef queryDatabaseTeammates(firstName, lastName, conn):\n value = sql3Commands.queryDatabaseListMyTeamMates(firstName, lastName, conn)\n if (value == []):\n print(\n firstName + \" \" + lastName + \"'s additional teammates could not be found, please check the name and refer to Help\")\n else:\n print(\"Teammates:\")\n for name in value:\n print(\" \" + name[0] + \" \" + name[1])\n\n\nmain()","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":9096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"472036301","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport json, os, shutil\n\nwith open('./mapping.json') as f:\n mapping = json.load(f)\n \nattributes = set()\nfor _, v in mapping.items():\n attributes.add(v['attribute'])\n \nprint(attributes)\n\n\nTDIR = os.path.abspath('../tree/')\nif not os.path.isdir(TDIR):\n os.mkdir(TDIR)\n\nfor d in ('output', 'log'):\n dir1 = os.path.join(TDIR, d)\n if not os.path.isdir(dir1):\n os.mkdir(dir1)\n for a in attributes:\n dir2 = os.path.join(dir1, a)\n if not os.path.isdir(dir2):\n os.mkdir(dir2)\n\n\nRDIR = os.path.abspath('../results/')\n\nfor _, v in mapping.items():\n attribute = v['attribute']\n job_id = v['job_id']\n graph_index = v['graph_index']\n \n logfile_src = os.path.join(RDIR, 'log_%d.txt'%job_id)\n outfile_src = os.path.join(RDIR, 'output_%d.txt'%job_id)\n assert(os.path.isfile(logfile_src))\n assert(os.path.isfile(outfile_src))\n \n logfile_dest = os.path.join(TDIR, 'log', attribute, 'log_%d.txt'%graph_index)\n outfile_dest = os.path.join(TDIR, 'output', attribute, 'output_%d.txt'%graph_index)\n \n shutil.copy2(logfile_src, logfile_dest)\n shutil.copy2(outfile_src, outfile_dest)\n\n","sub_path":"experiments/equality/scripts/create_tree.py","file_name":"create_tree.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"242308670","text":"import datetime as dt\nfrom functools import partial\nimport logging\nfrom math import isfinite\nimport os\nimport re\nfrom typing import Any, NamedTuple, Optional\nimport numpy as np\n\nimport jinja2\nimport requests\nfrom rich.progress import track\nfrom urllib.parse import urljoin\n\nfrom ..._version import get_versions\nfrom ...schema import (\n CompoundMicrostate,\n CompoundSeriesAnalysis,\n PointEstimate,\n CompoundAnalysis,\n)\nfrom ..constants import KT_KCALMOL, KT_PIC50\nfrom .molecules import generate_molecule_images, get_image_filename\n\n\ndef format_point(est: PointEstimate) -> str:\n \"\"\"\n Format a point estimate with appropriate precision given the\n associated uncertainty. If the point estimate is negative, wrap\n the result in a span tag with class `negative` for styling.\n \"\"\"\n prec = est.precision_decimals()\n if prec is None or not isfinite(est.point):\n return \"\"\n rounded = round(est.point, prec)\n if est.point >= 0:\n return f\"{rounded:.{prec}f}\"\n else:\n return f'−{abs(rounded):.{prec}f}'\n\n\ndef format_stderr(est: PointEstimate) -> str:\n \"\"\"\n Format an uncertainty with appropriate precision (one significant\n digit, by convention)\n \"\"\"\n prec = est.precision_decimals()\n if prec is None or not isfinite(est.point):\n return \"\"\n return f\"{round(est.stderr, prec):.{prec}f}\"\n\n\ndef format_pIC50(compound: CompoundAnalysis) -> str:\n \"\"\"\n Format the compound's experimental pIC50 if present, or TBD if not\n \"\"\"\n experimental_data = compound.metadata.experimental_data\n if \"pIC50\" in experimental_data:\n return experimental_data[\"pIC50\"]\n else:\n return \"TBD\"\n\n\ndef postera_url(compound_or_microstate_id: str) -> Optional[str]:\n \"\"\"\n If `compound_id` matches regex, link to Postera compound details\n \"\"\"\n import re\n\n match = re.match(\n \"^(?P[A-Z_]{3}-[A-Z_]{3}-[0-9a-f]{8}-[0-9]+)(_(?P[0-9]+))?([_0-9]*)$\",\n compound_or_microstate_id,\n )\n\n return (\n f\"https://postera.ai/covid/submissions/{match['compound_id']}\"\n if match\n else None\n )\n\n\ndef experimental_data_url(compound: CompoundAnalysis) -> Optional[str]:\n \"\"\"\n If `compound_id` contains experimental data, return the URL to Postera compound details\n \"\"\"\n experimental_data = compound.metadata.experimental_data\n if \"pIC50\" in experimental_data:\n return postera_url(compound.metadata.compound_id)\n else:\n return None\n\n\ndef format_compound_id(compound_id: str) -> str:\n \"\"\"\n Format a compound ID as a link if it is in PostEra format\n \"\"\"\n url = postera_url(compound_id)\n if url is None:\n return compound_id\n else:\n return f'{compound_id}'\n\n\nclass Progress(NamedTuple):\n completed: int\n total: int\n\n def percent_complete(self) -> float:\n return min(100.0, 100.0 * self.completed / self.total)\n\n\ndef _get_progress(\n project: int, api_url: str = \"http://aws3.foldingathome.org/api/\"\n) -> Optional[Progress]:\n \"\"\"\n Query a FAH work server for project status and return progress\n\n Parameters\n ----------\n project : int\n Project\n api_url : str, optional\n URL of the FAH work server API\n\n Returns\n -------\n Progress\n Number of completed and total work units\n \"\"\"\n url = urljoin(api_url, f\"projects/{project}\")\n try:\n response = requests.get(url=url).json()\n except Exception as exc:\n logging.warning(\"Failed to get progress from FAH work server: %s\", exc)\n return None\n\n completed_work_units = response[\"gens_completed\"]\n total_work_units = response[\"total_jobs\"]\n\n return Progress(completed=completed_work_units, total=total_work_units)\n\n\ndef get_sprint_number(description: str) -> Optional[int]:\n match = re.search(r\"Sprint (\\d+)\", description)\n return int(match[1]) if match else None\n\n\ndef _paginate(items, items_per_page):\n return (\n (\n (start + 1, min(len(items), start + items_per_page)),\n items[start : start + items_per_page],\n )\n for start in range(0, len(items), items_per_page)\n )\n\n\ndef _generate_paginated_index(\n write_html, url_prefix, items, items_per_page, description\n):\n pages = list(_paginate(items, items_per_page))\n\n def get_page_name(start_index, end_index):\n return (\n f\"{url_prefix}/index.html\"\n if start_index == 1\n else f\"{url_prefix}/index-{start_index}-{end_index}.html\"\n )\n\n for (prev_page, ((start_index, end_index), page_items), next_page) in track(\n zip(\n [None] + pages,\n pages,\n pages[1:] + [None],\n ),\n description=description,\n total=len(pages),\n ):\n write_html(\n page_items,\n template_file=f\"{url_prefix}/index.html\",\n output_file=get_page_name(start_index, end_index),\n start_index=start_index,\n end_index=end_index,\n prev_page=get_page_name(*prev_page[0]) if prev_page else None,\n next_page=get_page_name(*next_page[0]) if next_page else None,\n )\n\n\ndef generate_website(\n series: CompoundSeriesAnalysis,\n path: str,\n timestamp: dt.datetime,\n base_url: str,\n items_per_page: int = 100,\n num_top_compounds: int = 100,\n) -> None:\n\n generate_molecule_images(\n compounds=series.compounds,\n path=os.path.join(path, \"molecule_images\"),\n )\n\n template_path = os.path.join(os.path.dirname(__file__), \"templates\")\n template_loader = jinja2.FileSystemLoader(searchpath=template_path)\n environment = jinja2.Environment(loader=template_loader)\n environment.filters[\"format_point\"] = format_point\n environment.filters[\"format_stderr\"] = format_stderr\n environment.filters[\"format_compound_id\"] = format_compound_id\n environment.filters[\"format_pIC50\"] = format_pIC50\n environment.filters[\"postera_url\"] = postera_url\n environment.filters[\"experimental_data_url\"] = experimental_data_url\n environment.filters[\"smiles_to_filename\"] = get_image_filename\n\n for subdir in [\n \"compounds\",\n \"microstates\",\n \"transformations\",\n \"reliable_transformations\",\n \"retrospective_transformations\",\n ]:\n os.makedirs(os.path.join(path, subdir), exist_ok=True)\n\n def write_html(\n template_file: str, output_file: Optional[str] = None, **kwargs: Any\n ):\n\n if output_file is None:\n output_file = template_file\n\n environment.get_template(template_file).stream(\n base_url=base_url if base_url.endswith(\"/\") else f\"{base_url}/\",\n series=series,\n sprint_number=get_sprint_number(series.metadata.description),\n timestamp=timestamp,\n fah_xchem_version=get_versions()[\"version\"],\n KT_KCALMOL=KT_KCALMOL,\n KT_PIC50=KT_PIC50,\n microstate_detail={\n CompoundMicrostate(\n compound_id=compound.metadata.compound_id,\n microstate_id=microstate.microstate.microstate_id,\n ): (compound.metadata, microstate.microstate)\n for compound in series.compounds\n for microstate in compound.microstates\n },\n **kwargs,\n ).dump(os.path.join(path, output_file))\n\n write_html(\n \"index.html\",\n progress=_get_progress(series.metadata.fah_projects.complex_phase)\n or Progress(0, 1),\n num_top_compounds=num_top_compounds,\n )\n\n compounds_sorted = sorted(\n [compound for compound in series.compounds if compound.free_energy],\n key=lambda m: m.free_energy.point,\n )\n\n _generate_paginated_index(\n write_html=lambda items, **kwargs: write_html(\n compounds=items, num_top_compounds=num_top_compounds, **kwargs\n ),\n url_prefix=\"compounds\",\n items=compounds_sorted,\n items_per_page=items_per_page,\n description=\"Generating html for compounds index\",\n )\n\n for compound in track(\n compounds_sorted[:num_top_compounds],\n description=\"Generating html for individual compound views\",\n ):\n write_html(\n \"compounds/compound.html\",\n output_file=f\"compounds/{compound.metadata.compound_id}.html\",\n compound=compound,\n transformations=[\n transformation\n for transformation in series.transformations\n if transformation.transformation.initial_microstate.compound_id\n == compound.metadata.compound_id\n or transformation.transformation.final_microstate.compound_id\n == compound.metadata.compound_id\n ],\n )\n\n microstates_sorted = sorted(\n [\n microstate\n for compound in series.compounds\n for microstate in compound.microstates\n if microstate.free_energy\n ],\n key=lambda m: m.free_energy.point,\n )\n\n _generate_paginated_index(\n write_html=lambda items, **kwargs: write_html(\n microstates=items, total_microstates=len(microstates_sorted), **kwargs\n ),\n url_prefix=\"microstates\",\n items=microstates_sorted,\n items_per_page=items_per_page,\n description=\"Generating html for microstates index\",\n )\n\n _generate_paginated_index(\n write_html=lambda items, **kwargs: write_html(transformations=items, **kwargs),\n url_prefix=\"transformations\",\n items=series.transformations,\n items_per_page=items_per_page,\n description=\"Generating html for transformations index\",\n )\n\n _generate_paginated_index(\n write_html=lambda items, **kwargs: write_html(transformations=items, **kwargs),\n url_prefix=\"reliable_transformations\",\n items=series.transformations,\n items_per_page=items_per_page,\n description=\"Generating html for reliable transformations index\",\n )\n\n _generate_paginated_index(\n write_html=lambda items, **kwargs: write_html(transformations=items, **kwargs),\n url_prefix=\"retrospective_transformations\",\n items=sorted(\n [\n transformation\n for transformation in series.transformations\n if (transformation.absolute_error is not None)\n ],\n key=lambda transformation: -transformation.absolute_error.point,\n ),\n items_per_page=items_per_page,\n description=\"Generating html for retrospective transformations index\",\n )\n","sub_path":"fah_xchem/analysis/website/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"653631068","text":"#! /usr/bin/env python3\n\nimport socket\nimport math\nimport sys\nimport os\nimport multiprocessing\n\n\nclass SWEETClusterOptions:\n\n\n\tdef __init__(self, target_machine = ''):\n\t\tself.target_machine = target_machine\n\n\t\t# Total number of cores without hyperthreading\n\t\tself.total_max_cores = -1\n\n\t\t# Number of physical cores per node\n\t\tself.cores_per_node = -1\n\n\t\tself.setupTargetMachine(target_machine)\n\n\t\t#\n\t\t# Setup default values\n\t\t#\n\n\t\t# OpenMP threads in space\n\t\tself.par_space_cores = 1\n\n\t\t# Cores in time\n\t\tself.par_time_cores = 1\n\n\n\n\tdef setupTargetMachine(\n\t\tself,\n\t\ttarget_machine\n\t):\n\t\tself.target_machine = target_machine\n\n\t\tif self.target_machine == '':\n\t\t\t# Autodetect host with FQDN\n\t\t\t#hostname = socket.gethostname()\n\t\t\tfqdn = socket.getfqdn()\n\n\t\t\tself.target_machine = None\n\n\t\t\tif \".gw4.metoffice.gov.uk\" in fqdn:\n\t\t\t\tself.target_machine = \"isambard\"\n\n\t\t\telif \".yellowstone\" in fqdn:\n\t\t\t\tself.target_machine = \"yellowstone\"\n\n\t\t\telif \".cheyenne\" in fqdn:\n\t\t\t\tself.target_machine = \"cheyenne\"\n\n\t\t\telse:\n\t\t\t\tself.target_machine = socket.gethostname()\n\n\n\t\tif self.target_machine == 'isambard':\n\t\t\tself.total_max_cores = 4096\n\t\t\tself.total_max_modes = 512\n\t\t\tself.total_max_cores = self.cores_per_node*self.total_max_modes\n\t\t\traise Exception(\"TODO\")\n\n\t\telif self.target_machine == \"yellowstone\":\n\t\t\tself.cores_per_node = 16\n\t\t\tself.total_max_modes = 512\n\t\t\tself.total_max_cores = self.cores_per_node*self.total_max_modes\n\t\t\traise Exception(\"TODO\")\n\n\t\telif self.target_machine == \"cheyenne\":\n\t\t\tself.cores_per_node = 36\n\n\t\t\t# REAL number:\n\t\t\t# self.total_max_modes = 4032\n\n\t\t\t# Low number to avoid accidentally wasting computing time\n\t\t\tself.total_max_modes = 128\n\t\t\tself.total_max_cores = self.cores_per_node*self.total_max_modes\n\n\t\telse:\n\t\t\tprint(\"Unknown Target: \"+str(self.target_machine))\n\t\t\tprint(\"Using default values\")\n\n\t\t\tself.total_max_cores = multiprocessing.cpu_count()\n\t\t\tself.cores_per_node = self.total_max_cores\n\n\n\t\tself.total_max_nodes = self.total_max_cores//self.cores_per_node\n\n\t\tif self.total_max_nodes*self.cores_per_node != self.total_max_cores:\n\t\t\traise Exception(\"Inconsistency detected\")\n\n\n\n\tdef setup(\n\t\tpar_space_cores,\n\t\tpar_time_cores,\n\t):\n\t\tself.par_space_cores = par_space_cores\n\t\tself.par_time_cores = par_time_cores\n\n\n\n\tdef getUniqueID(self):\n\t\tretval = 'MPI'\n\t\tretval += '_space'+str(self.par_space_cores)\n\t\tretval += '_time'+str(self.par_time_cores)\n\n\t\treturn retval\n\n\n\n\t##################################################################\n\t# return header for job execution script and the parallel job execution command\n\t##################################################################\n\t#\n\t# \\return header, exec_prefix\n\t#\n\tdef getScriptHeader(self, jobid, runtimeOptions, dirname):\n\t\t#if self.par_mpi_time_threads != 1:\n\t\t#\tif self.max_cores_per_node % self.par_space_threads != 0:\n\t\t#\t\traise ValueError('Number of cores on node not evenly dividable by space threads')\n\n\t\treal_time_threads = self.par_time_cores\n\n\t\t# total number of used MPI ranks\n\t\ttotal_cores = self.par_space_cores*self.par_time_cores\n\t\tmpi_ranks_total = self.par_time_cores\n\t\tmpi_ranks_per_node = math.floor(self.cores_per_node/self.par_space_cores)\n\n\t\tcwd = os.getcwd()\n\n\t\tfor i in range(6):\n\t\t\tif i == 5:\n\t\t\t\traise Exception(\"Unable to find SWEET main directory\")\n\n\t\t\tsweetdir=os.path.normpath(os.getcwd()+(\"/..\"*i))\n\t\t\tif os.path.exists(sweetdir+'/local_software'):\n\t\t\t\tbreak\n\n\t\t#\n\t\t# SWEET specific allocation starts here\n\t\t#\n\t\t# Number of cores to use for space parallelization\n\t\t# self.par_space_cores\n\t\t#\n\t\t# Number of cores to use for time parallelization\n\t\t# self.par_time_cores\n\t\t#\n\n\t\t# SETUP variables which are shared by all job scripts\n\n\t\t# total number of nodes\n\t\ttotal_cores = self.par_space_cores*self.par_time_cores\n\n\t\t# total number of nodes\n\t\tnum_nodes = int(math.ceil(total_cores/self.cores_per_node))\n\n\t\t# number of cores (CPUs) per node\n\t\tnum_cores_per_node = self.cores_per_node\n\n\t\tif total_cores == 1:\n\t\t\tnum_cores_per_node = 1\n\n\t\t#\n\t\t# SETUP the following variables:\n\t\t#\n\t\t# content\n\t\t# e.g. \"/bin/bash\\n#PBS.....\"\n\t\t#\n\t\t# mpi_exec_prefix\n\t\t# e.g. mpirun -n XXX\n\t\t#\n\n\t\tif self.target_machine == 'yellowstone':\n\t\t\t#\n\t\t\t# YELLOWSTONE:\n\t\t\t# Each node has 16 cores\n\t\t\t# 8 cores per socket\n\t\t\t# hyperthreading enabled\n\t\t\t#\n\t\t\t# More example job scripts:\n\t\t\t# https://www2.cisl.ucar.edu/resources/computational-systems/yellowstone/using-computing-resources/running-jobs/platform-lsf-job-script-examples\n\t\t\t#\n\t\t\tcontent = \"#!/bin/bash\\n\"\n\t\t\tcontent += \"# TARGET MACHINE: \"+self.target_machine\n\n\t\t\tcontent += \"\"\"\n#\n# LSF batch script to run an MPI application\n#\n# YELLOW STONE SPECIFIC!!!\n# https://www2.cisl.ucar.edu/resources/computational-systems/yellowstone/\n#\n#BSUB -P NCIS0002\t# project code\n#BSUB -W 02:00\t\t# wall-clock time (hrs:mins)\n#\n#BSUB -n \"\"\"+str(mpi_ranks_total)+\"\"\"\t number of tasks in job\n#BSUB -R \"span[ptile=16]\" # run 16 MPI tasks per node\n#\n#BSUB -outdir \"\"\"+dirname+\"\"\"\n#BSUB -J \"\"\"+job_id+\"\"\"\t# job name\n#BSUB -o \"\"\"+dirname+\"\"\".out # output file name in which %J is replaced by the job ID\n#BSUB -e \"\"\"+dirname+\"\"\".out # error file name in which %J is replaced by the job ID\n#\n## https://www2.cisl.ucar.edu/resources/computational-systems/yellowstone/using-computing-resources/queues-and-charges\n#BSUB -q small\n#\n\n\"\"\"\n\t\t\traise Exception(\"TODO\")\n\t\t\t#\n\t\t\t# AND PAY ATTENTION TO NODE SHARING IF USING ONLY SINGLE CORE!!!!!!!!!!!\n\t\t\t#\n\t\t\tmpi_exec_prefix = \"\"\n\n\n\t\telif self.target_machine == 'cheyenne':\n\n\t\t\t#\n\t\t\t# CHEYENNE:\n\t\t\t# - Dual socket (18 cores / socket)\n\t\t\t# - 36 cores in total per node\n\t\t\t#\n\t\t\t# 9-D enhanced hypercube topology\n\t\t\t# 100-Gbps link bandwidth — 0.5 μs latency\n\t\t\t# 36 TB/s bisection bandwidth\n\t\t\t#\n\n\t\t\tcontent = \"#!/bin/bash\\n\"\n\t\t\tcontent += \"# TARGET MACHINE: \"+self.target_machine\n\t\t\tcontent += \"\"\"#\n## project code\n#PBS -A NCIS0002\n## regular limit: 12 hours\n## economy queue\n#PBS -q economy\n## shared queue\n######PBS -q share\n## wall-clock time (hrs:mins:secs)\n#PBS -l walltime=01:00:00\n## select one chunk with one CPU in it\n#PBS -l select=\"\"\"+str(num_nodes)+\"\"\":ncpus=\"\"\"+str(num_cores_per_node)+\"\"\":mpiprocs=\"\"\"+str(num_cores_per_node)+\"\"\"\n#\n#PBS -N \"\"\"+jobid[0:100]+\"\"\"\n#PBS -o \"\"\"+cwd+\"/\"+dirname+\"\"\"/output.out\n#PBS -e \"\"\"+cwd+\"/\"+dirname+\"\"\"/output.err\n\n\"\"\"\n\t\t\tmpi_exec_prefix = \"mpiexec_mpt \"\n\n\t\treturn content, mpi_exec_prefix\n\n\n","sub_path":"python_mods/SWEETClusterOptions.py","file_name":"SWEETClusterOptions.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"416488603","text":"import pydnameth as pdm\nfrom scripts.develop.routines import *\n\nf = open('cpgs.txt', 'r')\nitems = f.read().splitlines()\nx_ranges = [[5, 105]] * len(items)\ny_ranges = ['auto'] * len(items)\n\n\ndata = pdm.Data(\n path='',\n base='GSE87571'\n)\n\nannotations = pdm.Annotations(\n name='annotations',\n type='450k',\n exclude='bad_cpgs',\n select_dict={\n 'CHR': ['-X', '-Y']\n }\n)\n\nobservables = pdm.Observables(\n name='observables',\n types={}\n)\n\ncells = pdm.Cells(\n name='cells_horvath_calculator',\n types='any'\n)\n\nobservables_list = get_observables_list(data.base)\n\ndata_params = get_data_params(data.base)\n#data_params['observables'] = ['gender']\ndata_params['cells'] = ['CD8T', 'CD4T', 'NK', 'Bcell', 'Gran']\n\nattributes = pdm.Attributes(\n target='age',\n observables=observables,\n cells=cells\n)\n\npdm.betas_adj_plot_scatter(\n data=data,\n annotations=annotations,\n attributes=attributes,\n observables_list=observables_list,\n data_params=data_params,\n method_params={\n 'items': items,\n 'x_ranges': x_ranges,\n 'y_ranges': y_ranges,\n 'line': 'yes',\n 'fit': 'yes',\n 'semi_window': 8,\n 'box_b': 'Q5',\n 'box_t': 'Q95',\n 'legend_size': 2,\n 'add': 'none'\n }\n)","sub_path":"dna-methylation/scripts/develop/illumina450k/betas_adj/plot/scatter_from_txt.py","file_name":"scatter_from_txt.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"529996364","text":"import os\nimport sys\nimport pytest\nimport allure\nfrom allure_commons.types import AttachmentType\nfrom random import randint\nfrom selenium.webdriver import Chrome\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\")))\nprint(os.getcwd())\nfrom pages.Page import *\n\n\n@pytest.fixture(scope='session')\ndef driver():\n driver = Chrome(executable_path='../drivers/chromedriver.exe')\n driver.maximize_window()\n driver.implicitly_wait(20)\n driver.get('https://sleepy-brook-65250.herokuapp.com/')\n yield driver\n driver.close()\n\n\n@allure.story('Registration')\n@pytest.mark.parametrize('fname,lname,email,mobile,pwd,attachment',\n [('John', 'Sam', f'john{randint(1, 1000)}@xyz.com', '999999999', 'P@ssword',\n 'C:/Angappan/Automation/Practice/FoodToDoor/data/data.txt')])\ndef test_signup(driver, fname, lname, email, mobile, pwd, attachment):\n allure.dynamic.description('Validate Registration')\n home_page = HomePage(driver)\n home_page.click_register()\n register_page = RegisterPage(driver)\n register_page.fill_info(fname, lname, email, mobile, pwd, attachment)\n register_page.accept_terms()\n assert register_page.get_confirmation_msg() == 'You are registered please Login!!'\n","sub_path":"Tests/Test_FoodToDoor.py","file_name":"Test_FoodToDoor.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"141778924","text":"import math\n\n\n# WARM UP\n\n\ndef lesser_of_two_evens(a, b):\n return min(a, b) if a % 2 == 0 and b % 2 == 0 else max(a, b)\n\n\ndef animal_crackers(s):\n return str(s).split(' ')[0][0] == str(s).split(' ')[1][0]\n\n\ndef makes_twenty(n1, n2):\n return n1 == 20 or n2 == 20 or n1 + n2 == 20\n\n\n# LEVEL 1 Problems\n\n\ndef old_macdonald(name):\n result = \"\"\n for i, v in enumerate(name):\n result += str(name[i]).upper() if i == 3 or i == 0 else name[i]\n return result\n\n\ndef master_yoda(sentence):\n arr = str(sentence).split(' ')\n arr.reverse()\n return ' '.join(arr)\n\n\ndef almost_there(n):\n return abs(100 - n) <= 10 or abs(200 - n) <= 10\n\n\n# LEVEL 2 Problems\n\n\ndef has_33(nums):\n s = ''.join(str(x) for x in nums)\n return '33' in s\n\n\ndef proper_doll(text):\n result = \"\"\n for i in text:\n result += i * 3\n return result\n\n\ndef blackjack(*args):\n result = sum(args)\n if result <= 21:\n return result\n elif 11 in args and result > 21 >= result - 10:\n return result - 10\n else:\n return \"BUST\"\n\n\ndef summer_69(*args):\n found_six = False\n result = 0\n for i, v in enumerate(args):\n if args[i] == 6:\n found_six = True\n continue\n if found_six is True and args[i] <= 9:\n continue\n result += args[i]\n return result\n\n\n# CHALLENGING PROBLEMS\n\n\ndef spy_game(nums):\n code = [0, 0, 7, 'x']\n for num in nums:\n if num == code[0]:\n code.pop(0)\n return len(code) == 1\n\n\ndef count_primes(num):\n if num < 2:\n return 0\n\n count = 0\n\n for n in range(2, num + 1):\n prime = True\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n prime = False\n break\n if prime:\n count += 1\n return count\n\n\nprint(count_primes(12312311))\n","sub_path":"Udemy/sections_1-7/methods/problems/lesser_of_two_evens.py","file_name":"lesser_of_two_evens.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"226339578","text":"'''\n\nCode for calculating keys parallely on n-1 CPU cores, where n = Total CPU cores on the system.\n\n'''\nimport os,math,ntpath,socket,argparse\nfrom os.path import expanduser\nfrom pathlib import Path\nimport glob\nimport time\nimport pandas as pd\nfrom itertools import combinations\nfrom collections import Counter\nfrom joblib import Parallel, delayed, cpu_count\n\n__author__ = \"Venkata Sarika Kondra\"\n\n__version__ = \"1.0.1\"\n__maintainer__ = \"Venkata Sarika Kondra\"\n__email__ = \"c00219805@louisiana.edu\"\n\nparser = argparse.ArgumentParser(description='Parallel Key Generation.')\nparser.add_argument('--sample_name', '-sample', metavar='sample_name', default='t2', \\\n help='Name of the sample on which this script should be run.')\nparser.add_argument('--path', '-path', metavar='path', \\\n default=os.path.join(expanduser('~'),'Research', 'Protien_Database', \\\n 'extracted_new_samples', 'testing'), \\\n help='Directory of input sample and other files.')\nparser.add_argument('--thetaBounds', '-theta', metavar='thetaBounds', \\\n default = '0,12.11,17.32,21.53,25.21,28.54,31.64,34.55,37.34,40.03,42.64,45.17,47.64,50.05,52.43,54.77,57.08,59.38,61.64,63.87,66.09,68.30,70.5,72.69,79.2,81.36,83.51,85.67,87.8,90', \\\n #default='0 , 14.1, 20.31,25.49, 29.99, 34.1, 38, 41.7,45.3, 48.61, 51.91, 55.19, 58.29, 61.3, 64.39, 67.3, 70.3, 73.11, 81.69, 84.49, 87.29, 90 ', \\\n help='Bin Boundaries for Theta.')\nparser.add_argument('--distBounds', '-dist', metavar='distBounds', \\\n default = '3.83, 7.00, 9.00, 11.00, 14.00, 17.99, 21.25, 23.19, 24.8, 26.26,27.72, 28.9, 30.36, 31.62, 32.76, 33.84, 35.13, 36.26,37.62,38.73, 40.12,41.8, 43.41, 45.55, 47.46, 49.69, 52.65, 55.81, 60.2, 64.63, 70.04, 76.15,83.26, 132.45', \\\n #default='2.81, 7.00, 9.00, 11.00, 14.00, 17.4, 24.16, 30.19, 36.37, 44.78, 175.52', \\\n help='Bin Boundaries for maxDist.')\nparser.add_argument('--size_gap', '-size_gap', metavar='size_gap', \\\n default = 10000, \\\n help='Max Distance greater than this will be eliminated')\nparser.add_argument('--skip', '-skip', metavar='skip', default=False, \\\n help='To get only amino acids count make this True')\nparser.add_argument('--is_chain', '-is_chain', action='store_true', \\\n default=False, help='Pass this argument if there is chain information in the sample_details file.')\nparser.add_argument('--needDistribution', '-needDistribution', \\\n action='store_true', default=False, \\\n help='Enable this option if theta and distance distribution plots are required.')\nparser.add_argument('--needTriplets', '-needTriplets', \\\n action='store_true', default=False, \\\n help='Enable this option if triplet files are required.')\n\n#Changed according to Sarika's binning\ndef thetaClass_( binBoundaries, value, type):\n classL = -1\n for i in binBoundaries:\n if value < binBoundaries[0]:#Bins are seperately handled for theta and maxdist.\n if type == 0: #Thetas are not allowed to be less than zero.\n print(value,binBoundaries[0], 'out of index',binBoundaries ) \n else:\n classL = binBoundaries.index(binBoundaries[0])+1\n break\n if (value < i) :#If the value is less than the boundary it falls in previous bin.\n if type ==0: classL = binBoundaries.index(i) \n else: classL =binBoundaries.index(i) + 1\n break\n if value >= binBoundaries[-1]:\n if type ==0:\n if value == binBoundaries[-1]: classL = binBoundaries.index(binBoundaries[-1])\n else : classL = binBoundaries.index(binBoundaries[-1]) +2\n return classL\n\ndef calcDist(indexLabel1,indexLabel2):\n x1=xCord[indexLabel1]\n x2=xCord[indexLabel2]\n y1=yCord[indexLabel1]\n y2=yCord[indexLabel2]\n z1=zCord[indexLabel1]\n z2=zCord[indexLabel2]\n distance=(((x1-x2)**2+(y2-y1)**2+(z2-z1)**2)**0.5)\n return distance\n\ndef indexFind(index_of_2,i1,j1,k1):\n if index_of_2==i1:\n indexOf0=j1\n indexOf1=k1\n elif index_of_2==j1:\n indexOf0=i1\n indexOf1=k1\n elif index_of_2==k1:\n indexOf0=i1\n indexOf1=j1\n\n return indexOf0, indexOf1\n\ndef processFiles(filePath):\n fileName = ntpath.basename(filePath).split('.')[0].upper()\n print( fileName)\n start_time=time.time()\n if args.is_chain and (fileName not in protein_chain.keys()):\n print(\"{} not in sample_details file.\".format(fileName))\n error_string = \"not in sample_details\"\n if args.needDistribution:\n return (fileName + '({})'.format(error_string), 0, 0, 0, 0, 0, [], None, None)\n else:\n return (fileName + '({})'.format(error_string), 0, 0, 0, 0, 0, [])\n if os.path.exists(os.path.join(outFolder, \"{}.keys_theta{}_dist{}\".\\\n format(fileName, str(dTheta), str(dLen)))):\n print(\"{} already exists\".format(fileName))\n error_string = \"already exists\"\n if args.needDistribution:\n return (fileName+ '({})'.format(error_string), 0, 0, 0, 0, 0, [], None, None)\n else:\n return (fileName + '({})'.format(error_string), 0, 0, 0, 0, 0, [])\n #Read the chain name from details file if is_chain argument is passed\n if args.is_chain:\n chainName = None\n print( fileName, ':', chainName)\n\n filesDict={}\n thetaDict = {}\n lengthDict = {}\n inFile=open(filePath,'r')\n outFile2 = open(os.path.join(outFolder, \"{}.keys_theta{}_dist{}\".\\\n format(fileName, str(dTheta), str(dLen))), \"w\") \n\n if args.needTriplets: \n fileTriplets = open(os.path.join(outFolder,\"{}.triplets_theta{}_dist{}\". \\\n format(fileName, str(dTheta), str(dLen))), \"w\")\n\n allDistances = []\n\n global xCord, yCord, zCord\n aminoAcidName={}\n xCord={}\n yCord={}\n zCord={}\n seq_number={}\n counter=0\n aminoacidCount = []\n c = 0\n unknown_aas = set()\n for i in inFile:\n if (i[0:6].rstrip()==\"NUMMDL\"):\n numOfModels=i[10:14].rstrip()\n if not args.is_chain:\n if ((i[0:6].rstrip()==\"ENDMDL\") or (i[0:6].rstrip()=='TER')):\n break\n else:\n if (chainName != None) and (i[21] != chainName):\n break \n if (i[0:6].rstrip()==\"MODEL\" and int(i[10:14].rstrip())>1):\n break\n\n if args.is_chain:\n if((i[0:4].rstrip())==\"ATOM\" and (i[13:15].rstrip())==\"CA\" \\\n and (i[16]=='A'or i[16]==' ') and i[17:20]!= \"UNK\" \\\n and (i[21] == protein_chain[fileName])): \n\n aminoacidCount.append(i[17:20])\n if i[17:20] not in aminoAcidLabel.keys():\n print(i[17:20])\n unknown_aas.add(i[17:20])\n continue\n aminoAcidName[counter]=int(aminoAcidLabel[i[17:20]])\n xCord[counter]=(float(i[30:38]))\n yCord[counter]=(float(i[38:46]))\n zCord[counter]=(float(i[46:54]))\n seq_number[counter]=str(i[22:27])\n counter+=1\n chainName = i[21]\n else:\n if(i[0:4].rstrip())==\"ATOM\" and (i[13:15].rstrip())==\"CA\" \\\n and (i[16]=='A'or i[16]==' ') and i[17:20]!= \"UNK\" : \n aminoacidCount.append(i[17:20])\n if i[17:20] not in aminoAcidLabel.keys():\n unknown_aas.add(i[17:20])\n continue\n aminoAcidName[counter]=int(aminoAcidLabel[i[17:20]])\n xCord[counter]=(float(i[30:38]))\n yCord[counter]=(float(i[38:46]))\n zCord[counter]=(float(i[46:54]))\n seq_number[counter]=str(i[22:27])\n counter+=1\n #print(seq_number)\n protLen=len(yCord)\n #if (protLen < 200) or (protLen > 500):\n # return (fileName,protLen,0)\n if unknown_aas:\n print('Unknown amino acids found. Skipped {} protein.{}'.format(fileName, list(unknown_aas)))\n if args.needDistribution:\n return (fileName, 0, \\\n 0, 0, 0, 0, \";\".join(list(unknown_aas)),{}, {})\n else:\n return (fileName, protLen, \\\n 0, 0, 0, 0, \";\".join(list(unknown_aas)))\n if not args.skip:\n initialLabel=[]\n sortedLabel=[]\n sortedIndex=[]\n outDist={}\n for m in range(0,3):\n initialLabel.append(0)\n sortedLabel.append(0)\n sortedIndex.append(0)\n lst_combs = list(combinations(range(0,protLen),3))\n # for i in range(0,protLen-2):\n # for j in range(i+1,protLen-1):\n # for k in range(j+1, protLen):\n for i,j,k in lst_combs:\n global i1,j1,k1\n #print(i,j,k)\n i1 = i\n j1 = j\n k1 = k\n keepLabelIndex={}\n keepLabelIndex[aminoAcidName[i]] = i\n keepLabelIndex[aminoAcidName[j]] = j\n keepLabelIndex[aminoAcidName[k]] = k\n initialLabel[0] = aminoAcidName[i]\n initialLabel[1] = aminoAcidName[j]\n initialLabel[2] = aminoAcidName[k]\n sortedLabel = list(initialLabel)\n sortedLabel.sort(reverse=True)\n if (sortedLabel[0] == sortedLabel[1]) and \\\n (sortedLabel[1] == sortedLabel[2]):\n dist1_2Temp = calcDist(i,j)\n dist1_3Temp = calcDist(i,k)\n dist2_3Temp = calcDist(j,k)\n if dist1_2Temp>=(max(dist1_2Temp,dist1_3Temp,dist2_3Temp)):\n indexOf0 = i\n indexOf1 = j\n indexOf2 = k\n elif dist1_3Temp>=(max(dist1_2Temp,dist1_3Temp,dist2_3Temp)):\n indexOf0 = i\n indexOf1 = k\n indexOf2 = j\n else:\n indexOf0 = j\n indexOf1 = k\n indexOf2 = i\n elif(aminoAcidName[i] != aminoAcidName[j]) and \\\n (aminoAcidName[i] != aminoAcidName[k]) and \\\n (aminoAcidName[j] != aminoAcidName[k]):\n for index_ in range(0,3):\n sortedIndex[index_] = keepLabelIndex[sortedLabel[index_]]\n indexOf0 = sortedIndex[0]\n indexOf1 = sortedIndex[1]\n indexOf2 = sortedIndex[2]\n\n elif(sortedLabel[0] == sortedLabel[1]) and \\\n (sortedLabel[1] != sortedLabel[2]):\n indexOf2 = keepLabelIndex[sortedLabel[2]]\n indices = indexFind(indexOf2,i,j,k)\n a = indexOf2\n b = indices[0]\n c = indices[1]\n dist1_3Temp = calcDist(b,a)\n dist2_3Temp = calcDist(c,a)\n if dist1_3Temp >= dist2_3Temp:\n indexOf0 = indices[0]\n indexOf1 = indices[1] \n else:\n indexOf0 = indices[1]\n indexOf1 = indices[0]\n\n elif(sortedLabel[0] != sortedLabel[1]) and (sortedLabel[1] == sortedLabel[2]):\n indexOf0 = keepLabelIndex[sortedLabel[0]]\n indices =indexFind(indexOf0,i,j,k)\n if calcDist(indexOf0,indices[0])>= calcDist(indexOf0,indices[1]):\n indexOf1=indices[0]\n indexOf2=indices[1] \n else:\n indexOf2=indices[0]\n indexOf1=indices[1]\n dist01=calcDist(indexOf0,indexOf1)\n s2=dist01/2\n dist02=calcDist(indexOf0,indexOf2)\n s1=dist02\n dist12=dist01\n dist03=calcDist(indexOf1,indexOf2)\n maxDist=max(dist01,dist02,dist03)\n allDistances.append(maxDist)\n if maxDist < int(args.size_gap):\n\n s3 = (((xCord[indexOf0] + xCord[indexOf1])/2 - xCord[indexOf2])**2 + \\\n ((yCord[indexOf0] + yCord[indexOf1])/2 - yCord[indexOf2])**2 + \\\n ((zCord[indexOf0] + zCord[indexOf1])/2 - zCord[indexOf2])**2)**0.5\n Theta1 = 180*(math.acos((s1**2-s2**2-s3**2)/(2*s2*s3)))/3.14\n if Theta1 <= 90:\n Theta = Theta1\n else:\n Theta=abs(180-Theta1)\n if args.needDistribution:\n try:\n thetaDict[round(Theta,0)] += 1\n except:\n thetaDict[round(Theta,0)] = 1\n\n try:\n lengthDict[round(maxDist,1)] += 1\n except:\n lengthDict[round(maxDist,1)] = 1\n\n classT1=thetaClass_(thetaBounds,Theta,0)\n classL1=thetaClass_(distBounds, maxDist,1)\n\n ##getting the positions of AminoAcids in sequence\n position0 = str(list(seq_number.values())[indexOf0])\n position1 = str(list(seq_number.values())[indexOf1])\n position2 = str(list(seq_number.values())[indexOf2])\n\n aacd0 = list(aminoAcidLabel.keys())[list(aminoAcidLabel.values()).index(aminoAcidName[indexOf0])]\n aacd1 = list(aminoAcidLabel.keys())[list(aminoAcidLabel.values()).index(aminoAcidName[indexOf1])]\n aacd2 = list(aminoAcidLabel.keys())[list(aminoAcidLabel.values()).index(aminoAcidName[indexOf2])]\n #print(aminoAcidLabel.keys())\n\n x0 = str(xCord.get(indexOf0))\n y0 = str(yCord.get(indexOf0))\n z0 = str(zCord.get(indexOf0))\n\n x1 = str(xCord.get(indexOf1))\n y1 = str(yCord.get(indexOf1))\n z1 = str(zCord.get(indexOf1))\n\n x2 = str(xCord.get(indexOf2))\n y2 = str(yCord.get(indexOf2))\n z2 = str(zCord.get(indexOf2))\n\n\n key_2 = dLen*dTheta*(numOfLabels**2)*(aminoAcidName[indexOf0]-1) + \\\n dLen*dTheta*(numOfLabels)*(aminoAcidName[indexOf1]-1) + \\\n dLen*dTheta*(aminoAcidName[indexOf2]-1) + dTheta*(classL1-1) + (classT1-1) \n\n if maxDist >53.1004999882:\n c = c+1 \n if key_2 in filesDict:\n filesDict[key_2] += 1\n else:\n filesDict[key_2] = 1\n\n if args.needTriplets: \n line = (str(key_2) +\"\\t\" + str(aacd0) + \"\\t\" + str(position0) + \"\\t\" + \\\n str(aacd1) + \"\\t\" + str(position1) + \"\\t\" + str(aacd2) + \"\\t\" + \\\n str(position2) + \"\\t\" + str(classT1) + \"\\t\" + str(Theta) + \"\\t\" +\\\n str(classL1) + \"\\t\" + str(maxDist) + \"\\t\" + x0 + \"\\t\" + y0 + \"\\t\" + \\\n z0 + \"\\t\" + x1 + \"\\t\" + y1 + \"\\t\" + z1 + \"\\t\" + x2 + \"\\t\" + y2 + \"\\t\" + z2 + \"\\n\")\n fileTriplets.writelines(line)\n\n for value_ in filesDict:\n outFile2.writelines([str(value_),'\\t', str(filesDict[value_]),'\\n'])\n outFile2.close()\n\n if args.needTriplets:\n fileTriplets.close()\n end_time=time.time()\n total_time=((end_time)-(start_time))\n print(\"FILENAME=\",fileName,\"NUM OF AMINOACIDS=\",protLen)\n print(\"{} took : {} mins.\".format(fileName, total_time/60))\n print('c: ', c)\n if args.needDistribution:\n return (fileName, \\\n protLen, \\\n len(filesDict), \\\n sum(list(filesDict.values())), \\\n max(allDistances) if len(allDistances) > 0 else 0, \\\n min(allDistances) if len(allDistances) > 0 else 0, \\\n list(unknown_aas),\n thetaDict, \\\n lengthDict )\n else:\n return (fileName, \\\n protLen, \\\n len(filesDict), \\\n sum(list(filesDict.values())), \\\n max(allDistances) if len(allDistances) > 0 else 0, \\\n min(allDistances) if len(allDistances) > 0 else 0,\n list(unknown_aas))\n\nif __name__ == '__main__':\n \"\"\"Executable code starts here.\"\"\"\n start_time = time.time()\n args = parser.parse_args()\n thetaBounds = list(map(float, args.thetaBounds.split(',')))\n dTheta = len(thetaBounds) - 1\n distBounds = list(map(float, args.distBounds.split(',')))\n dLen = len(distBounds) + 1\n numOfLabels = 20\n\n print(\"Working on theta: [{}], dist: [{}] \\nSize Gap: [{}] \\nPrinting Distribution Files?: [{}] \\nUsing Chain Information?: [{}]\"\\\n .format(str(dTheta), str(dLen), str(args.size_gap), str(args.needDistribution), str(args.is_chain)))\n\n aminoAcidCode=open(os.path.join(args.path, \"aminoAcidCode_map.txt\"),\"r\") \n aminoAcidLabel={}\n for amino in aminoAcidCode:\n amino = amino.split()\n aminoAcidLabel[amino[0]] = int(amino[1])\n aminoAcidCode.close()\n\n if args.is_chain:\n df = pd.read_csv(os.path.join(args.path, args.sample_name, \"sample_details.csv\"))\n df.rename(columns={'PDB ID':'protein', 'Chain ID': 'chain'}, inplace=True)\n df['protein'] = df['protein'].str.upper()\n df['chain'] = df['chain'].str.upper()\n protein_chain = dict(zip(df.protein, df.chain))\n\n outFolder = os.path.join(args.path, args.sample_name, \"theta{}_dist{}\".format(str(dTheta), str(dLen)))\n #Create output directory\n if not os.path.exists(outFolder):\n os.makedirs(outFolder) \n\n fileType = \"*.pdb\" #\"*.ent\"# \n files=glob.glob(os.path.join(args.path, args.sample_name, fileType)) \n result = Parallel(n_jobs=cpu_count() - 1, verbose=10, backend=\"multiprocessing\", batch_size=\"auto\")\\\n (delayed(processFiles)(fileName) for fileName in files)\n #It gets enabled if you need to see the Theta and Distance Distribution\n if args.needDistribution:\n d_theta = {}\n d_dist = {}\n req_result = []\n for row in result:\n d_theta = Counter(d_theta) + Counter(row[6])\n d_dist = Counter(d_dist) + Counter(row[7])\n req_result.append((row[0], row[1], row[2], row[3], row[4], row[5]))\n pd.DataFrame(d_theta.items(),columns = ['theta','freq']).sort_values('theta').to_csv('{}//theta_distribution.csv'.\\\n format(outFolder))\n pd.DataFrame(d_dist.items(),columns = ['length','freq']).sort_values('length').to_csv('{}//length_distribution.csv'.\\\n format(outFolder))\n result = req_result\n \n df2 = pd.DataFrame(result,columns = ['protein','aa_count','#keys', '#keys with freq', 'max_distance', 'min_distance', 'unknown_aas'])\n df2.to_csv(os.path.join(args.path, args.sample_name, 'sample_details2.csv'))\n print(\" {} proteins are exempted from Key Calculation: \".format(len(df2[df2['#keys'] == 0])))\n print(df2[df2['#keys'] == 0])\n\n print(\"Parallel Key Generation completed in {} mins.\".format((time.time() - start_time)/60))\n \n","sub_path":"code/Classification/lib/key_generation_parallel.py","file_name":"key_generation_parallel.py","file_ext":"py","file_size_in_byte":21028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"520726586","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-12-02 22:10:49\n# @Author : Zhang Yahan (zyahan1997@163.com)\n# @Link : http://www.github.com/zhangyahan/\n# @Version : $Id$\n\nfrom flask import (Flask,\n\t\t\t\t render_template,\n\t\t request,\n\t\t redirect,\n\t\t session,\n\t\t url_for,\n\t\t jsonify,\n\t\t Markup,\n\t\t flash,\n\t\t get_flashed_messages)\nimport functools\n\napp = Flask(__name__)\n# 导入配置文件\napp.config.from_object('settings.Dev')\n\nSTUDENT_DICT = {\n\t1:{'name': '王花花', 'age': 21, 'gender': '女'},\n\t2:{'name': '李狗蛋', 'age': 18, 'gender': '男'},\n\t3:{'name': '王铁花', 'age': 38, 'gender': '女'},\n}\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n\n\tif request.method == \"GET\":\n\t\treturn render_template('login.html')\n\tusername = request.form.get('username', '')\n\tpassword = request.form.get('password', '')\n\tif username == 'zyh' and password == '123456':\n\t\tsession['username'] = username\n\t\treturn redirect(url_for('index'))\n\treturn render_template('login.html', error_message='用户名或密码错误')\n\n# @app.before_request\n# def xxxxxx():\n# \tif request.path == '/login':\n# \t\treturn None\n# \tif not session.get('username', ''):\n# \t\treturn '滚'\n\n\n@app.route('/')\n@app.route('/index', endpoint='index')\ndef index():\n\tstud = STUDENT_DICT\n\treturn render_template('index.html', stud=stud)\n\n\n@app.route('/delinfo/')\ndef delinfo(nid):\n\tif nid in STUDENT_DICT:\n\t\tdel STUDENT_DICT[nid]\n\n\treturn redirect(url_for('index'))\n\n\n@app.route('/catinfo/')\ndef catinfo(nid):\n\tinfo = STUDENT_DICT[nid]\n\treturn render_template('info.html', info=info)\n\n@app.template_global()\ndef func(num):\n\treturn num + 1\n\n@app.template_filter()\ndef func_params(a, b, c):\n\treturn a + b + c\n\n@app.route('/tpl')\ndef tpl():\n\tcontext = {\n\t\t'users': ['王花花', '李狗蛋', '赵铁柱'],\n\t\t'txt': Markup(''),\n\t}\n\tprint()\n\treturn render_template('tpl.html', **context)\n\n\n@app.route('/page1')\ndef page1():\n\t# session['uuu'] = 123\n\tflash('临时数据存储')\n\treturn '1'\n\n\n@app.route('/page2')\ndef page2():\n\t# print(session['uuu'])\n\tprint(get_flashed_messages())\n\treturn '2'\n\nif __name__ == '__main__':\n\tapp.run()\n","sub_path":"Flask/02/app01.py","file_name":"app01.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"634475651","text":"\"\"\"\nTrains MFS models.\n\"\"\"\nimport argparse\nimport os\n\n\ndef main():\n \"\"\"\n Main function.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('-prefix', default=\"\", help=\"prefix for all datasets we wish to train on\")\n parser.add_argument('-ns', required=True, type=int, help=\"max num. samples of expansions to take per abbreviation\")\n\n opt = parser.parse_args()\n\n # look for all pickle files\n for file in os.listdir(\".\"):\n if file.endswith(\".pickle\") and file.startswith(opt.prefix):\n # build command\n command = \"python train_mfs.py\"\n command += \" -dataset=%s\" % file\n command += \" -ns=%s\" % opt.ns\n print(command)\n os.system(command)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"baselines/train_mfs_models.py","file_name":"train_mfs_models.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"576588980","text":"def count_words(s):\n s = s.split()\n end_with = 0\n in_word = 0\n for i in s:\n if(i[-1:] == '.' or i[-1:] == ','):\n i = i[:-1]\n if(i[-2:] == 'on'):\n end_with+=1\n i = i[1:-1]\n if 'on' in i:\n in_word+=1\n return([end_with,in_word])\nmy_string = \"Strings are amongst the most popular data types in Python. We can create the strings by enclosing characters in quotes. Python treats single quotes the same as double quotes.\"\ncnt = my_string.lower().count('string')\nprint(\"Number of Occurences of 'string':\",cnt)\nx = count_words(my_string)\nprint(\"Words ending with 'on':\",x[0])\nprint(\"Words with 'on' in between first and last letters:\",x[1])\n\n# OUTPUT \n# Number of Occurences of 'string': 2\n# Words ending with 'on': 2\n# Words with 'on' in between first and last letters: 1\n\n","sub_path":"assignment47.py","file_name":"assignment47.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"85129728","text":"#!/usr/bin/env python3\n# encoding: utf-8\n# MA510 HW1 Problem 4, additional test\n# Calculate the harmonic series separately\n# by increasing and decreasing series\n# and compare the results with the accurate value\n# by calculating the fractions\n# Author: Yupu(Ethan) Song\n# Date: Sep 5, 2016\n\nfrom fractions import Fraction\n\nfor j in range(0,41):\n inc_acc = 0\n dec_acc = 0\n if j == 0:\n xrange = range(1,101) #[1,100]\n else:\n xrange = range(j*100+1,(j+1)*100 + 1)\n for i in xrange:\n series_inc = list(range(1,i+1))\n series_dec = list(range(i,0,-1))\n inc_sum = float(sum([(1/x) for x in series_inc]))\n #S1\n dec_sum = float(sum([(1/x) for x in series_dec]))\n #S2\n S_inc = sum(Fraction(1,x) for x in series_inc)\n S_dec = sum(Fraction(1,x) for x in series_dec)\n #S_inc and S_dec, standing for the exact value\n #They are exactly the same, checked by the following\n if S_inc != S_dec:\n print(\"Oops!Unexpected...\")\n break\n if abs(inc_sum - S_inc) < abs(dec_sum - S_dec):\n inc_acc += 1\n elif abs(inc_sum - S_inc) > abs(dec_sum - S_dec):\n dec_acc += 1\n if j == 0:\n print(\"range = [1, 100]\")\n else:\n print(\"range = [\", j*100+1,\",\", (j+1)*100,\"]\")\n print(\"Accuracy distribution:(incrasing series wins, decreasing wins)\", inc_acc, dec_acc)\n\n\n\n#series_inc = list(range(1,5001))\n#series_dec = list(range(5000,0,-1))\n#inc_sum = sum([(1/x) for x in series_inc])\n#S1\n#dec_sum = sum([(1/x) for x in series_dec])\n#S2\n#S_inc = sum(Fraction(1,x) for x in series_inc)\n#S_dec = sum(Fraction(1,x) for x in series_dec)\n#S_inc and S_dec, standing for the exact value\n#They are exactly the same\n#print(\"S1 = \",inc_sum, \"S2 = \",dec_sum)\n#print(\"|S1 - S2| = \", abs(inc_sum - dec_sum))\n#print(\"Calculation by fraction,\\nS_inc == S_dec is \", S_inc == S_dec)\n#print(\"|S1 - S_inc| =\", abs(inc_sum - S_inc))\n#print(\"|S2 - S_dec| =\", abs(dec_sum - S_dec))\n","sub_path":"hw1/harmonicSeries_Test.py","file_name":"harmonicSeries_Test.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"548740500","text":"\"\"\"\nУтилита для конвертации выписки Сбербанка по карте из формата PDF в формат Excel.\n\"\"\"\n\nNAME='Утилита для конвертации выписки Сбербанка по карте из формата PDF в формат Excel'\nAUTHOR='ev2geny@gmail.com'\nPERMANENT_LOCATION='https://github.com/Ev2geny/Sberbank2Excel/releases/latest'\nVERSION='3.0.0'\n\n# sources used:\n# https://likegeeks.com/python-gui-examples-tkinter-tutorial/\n\n\nfrom tkinter import *\nimport tkinter.filedialog\nfrom tkinter import scrolledtext\nfrom tkinter import Menu\nfrom tkinter import messagebox\nimport traceback\nimport logging\n\nfrom core.sberbankPDF2Excel import sberbankPDF2Excel\n\n\n# defining global variable, which will hold files tuple\nfiles = ()\n\ndef btn_selectFiles_clicked():\n global files\n\n files = tkinter.filedialog.askopenfilenames(parent=window,\n title='Выберете файл(ы)',\n filetypes =((\"PDF файл\", \"*.pdf\"),(\"All Files\",\"*.*\")) )\n\n SelectedFiles_ScrolledText.configure(state=NORMAL)\n # empty scrollText widget\n SelectedFiles_ScrolledText.delete('1.0', END)\n created_excel_files_scrollText.delete('1.0', END)\n\n # Populating SelectedFiles_ScrolledText widget\n for file in files:\n SelectedFiles_ScrolledText.insert(INSERT, file+'\\n')\n\n SelectedFiles_ScrolledText.configure(state=DISABLED)\n \n\ndef btn_convertFiles_clicked():\n \"\"\"\n main function, which performs functionality by calling calls ProjectExpenditure2Excel.ProjectExpenditure2Excel(file)\n and converts file to Excel\n \"\"\"\n # empty scrollText widget\n created_excel_files_scrollText.delete('1.0',END)\n\n qntFiles=len(files)\n qntFilesConverted=0\n for file in files:\n try:\n created_excel_files_scrollText.insert(INSERT, sberbankPDF2Excel(file) + '\\n')\n qntFilesConverted=qntFilesConverted+1\n except:\n print('Error occured, when converting file \"'+'file'+'\" '+ str(sys.exc_info()[0]))\n print(traceback.format_exc())\n print('Skipping this file conversion')\n\n \n if qntFiles==qntFilesConverted:\n print('Все файлы успешно сконвертированы')\n else:\n print(f'!!!!!!! {qntFiles-qntFilesConverted} файл(а) из {qntFiles} не были сконвертированы')\n\nwindow = Tk()\nmenu = Menu(window)\nhelp_about=Menu(menu)\n\ndef help_about_clicked():\n\n info_string = f'{NAME}\\nВерсия={VERSION}\\nАвтор={AUTHOR}\\nГде скачать={PERMANENT_LOCATION}\\n{__doc__}'\n print(info_string)\n messagebox.showinfo('', info_string)\n\nhelp_about.add_command(label='About',command=help_about_clicked)\n\nmenu.add_cascade(label='Help', menu=help_about)\nwindow.config(menu=menu)\n \nwindow.title(f'{NAME} Версия={VERSION}')\n \nwindow.geometry('720x380')\n \nLabel(window, text=\"\"\"\nШаг 1: Выберите один или несколько файлов в формате PDF\n\"\"\",justify=LEFT).grid(column=0, row=0,sticky=\"W\")\n \nButton(window, text=\"Выбрать файлы\", command=btn_selectFiles_clicked).grid(column=0, row=2)\n \n\nLabel(window, text='Выбранные файлы:').grid(column=0,row=3,sticky=\"W\")\nSelectedFiles_ScrolledText = scrolledtext.ScrolledText(window,width=80,height=4,state=DISABLED)\nSelectedFiles_ScrolledText.grid(column=0,row=4)\n\nLabel(window, text=\"Шаг 2. Сконвертируйте файлы в формат Excel\").grid(column=0,row=5,sticky=\"W\")\n\nButton(window,text=\"Сконвертировать \\n выбранные файлы\", command=btn_convertFiles_clicked).grid(column=0,row=6)\n\nLabel(window, text='Созданные файлы в формате Excel:').grid(column=0,row=7,sticky=\"W\")\ncreated_excel_files_scrollText = scrolledtext.ScrolledText(window,width=80,height=4)\ncreated_excel_files_scrollText.grid(column=0,row=8)\n \nwindow.mainloop()\n\n","sub_path":"core/sberbankPDF2ExcelGUI.py","file_name":"sberbankPDF2ExcelGUI.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"74969586","text":"def caesar(msg, direction, shift):\n global alphabet\n result = ''\n if direction == 'encode':\n for i in msg:\n result += (chr(((ord(i)+shift-65) % 26)+65))\n return result\n elif direction == 'decode':\n return \"Not implemented yet\"\n else:\n return \"Invalid direction\"\n\n\nalphabet = [chr(x) for x in range(65, 91)]\n\nact_direction = input(\"Type 'encode' to encrypt, type 'decode' to decrypt:\\n\")\ntext = input(\"Type your message:\\n\").upper()\nact_shift = int(input(\"Type the shift number:\\n\"))\n\nprint(caesar(text, act_direction, act_shift))\n\n\n\n","sub_path":"day8_caesar_cipher/caesar_cipher.py","file_name":"caesar_cipher.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"613897865","text":"#!/usr/bin/env python3\n#-*-coding:utf-8-*-\n# __all__=\"\"\n# __datetime__=\"\"\n# __purpose__=\"\"\n\nimport pika\n# tcp连接\nconnection = pika.BlockingConnection(pika.ConnectionParameters(\"localhost\"))\n# 创建channel连接\nchannel = connection.channel()\n# print(channel)\nchannel.queue_declare(queue=\"one\")\nchannel.basic_publish(exchange=\"\",\n routing_key=\"one\",\n body=\"this one\")\nprint(\"send this one by one\")\nconnection.close()","sub_path":"rabbitmq_send.py","file_name":"rabbitmq_send.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"352344720","text":"import pandas as pd\nimport numpy as np\nimport collections\n\ndata = [\n dict(age=1, job=0, house=0, loan=0, label=0),\n dict(age=1, job=0, house=0, loan=1, label=0),\n dict(age=1, job=1, house=0, loan=1, label=1),\n dict(age=1, job=1, house=1, loan=0, label=1),\n dict(age=1, job=0, house=0, loan=0, label=0),\n dict(age=2, job=0, house=0, loan=0, label=0),\n dict(age=2, job=0, house=0, loan=1, label=0),\n dict(age=2, job=1, house=1, loan=1, label=1),\n dict(age=2, job=0, house=1, loan=2, label=1),\n dict(age=2, job=0, house=1, loan=2, label=1),\n dict(age=3, job=0, house=1, loan=2, label=1),\n dict(age=3, job=0, house=1, loan=1, label=1),\n dict(age=3, job=1, house=0, loan=1, label=1),\n dict(age=3, job=1, house=0, loan=2, label=1),\n dict(age=3, job=0, house=0, loan=0, label=0),\n\n]\n\ntrain=pd.DataFrame(data, columns=data[0].keys())\nprint(train)\n\ndef calc_stat(df, label_name='label'):\n \"\"\"\n 提取统计信息\n\n :param df: DataFrame, 包含标签信息\n :param label_name: 标签所在的列名\n :return: label_tbls: dictionary, 相同分类值得坐标集合, 类值为KEY\n freq_tbls: dictionary, 每个feature不同取值 对应 标签不同取值的 个数统计, FEATURE值为Key\n value_per_feature: dictionary, 每个feature的可能取值, FEATURE值为Key\n\n \"\"\"\n\n # 每个特征的可能取值\n values_per_feature = dict()\n for feature in df.columns:\n values_per_feature[feature] = df[feature].unique()\n\n # build frequency table\n # 每一个feature的取值对应分类的统计\n freq_tbls = dict()\n for feature in values_per_feature.keys():\n if feature == label_name: continue\n d = []\n for value in values_per_feature[feature]:\n d1 = []\n for label_value in values_per_feature[label_name]:\n d1.append(\n len(\n train.query(feature + ' == @value and ' + label_name + '==@label_value')\n )\n )\n d.append(d1)\n freq_tbls[feature] = pd.DataFrame(d, columns=values_per_feature[label_name], index=values_per_feature[feature])\n\n # 分类的坐标信息\n label_tbls = collections.defaultdict(list)\n for i, c in enumerate(df[label_name]):\n label_tbls[c].append(i)\n\n return label_tbls, freq_tbls, values_per_feature\n\n\n\"\"\"\ntest code \n\nlabel_tbls, freq_tbls , v_f= calc_stat(train)\n\nprint(\"Frequency Tables\".center(20, \"=\"))\nfor key, item in freq_tbls.items():\n print(key.center(20, '-'))\n print(item)\nprint(\"Label Tables\".center(20, \"=\"))\nfor key, item in label_tbls.items():\n print(key, item)\nprint(\"Values per Feature\".center(20, \"=\"))\nfor key, item in v_f.items():\n print(key, item)\n \n age job house loan label\n0 1 0 0 0 0\n1 1 0 0 1 0\n2 1 1 0 1 1\n3 1 1 1 0 1\n4 1 0 0 0 0\n5 2 0 0 0 0\n6 2 0 0 1 0\n7 2 1 1 1 1\n8 2 0 1 2 1\n9 2 0 1 2 1\n10 3 0 1 2 1\n11 3 0 1 1 1\n12 3 1 0 1 1\n13 3 1 0 2 1\n14 3 0 0 0 0\n==Frequency Tables==\n--------age---------\n 0 1\n1 3 2\n2 2 3\n3 1 4\n--------job---------\n 0 1\n0 6 4\n1 0 5\n-------house--------\n 0 1\n0 6 3\n1 0 6\n--------loan--------\n 0 1\n0 4 1\n1 2 4\n2 0 4\n====Label Tables====\n0 [0, 1, 4, 5, 6, 14]\n1 [2, 3, 7, 8, 9, 10, 11, 12, 13]\n=Values per Feature=\nage [1 2 3]\njob [0 1]\nhouse [0 1]\nloan [0 1 2]\nlabel [0 1]\n\n\"\"\"\n\n\ndef empirical_entropy(plist):\n \"\"\"\n refer to page 62 李航 统计学习方法\n H(D) = -sum(Ck/D * log(Ck/D) / log(2)\n :param plist: Ck/D\n :return: empirical entropy scalar\n \"\"\"\n # we first exclude 0, b/c definition 0*log0 == 0\n probs = [x for x in plist if x != 0]\n # we also check if there is negative value, since it is illeague\n tmp = [x for x in probs if x > 0 ]\n assert(len(tmp) == len(probs))\n\n return sum(\n [-p * np.log(p)/np.log(2) for p in probs]\n )\n\ndef empirical_conditional_entropy(freq_tbl):\n \"\"\"\n Refer to page 62 李航 统计学习方法\n H(D|A) = - sum(Di/D * sum(Dik/Di * log(Dik/Di) / log(2) )\n :param freq_tbl: 一个特定feature的frequency table\n :return: H(D|A)\n \"\"\"\n Di = freq_tbl.sum(axis=1)\n Di_D = Di / sum(Di)\n Dik_Di = freq_tbl.div(Di, axis=0)\n H_D_given_A = 0\n for i in range(len(freq_tbl)):\n tmp = [x * np.log(x) / np.log(2) for x in Dik_Di.iloc[i] if x != 0]\n H_D_given_A += Di_D.iloc[i] * sum(tmp)\n\n return -H_D_given_A\n\ndef info_gain(freq_tbl):\n D = freq_tbl.values.sum()\n Ck = freq_tbl.sum(axis=0)\n Ck_distribution = [x/D for x in Ck]\n H_D = empirical_entropy(Ck_distribution)\n H_D_given_A = empirical_conditional_entropy(freq_tbl)\n return H_D - H_D_given_A\n\ndef info_gain_ratio(freq_tbl):\n gain = info_gain(freq_tbl)\n D = freq_tbl.values.sum()\n Di = freq_tbl.sum(axis=1)\n H_a_D = -sum([x/D * np.log(x/D) / np.log(2) for x in Di])\n return gain/H_a_D\n\nlabel_tbls, freq_tbls , v_f= calc_stat(train)\n\n# calculate 数据D的经验熵H(D)\nCk = []\nfor key, item in label_tbls.items():\n Ck.append(len(item))\nD = len(train)\nprobs = [x/D for x in Ck]\nH_D = empirical_entropy(probs)\nprint(\"empirical entropy is\", H_D)\n\nfor feature, item in freq_tbls.items():\n # D_features = list(item.sum(axis=1))\n # H_D_given_A = empirical_conditional_entropy(freq_tbls[feature])\n # print(feature, H_D, H_D_given_A, H_D-H_D_given_A)\n print(feature, \"information gain\", info_gain(freq_tbl=freq_tbls[feature]), info_gain_ratio(freq_tbls[feature]))\n","sub_path":"dt/infogain.py","file_name":"infogain.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"441945510","text":"\nimport concurrent.futures\nimport json\nfrom typing import Union, List\n\nimport elasticapm\n\nfrom assemblyline.common import forge\nfrom assemblyline.common.dict_utils import recursive_update, flatten\nfrom assemblyline.common.isotime import now_as_iso\nfrom assemblyline.datastore import Collection\nfrom assemblyline.odm import Model\nfrom assemblyline.odm.models.alert import Alert\nfrom assemblyline.odm.models.cached_file import CachedFile\nfrom assemblyline.odm.models.emptyresult import EmptyResult\nfrom assemblyline.odm.models.error import Error\nfrom assemblyline.odm.models.file import File\nfrom assemblyline.odm.models.filescore import FileScore\nfrom assemblyline.odm.models.heuristic import Heuristic\nfrom assemblyline.odm.models.result import Result\nfrom assemblyline.odm.models.service import Service\nfrom assemblyline.odm.models.service_delta import ServiceDelta\nfrom assemblyline.odm.models.signature import Signature\nfrom assemblyline.odm.models.submission import Submission\nfrom assemblyline.odm.models.submission_summary import SubmissionSummary\nfrom assemblyline.odm.models.submission_tree import SubmissionTree\nfrom assemblyline.odm.models.user import User\nfrom assemblyline.odm.models.user_favorites import UserFavorites\nfrom assemblyline.odm.models.user_settings import UserSettings\nfrom assemblyline.odm.models.vm import VM\nfrom assemblyline.odm.models.workflow import Workflow\nfrom assemblyline.remote.datatypes.lock import Lock\n\ndays_until_archive = forge.get_config().datastore.ilm.days_until_archive\n\n\nclass AssemblylineDatastore(object):\n def __init__(self, datastore_object):\n\n self.ds = datastore_object\n self.ds.register('alert', Alert)\n self.ds.register('cached_file', CachedFile)\n self.ds.register('emptyresult', EmptyResult)\n self.ds.register('error', Error)\n self.ds.register('file', File)\n self.ds.register('filescore', FileScore)\n self.ds.register('heuristic', Heuristic)\n self.ds.register('result', Result)\n self.ds.register('service', Service)\n self.ds.register('service_delta', ServiceDelta)\n self.ds.register('signature', Signature)\n self.ds.register('submission', Submission)\n self.ds.register('submission_tree', SubmissionTree)\n self.ds.register('submission_summary', SubmissionSummary)\n self.ds.register('user', User)\n self.ds.register('user_avatar')\n self.ds.register('user_favorites', UserFavorites)\n self.ds.register('user_settings', UserSettings)\n self.ds.register('workflow', Workflow)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.ds.close()\n\n def enable_archive_access(self):\n self.ds.archive_access = True\n\n def disable_archive_access(self):\n self.ds.archive_access = False\n\n @property\n def alert(self) -> Collection:\n return self.ds.alert\n\n @property\n def cached_file(self) -> Collection:\n return self.ds.cached_file\n\n @property\n def emptyresult(self) -> Collection:\n return self.ds.emptyresult\n\n @property\n def error(self) -> Collection:\n return self.ds.error\n\n @property\n def file(self) -> Collection:\n return self.ds.file\n\n @property\n def filescore(self) -> Collection:\n return self.ds.filescore\n\n @property\n def heuristic(self) -> Collection:\n return self.ds.heuristic\n\n @property\n def result(self) -> Collection:\n return self.ds.result\n\n @property\n def service(self) -> Collection:\n return self.ds.service\n\n @property\n def service_client(self) -> Collection:\n return self.ds.service_client\n\n @property\n def service_delta(self) -> Collection:\n return self.ds.service_delta\n\n @property\n def signature(self) -> Collection:\n return self.ds.signature\n\n @property\n def submission(self) -> Collection:\n return self.ds.submission\n\n @property\n def submission_summary(self) -> Collection:\n return self.ds.submission_summary\n\n @property\n def submission_tree(self) -> Collection:\n return self.ds.submission_tree\n\n @property\n def user(self) -> Collection:\n return self.ds.user\n\n @property\n def user_avatar(self) -> Collection:\n return self.ds.user_avatar\n\n @property\n def user_favorites(self) -> Collection:\n return self.ds.user_favorites\n\n @property\n def user_settings(self) -> Collection:\n return self.ds.user_settings\n\n @property\n def vm(self) -> Collection:\n return self.ds.vm\n\n @property\n def workflow(self) -> Collection:\n return self.ds.workflow\n\n def get_collection(self, collection_name):\n if collection_name in self.ds.get_models():\n return getattr(self, collection_name)\n else:\n raise AttributeError(f'Collection {collection_name} does not exist.')\n\n @staticmethod\n def create_empty_result_from_key(key, cl_engine=forge.get_classification(), as_obj=True):\n sha256, svc_name, svc_version, _ = key.split(\".\", 3)\n svc_version = svc_version[1:]\n\n data = Result({\n \"archive_ts\": now_as_iso(days_until_archive * 24 * 60 * 60),\n \"expiry_ts\": now_as_iso(days_until_archive * 24 * 60 * 60),\n \"classification\": cl_engine.UNRESTRICTED,\n \"response\": {\n \"service_name\": svc_name,\n \"service_version\": svc_version,\n },\n \"sha256\": sha256\n })\n if as_obj:\n return data\n else:\n return data.as_primitives()\n\n @elasticapm.capture_span(span_type='datastore')\n def delete_submission_tree(self, sid, cl_engine=forge.get_classification(), cleanup=True, transport=None):\n submission = self.submission.get(sid, as_obj=False)\n errors = submission['errors']\n results = submission[\"results\"]\n files = []\n fix_classification_files = []\n\n temp_files = [x[:64] for x in errors]\n temp_files.extend([x[:64] for x in results])\n temp_files = list(set(temp_files))\n for temp in temp_files:\n query = f\"errors:{temp}* OR results:{temp}*\"\n if self.submission.search(query, rows=0, as_obj=False)[\"total\"] < 2:\n files.append(temp)\n else:\n fix_classification_files.append(temp)\n errors = [x for x in errors if x[:64] in files]\n results = [x for x in results if x[:64] in files]\n\n # Delete childs\n for e in errors:\n self.error.delete(e)\n for r in results:\n if r.endswith(\".e\"):\n self.emptyresult.delete(r)\n else:\n self.result.delete(r)\n for f in files:\n self.file.delete(f)\n if transport:\n transport.delete(f)\n\n if fix_classification_files and cleanup:\n # Fix classification for the files that remain in the system\n for f in fix_classification_files:\n cur_file = self.file.get(f, as_obj=False)\n if cur_file:\n classifications = []\n # Find possible submissions that uses that file and the min classification for those submissions\n for item in self.submission.stream_search(f\"files.sha256:{f} OR results:{f}* OR errors:{f}*\",\n fl=\"classification,id\", as_obj=False):\n if item['id'] != sid:\n classifications.append(item['classification'])\n classifications = list(set(classifications))\n if len(classifications) > 0:\n new_file_class = classifications[0]\n else:\n new_file_class = cl_engine.UNRESTRICTED\n\n for c in classifications:\n new_file_class = cl_engine.min_classification(new_file_class, c)\n\n # Find the results for that classification and alter them if the new classification does not match\n for item in self.result.stream_search(f\"id:{f}*\", fl=\"classification,id\", as_obj=False):\n new_class = cl_engine.max_classification(\n item.get('classification', cl_engine.UNRESTRICTED), new_file_class)\n if item.get('classification', cl_engine.UNRESTRICTED) != new_class:\n parts = cl_engine.get_access_control_parts(new_class)\n update_params = [(Collection.UPDATE_SET, 'classification', new_class)]\n update_params.extend([(Collection.UPDATE_SET, k, v) for k, v in parts.items()])\n self.result.update(item['id'], update_params)\n\n # cur_res = self.result.get(item['id'], as_obj=False)\n # if cur_res:\n # Old way\n # cur_res['classification'] = new_class\n # self.result.save(item['id'], cur_res)\n\n # Alter the file classification if the new classification does not match\n if cur_file['classification'] != new_file_class:\n parts = cl_engine.get_access_control_parts(new_file_class)\n update_params = [(Collection.UPDATE_SET, 'classification', new_file_class)]\n update_params.extend([(Collection.UPDATE_SET, k, v) for k, v in parts.items()])\n self.file.update(f, update_params)\n\n # Old way\n # cur_file['classification'] = new_file_class\n # self.file.save(f, cur_file)\n\n self.submission.delete(sid)\n self.submission_tree.delete(sid)\n self.submission_summary.delete(sid)\n\n @elasticapm.capture_span(span_type='datastore')\n def get_all_heuristics(self):\n return {h['id']: h for h in self.ds.heuristic.stream_search(\"id:*\", as_obj=False)}\n\n @elasticapm.capture_span(span_type='datastore')\n def get_multiple_results(self, keys, cl_engine=forge.get_classification(), as_obj=False):\n empties = {k: self.create_empty_result_from_key(k, cl_engine, as_obj=as_obj)\n for k in keys if k.endswith(\".e\")}\n keys = [k for k in keys if not k.endswith(\".e\")]\n results = self.result.multiget(keys, as_dictionary=True, as_obj=as_obj)\n results.update(empties)\n return results\n\n @elasticapm.capture_span(span_type='datastore')\n def get_single_result(self, key, cl_engine=forge.get_classification(), as_obj=False):\n if key.endswith(\".e\"):\n data = self.create_empty_result_from_key(key, cl_engine, as_obj=as_obj)\n else:\n data = self.result.get(key, as_obj=False)\n\n return data\n\n @elasticapm.capture_span(span_type='datastore')\n def get_file_submission_meta(self, sha256, fields, access_control=None):\n query = f\"files.sha256:{sha256} OR results:{sha256}*\"\n with concurrent.futures.ThreadPoolExecutor(len(fields)) as executor:\n res = {field: executor.submit(self.submission.facet,\n field,\n query=query,\n limit=100,\n access_control=access_control)\n for field in fields}\n\n return {k.split(\".\")[-1]: v.result() for k, v in res.items()}\n\n @elasticapm.capture_span(span_type='datastore')\n def get_file_list_from_keys(self, keys):\n # TODO: needed?\n if len(keys) == 0:\n return {}\n keys = [x for x in list(keys) if not x.endswith(\".e\")]\n items = self.result.multiget(keys)\n\n out = {}\n for key, item in items.items():\n extracted = item['response']['extracted']\n if len(extracted) == 0:\n continue\n if key[:64] not in out:\n out[key[:64]] = []\n out[key[:64]].extend(extracted)\n\n return out\n\n @elasticapm.capture_span(span_type='datastore')\n def get_file_scores_from_keys(self, keys):\n # TODO: needed?\n if len(keys) == 0:\n return {}\n keys = [x for x in list(keys) if not x.endswith(\".e\")]\n items = self.result.multiget(keys)\n\n scores = {x[:64]: 0 for x in keys}\n for key, item in items.items():\n score = item[\"result\"][\"score\"]\n scores[key[:64]] += score\n\n return scores\n\n @elasticapm.capture_span(span_type='datastore')\n def get_signature_last_modified(self, sig_type=None):\n if sig_type is None:\n sig_type = \"*\"\n\n res = self.signature.search(f\"type:{sig_type}\", fl=\"last_modified\",\n sort=\"last_modified desc\", rows=1, as_obj=False)\n if res['total'] > 0:\n return res['items'][0]['last_modified']\n return '1970-01-01T00:00:00.000000Z'\n\n @elasticapm.capture_span(span_type='datastore')\n def get_or_create_file_tree(self, submission, max_depth):\n if isinstance(submission, Model):\n submission = submission.as_primitives()\n\n num_files = len(list(set([x[:64] for x in submission['results']])))\n max_score = submission['max_score']\n\n cached_tree = self.submission_tree.get_if_exists(submission['sid'], as_obj=False)\n if cached_tree:\n tree = json.loads(cached_tree['tree'])\n if self._is_valid_tree(tree, num_files, max_score):\n return tree\n\n files = {}\n scores = {}\n file_hashes = [x[:64] for x in submission['results']]\n file_hashes.extend([x[:64] for x in submission['errors']])\n file_hashes.extend([f['sha256'] for f in submission['files']])\n file_data_map = self.file.multiget(list(set(file_hashes)), as_dictionary=True, as_obj=False)\n\n for key, item in self.result.multiget([x for x in submission['results'] if not x.endswith(\".e\")],\n as_obj=False).items():\n sha256 = key[:64]\n\n # Get scores\n if sha256 not in scores:\n scores[sha256] = 0\n scores[sha256] += item[\"result\"][\"score\"]\n\n # Get files\n extracted = item['response']['extracted']\n if len(extracted) == 0:\n continue\n if sha256 not in files:\n files[sha256] = []\n files[sha256].extend(extracted)\n\n tree_cache = []\n\n def recurse_tree(child_p, placeholder, parents_p, lvl=0):\n if lvl == max_depth + 1:\n # Enforce depth protection while building the tree\n return\n\n if child_p['sha256'] in placeholder:\n placeholder[child_p['sha256']]['name'].append(child_p['name'])\n else:\n children_list = {}\n truncated = False\n child_list = files.get(child_p['sha256'], [])\n for new_child in child_list:\n if new_child['sha256'] in tree_cache:\n truncated = True\n continue\n tree_cache.append(child['sha256'])\n\n if new_child['sha256'] not in parents_p:\n recurse_tree(new_child, children_list,\n parents_p + [child_p['sha256']], lvl + 1)\n\n try:\n placeholder[child_p['sha256']] = {\n \"name\": [child_p['name']],\n \"type\": file_data_map[child_p['sha256']]['type'],\n \"sha256\": file_data_map[child_p['sha256']]['sha256'],\n \"size\": file_data_map[child_p['sha256']]['size'],\n \"children\": children_list,\n \"truncated\": truncated,\n \"score\": scores.get(child_p['sha256'], 0),\n }\n except KeyError as e:\n missing_key = str(e).strip(\"'\")\n file_data_map[missing_key] = self.file.get(missing_key, as_obj=False)\n placeholder[child_p['sha256']] = {\n \"name\": [child_p['name']],\n \"type\": file_data_map[child_p['sha256']]['type'],\n \"sha256\": file_data_map[child_p['sha256']]['sha256'],\n \"size\": file_data_map[child_p['sha256']]['size'],\n \"children\": children_list,\n \"truncated\": truncated,\n \"score\": scores.get(child_p['sha256'], 0),\n }\n\n tree = {}\n for f in submission['files']:\n sha256 = f['sha256']\n name = f['name']\n\n if sha256 in tree:\n tree[sha256]['name'].append(name)\n else:\n parents = [sha256]\n children = {}\n c_list = files.get(sha256, [])\n for child in c_list:\n tree_cache.append(child['sha256'])\n recurse_tree(child, children, parents)\n\n tree[sha256] = {\n \"name\": [name],\n \"children\": children,\n \"type\": file_data_map[sha256]['type'],\n \"sha256\": file_data_map[sha256]['sha256'],\n \"size\": file_data_map[sha256]['size'],\n \"truncated\": False,\n \"score\": scores.get(sha256, 0),\n }\n\n cached_tree = {\n 'expiry_ts': now_as_iso(days_until_archive * 24 * 60 * 60),\n 'tree': json.dumps(tree)\n }\n\n self.submission_tree.save(submission['sid'], cached_tree)\n return tree\n\n @staticmethod\n def _is_valid_tree(tree, num_files, max_score):\n def _count_children(sub_tree, cur_files, cur_score):\n temp_score = cur_score\n for k, v in sub_tree.items():\n if v['score'] > temp_score:\n temp_score = v['score']\n cur_files.append(k)\n cur_files, temp_score = _count_children(v.get(\"children\", {}), cur_files, temp_score)\n return cur_files, temp_score\n\n files, tree_score = _count_children(tree, [], 0)\n files = list(set(files))\n\n if len(files) < num_files:\n return False\n\n if tree_score != max_score:\n return False\n\n return True\n\n @elasticapm.capture_span(span_type='datastore')\n def get_summary_from_keys(self, keys):\n out = {\n \"tags\": [],\n \"attack_matrix\": [],\n \"heuristics\": {\n \"info\": [],\n \"suspicious\": [],\n \"malicious\": []\n }\n }\n done_map = {\n \"heuristics\": set(),\n \"attack\": set(),\n \"tags\": set()\n }\n\n if len(keys) == 0:\n return out\n\n keys = [x for x in list(keys) if not x.endswith(\".e\")]\n items = self.result.multiget(keys, as_obj=False)\n\n for key, item in items.items():\n for section in item.get('result', {}).get('sections', []):\n h_type = \"info\"\n\n if section.get('heuristic', False):\n # Get the heuristics data\n if section['heuristic']['score'] < 100:\n h_type = \"info\"\n elif section['heuristic']['score'] < 1000:\n h_type = \"suspicious\"\n else:\n h_type = \"malicious\"\n\n cache_key = f\"{section['heuristic']['heur_id']}_{key}\"\n if cache_key not in done_map['heuristics']:\n out['heuristics'][h_type].append({\n 'heur_id': section['heuristic']['heur_id'],\n 'name': section['heuristic']['name'],\n 'key': key\n })\n done_map['heuristics'].add(cache_key)\n\n if section['heuristic'].get('attack_id', False):\n # Get attack matrix data\n attack_id = section['heuristic']['attack_id']\n\n cache_key = f\"{attack_id}_{key}\"\n if cache_key not in done_map['attack']:\n out['attack_matrix'].append({\n \"key\": key,\n \"attack_id\": attack_id,\n \"h_type\": h_type,\n \"name\": section['heuristic']['attack_pattern'],\n \"categories\": section['heuristic']['attack_categories']\n })\n done_map['attack'].add(cache_key)\n\n # Get tagging data\n for tag_type, tags in flatten(section.get('tags', {})).items():\n if tags is not None:\n for tag in tags:\n cache_key = f\"{tag_type}_{tag}_{key}\"\n\n if cache_key not in done_map['tags']:\n out['tags'].append({\n 'type': tag_type,\n 'h_type': h_type,\n 'short_type': tag_type.rsplit(\".\", 1)[-1],\n 'value': tag,\n 'key': key\n })\n done_map['tags'].add(cache_key)\n\n return out\n\n @elasticapm.capture_span(span_type='datastore')\n def get_tag_list_from_keys(self, keys):\n if len(keys) == 0:\n return []\n keys = [x for x in list(keys) if not x.endswith(\".e\")]\n items = self.result.multiget(keys, as_obj=False)\n\n out = []\n for key, item in items.items():\n for section in item.get('result', {}).get('sections', []):\n for tag_type, tags in flatten(section.get('tags', {})).items():\n if tags is not None:\n for tag in tags:\n out.append({\n 'type': tag_type,\n 'short_type': tag_type.rsplit(\".\", 1)[-1],\n 'value': tag,\n 'key': key\n })\n\n return out\n\n @elasticapm.capture_span(span_type='datastore')\n def get_attack_matrix_from_keys(self, keys):\n if len(keys) == 0:\n return []\n keys = [x for x in list(keys) if not x.endswith(\".e\")]\n items = self.result.multiget(keys, as_obj=False)\n\n out = []\n for key, item in items.items():\n for section in item.get('result', {}).get('sections', []):\n attack_id = section.get('heuristic', {}).get('attack_id', None)\n if attack_id:\n out.append({\n \"key\": key,\n \"attack_id\": attack_id,\n \"name\": section['heuristic']['attack_pattern'],\n \"categories\": section['heuristic']['attack_categories']\n })\n\n return out\n\n @elasticapm.capture_span(span_type='datastore')\n def get_service_with_delta(self, service_name, version=None, as_obj=True):\n svc = self.ds.service_delta.get(service_name)\n if svc is None:\n return svc\n\n if version is not None:\n svc.version = version\n\n svc_version_data = self.ds.service.get(f\"{service_name}_{svc.version}\")\n if svc_version_data is None:\n return svc_version_data\n\n svc_version_data = recursive_update(svc_version_data.as_primitives(strip_null=True),\n svc.as_primitives(strip_null=True))\n if as_obj:\n return Service(svc_version_data)\n else:\n return svc_version_data\n\n @elasticapm.capture_span(span_type='datastore')\n def list_all_services(self, as_obj=True, full=False) -> Union[List[dict], List[Service]]:\n \"\"\"\n :param as_obj: Return ODM objects rather than dicts\n :param full: If true retrieve all the fields of the service object, otherwise only\n fields returned by search are given.\n \"\"\"\n items = list(self.ds.service_delta.stream_search(\"id:*\", as_obj=False))\n\n if full:\n service_data = self.ds.service.multiget([f\"{item['id']}_{item['version']}\" for item in items],\n as_dictionary=False)\n service_delta = self.ds.service_delta.multiget([item['id'] for item in items], as_dictionary=False)\n services = [recursive_update(data.as_primitives(strip_null=True), delta.as_primitives(strip_null=True))\n for data, delta in zip(service_data, service_delta)]\n\n else:\n services_versions = {item['id']: item for item in self.ds.service.stream_search(\"id:*\", as_obj=False)}\n services = [recursive_update(services_versions[f\"{item['id']}_{item['version']}\"], item)\n for item in items if f\"{item['id']}_{item['version']}\" in services_versions]\n\n if as_obj:\n mask = None\n if not full and services:\n mask = services[0].keys()\n return [Service(s, mask=mask) for s in services]\n else:\n return services\n\n @elasticapm.capture_span(span_type='datastore')\n def list_all_heuristics(self, as_obj=True) -> Union[List[dict], List[Heuristic]]:\n \"\"\"\n :param as_obj: Return ODM objects rather than dicts\n \"\"\"\n heuristics = list(self.ds.heuristic.stream_search(\"id:*\", as_obj=as_obj))\n return heuristics\n\n @elasticapm.capture_span(span_type='datastore')\n def save_or_freshen_file(self, sha256, fileinfo, expiry, classification,\n cl_engine=forge.get_classification(), redis=None):\n with Lock(f'save-or-freshen-file-{sha256}', 5, host=redis):\n current_fileinfo = self.ds.file.get(sha256, as_obj=False) or {}\n\n # Remove control fields from file info and update current file info\n for x in ['classification', 'expiry_ts', 'seen', 'archive_ts']:\n fileinfo.pop(x, None)\n current_fileinfo.update(fileinfo)\n\n current_fileinfo['archive_ts'] = now_as_iso(days_until_archive * 24 * 60 * 60)\n\n # Update expiry time\n current_expiry = current_fileinfo.get('expiry_ts', expiry)\n if current_expiry and expiry:\n current_fileinfo['expiry_ts'] = max(current_expiry, expiry)\n else:\n current_fileinfo['expiry_ts'] = None\n\n # Update seen counters\n now = now_as_iso()\n current_fileinfo['seen'] = seen = current_fileinfo.get('seen', {})\n seen['count'] = seen.get('count', 0) + 1\n seen['last'] = now\n seen['first'] = seen.get('first', now)\n\n # Update Classification\n classification = cl_engine.min_classification(\n current_fileinfo.get('classification', classification),\n classification\n )\n current_fileinfo['classification'] = classification\n self.ds.file.save(sha256, current_fileinfo)\n","sub_path":"assemblyline/datastore/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":27755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"595021907","text":"\"\"\"\nLIBRARY & PACKAGES \n\"\"\"\nimport os \nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom pylab import savefig\n\n#Set working directory \nwd = '../Uptake/2015' \nos.chdir(wd)\n\ndef data_extract(): \n data = pd.read_csv(\"filtered_2015.csv\")\n #relevant Smart stats: 1, 3, 5, 9, 192, 194, 197, 198\n df = data[[\"failure\", \"smart_1_raw\", \"smart_3_raw\", \"smart_5_raw\", \"smart_9_raw\", \"smart_192_raw\", \"smart_194_raw\",\"smart_197_raw\", \"smart_198_raw\"]]\n df.rename(columns=lambda x: x.replace('smart_',''), inplace=True)\n print(df.columns)\n return df\n\n#see the failure with each smart stats \ndef data_manipulate(df): \n corr = df.corr()\n ax = sns.heatmap(\n corr, \n vmin=-1, vmax=1, center=0,\n cmap=sns.diverging_palette(20, 220, n=200),\n square=True\n )\n ax.set_xticklabels(\n ax.get_xticklabels(),\n rotation=45,\n horizontalalignment='right'\n )\n figure = ax.get_figure()\n return figure.savefig(\"output.png\")\n\ndata_extract()\n#data_manipulate(data_extract())\n","sub_path":"eda.py","file_name":"eda.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"187794507","text":"#!/usr/bin/python\n\nimport select\nimport socket\nimport sys\nimport struct\nimport serial\nfrom xbee import ZigBee\nimport binascii\nfrom xbeeser import *\n\naports=0\naips=0\nasensors=0\nloop=0\n#untuk pengiriman dengan data hingga 2^32 - 1 pada length\n\nformat = struct.Struct('!I')\n\n\"\"\"\n Network Section\n\"\"\"\ndef send(sock, message):\n sock.send(format.pack(len(message)) + message)\n\ndef file_read():\n translasi = file(\"translasi.txt\", 'r')\n cols, indexToName = getColumns(translasi)\n translasi.close()\n aports=cols['PORT']\n aips=cols['IP']\n asensors=cols['SENSOR']\n return aports, aips, asensors\n\ndef getColumns(inFile, delim=\"\\t\", header=True):\n \"\"\"\n Get columns of data from inFile. The order of the rows is respected\n :param inFile: column file separated by delim\n :param header: if True the first line will be considered a header line\n :returns: a tuple of 2 dicts (cols, indexToName). cols dict has keys that \n are headings in the inFile, and values are a list of all the entries in that\n column. indexToName dict maps column index to names that are used as keys in \n the cols dict. The names are the same as the headings used in inFile. If\n header is False, then column indices (starting from 0) are used for the \n heading names (i.e. the keys in the cols dict)\n \"\"\"\n cols = {}\n indexToName = {}\n for lineNum, line in enumerate(inFile):\n if lineNum == 0:\n headings = line.split(delim)\n i = 0\n for heading in headings:\n heading = heading.strip()\n if header:\n cols[heading] = []\n indexToName[i] = heading\n else:\n # in this case the heading is actually just a cell\n cols[i] = [heading]\n indexToName[i] = i\n i += 1\n else:\n cells = line.split(delim)\n i = 0\n for cell in cells:\n cell = cell.strip()\n cols[indexToName[i]] += [cell]\n i += 1\n return cols, indexToName\ndef serve(ports):\n\n listeners, sockets = [], []\n for port in ports:\n listener = socket.socket()\n listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n listener.bind(('127.0.0.1', port))\n listener.setblocking(False)\n listener.listen(5)\n listeners.append(listener)\n sockets.append(listener)\n print(listener.getsockname(), ' listening')\n while True:\n # debugging sensor data value\n print_status()\n\n # fetch data first before send it to client\n\n data_suhu = sensor_suhu()\n data_api = sensor_api()\n\n r, w, x = select.select(sockets, sockets, sockets)\n for sock in r:\n if sock in listeners:\n c, a = sock.accept()\n print(sock.getsockname(), ' <- ', a)\n aports, aips, asensors=file_read()\n dport=sock.getsockname()\n if int (dport[1]) == 2222:\n #c.send('nilai sensor api:')\n c.send(str(data_api))\n elif int (dport[1]) == 2223:\n #c.send('nilai sensor suhu:')\n c.send(str(data_suhu))\n sockets.append(c)\n else:\n buf = sock.recv(80)\n if not buf:\n print(sock.getpeername(), ' EOF')\n sockets.remove(sock)\n else:\n print(sock.getpeername(), ' <- ', buf)\n for sock in w:\n pass\n for sock in x:\n print(sock.getpeername(), ' error')\n sockets.remove(sock)\n\nif __name__ == '__main__':\n\n translasi = file(\"translasi.txt\", 'r')\n cols, indexToName = getColumns(translasi)\n translasi.close()\n #serve(cols['PORT'],cols['SENSOR'])\n serve (int(arg) for arg in cols['PORT'])\n #serve(int(arg) for arg in sys.argv[1:])","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"260969555","text":"import csv\nfrom datetime import datetime\n\nimport django.conf as conf\nimport django.core.mail as mail\n\nfrom django.contrib.auth.decorators import permission_required, \\\n user_passes_test\nfrom django.core.urlresolvers import reverse\nfrom django.http import Http404, HttpResponse, HttpResponseRedirect\nfrom django.template import RequestContext, TemplateDoesNotExist\nfrom django.template.loader import get_template, render_to_string\n\nfrom free103.apply import forms, models\n\ndef index(request):\n context = RequestContext(request)\n template = get_template('apply/index.html')\n return HttpResponse(template.render(context))\n\n@user_passes_test(lambda u: u.is_staff)\ndef admin(request):\n context = RequestContext(request)\n template = get_template('apply/admin/index.html')\n return HttpResponse(template.render(context))\n\n@permission_required('apply.change_airtime')\ndef admin_airtime(request):\n context = RequestContext(request)\n applications = models.AirtimeApp.objects.all().order_by('applicant')\n context['applications'] = applications\n template = get_template('apply/admin/airtime/index.html')\n return HttpResponse(template.render(context))\n\n@permission_required('apply.change_airtimeapp')\ndef admin_airtime_csv(request):\n applications = models.AirtimeApp.objects.all()\n response = HttpResponse(mimetype='text/csv')\n response['Content-Disposition'] = 'attachment; filename=airtime_apps.csv'\n writer = csv.writer(response)\n field_names = [field.name for field in applications[0]._meta.fields]\n writer.writerow(field_names)\n for application in applications:\n values = []\n for name in field_names:\n value = getattr(application, name)\n values.append(unicode(value).encode('utf8'))\n writer.writerow(values)\n return response\n\n@permission_required('apply.change_airtimeapp')\ndef admin_airtime_app(request, id):\n try:\n application = models.AirtimeApp.objects.get(id=id)\n except models.AirtimeApp.DoesNotExist:\n raise Http404\n context = RequestContext(request)\n preview = application.__dict__.copy()\n context['preview'] = preview\n template = get_template('apply/admin/airtime/application.html')\n return HttpResponse(template.render(context))\n\n@permission_required('apply.change_nyscaapp')\ndef admin_nysca(request):\n context = RequestContext(request)\n applications = models.NyscaApp.objects.all().order_by('applicant')\n context['applications'] = applications\n template = get_template('apply/admin/nysca/index.html')\n return HttpResponse(template.render(context))\n\n@permission_required('apply.change_nyscaapp')\ndef admin_nysca_csv(request):\n applications = models.NyscaApp.objects.all()\n response = HttpResponse(mimetype='text/csv')\n response['Content-Disposition'] = 'attachment; filename=nysca_apps.csv'\n writer = csv.writer(response)\n m2m_other_map = {\n 'genre_other': 'genres', \n 'category_other': 'categories', \n 'market_other': 'markets',\n }\n field_names = []\n for field in applications[0]._meta.fields:\n if field.name in m2m_other_map:\n name = m2m_other_map[field.name]\n else:\n name = field.name\n if name == 'total_expenses':\n field_names.append('expense_items')\n elif name == 'total_income':\n field_names.append('other_incomes')\n field_names.append(name)\n writer.writerow(field_names)\n # invert map\n m2m_other_map = dict((v, k) for (k, v) in m2m_other_map.iteritems())\n for application in applications:\n values = []\n for name in field_names:\n if name in m2m_other_map:\n value = application.get_m2m_string(name, m2m_other_map[name])\n elif name == 'expense_items':\n value = '\\n'.join(unicode(ei) for ei in\n application.nyscaexpenseitem_set.all())\n elif name == 'other_incomes':\n value = '\\n'.join(unicode(ei) for ei in\n application.nyscaotherincome_set.all())\n else:\n value = getattr(application, name)\n values.append(unicode(value).encode('utf8'))\n writer.writerow(values)\n return response\n\n@permission_required('apply.change_nyscaapp')\ndef admin_nysca_app(request, id):\n try:\n application = models.NyscaApp.objects.get(id=id)\n except models.NyscaApp.DoesNotExist:\n raise Http404\n context = RequestContext(request)\n preview = application.__dict__.copy()\n preview['genres'] = application.genres.all()\n preview['markets'] = application.markets.all()\n preview['categories'] = application.categories.all()\n expense_items = application.nyscaexpenseitem_set.all()\n other_incomes = application.nyscaotherincome_set.all()\n preview = _nysca_preview_prep(preview, expense_items, other_incomes)\n context['preview'] = preview\n template = get_template('apply/admin/nysca/application.html')\n return HttpResponse(template.render(context))\n\ndef airtime(request):\n context = RequestContext(request)\n template = get_template('apply/airtime/information.html')\n return HttpResponse(template.render(context))\n\ndef airtime_application(request):\n context = RequestContext(request)\n errors = False\n if request.method == 'POST':\n # save to SavedAIRtimeApp for in-process forms\n #if request.POST.get('save'):\n # saved_app = SavedAIRtimeApp(data=request.POST)\n # saved_app.save()\n form = forms.AirtimeAppForm(request.POST)\n if form.is_valid():\n preview = form.cleaned_data.copy()\n context['preview'] = preview\n if request.POST.get('submit'):\n airtime_app_instance = form.save()\n context['submitted'] = True\n #return HttpResponseRedirect(\n # reverse('free103.apply.views.submitted'))\n else:\n errors = True\n else:\n form = forms.AirtimeAppForm()\n context['form'] = form\n context['errors'] = errors\n context['session_time'] = request.session.get('time')\n request.session['time'] = datetime.now()\n template = get_template('apply/airtime/application.html')\n return HttpResponse(template.render(context))\n\ndef airtime_overview(request):\n context = RequestContext(request)\n template = get_template('apply/airtime/overview.html')\n return HttpResponse(template.render(context))\n\ndef airtime_overview_resource(request, resource_name):\n context = RequestContext(request)\n template_path = 'apply/airtime/overview/%s.html' % resource_name\n try:\n template = get_template(template_path)\n except TemplateDoesNotExist:\n raise Http404\n return HttpResponse(template.render(context))\n\ndef nysca(request):\n context = RequestContext(request)\n template = get_template('apply/nysca/information.html')\n return HttpResponse(template.render(context))\n\ndef nysca_application(request):\n context = RequestContext(request)\n errors = False\n nysca_app = models.NyscaApp()\n if request.method == 'POST':\n # save to SavedNyscaApp for in-process forms\n #if request.POST.get('save'):\n # saved_app = SavedNyscaApp(data=request.POST)\n # saved_app.save()\n form = forms.NyscaAppForm(request.POST)\n ei_formset = forms.NyscaExpenseItemFormSet(request.POST, instance=nysca_app)\n oi_formset = forms.NyscaOtherIncomeFormSet(request.POST, instance=nysca_app)\n if (form.is_valid() and ei_formset.is_valid() and \n oi_formset.is_valid()):\n preview = form.cleaned_data.copy()\n expense_items = ei_formset.cleaned_data\n other_incomes = oi_formset.cleaned_data\n preview = _nysca_preview_prep(preview, expense_items, other_incomes)\n context['preview'] = preview\n if request.POST.get('submit'):\n nysca_app_instance = form.save()\n ei_instances = ei_formset.save(commit=False)\n oi_instances = oi_formset.save(commit=False)\n for instances in (ei_instances, oi_instances):\n for instance in instances:\n instance.application = nysca_app_instance\n instance.save()\n applicant = form.cleaned_data['applicant']\n applicant_email = form.cleaned_data['email']\n subject = render_to_string('apply/nysca/email_subject.txt')\n subject = ''.join(subject.splitlines())\n message = render_to_string('apply/nysca/email.txt',\n {'applicant': applicant})\n mail.send_mail(subject, message, conf.settings.SERVER_EMAIL, \n [applicant_email])\n mail.send_mail(subject, \n 'Distribution Grant application sent in by %s' % applicant,\n conf.settings.SERVER_EMAIL, ['regrant@free103point9.org'])\n context['submitted'] = True\n else:\n errors = True\n else:\n form = forms.NyscaAppForm()\n ei_formset = forms.NyscaExpenseItemFormSet(instance=nysca_app)\n oi_formset = forms.NyscaOtherIncomeFormSet(instance=nysca_app)\n context['form'] = form\n context['ei_formset'] = ei_formset\n context['oi_formset'] = oi_formset\n context['errors'] = errors\n context['session_time'] = request.session.get('time')\n request.session['time'] = datetime.now()\n template = get_template('apply/nysca/application.html')\n return HttpResponse(template.render(context))\n\ndef nysca_overview(request):\n context = RequestContext(request)\n template = get_template('apply/nysca/overview.html')\n return HttpResponse(template.render(context))\n\ndef nysca_overview_resource(request, resource_name):\n context = RequestContext(request)\n template_path = 'apply/nysca/overview/%s.html' % resource_name\n try:\n template = get_template(template_path)\n except TemplateDoesNotExist:\n raise Http404\n return HttpResponse(template.render(context))\n\ndef _nysca_preview_prep(preview, expense_items, other_incomes):\n preview['genres'] = ', '.join(x.name for x in preview['genres'] if not x.name.startswith('Other'))\n preview['markets'] = ', '.join(x.name for x in preview['markets'] if not x.name.startswith('Other'))\n preview['categories'] = ', '.join(x.name for x in preview['categories'] if not x.name.startswith('Other'))\n preview['expense_items'] = expense_items\n preview['other_incomes'] = other_incomes\n return preview\n\ndef submitted(request):\n context = RequestContext(request)\n template = get_template('apply/submitted.html')\n return HttpResponse(template.render(context))\n\n\n# deprecated from here on down\n\n#def nysca_preview(request):\n# context = RequestContext(request)\n# preview = request.GET.copy()\n# preview['genres'] = ', '.join(models.NyscaGenre.objects.get(id=x).name \n# for x in request.GET.getlist('genres'))\n# preview['markets'] = ', '.join(models.NyscaMarket.objects.get(id=x).name \n# for x in request.GET.getlist('markets'))\n# preview['categories'] = ', '.join(\n# models.NyscaCategory.objects.get(id=x).name \n# for x in request.GET.getlist('categories'))\n# #_preview_booleans(preview)\n# _preview_budget_items(preview)\n# context['preview'] = preview\n# template = get_template('apply/nysca/preview.html')\n# return HttpResponse(template.render(context))\n \n#def _preview_budget_items(preview):\n# expense_item_names = []\n# expense_item_amounts = []\n# other_income_names = []\n# other_income_amounts = []\n# for key in preview:\n# if key.startswith('nyscaexpenseitem'):\n# if key.endswith('name'):\n# expense_item_names.append((int(key[21]), preview[key]))\n# if key.endswith('amount'):\n# expense_item_amounts.append((int(key[21]), preview[key]))\n# if key.startswith('nyscaotherincome'):\n# if key.endswith('name'):\n# other_income_names.append((int(key[21]), preview[key]))\n# if key.endswith('amount'):\n# other_income_amounts.append((int(key[21]), preview[key]))\n# for budget_list in (expense_item_names, expense_item_amounts, \n# other_income_names, other_income_amounts):\n# budget_list.sort()\n# expense_item_names = [x[1] for x in expense_item_names]\n# expense_item_amounts = [x[1] for x in expense_item_amounts]\n# other_income_names = [x[1] for x in other_income_names]\n# other_income_amounts = [x[1] for x in other_income_amounts]\n# preview['expense_items'] = zip(expense_item_names, expense_item_amounts)\n# preview['other_incomes'] = zip(other_income_names, other_income_amounts)\n\n","sub_path":"free103/apply/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"372801424","text":"\"\"\" @brief APPENDS VLOOKUP AND JOINS DEXI AND OTHER (Ed's) SCRAPPER \n\"\"\"\n\nfrom openpyxl import Workbook, load_workbook\n\n# dexi at even numbers, eds at odd numbers\n# CHANGE OUTPUT FILE NAME!\n# files_arr = ['superserver_1u_dexi_test-fmt2', 'SupermicroServer1U-fmt1-fmt2']\n# dest_filename = './compare-folder/compare-1u.xlsx'\n\nfiles_arr = ['superserver_2u_dexi_test-fmt2', 'SupermicroServer2U-fmt1-fmt2']\ndest_filename = './compare-folder/compare-2u.xlsx'\n\n# files_arr = ['superserver_3u_dexi_test-fmt2', 'SupermicroServer3U-fmt1-fmt2']\n# dest_filename = './compare-folder/compare-3u.xlsx'\n\n# files_arr = ['superserver_4u_dexi_test-fmt2', 'SupermicroServer4U-fmt1-fmt2']\n# dest_filename = './compare-folder/compare-4u.xlsx'\n\n# ---------------------------\ndexi_input_name = files_arr[0]\nother_input_name = files_arr[1]\n\n# import files, get active sheet (not sure if needed but whatever)\ndexi_wb = load_workbook('./output-xl/' + dexi_input_name + '.xlsx')\ndexi_wb_ws = dexi_wb.active\n\nother_wb = load_workbook('./output-xl/' + other_input_name + '.xlsx')\nother_wb_ws = other_wb.active\n\n\n\n# create workbook\nwb = Workbook()\n\ndexi_ws = wb.active\ndexi_ws.title = 'dexi'\ndexi_ws.sheet_properties.tabColor = '00ff00'\n\nother_ws = wb.create_sheet(title='ed')\nother_ws.sheet_properties.tabColor = '0000ff'\n\n\n# iterate over rows, enumarate will allow access to index\nfor i, row in enumerate(dexi_wb_ws.iter_rows(values_only=True), start=1):\n new_row = list(row) # convert tuple into list\n new_row.append('=VLOOKUP(S' + str(i) + ',ed!$S$1:$S$15000,1,0)')\n dexi_ws.append(new_row)\n\nfor i, row in enumerate(other_wb_ws.iter_rows(values_only=True), start=1):\n new_row = list(row)\n new_row.append('=VLOOKUP(S' + str(i) + ',dexi!$S$1:$S$15000,1,0)')\n other_ws.append(new_row)\n\n\nprint(wb.sheetnames)\n\nwb.save(filename=dest_filename)","sub_path":"add_vlookup.py","file_name":"add_vlookup.py","file_ext":"py","file_size_in_byte":1829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"100689682","text":"import json\n\nfrom app.common.errors import EntityNotFoundError, InvalidDataError\nfrom app.models.carbon_forms_model import CarbonFormAnswersModel\nfrom app.models.workshop_model import WorkshopParticipantStatus\n\n\ndef test_post_carbon_form_answers(client, workshop, participant):\n count = len(CarbonFormAnswersModel.objects)\n\n data = {\n \"email\": participant.email,\n \"answers\": {\"meat_per_day\": 9000, \"car_type\": \"futuristic\"},\n }\n response = client.post(\n \"/api/v1/carbon_forms/{}\".format(workshop.workshopId), data=json.dumps(data),\n )\n\n response_data, status_code = json.loads(response.data), response.status_code\n\n expected_result = {\n \"id\": response_data[\"id\"], # yeah too lazy to fetch the id\n \"workshopId\": workshop.id,\n \"participantId\": participant.id,\n \"answers\": {\"meat_per_day\": 9000, \"car_type\": \"futuristic\"},\n }\n\n workshop.reload()\n\n assert status_code == 200\n assert len(CarbonFormAnswersModel.objects) == count + 1\n assert response_data == expected_result\n assert workshop.participants[0].status == WorkshopParticipantStatus.TOCHECK.value\n\n\ndef test_post_carbon_form_answers_inexisting_workshop(client):\n data = {\n \"email\": \"email@test.com\",\n \"answers\": {\"meat_per_day\": 9000, \"car_type\": \"futuristic\"},\n }\n response = client.post(\n \"/api/v1/carbon_forms/{}\".format(\"inexistingId\"), data=json.dumps(data),\n )\n\n response_data, status_code = json.loads(response.data), response.status_code\n\n assert status_code == EntityNotFoundError.code\n assert response_data == EntityNotFoundError().get_content()\n\n\ndef test_post_carbon_form_answers_non_existing_participant(client, workshop):\n data = {\n \"email\": \"email@test.com\",\n \"answers\": {\"meat_per_day\": 9000, \"car_type\": \"futuristic\"},\n }\n response = client.post(\n \"/api/v1/carbon_forms/{}\".format(workshop.id), data=json.dumps(data),\n )\n\n response_data, status_code = json.loads(response.data), response.status_code\n\n assert status_code == InvalidDataError.code\n assert \"This email does not belong to one of the workshop's participants\" in str(\n response_data\n )\n\n\ndef test_post_carbon_form_answers_participant_not_in_workshop(\n client, workshop, participant, workshops\n):\n data = {\n \"email\": participant.email,\n \"answers\": {\"meat_per_day\": 9000, \"car_type\": \"futuristic\"},\n }\n response = client.post(\n \"/api/v1/carbon_forms/{}\".format(workshops[0].id), data=json.dumps(data),\n )\n\n response_data, status_code = json.loads(response.data), response.status_code\n\n assert status_code == InvalidDataError.code\n assert \"This email does not belong to one of the workshop's participants\" in str(\n response_data\n )\n\n\ndef test_post_carbon_form_answers_already_existing(\n client, workshop, participant, carbon_form_answers\n):\n data = {\n \"email\": participant.email,\n \"answers\": {\"meat_per_day\": 9000, \"car_type\": \"futuristic\"},\n }\n response = client.post(\n \"/api/v1/carbon_forms/{}\".format(workshop.id), data=json.dumps(data),\n )\n\n response_data, status_code = json.loads(response.data), response.status_code\n\n assert status_code == InvalidDataError.code\n assert (\n \"Participant has already answered to the carbon form for this workshop\"\n in str(response_data)\n )\n","sub_path":"tests/test_carbon_forms.py","file_name":"test_carbon_forms.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"482030460","text":"import pickle\nimport os\nimport cv2 as cv\nimport numpy as np\n\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau\n\nfrom unet_with_batch_norm import UNet\n\ndef load_src(name, fpath):\n import os, imp\n return imp.load_source(name, os.path.join(os.path.dirname(__file__), fpath))\nload_src(\"losses_for_segmentation\", \"../../utils/losses_for_segmentation.py\")\nload_src(\"data_loader\", \"../../utils/data_loader.py\")\n\nfrom losses_for_segmentation import jaccard_distance, dice_coef_loss, dice_coef\nfrom data_loader import data_loader\n\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" \nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"2\"\n\n#----------------------------INPUT PARAMETERS---------------------------\nWEIGHT_PATH = '../../weights/Unet/full_augmentation_data/unet_on_lumen/'\nDATA_PATH = '../../dataset/augmentation/lumen_augmentation/'\n\n# input image properties\nIMG_HEIGHT = 544\nIMG_WIDTH = 544\nCHANNELS_NUM = 3\n\n# model parameters\nMODEL_DEPTH = 5\nBATCH_NORM = True\nDROUPOUT = 0.5\nMAIN_ACTIVATION_FUNCION = 'relu'\n\n#training\nNUM_EPOCHS = 100\nBATCH_SIZE = 4\n\n#-------------------------END_OF_INPUTING_PARAMETERS--------------------\n\n# load images\nX, y = data_loader(DATA_PATH)\nX_train, y_train, X_val, y_val = X[5:], y[5:], X[:5], y[:5]\n\n# create model\nmodel = UNet((IMG_HEIGHT,IMG_WIDTH, CHANNELS_NUM), start_ch=32, depth=MODEL_DEPTH, \n batch_norm=BATCH_NORM, dropout=DROUPOUT, activation=MAIN_ACTIVATION_FUNCION)\nmodel.compile(loss='binary_crossentropy', optimizer=\"adam\", metrics=[\"accuracy\", dice_coef])\nmodel.summary()\n\n# create model callbacks\nearly_stopping = EarlyStopping(patience=10,verbose=1)\n# filepath=\"weights-improvement-{epoch:02d}-{val_acc:.2f}.hdf5\"\nfilepath = \"best_weights_lumen.hdf5\"\nmodel_checkpoint = ModelCheckpoint(os.path.join(WEIGHT_PATH,filepath))\nreduce_lr = ReduceLROnPlateau(factor=0.1, patience=5, min_lr=0.00001, verbose=1)\n\n# train prcess\n\nhistory = model.fit(X_train, y_train,\n validation_data=[X_val,y_val],\n epochs=NUM_EPOCHS,\n batch_size=BATCH_SIZE,\n callbacks=[early_stopping,model_checkpoint,reduce_lr]\n )\n\n\n# save history of the training process\ndef save(obj, name):\n try:\n filename = open(name + \".pickle\",\"wb\")\n pickle.dump(obj, filename)\n filename.close()\n return(True)\n except:\n return(False)\n\nsave(history, 'lumen_history')\n\n\n","sub_path":"models/UnetKeras/trainModelLumen.py","file_name":"trainModelLumen.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"396667611","text":"\"\"\"\nTrellis Histogram\n-----------------\nThis example shows how to make a basic trellis histogram.\nhttps://vega.github.io/vega-lite/examples/trellis_bar_histogram.html\n\"\"\"\nimport altair as alt\n\ncars = alt.load_dataset('cars')\n\nalt.Chart(cars).mark_bar().encode(\n alt.X(\"Horsepower:Q\", bin=True),\n y='count()',\n row='Origin'\n)\n","sub_path":"altair/vegalite/v2/examples/trellis_histogram.py","file_name":"trellis_histogram.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"543344507","text":"from twilio.rest import Client\n\n# put your own credentials here\naccount_sid = \"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\nauth_token = \"your_auth_token\"\n\nclient = Client(account_sid, auth_token)\n\nfax = client.fax.v1 \\\n .faxes(sid=\"FXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\") \\\n .update(status=\"canceled\")\n\nprint(fax.status)\n","sub_path":"fax/instance-post-example/instance-post-example.6.x.py","file_name":"instance-post-example.6.x.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"313200316","text":"import pandas as pd\nimport numpy as np\nimport funcs\nimport random\nimport copy\nimport os\nimport matlab.engine\nfrom sklearn.preprocessing import normalize\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import mean_absolute_error\nfrom numpy.linalg import norm\nfrom scipy.stats import entropy\n\n\ndef item_user_selection():\n df_item_age_uid = pd.read_csv('../../../data/movielens_rating.csv')\n df_item_age_dropU = df_item_age_uid.drop(['uid'], axis=1)\n\n df_item_age = df_item_age_dropU.groupby(['age']).sum()\n df_item_age.loc['sum_user'] = df_item_age.sum()\n\n ### drop the item has very limited users\n df_item_age_dropI = df_item_age.drop(df_item_age.columns[df_item_age.apply(lambda col: col.sum() < 4)], axis=1)\n df_item_age_uid_dropI = df_item_age_uid.drop(df_item_age.columns[df_item_age.apply(lambda col: ((col != 0).astype(int).sum()) < 3)], axis=1)\n df_item_age_uid_dropI = df_item_age_uid_dropI[df_item_age_uid_dropI.age > 17]\n df_item_age_uid_dropI = df_item_age_uid_dropI[df_item_age_uid_dropI.age < 51]\n\n df_item_age_dropI.to_csv('../../../data/movie_ages.csv', index=True)\n df_item_age_uid_dropI.to_csv('../../../data/movie_ages_uid.csv', index=False)\n\n return df_item_age_uid_dropI.reset_index(drop=True)\n\n\ndef get_obf_X(df_cluster, xpgg):\n user_cluster_dict = {}\n cluster_vec = {}\n user_ageGroup_dict = {}\n ageGroup_vec = {}\n user_size = df_cluster.shape[0]\n for i in range(user_size):\n user_id = df_cluster['uid'][i]\n cluster_id = df_cluster['cluster'][i]\n user_cluster_dict[user_id] = cluster_id\n if cluster_id in cluster_vec:\n cluster_vec[cluster_id].append(user_id)\n else:\n cluster_vec[cluster_id] = [user_id]\n\n age_group = df_cluster['age_group'][i]\n user_ageGroup_dict[user_id] = age_group\n if age_group in ageGroup_vec:\n ageGroup_vec[age_group].append(user_id)\n else:\n ageGroup_vec[age_group] = [user_id]\n\n cluster_size = len(cluster_vec)\n ageGroup_size = len(ageGroup_vec)\n print('ageGroup_size in get_obf_X:', ageGroup_size)\n\n X_obf = {}\n X_ori = {}\n\n xpgg[xpgg < 0.00001] = 0\n xpgg_norm = normalize(xpgg, axis=0, norm='l1')\n print(\"obfuscating...\")\n for i in range(user_size):\n user_id = df_cluster['uid'][i]\n # selecting one cluster to change\n while True:\n change_index = np.random.choice(range(0, cluster_size * ageGroup_size), 1, p=xpgg_norm[:,\n user_ageGroup_dict[user_id] + (\n user_cluster_dict[\n user_id] - 1) * ageGroup_size])[\n 0]\n change_cluster_index = int(change_index / ageGroup_size) + 1\n change_ageGroup_index = change_index % ageGroup_size\n potential_users = list(set(cluster_vec[change_cluster_index]) & set(ageGroup_vec[change_ageGroup_index]))\n if len(potential_users) > 0: # potential users may be empty by a slight probability\n break\n else:\n print(\"not find potential users, re-pick\")\n uidx = np.random.choice(potential_users, 1)[0]\n X_ori[user_id] = df_cluster[df_cluster['uid'] == user_id].values[0, :-1]\n X_obf[user_id] = df_cluster[df_cluster['uid'] == uidx].values[0, :-3]\n return X_obf, X_ori\n\n\ndef age_group_initiate_movieLens(age_list):\n # * 1: \"Under 18\"\n # * 18: \"18-24\"\n # * 25: \"25-34\"\n # * 35: \"35-44\"\n # * 45: \"45-49\"\n # * 50: \"50-55\"\n # * 56: \"56+\"\n age_group = {}\n group_age_dict = {} ## key: group; value: age list\n age_max = age_list[-1]\n for age in age_list:\n if age < 25:\n age_group_code = 0\n elif age < 35:\n age_group_code = 1\n elif age < 45:\n age_group_code = 2\n else:\n age_group_code = 3\n age_group[age] = age_group_code\n\n if age_group_code in group_age_dict:\n group_age_dict[age_group_code].append(age)\n else:\n group_age_dict[age_group_code] = [age]\n\n return age_group, group_age_dict\n\n\ndef update_age_group(df_train, age_group_dict):\n for k, v in age_group_dict.items():\n df_train.loc[df_train['age'] == k, 'age_group'] = v\n return df_train\n\n\ndef reducible_scale(df_train, group_age_list, k, l):\n l_cur = l_diversity(df_train, group_age_list)\n range = int(np.exp(l_cur) - np.exp(l))\n group_age_list.sort()\n left_range = range\n right_range = range\n while left_range > 0:\n group_age_list_left = group_age_list[left_range:]\n k_left = k_anonymity(df_train, group_age_list_left)\n if k_left >= k:\n break\n else:\n left_range = left_range - 1\n\n while right_range > 0:\n group_age_list_right = group_age_list[:-right_range]\n k_right = k_anonymity(df_train, group_age_list_right)\n if k_right >= k:\n break\n else:\n right_range = right_range - 1\n\n return left_range, right_range\n\n\ndef k_anonymity(df_train, group_age_list):\n return df_train.loc[df_train['age'].isin(group_age_list)].shape[0]\n\n\ndef l_diversity(df_train, group_age_list):\n age_dtr = np.zeros(len(group_age_list))\n for i in range(len(group_age_list)):\n age_dtr[i] = df_train.loc[df_train['age'] == group_age_list[i]].shape[0]\n age_dtr_norm = age_dtr / norm(age_dtr, ord=1)\n return entropy(age_dtr_norm)\n\n\ndef age_group_adjust_greedy(df_train, group_age_dict, k, l):\n reducible_groups = {}\n for group in group_age_dict:\n left_range, right_range = reducible_scale(df_train, group_age_dict[group], k, l)\n if (left_range > 0 and group > 0) or (right_range > 0 and group < len(group_age_dict) - 1):\n reducible_groups[group] = [left_range, right_range]\n\n adjustable_groups = {}\n #### selecting the best move\n j = 0\n for reduce_group in reducible_groups:\n left_range, right_range = reducible_groups[reduce_group]\n if reduce_group == 0:\n for reduce_range in range(1, right_range + 1):\n adjustable_groups[j] = copy.deepcopy(group_age_dict)\n age_move = adjustable_groups[j][reduce_group][-reduce_range:]\n # print(j, adjustable_groups[j],adjustable_groups[j][reduce_group][:-reduce_range],adjustable_groups[j][reduce_group+1],age_move)\n adjustable_groups[j][reduce_group] = adjustable_groups[j][reduce_group][:-reduce_range]\n adjustable_groups[j][reduce_group + 1].extend(age_move)\n adjustable_groups[j][reduce_group + 1].sort()\n del age_move[:]\n j = j + 1\n elif reduce_group == len(group_age_dict) - 1:\n for reduce_range in range(1, left_range + 1):\n adjustable_groups[j] = copy.deepcopy(group_age_dict)\n age_move = group_age_dict[reduce_group][:reduce_range]\n adjustable_groups[j][reduce_group] = adjustable_groups[j][reduce_group][reduce_range:]\n adjustable_groups[j][reduce_group - 1].extend(age_move)\n adjustable_groups[j][reduce_group - 1].sort()\n del age_move[:]\n j = j + 1\n else:\n for reduce_range in range(1, right_range + 1):\n adjustable_groups[j] = copy.deepcopy(group_age_dict)\n age_move = group_age_dict[reduce_group][-reduce_range:]\n adjustable_groups[j][reduce_group] = adjustable_groups[j][reduce_group][:-reduce_range]\n adjustable_groups[j][reduce_group + 1].extend(age_move)\n adjustable_groups[j][reduce_group + 1].sort()\n del age_move[:]\n j = j + 1\n for reduce_range in range(1, left_range + 1):\n adjustable_groups[j] = copy.deepcopy(group_age_dict)\n age_move = group_age_dict[reduce_group][:reduce_range]\n adjustable_groups[j][reduce_group] = adjustable_groups[j][reduce_group][reduce_range:]\n adjustable_groups[j][reduce_group - 1].extend(age_move)\n adjustable_groups[j][reduce_group - 1].sort()\n del age_move[:]\n j = j + 1\n\n return adjustable_groups, reducible_groups\n\n\ndef recommendation(X_obf, X_ori, df_test):\n df_X_obf = pd.DataFrame.from_dict(X_obf).T\n df_X_ori = pd.DataFrame.from_dict(X_ori).T\n users = list(X_obf.keys())\n\n random.seed(10)\n random.shuffle(users)\n user_train = users[:int(len(users) * 0.7)]\n user_test = list(set(users) - set(user_train))\n df_obf_trainUser_KnownItem = df_X_obf.drop(user_test).values\n df_obf_testUser_KnownItem = df_X_obf.drop(user_train).values\n\n testUser_obf_similarity = cosine_similarity(df_obf_testUser_KnownItem, df_obf_trainUser_KnownItem)\n normed_testUser_obf_similarity = normalize(testUser_obf_similarity, axis=1, norm='l1')\n\n df_test_n = df_test.set_index('uid')\n df_test_n = df_test_n.drop(['age'], axis=1)\n\n df_trainUser_RcdItem_df = df_test_n.drop(user_test)\n df_trainUser_RcdItem = df_trainUser_RcdItem_df.values\n df_testUser_RcdItem = df_test_n.drop(user_train).values\n\n trainUser_RcdItem_rating_or_not = df_trainUser_RcdItem_df.copy()\n trainUser_RcdItem_rating_or_not[trainUser_RcdItem_rating_or_not > 0] = 1\n # RcdItem_rating_user_num = (np.array(RcdItem_rating_user_num.values)+1)/len(user_train)\n trainUser_RcdItem_rating_or_not_value = trainUser_RcdItem_rating_or_not.values\n\n small_number = 0.00000001\n testUser_obf_items = np.matrix(normed_testUser_obf_similarity) * np.matrix(df_trainUser_RcdItem) / (\n np.matrix(normed_testUser_obf_similarity) * np.matrix(\n trainUser_RcdItem_rating_or_not_value) + small_number)\n\n binary_df_testUser_RcdItem = df_testUser_RcdItem.copy()\n binary_df_testUser_RcdItem[binary_df_testUser_RcdItem > 0] = 1 # get the items rated by test users\n testUser_obf_items = np.array(testUser_obf_items) * np.array(binary_df_testUser_RcdItem) # element-wise multiply\n\n row, col = testUser_obf_items.shape\n testUser_obf_items = testUser_obf_items.reshape(row * col, )\n df_testUser_RcdItem = df_testUser_RcdItem.reshape(row * col, )\n rmse_obf = np.sqrt(np.sum((testUser_obf_items - df_testUser_RcdItem) ** 2) / np.count_nonzero(df_testUser_RcdItem))\n\n df_ori_trainUser_KnownItem = df_X_ori.drop(user_test).values[:, :-2]\n df_ori_testUser_KnownItem = df_X_ori.drop(user_train).values[:, :-2]\n testUser_ori_similarity = cosine_similarity(df_ori_testUser_KnownItem, df_ori_trainUser_KnownItem)\n normed_testUser_ori_similarity = normalize(testUser_ori_similarity, axis=1, norm='l1')\n\n testUser_ori_items = np.matrix(normed_testUser_ori_similarity) * np.matrix(df_trainUser_RcdItem) / (\n np.matrix(normed_testUser_ori_similarity) * np.matrix(\n trainUser_RcdItem_rating_or_not_value) + small_number)\n testUser_ori_items = np.array(testUser_ori_items) * np.array(binary_df_testUser_RcdItem) # element-wise multiply\n\n row, col = testUser_ori_items.shape\n testUser_ori_items = testUser_ori_items.reshape(row * col, )\n rmse_ori = np.sqrt(np.sum((testUser_ori_items - df_testUser_RcdItem) ** 2) / np.count_nonzero(df_testUser_RcdItem))\n\n\n return rmse_ori, rmse_obf\n\n\nif __name__ == '__main__':\n\n\t# Hyobscure settings for k&alpha experiments\n\tage_group_number = 4\n\tcluster_num = 10\n\tdeltaX = 0.55\n\n\tk_threshold = 60\n\talpha = 500\n\tl_threshold_list = [3, 4, 5, 6]\n\tbeta_list = [8, 9, 10, 11]\n\n\tavailable_seeds = [3, 4, 5, 7, 9, 10, 12, 13, 16, 19, 20, 21, 22, 23, 25, 26, 27, 29, 31, 34]\n\n\tdf_item_age_uid = item_user_selection()\n\tage_list = list(set(df_item_age_uid['age'].values))\n\tage_list.sort()\n\tmin_age = age_list[0]\n\tdf_item_age_uid['age_group'] = pd.Series(np.zeros(df_item_age_uid.shape[0]), index=df_item_age_uid.index,\n\t\t\t\t\t\t\t\t\t\t\t dtype='int32')\n\tcols = list(df_item_age_uid.columns.values)\n\tcols_change = cols[:-3]\n\tcols_change.extend(['age_group', 'age', 'uid'])\n\tdf_item_ageGroup_uid = df_item_age_uid[cols_change]\n\tage_group_dict, group_age_dict = age_group_initiate_movieLens(age_list)\n\tupdate_age_group(df_item_ageGroup_uid, age_group_dict)\n\trandom.seed(32)\n\tdf_cluster = funcs.Kmeans_clustering(df_item_ageGroup_uid, cluster_num, -3)\n\n\tfor beta in beta_list:\n\t\tfor l_threshold in l_threshold_list:\n\t\t\twith open(\"l_beta_temp\", 'a') as file_out:\n\t\t\t\tfile_out.write(\"deltaX: {}, cluster num: {}, l_threshold: {}, beta: {}, time: {}\\n\".format(deltaX, cluster_num, l_threshold, beta, datetime.datetime.now()))\n\n\t\t\twith open(\"k_alpha_result\", 'a') as file_out_overall:\n\t\t\t\tfile_out_overall.write(\"deltaX: {}, cluster num: {}, l_threshold: {}, beta: {}, time: {}\\n\".format(deltaX, cluster_num, l_threshold, beta, datetime.datetime.now()))\n\n\t\t\tresults = {}\n\t\t\tresults['ori_age_rf'] = []\n\t\t\tresults['obf_age_rf'] = []\n\t\t\tresults['ori_rec'] = []\n\t\t\tresults['obf_rec'] = []\n\n\t\t\tfor r in available_seeds:\n\t\t\t\ttry:\n\t\t\t\t\tage_group_dict, group_age_dict = age_group_initiate_movieLens(age_list)\n\t\t\t\t\trandom.seed(r * 10)\n\n\t\t\t\t\titems = list(df_item_age_uid)\n\t\t\t\t\titems.remove('age')\n\t\t\t\t\titems.remove('age_group')\n\t\t\t\t\titems.remove('uid')\n\t\t\t\t\trandom.shuffle(items)\n\t\t\t\t\titems_train = items[:int(len(items) * 0.8)]\n\t\t\t\t\titems_test = list(set(items) - set(items_train))\n\t\t\t\t\tdf_train_items = df_cluster.drop(items_test, axis=1)\n\t\t\t\t\tdf_test_items = df_cluster.drop(items_train, axis=1)\n\n\t\t\t\t\ttrain_idx_list = []\n\t\t\t\t\ttest_idx_list = []\n\t\t\t\t\tprint(\"run seed {}...\".format(r))\n\t\t\t\t\tfor i in range(cluster_num):\n\t\t\t\t\t\tdf_c = df_train_items.loc[df_train_items['cluster'] == i + 1]\n\t\t\t\t\t\tdf_c_train = df_c.sample(frac=0.5, random_state=r * 10)\n\t\t\t\t\t\tdf_c_test = df_c.drop(df_c_train.index)\n\n\t\t\t\t\t\ttrain_idx_list.extend(list(df_c_train.index))\n\t\t\t\t\t\ttest_idx_list.extend(list(df_c_test.index))\n\n\t\t\t\t\tdf_train = df_train_items.loc[train_idx_list]\n\t\t\t\t\tdf_test = df_train_items.loc[test_idx_list]\n\t\t\t\t\tdf_train = df_train.reset_index(drop=True)\n\t\t\t\t\tdf_test = df_test.reset_index(drop=True)\n\n\t\t\t\t\tdf_test_rec_items = df_test_items.loc[test_idx_list]\n\t\t\t\t\tdf_test_rec_items = df_test_rec_items.reset_index(drop=True)\n\n\t\t\t\t\tprint(\"all users num: {}\".format(len(df_item_ageGroup_uid)))\n\t\t\t\t\tprint(\"split train and test over\")\n\t\t\t\t\tprint(\"train num {}\".format(len(df_train)))\n\t\t\t\t\tprint(\"test num {}\".format(len(df_test)))\n\t\t\t\t\tprint(\"train items {}\".format(df_train_items.shape[1]))\n\t\t\t\t\tprint(\"test items {}\".format(df_test_items.shape[1]))\n\n\t\t\t\t\tdf_test_copy = copy.deepcopy(df_test)\n\t\t\t\t\tdf_test_copy['age_group'] = pd.Series(np.zeros(df_test_copy.shape[0]), index=df_test_copy.index,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t dtype='int32')\n\t\t\t\t\txpgg = np.ones((cluster_num * age_group_number, cluster_num * age_group_number)) * 0.00000001\n\t\t\t\t\tJSD_Mat = np.ones((cluster_num * age_group_number, cluster_num * age_group_number))\n\t\t\t\t\tpgy = np.ones((len(age_list), cluster_num * age_group_number)) * 0.00000001\n\t\t\t\t\tgroup_min_age_dict = {}\n\t\t\t\t\tgroup_usersize_dict = {}\n\t\t\t\t\tmin_distortion_budget = 0\n\n\t\t\t\t\tfor op in range(0, 5):\n\t\t\t\t\t\tage_xpgg_dict = {}\n\t\t\t\t\t\t###### Compute JSD, pgy, xpgg\n\t\t\t\t\t\tJSD_Mat_dict = {}\n\t\t\t\t\t\tpgy_dict = {}\n\n\t\t\t\t\t\tfor ag in range(age_group_number):\n\t\t\t\t\t\t\tgroup_min_age_dict[ag] = group_age_dict[ag][0]\n\t\t\t\t\t\t\tprint(group_min_age_dict[ag])\n\t\t\t\t\t\t\tdf_test_ag = df_test.loc[df_test['age_group'] == ag]\n\t\t\t\t\t\t\tage_list_ag = group_age_dict[ag]\n\t\t\t\t\t\t\tgroup_usersize_dict[ag] = df_test_ag.shape[0]\n\n\t\t\t\t\t\t\tJSD_Mat_dict[ag] = funcs.cal_JSD_Matrix_withoutAgeGroup(df_test_ag, cluster_num, 4)\n\t\t\t\t\t\t\tprint(ag, cluster_num, age_list_ag)\n\t\t\t\t\t\t\tpgy_dict[ag] = funcs.cal_pgy_withoutAgeGroup(df_test_ag, cluster_num, age_list_ag)\n\t\t\t\t\t\t\tpd.DataFrame(JSD_Mat_dict[ag]).to_csv('tmp/JSDM_ageGroup_hyobscure.csv', index=False, header=None)\n\t\t\t\t\t\t\tpd.DataFrame(pgy_dict[ag]).to_csv('tmp/pgy_ageGroup_hyobscure.csv', index=False, header=None)\n\n\t\t\t\t\t\t\teng = matlab.engine.start_matlab()\n\t\t\t\t\t\t\teng.edit('../../matlab/age_k&l_scenario_I/HyObscure', nargout=0)\n\t\t\t\t\t\t\teng.cd('../../matlab/age_k&l_scenario_I', nargout=0)\n\t\t\t\t\t\t\tage_xpgg_dict[ag], distortion_budget = np.array(eng.HyObscure(deltaX, nargout=2))\n\t\t\t\t\t\t\tage_xpgg_dict[ag] = np.array(age_xpgg_dict[ag])\n\n\t\t\t\t\t\t\tif np.isnan(distortion_budget):\n\t\t\t\t\t\t\t\traise ValueError\n\n\t\t\t\t\t\tfor ag in range(age_group_number):\n\t\t\t\t\t\t\tfor age in group_age_dict[ag]:\n\t\t\t\t\t\t\t\tfor col in range(cluster_num):\n\t\t\t\t\t\t\t\t\tpgy[age - group_min_age_dict[0], ag + col * age_group_number] = pgy_dict[ag][age -\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t group_min_age_dict[\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t ag], col] * \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tgroup_usersize_dict[\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tag] / \\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tdf_test.shape[0]\n\n\t\t\t\t\t\tfor ag in range(age_group_number):\n\t\t\t\t\t\t\tfor row in range(cluster_num):\n\t\t\t\t\t\t\t\tfor col in range(cluster_num):\n\t\t\t\t\t\t\t\t\txpgg[ag + row * age_group_number, ag + col * age_group_number] = age_xpgg_dict[ag][\n\t\t\t\t\t\t\t\t\t\trow, col]\n\t\t\t\t\t\t\t\t\tJSD_Mat[ag + row * age_group_number, ag + col * age_group_number] = JSD_Mat_dict[ag][\n\t\t\t\t\t\t\t\t\t\trow, col]\n\n\t\t\t\t\t\tpd.DataFrame(xpgg).to_csv('xpgg.csv', index=False, header=None)\n\t\t\t\t\t\tpd.DataFrame(pgy).to_csv('pgy_full.csv', index=False, header=None)\n\t\t\t\t\t\tpd.DataFrame(JSD_Mat).to_csv('JSD_full.csv', index=False, header=None)\n\n\t\t\t\t\t\tmin_JSD_Mat = JSD_Mat\n\t\t\t\t\t\tmin_pgy = pgy\n\t\t\t\t\t\t### change age group by greedy approach\n\t\t\t\t\t\tmean_Utility = funcs.Mean_JSD(JSD_Mat, xpgg)\n\t\t\t\t\t\tmean_Privacy = funcs.Mean_KL_div(pgy, xpgg)\n\t\t\t\t\t\tmin_mean_Utility = mean_Utility\n\t\t\t\t\t\tmin_mean_Privacy = mean_Privacy\n\n\t\t\t\t\t\tadjustable_groups, reducible_groups = age_group_adjust_greedy(df_item_age_uid, group_age_dict,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t k_threshold, np.log(l_threshold), beta, alpha)\n\t\t\t\t\t\tmin_group = 0\n\t\t\t\t\t\tfor i in adjustable_groups:\n\t\t\t\t\t\t\tage_group_dict_cur = {}\n\t\t\t\t\t\t\tfor group, group_age_list in adjustable_groups[i].items():\n\t\t\t\t\t\t\t\tfor age in group_age_list:\n\t\t\t\t\t\t\t\t\tage_group_dict_cur[age] = group\n\n\t\t\t\t\t\t\tdf_test_new = update_age_group(df_test, age_group_dict_cur)\n\t\t\t\t\t\t\tnew_JSD_Mat = funcs.cal_JSD_Matrix_withAgeGroup(df_test_new, cluster_num, age_group_number, 4)\n\t\t\t\t\t\t\tnew_pgy = funcs.cal_pgy_withAgeGroup(df_test_new, cluster_num, age_group_number, age_list)\n\t\t\t\t\t\t\tnew_mean_Utility = funcs.Mean_JSD(new_JSD_Mat, xpgg)\n\t\t\t\t\t\t\tnew_mean_Privacy = funcs.Mean_KL_div(new_pgy, xpgg)\n\t\t\t\t\t\t\tif new_mean_Utility < min_mean_Utility and new_mean_Privacy < min_mean_Privacy:\n\t\t\t\t\t\t\t\tmin_mean_Utility = new_mean_Utility\n\t\t\t\t\t\t\t\tmin_mean_Privacy = new_mean_Privacy\n\t\t\t\t\t\t\t\tmin_group_age_dict = copy.deepcopy(adjustable_groups[i])\n\t\t\t\t\t\t\t\tmin_age_group_dict = copy.deepcopy(age_group_dict_cur)\n\t\t\t\t\t\t\t\tmin_JSD_Mat = new_JSD_Mat\n\t\t\t\t\t\t\t\tmin_pgy = new_pgy\n\t\t\t\t\t\t\t\tmin_group = i\n\t\t\t\t\t\t\tprint(op, i, min_group, mean_Privacy, mean_Utility, min_mean_Privacy, min_mean_Utility,\n\t\t\t\t\t\t\t\t new_mean_Privacy, new_mean_Utility)\n\n\t\t\t\t\t\tif min_mean_Privacy < mean_Privacy and min_mean_Utility < mean_Utility:\n\t\t\t\t\t\t\tprint(\"find a better age group:\", group_age_dict)\n\t\t\t\t\t\t\tage_group_dict = min_age_group_dict\n\t\t\t\t\t\t\tgroup_age_dict = min_group_age_dict\n\t\t\t\t\t\t\tdf_test = update_age_group(df_test, age_group_dict)\n\t\t\t\t\t\t\tmin_distortion_budget = min_mean_Utility\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\tuser_num = df_test_copy.shape[0]\n\t\t\t\t\tX_ori = {}\n\t\t\t\t\tfor k in range(user_num):\n\t\t\t\t\t\tuser_id = df_test_copy['uid'][k]\n\t\t\t\t\t\tX_ori[user_id] = df_test_copy[df_test_copy['uid'] == user_id].values[0, :-1]\n\t\t\t\t\tfor k in X_ori.keys():\n\t\t\t\t\t\tuser_age = X_ori[k][-2]\n\t\t\t\t\t\tX_ori[k][-3] = age_group_dict[user_age]\n\n\t\t\t\t\tdf_test = update_age_group(df_test, age_group_dict)\n\t\t\t\t\tdf_train = update_age_group(df_train, age_group_dict)\n\t\t\t\t\tdf_test_rec_items = update_age_group(df_test_rec_items, age_group_dict)\n\t\t\t\t\tmodel = funcs.train_rf_model(df_train)\n\t\t\t\t\t# xgboost\n\t\t\t\t\t# model = funcs.train_xgb_model(df_train)\n\t\t\t\t\tprint(\"model train over, start obfuscating...\")\n\n\t\t\t\t\tX_obf_dict = {}\n\n\t\t\t\t\tfor i in range(25):\n\t\t\t\t\t\tX_obf_dict[i], _ = get_obf_X(df_test, xpgg)\n\n\t\t\t\t\tmae_oris = []\n\t\t\t\t\tmae_obfs = []\n\n\t\t\t\t\tfor i in range(25):\n\n\t\t\t\t\t\tdf_X_obf = pd.DataFrame.from_dict(X_obf_dict[i]).T\n\t\t\t\t\t\tdf_x_obf_items = df_X_obf.values\n\t\t\t\t\t\tdf_X_ori = pd.DataFrame.from_dict(X_ori).T\n\t\t\t\t\t\tdf_x_ori_items = df_X_ori.values[:, :-2]\n\t\t\t\t\t\tdf_x_y = df_X_ori.values[:, -2]\n\t\t\t\t\t\ty_pred_ori = model.predict(df_x_ori_items)\n\t\t\t\t\t\ty_pred_obf = model.predict(df_x_obf_items)\n\n\t\t\t\t\t\tmae_ori = mean_absolute_error(df_x_y, y_pred_ori)\n\t\t\t\t\t\tmae_obf = mean_absolute_error(df_x_y, y_pred_obf)\n\n\t\t\t\t\t\tmae_oris.append(mae_ori)\n\t\t\t\t\t\tmae_obfs.append(mae_obf)\n\n\t\t\t\t\t# test on obfuscated data and original data\n\n\t\t\t\t\tmae_ori = np.mean(mae_oris)\n\t\t\t\t\tmae_obf = np.mean(mae_obfs)\n\n\t\t\t\t\tresults['ori_age_rf'].append(mae_ori)\n\t\t\t\t\tresults['obf_age_rf'].append(mae_obf)\n\n\n\t\t\t\t\twith open(\"l_beta_temp\", 'a') as file_out:\n\t\t\t\t\t\tfile_out.write(\"%s\\t%s\\t%s\\n\" % (r * 10, mae_ori, mae_obf))\n\t\t\t\t\t\tfile_out.flush()\n\n\t\t\t\texcept ValueError:\n\t\t\t\t\tprint(\"distortion budget error\")\n\n\t\t\tavg_mae_ori_rf = np.mean(np.array(results['ori_age_rf']))\n\t\t\tavg_mae_obf_rf = np.mean(np.array(results['obf_age_rf']))\n\n\t\t\twith open(\"l_beta_result\", 'a') as file_out_overall:\n\t\t\t\tfile_out_overall.write(\n\t\t\t\t\t\"%s\\t%s\\t%s\\t%s\\n\" % (cluster_num, deltaX,avg_mae_ori_rf, avg_mae_obf_rf))\n\t\t\t\tfile_out_overall.flush()\n","sub_path":"code/python/age_l&beta/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"80020642","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import interp\nfrom sklearn.metrics import auc, roc_curve\nimport pandas as pd\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\n\nLW = 2\nRANDOM_STATE = 42\nrepeater=1\nrangeToTest=60000\n\nclass DummySampler(object):\n\n def sample(self, X, y):\n return X, y\n\n def fit(self, X, y):\n return self\n\n def fit_sample(self, X, y):\n return self.sample(X, y)\n\n# Load the dataset\ndftraining = pd.read_csv(\"all_mean_in_class_training.csv\")\ndftraining = pd.get_dummies(dftraining, columns=['class'])\ndftraining = dftraining.drop(['Unnamed: 0','class_neg'], axis=1)\n\ndftest = pd.read_csv(\"all_mean_in_class_test.csv\")\ndftest = pd.get_dummies(dftest, columns=['class'])\ndftest = dftest.drop(['Unnamed: 0','class_neg'], axis=1)\n\nXtraining = dftraining.drop(['class_pos'], axis = 1)\nYtraining = dftraining['class_pos']\n\nXtesting = dftest.drop(['class_pos'], axis = 1)\nYtesting = dftest['class_pos']\n\n\nXtraining,ytraining = Xtraining.values, Ytraining.values\n\nXtesting, ytesting = Xtesting.values,Ytesting.values\n\nXtraining = StandardScaler().fit_transform(Xtraining)\nXtesting = StandardScaler().fit_transform(Xtesting)\n\nclassifiers= [['3NN', KNeighborsClassifier(3)]]\n\nvalues = np.logspace(1,9,dtype='int')[10:12]\nfor i in values:\n classifier =[]\n string = '{}NN'.format(i)\n classifier.append(string)\n classifier.append(KNeighborsClassifier(n_neighbors=i))\n classifiers.append(classifier)\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\n\nAllmean_tpr = dict()\nfor classifier in classifiers:\n Allmean_tpr[classifier[0]]=0.0\nAllmean_fpr = np.linspace(0, 1, 100)\nfor i in range(0,repeater):\n for classifier in classifiers:\n mean_tpr = 0.0\n mean_fpr = np.linspace(0, 1, 100)\n Xtrainer, Ytrainer = SMOTE(ratio=1).fit_sample(Xtraining, ytraining)\n probas_ = classifier[1].fit(Xtrainer, Ytrainer).predict_proba(Xtesting)\n fpr, tpr, thresholds = roc_curve(ytesting, probas_[:, 1])\n mean_tpr = interp(mean_fpr, fpr, tpr)\n mean_tpr[0] = 0.0\n roc_auc = auc(fpr, tpr) \n mean_tpr[-1] = 1.0\n Allmean_tpr[classifier[0]]+=mean_tpr\n \nfor classifier in classifiers: \n Allmean_tpr[classifier[0]] /= repeater\n Allmean_auc = auc(Allmean_fpr, Allmean_tpr[classifier[0]])\n plt.plot(Allmean_fpr, Allmean_tpr[classifier[0]], linestyle='--',\n label=f'{classifier[0]} (area = %0.2f)'.format(classifier[0]) % Allmean_auc, lw=LW)\n \nplt.plot([0, 1], [0, 1], linestyle='--', lw=LW, color='k',\n label='Luck')\n\n# make nice plotting\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.get_xaxis().tick_bottom()\nax.get_yaxis().tick_left()\nax.spines['left'].set_position(('outward', 10))\nax.spines['bottom'].set_position(('outward', 10))\nplt.xlim([0, 1])\nplt.ylim([0, 1])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Com SMOTE')\n\nplt.legend(loc=\"lower right\")\n\nplt.show()\n","sub_path":"d1/KNNKvariationwithSMOTE.py","file_name":"KNNKvariationwithSMOTE.py","file_ext":"py","file_size_in_byte":3088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"48188152","text":"\n#--------------------------------------------\n# 2017.03.22\n# 2012180005 김건우\n#--------------------------------------------\n\n'''\n#--------------------------------------------\n# 3 - 06\n#--------------------------------------------\n\n#print('\\n\\n\\n\\n')\nprint(\"Task 3-06\")\n\nASCII = eval( input( \"ASCII 코드를 입력하세요 : \" ) )\n\ndef ASCII_To_Char() :\n global ASCII , Result\n print( chr( ASCII ) )\n\nASCII_To_Char()\n\n#print('\\n\\n\\n\\n')\n\n'''\n'''\n#--------------------------------------------\n# 3 - 07\n#--------------------------------------------\n\n#print('\\n\\n\\n\\n')\nprint(\"Task 3-07\")\n\ndef Random() :\n import time\n ASCII = int( time.time() )\n Char = chr( ( ASCII % 26 ) + ord( 'A' ))\n print( Char )\n\nRandom()\n \n\n'''\n'''\n#--------------------------------------------\n# 3 - 08\n#--------------------------------------------\n\nprint('\\n\\n\\n\\n')\nprint(\"Task 3-08\")\n\ndef Management( ) :\n Name = str( input( \"사원의 이름을 입력해주세요 : \" ) )\n TPW = int( input( \"주당 근무 시간을 입력하세요 : \" ) )\n Pay = int( input( \"시간당 급여를 입력하세요 : \" ) )\n WTR = float( input( \"원천징수세율을 입력하세요 : \" ) )\n LTR = float( input( \"지방 세율을 입력하세요 : \" ) )\n \n TotalPay = TPW * Pay\n WT = int( TotalPay * WTR )\n LT = int( TotalPay * LTR )\n\n print(\"\\n\\n\")\n \n print( \"사원 이름 : \" , Name , sep = '' )\n print( \"주당 근무 시간 : \" , TPW , sep = '')\n print( \"임금 : \" , Pay , sep = '' )\n print( \"총 급여 : \" , TotalPay , sep = '' )\n \n print( \"공제 : \" )\n print( \" 원천 징수세 (\" , WTR * 100 , \"%) : \" , WT , sep = '' )\n print( \" 주민세 (\" , LTR * 100 , \"%) : \" , LT , sep = '' )\n\n print( \" 총 공제 : \" , WT + LT , sep = '' )\n print( \"공제 후 급여 : \" , TotalPay - WT - LT , sep = '' )\n \nManagement()\n\nprint('\\n\\n\\n\\n')\n'''\n\n'''\n#--------------------------------------------\n# 10 - 2\n#--------------------------------------------\n\nprint('\\n\\n\\n\\n')\nprint(\"Task 10-02\")\n\ndef Reverse_Input( L_List ) :\n \n i = input( \"정수들을 적어 주세요 : \" ).split()\n\n L_List = [ eval(i) for i in s.split() ]\n\n L_List.sort()\n L_List.reverse()\n\n return L_List\n\nG_List = []\n\nReverse_Input( G_List )\n\nprint( \"역순 정렬 결과 : \", G_List )\n\nprint('\\n\\n\\n\\n')\n\n\n'''\n\n#--------------------------------------------\n# 10 - 3\n#--------------------------------------------\n\nprint('\\n\\n\\n\\n')\nprint(\"Task 10-03\")\n\ndef Reverse_Input( L_Dic ) :\n\n L_List = []\n L_List = input( \"정수들을 적어 주세요 : \" ).split()\n \n for Ln in L_List :\n if Ln in L_Dic.keys() :\n L_Dic[ Ln ] += 1\n\n else :\n L_Dic[ Ln ] = 1\n \n print( L_Dic )\n\n return L_Dic\n\nG_Dic = {}\n\nG_Dic = Reverse_Input( G_Dic )\n\nfor Dc , Dv in G_Dic.items() :\n print( Dc , \"-\" , Dv , \"번 나타납니다.\")\n\nprint('\\n\\n\\n\\n')\n\n'''\n#--------------------------------------------\n# 10 - 4\n#--------------------------------------------\n\nprint('\\n\\n\\n\\n')\nprint(\"Task 10-04\")\n\ndef ScoreAverage( List ) :\n Size = 0\n Total = 0\n \n for Count in List :\n Size += 1\n Total += Count \n \n return Total / Size\n\ndef ScoreJudgement( List , TotalAverage ) :\n L_Dic = { \"Up\" : [] , \"Down\" : [] , \"Avg\" : [] }\n\n for Score in List :\n if Score > TotalAverage :\n L_Dic[ \"Up\" ].append( Score )\n \n elif Score < TotalAverage :\n L_Dic[ \"Down\" ].append( Score )\n \n else :\n L_Dic[ \"Avg\" ].append( Score )\n\n return L_Dic\n\ntmp = []\nScoreList_Global = []\n\ntmp = input( \"정수를 입력하세요 : \" ).split()\n\nfor i in tmp :\n ScoreList_Global.append( int( i ) )\n\nAverage = ScoreAverage( ScoreList_Global )\nScoreList_Global.sort()\nScoreDic = ScoreJudgement( ScoreList_Global , Average )\n\nprint( \"입력 원소 : \" , ScoreList_Global )\nprint( \"평균 :\" , Average )\n\nprint( \"평균 이상 원소 : \", end = '' )\n\nfor U in ScoreDic[ \"Up\" ] :\n print( U , end = ' ' )\nprint( '\\n' )\n\nprint( \"평균 이하 원소 : \", end = '' )\n\nfor D in ScoreDic[ \"Down\" ] :\n print( D , end = ' ' )\nprint( '\\n' )\n\nprint( \"평균 원소 : \", end = '' )\n\nfor A in ScoreDic[ \"Avg\" ] :\n print( A , end = ' ' )\nprint( '\\n' )\n\n'''\n'''\n#--------------------------------------------\n# 10 - 5\n#--------------------------------------------\n\nprint('\\n\\n\\n\\n')\nprint(\"Task 10-05\")\n\ndef ListJudgement( List ) :\n tmp_List = []\n\n for Value in List :\n if Value not in tmp_List :\n tmp_List.append( Value )\n \n return tmp_List\n\ntmp = []\nEle_List = []\n\ntmp = input( \"정수를 입력하세요 : \" ).split()\n\nfor i in tmp :\n Ele_List.append( int( i ) )\n\nprint( \"입력 하신 정수 목록 : \" , Ele_List )\n\nEle_List = ListJudgement( Ele_List )\n\nprint( \"중복을 제외한 정수 목록 : \" , Ele_List )\n\n'''\n","sub_path":"Task/Task04.py","file_name":"Task04.py","file_ext":"py","file_size_in_byte":5081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"251551169","text":"\"\"\"// Context: You are given requirements for a utility function that needs\n to be written in C++. It has the following function signature:\n//\n// uint64_t countNestedParentheses(const std::string& str);\n//\n// The requirements/behavior of the function can be described as:\n//\n// Given an arbitrary string of characters, count the maximum level of nested parentheses in the string. Examples:\n//\n// 0: ' '\n// 1: ( )\n// 1: ( ) )\n// 2: ( 2 + ( 3 * 4 ) )\n// 3: ( ( ( 2 * 2 ) + 1 ) / 8 ) ( )\n//\n// Tasks:\n// 1. Define a complete list of tests that need to be written in order to test this function. Just a set of names and descriptions will do.\n// 2. Implement at least 2 of these tests.\n// 3. Implement the function.\n\"\"\"\n\n#tests\n# no characters, null values, and a empty string should be tested, and either return error values or 0.\n# '' ----> 0\n# null --> 0\n# no input --> 0 or Error\n\n# () ----> 1\n# )( ----> 0\n# )()(---> 1\n# ()) ---> 1\n# ((() ---> 1\n#()))\n\n# (2 + (3*4)) ----> 2\n# (((2*2) + 1) / 8) () ---> 3\n# hello[][{}] ---> 0\n\n\n#One way to do this is with recursion, and to get the maximum depth of the thing\n# I could also loop through the characters of the stack. If the stack is empty then don't push a closing paren on\n# If I come across a open paren, push it onto the stack.\n# keep track of the 'max depth' of the stack.\n\ndef match_parens(s):\n\n max_depth = 0\n current_open_parens = 0\n for char in s:\n if char == '(':\n current_open_parens +=1\n #I'd like a new name for max_depth\n max_depth = max(current_open_parens, max_depth)\n elif char == ')' and current_open_parens > 0:\n current_open_parens -=1\n\n max_depth = max_depth - current_open_parens\n return max_depth\n\nprint(match_parens('()'))\nprint(match_parens(')('))\nprint(match_parens('(((2*2)+1)/8)()'))\nprint(match_parens('(()2*2)+1)/8)()'))\nprint(match_parens('((()'))","sub_path":"coding-challenges/Blue_origin_matching_parentheses.py","file_name":"Blue_origin_matching_parentheses.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"623280811","text":"#!/usr/bin/env python3\n\nimport sys\nif len(sys.argv) < 2:\n print(\"Usage: python3 {} {} \".format(sys.argv[0], \"*.5evidence.xls\"))\n exit()\n\n\ndef get_pattern(hap1, hap2):\n code = {'-': 0, 'A': 2, 'T': 3, 'G': 5, 'C': 7}\n return code[hap1] * code[hap2]\n\n\n\ndef call_haplotype(base_dis, ty=None):\n bases = {'A': int(base_dis[0]),\n 'T': int(base_dis[1]),\n 'G': int(base_dis[2]),\n 'C': int(base_dis[3])}\n pi = float(base_dis[4])\n sorted_bases = sorted(bases, key=lambda k: bases[k], reverse=True)\n hap1 = sorted_bases[0]\n hap2 = sorted_bases[1]\n hap3 = sorted_bases[2]\n gt = {}\n if pi == 0:\n ##this is a homozygous site, bases[hap2] == 0\n return (hap1, bases[hap1], hap1, bases[hap1])\n elif ty == 'tenx':\n if pi <= 0.15: # this is a homozygous pattern\n if bases[hap2] >= 5 and bases[hap1] / bases[hap2] < 5:\n return False\n elif bases[hap2] >= 20:\n return (hap1, bases[hap1], hap2, bases[hap2])\n else:\n return (hap1, bases[hap1], hap1, bases[hap1]) #homozygous\n elif pi >= 0.4 and bases[hap3] >= 5:\n return False # what a mass!\n else:\n ## this is a heterozgyous pattern\n if bases[hap2] <= 3:\n return False\n else:\n return (hap1, bases[hap1], hap2, bases[hap2])\n else:\n return (hap1, bases[hap1], hap2, bases[hap2])\n\n\ndef which_wrong(tenx1, tenx2, mat, pat):\n # mat == pat\n if mat == pat:\n if mat == tenx1:\n return \"eithor\", tenx2\n elif mat == tenx2:\n return \"eithor\", tenx1\n else:\n return \"both\"\n else:\n if mat == tenx1 and pat != tenx2:\n return \"pat\", tenx2\n elif mat == tenx2 and pat != tenx1:\n return \"pat\", tenx1\n elif pat == tenx1 and mat != tenx2:\n return \"mat\", tenx2\n elif pat == tenx2 and mat != tenx1:\n return \"mat\", tenx1\n else:\n return 'both'\n\n\ndef backtracing(assembly_assumed, assembly, corrected, raw):\n cor_hap1, base_cor_hap1, cor_hap2, base_cor_hap2 = corrected\n raw_hap1, base_raw_hap1, raw_hap2, base_raw_hap2 = raw\n if assembly_assumed == assembly:\n \"\"\"\n if assembly == cor_hap1:\n if assembly == raw_hap1:\n return \"nothing\"\n else:\n return \"correcting_nice\"\n else:\n if assembly == raw_hap1:\n return \"polishing_nice\"\n else:\n if cor_hap1 == raw_hap1:\n return \"polishing_nice\"\n else:\n return \"other\"\n \"\"\"\n return \"nothing\"\n else:\n if assembly == cor_hap1:\n if cor_hap2 == assembly_assumed and base_cor_hap2 >= 5:\n return \"assigning_error\"\n else:\n # chain: assembly -> cor_hap1 -> raw_hap1\n return \"sequencing_error\" # error from original\n else:\n # chain: assembly ->x cor_hap1\n if cor_hap1 == assembly_assumed:\n if cor_hap2 == assembly:\n return \"assigning_error\"\n else:\n return \"polishing_error\"\n elif cor_hap2 == assembly_assumed and base_cor_hap2 >= 5:\n return \"assigning_error\"\n else:\n if cor_hap1 == raw_hap1 or cor_hap1 == raw_hap2:\n return \"sequencing_error\"\n else:\n return \"complex_error\"\n\n\n\nclass Record():\n def __init__(self, record):\n arr = record.strip().split(\"\\t\")\n self.pos = arr[1]\n self.matref = arr[2]\n self.patref = arr[4]\n self.mummer = arr[5]\n self.gatk = arr[6]\n self.note1 = arr[8]\n self.note2 = arr[9]\n self.tenx = arr[13:18]\n self.matCor = arr[21:26]\n self.matRaw = arr[29:34]\n self.patCor = arr[37:42]\n self.patRaw = arr[45:50]\n self.matcpos = arr[19]\n self.matrpos = arr[27]\n self.patcpos = arr[35]\n self.patrpos = arr[43]\n if arr[25] != \"-\" and arr[33] != \"-\" and arr[41] != \"-\" and arr[49] != \"-\":\n self.matpi = float(arr[25]) + float(arr[33])\n self.patpi = float(arr[41]) + float(arr[49])\n\n def get_tenx_info(self):\n return call_haplotype(self.tenx, ty='tenx')\n\n def get_matCor_info(self):\n return call_haplotype(self.matCor)\n\n def get_matRaw_info(self):\n return call_haplotype(self.matRaw)\n\n def get_patCor_info(self):\n return call_haplotype(self.patCor)\n\n def get_patRaw_info(self):\n return call_haplotype(self.patRaw)\n\n\n\ndef main():\n\n tag = open(sys.argv[1] + \".tag\", 'w')\n with open(sys.argv[1], 'r') as fh:\n\n\n for i in fh:\n i = i.strip()\n if i.startswith(\"#\"):\n tag.write(i + \"\\tINFO\\tSNP\\n\")\n continue\n SNP = Record(i)\n \n if SNP.note1 == \"GR\" or SNP.note2 == \"LOW\":\n tag.write(i + \"\\thard2id\\t-\\n\")\n continue\n\n\n # case 3, this site is located in grey region (GR) which is not on the\n # alignment of maternal/paternal genome, and 10x mapping in this site has\n # a low depth (<10), so it is hard to identity\n \n \"\"\"\n if SNP.note2 == \"LOW\":\n # just see maternal evidence chain and paternal evidence, if both good\n if SNP.matrpos == \"-\" or SNP.matcpos == \"-\" or SNP.patcpos == \"-\" or SNP.patrpos == \"-\":\n tag.write(i + \"\\t\" + \"no_pacbio_read\\t-\\n\")\n continue\n error_type_mat = backtracing(SNP.matref, SNP.matref, SNP.get_matCor_info(), SNP.get_matRaw_info())\n error_type_pat = backtracing(SNP.patref, SNP.patref, SNP.get_patCor_info(), SNP.get_patRaw_info())\n if 'error' in error_type_mat and 'error' not in error_type_pat:\n error_type = error_type_mat + \"_mat\" + \"-\" + \"nothing_pat\"\n elif 'error' in error_type_pat and 'error' not in error_type_mat:\n error_type = \"nothing_mat\" + \"-\" + error_type_pat + \"pat\"\n else:\n error_type = error_type_mat + \"_mat\" + \"-\" + error_type_pat + \"_pat\"\n\n if SNP.matref == SNP.patref:\n tag.write(i + \"\\t\" + error_type + \"\\t\" + \"False\\n\")\n else:\n tag.write(i + \"\\t\" + error_type + \"\\t\" + \"True\\n\")\n continue\n \"\"\"\n # case 4, \n if SNP.get_tenx_info() == False:\n tag.write(i + \"\\thard2id\\t-\\n\")\n continue\n else:\n tenx_hap1, n1, tenx_hap2, n2 = SNP.get_tenx_info()\n\n\n # case 5, \n \"\"\"\n if SNP.note1 == \"GR\":\n # no paternal pacbio mapping result, so juct check maternal\n # backtracing(maternal) == 'nothing' and SNP.matref in [tenx1, tenx2]\n if SNP.matrpos == \"-\" or SNP.matcpos == \"-\":\n tag.write(i + \"\\t\" + \"no_pacbio_read\\t-\\n\")\n continue\n\n if SNP.matref in [tenx_hap1, tenx_hap2]:\n error_type_mat = backtracing(SNP.matref, SNP.matref, SNP.get_matCor_info(), SNP.get_matRaw_info())\n error_type = error_type_mat + \"_mat\"\n else:\n error_type = \"sequencing_error_mat\"\n if tenx_hap1 == tenx_hap2:\n tag.write(i + \"\\t\" + error_type + \"\\t\" + \"False\\n\")\n else:\n tag.write(i + \"\\t\" + error_type + \"\\t\" + \"True\\n\")\n continue\n \"\"\"\n\n \n if SNP.patref == SNP.gatk and SNP.mummer == \"-\" and tenx_hap1 != tenx_hap2:\n tag.write(i + \"\\tmummer_false_negative\\tTrue\\n\")\n continue\n \n\n assembled_haplotypes = {SNP.matref, SNP.patref}\n tenx_haplotypes = {tenx_hap1, tenx_hap2}\n if assembled_haplotypes == tenx_haplotypes:\n tag.write(i + \"\\tNo_doubt\\tTrue\\n\")\n continue\n\n \"\"\"\n this an evidence chain to check which step error occur.\n 10x pattern[h1,h2]\n ||\n maternal assembly pattern paternal\n / \\\n maternal corrected[h1,h2] paternal corrected[h1,h2]\n / \\\n maternal raw[h1,h2] paternal raw[h1,h2]\n \"\"\"\n # the assemblied haplotypes are not consistent with 10x haplotypes\n\n if which_wrong(tenx_hap1, tenx_hap2, SNP.matref, SNP.patref) == 'both':\n error_type = \"terrible_error_both\"\n else:\n # case 6, \n if SNP.matrpos == \"-\" or SNP.matcpos == \"-\" or SNP.patcpos == \"-\" or SNP.patrpos == \"-\":\n tag.write(i + \"\\t\" + \"hard2id\\t-\\n\")\n continue\n\n who, shoulde_be = which_wrong(tenx_hap1, tenx_hap2, SNP.matref, SNP.patref)\n\n if who == 'mat':\n # error occur in mat\n error_type = backtracing(shoulde_be, SNP.matref, SNP.get_matCor_info(), SNP.get_matRaw_info())\n error_type += \"_mat\"\n elif who == 'pat':\n error_type = backtracing(shoulde_be, SNP.patref, SNP.get_patCor_info(), SNP.get_patRaw_info())\n error_type += \"_pat\"\n else:\n # eithor mat wrong or pat wrong, this is very complicated, you need check both\n # of them, then determin which one is more likely wrong.\n\n error_type_mat1 = backtracing(shoulde_be, SNP.matref, SNP.get_matCor_info(), SNP.get_matRaw_info())\n error_type_pat1 = backtracing(SNP.patref, SNP.patref, SNP.get_patCor_info(), SNP.get_patRaw_info())\n\n error_type_mat2 = backtracing(SNP.matref, SNP.matref, SNP.get_matCor_info(), SNP.get_matRaw_info())\n error_type_pat2 = backtracing(shoulde_be, SNP.patref, SNP.get_patCor_info(), SNP.get_patRaw_info())\n\n\n if 'error' in error_type_mat1 and 'error' not in error_type_pat1:\n error_type_mat = backtracing(shoulde_be, SNP.matref,\n SNP.get_matCor_info(),\n SNP.get_matRaw_info())\n error_type = error_type_mat + \"_mat\" + \"-\" + \"nothing_pat\"\n elif 'error' not in error_type_mat2 and 'error' in error_type_pat2:\n error_type_pat = backtracing(shoulde_be, SNP.patref,\n SNP.get_patCor_info(),\n SNP.get_patRaw_info())\n error_type = \"nothing_mat\" + \"-\" + error_type_pat + \"_pat\"\n else:\n error_type = \"hard2id\"\n #output\n if (tenx_hap1 == tenx_hap2):\n tag.write(i + \"\\t\" + error_type + \"\\t\" + \"False\\n\")\n else:\n tag.write(i + \"\\t\" + error_type + \"\\t\" + \"True\\n\")\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Sequencing_and_polishing_error/snp_5evidence.statistic.v2.py","file_name":"snp_5evidence.statistic.v2.py","file_ext":"py","file_size_in_byte":11615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"406868263","text":"import concurrent.futures\nimport requests\nimport threading\nimport time\n#import psutil\n\n\ndef get_session():\n if not hasattr(thread_local, \"session\"):\n thread_local.session = requests.Session()\n return thread_local.session\n\n\ndef download_site(url):\n session = get_session()\n with session.get(url) as response:\n res = f\"Read {len(response.content)} from {url}\"\n if debug:\n print(end='')\n time.sleep(.1)\n\n\ndef download_all_sites(sites, no_of_threads=5):\n with concurrent.futures.ThreadPoolExecutor(max_workers=no_of_threads) as executor:\n executor.map(download_site, sites)\n\n\nif __name__ == \"__main__\":\n sites = [\n \"https://www.jython.org\",\n \"http://olympus.realpython.org/dice\",\n ] * 80\n for no_of_threads in range(1, 50, 2):\n thread_local = threading.local()\n debug = True\n start_time = time.time()\n download_all_sites(sites, no_of_threads)\n duration = time.time() - start_time\n print(f\"Downloaded {len(sites)} in {duration} seconds using {no_of_threads} Threads\")\n # print(f\"Memory used:{psutil.virtual_memory()}\")\n","sub_path":"linear_thread.py","file_name":"linear_thread.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"286821573","text":"#!/usr/bin/env python\n\n#########################################################\n# Filter entries in fasta file for minimum length #\n# and save in new fasta file #\n# usage: filter_fasta.py FASTAFILE MINLENGTH OUTPUTFILE #\n# F. Klincke #\n# September 2019 #\n#########################################################\n\nimport sys\nimport os\n\n\ndef filter_fasta_minlength(fasta, min_length, out):\n \"\"\" Filters entries in fasta file for minimum length\n and save as new fasta file \"\"\"\n out = open(out, 'w')\n with open(fasta, 'r') as infile:\n seq = []\n header = \"\"\n for line in infile:\n if line[0] == '>':\n if len(seq) > 0: # start outputting from second entry\n l = map(len, seq)\n if sum(l) >= min_length:\n out.write(\"\".join([header, \"\".join(seq)]))\n #out.write(\"\\n\".join(seq))\n header = line\n seq = []\n else:\n seq.append(line)\n if len(seq) > 0: #handle last fasta entry\n l = map(len, seq)\n if sum(l) >= min_length:\n\n out.write(\"\".join([header, \"\".join(seq)]))\n out.close()\n\n\ntry:\n fastafile = sys.argv[1]\n if not os.path.isfile(fastafile):\n raise FileNotFoundError(\"FileNotFoundError: Fasta file {} not found\".format(fastafile))\n min_len = int(sys.argv[2])\n if min_len < 1:\n raise ValueError\n outfile = sys.argv[3]\nexcept FileNotFoundError as error:\n print(error)\n sys.exit(1)\nexcept ValueError:\n print(\"ValueError: minimum length needs to be a positive integer\")\n sys.exit(1)\nexcept IndexError:\n print(\"IndexError: need an ouputfile\")\n sys.exit(1)\n \n\nfilter_fasta_minlength(fastafile, min_len, outfile)\n\n","sub_path":"filter_fasta.py","file_name":"filter_fasta.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"127929259","text":"#!/bin/python\nimport re\n\nimport pyemoji\nimport json\nimport socket, sys\nimport bluetooth\nimport threading\nimport signal\nimport dbus\nimport dbus.service\nfrom pprint import pprint\n\ncontact = None\nnumCurrentlyKeyIn = False\ntextCurrentlyKeyIn = False\n\nclass th_recv(threading.Thread):\n msg = None\n sock = None\n quit = False\n\n def __init__(self, s):\n threading.Thread.__init__(self)\n self.sock = s\n \n def parseJson(self):\n o = json.loads(self.msg)\n # print(o[\"header\"][\"type\"]) # @debug\n # print(o[\"content\"][\"num\"] + o[\"content\"][\"message\"]) # @debug\n if(o['header']['type'] == 'contact'):\n global contact\n contact = o['content']\n contact = remove_duplicates(contact)\n return None, None\n return o[\"content\"][\"num\"], pyemoji.decode(o[\"content\"][\"message\"])\n\n def run(self):\n lenSend = sock.send(bytes(\"system:!contact!\", 'UTF-8'))\n \n while not self.quit:\n self.receive()\n if self.msg != \"\":\n if numCurrentlyKeyIn:\n complement = \"\\n\\nNumero du destinataire : \"\n elif textCurrentlyKeyIn:\n complement = \"\\n\\nTappez votre message : \"\n else :\n complement = \"\\n\"\n num, text = self.parseJson()\n if(num != None and text != None):\n print(\"\\n >>> message reçu : \\n De : \"+num+\"\\n :: \"+text+complement)\n else:\n pprint(contact)\n print(complement)\n\n def receive(self):\n self.msg = \"\"\n try:\n lenToReceive = self.sock.recv(50)\n except ConnectionResetError as e:\n self.quit = True\n return \"\"\n\n recu=0\n lenToReceive = lenToReceive.decode(\"utf-8\")\n\n #case if phone send size and message in same datagram\n regChiffre = re.compile(r\"^[0-9]*$\")\n\n if regChiffre.match(lenToReceive) == None:\n lenToReceive,self.msg = lenToReceive.split('{', maxsplit=1)\n self.msg = '{'+self.msg\n recu = len(self.msg)\n \n while not self.quit and recu < int(lenToReceive):\n try:\n x = self.sock.recv(10)\n except ConnectionResetError as e:\n self.quit = True\n return \"\"\n recu +=10\n # self.msg += pyemoji.decode(x.decode(\"utf-8\"))\n self.msg += x.decode(\"latin1\")\n # print(\"msg : \"+str(self.msg))\n # print(recu)\n\n def interupt(self):\n self.quit = True\n\nclass MyException(Exception):\n def __init__(self, arg):\n self.value = arg\n \n def __str__(self):\n return repr(self.value)\n\n \n\ndef kill_thread(_sock):\n thReceive.interupt()\n signal.alarm(1)\n thReceive.join()\n sock.close()\n\ndef turnOnBluetoothAdapter(state = \"on\"):\n # dbus-send --system --type=method_call --dest=org.bluez\n # /org/bluez/hci0\n # org.freedesktop.DBus.Properties.Set\n # string:org.bluez.Adapter1\n # string:Powered\n # variant:boolean:true\n bus = dbus.SystemBus()\n objBluez = bus.get_object(\"org.bluez\", \"/org/bluez/hci0\")\n adapter = dbus.Interface(objBluez, \"org.freedesktop.DBus.Properties\")\n\n if state == \"on\" and not adapter.Get('org.bluez.Adapter1','Powered'):\n adapter.Set(\"org.bluez.Adapter1\",\"Powered\", True)\n elif state == \"off\" and adapter.Get('org.bluez.Adapter1','Powered'):\n adapter.Set(\"org.bluez.Adapter1\",\"Powered\", False)\n\n\ndef nomToNum(nom):\n num = []\n if contact != None:\n for l in contact:\n if nom in l.values():\n num.append(str(l['num']))\n if len(num)==0:\n raise MyException(\"Contact \"+nom+\" not found into the phonebook\")\n else:\n raise MyException(\"Contact \"+nom+\" not found into the phonebook\")\n return num\n\ndef remove_duplicates(lst, equals=lambda x, y: x == y):\n if not isinstance(lst, list):\n raise TypeError('This function works only with lists.')\n i1 = 0\n l = (len(lst) - 1)\n while i1 < l:\n elem = lst[i1]['nom']\n i2 = i1 + 1\n print(\"elem : \"+elem)\n while i2 <= l:\n if equals(elem, lst[i2]['nom']):\n del lst[i2]\n l -= 1\n else:\n i2 += 1\n i1 += 1\n return lst\n\n\ndef makeAChoice(num):\n while True:\n i = 0\n for n in num:\n print(str(i)+\" : \"+n)\n i+=1\n c = input(\"Choisissez le numéro que vous souhaitez utiliser : \")\n if int(c) < i:\n break\n \n return num[int(c)]\n\nif __name__ == \"__main__\":\n # port = 23\n addr = \"84:8E:DF:28:89:0C\"\n old = [False, False]\n\n turnOnBluetoothAdapter(\"on\")\n\n while 1:\n searchBlueSms = bluetooth.find_service(address=addr, name='BlueSms')\n if not searchBlueSms:\n print(\"Erreur : aucun serveur BlueSms à proximité\")\n sys.exit(1)\n\n for dev in searchBlueSms:\n if dev['name'] == \"BlueSms\":\n print(\"Connection to BlueSms server on \"+dev['host']+\"\\nport number \"+str(dev['port']))\n port = dev['port']\n addr = dev['host']\n\n sock=socket.socket( socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM )\n # sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)\n serv = (addr, port)\n\n\n res = sock.connect(serv)\n if res == 0:\n print(\"connection error\")\n\n thReceive = th_recv(sock)\n thReceive.start()\n\n while 1:\n try:\n # num = \"\"\n # text = \"\"\n numCurrentlyKeyIn = True\n num = input('Numero ou nom du destinataire : ')\n numCurrentlyKeyIn = False\n textCurrentlyKeyIn = True\n text = input(\"Tappez votre message : \")\n textCurrentlyKeyIn = False\n\n old = [num, text]\n if num and text:\n regNum = re.compile(r\"^[0+]([[0-9]-])*\")\n regNom = re.compile(r\"^!.*!$\")\n if regNum.match(num) or regNom.match(text):\n print('num : '+num)\n else :\n print('nom : '+num)\n\n try:\n num = nomToNum(num)\n if len(num) > 1:\n num = makeAChoice(num)\n else:\n num = num[0]\n \n except MyException as e:\n print(e)\n continue\n \n lenSend = sock.send(bytes(num+\":\"+text, 'UTF-8'))\n print(str(lenSend)+\" caractère envoyé\")\n if text == \"quit\" or text == \"!shutdown!\":\n kill_thread(sock)\n turnOnBluetoothAdapter(\"off\")\n sys.exit(1)\n elif not old[0] and not old[1] and not num and not text:\n kill_thread(sock)\n turnOnBluetoothAdapter(\"off\")\n sys.exit(1)\n\n except OSError as e:\n print(\"Fin de la connection le serveur a été déconnecté !!! \")\n break\n\n kill_thread(sock)\n \n turnOnBluetoothAdapter(\"off\")\n\n","sub_path":"python/BluetoothClientSocket_Python3.py","file_name":"BluetoothClientSocket_Python3.py","file_ext":"py","file_size_in_byte":7545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"451512137","text":"\r\n#######最基础版本9.28\r\n\r\n\r\nfrom torch import nn\r\nimport torch\r\n\r\nimport torch.nn.functional as F\r\n\r\nfrom torchtext import data\r\nfrom torchtext import datasets\r\nimport numpy as np\r\n\r\ntorch.cuda.current_device()\r\ntorch.cuda._initialized=True\r\nLABEL = data.Field()\r\nSENTENCE1=data.Field()\r\nSENTENCE2=data.Field()\r\n\r\nfields = {'gold_label':('label',LABEL),'sentence1':('st1',SENTENCE1),'sentence2':('st2',SENTENCE2)}\r\n\r\ntrain_data , test_data = data.TabularDataset.splits(path = 'E:\\pycharmproject\\FuDanNlpDemo3\\source\\snli_1.0',train='snli_1.0_train.jsonl',test='snli_1.0_test.jsonl',format='json',fields=fields)\r\n\r\n##################应该把sent1和sent2进行pad\r\n\r\nneutral_count = 0\r\ncontract_count = 0\r\nentail_count = 0\r\nxiahua_count = 0\r\nfor i in train_data:\r\n\r\n length1 = len(vars(i)['st1'])\r\n length2 = len(vars(i)['st2'])\r\n maxlength = length1 if length1>length2 else length2\r\n while(maxlength-length1):\r\n vars(i)['st1'].append('')\r\n length1+=1\r\n while(maxlength-length2):\r\n vars(i)['st2'].append('')\r\n length2+=1\r\n if vars(i)['label'] == ['neutral']:\r\n neutral_count +=1\r\n if vars(i)['label'] == ['contradiction']:\r\n contract_count+=1\r\n if vars(i)['label'] == ['entailment'] :\r\n entail_count +=1\r\n if vars(i)['label']==['-']:\r\n xiahua_count+=1\r\n\r\n\r\nprint(f'neutral_count:{neutral_count},contract_count:{contract_count}entailment_count :{entail_count} xiahua_count:{xiahua_count}')\r\nprint(f\"合计: {neutral_count+contract_count+entail_count+xiahua_count}\")\r\nprint(f\"训练集的大小为{len(train_data)}\")\r\nfor i in test_data:\r\n\r\n length1 = len(vars(i)['st1'])\r\n length2 = len(vars(i)['st2'])\r\n maxlength = length1 if length1 > length2 else length2\r\n while (maxlength - length1):\r\n vars(i)['st1'].append('')\r\n length1 += 1\r\n while (maxlength - length2):\r\n vars(i)['st2'].append('')\r\n length2 += 1\r\n\r\nprint(vars(train_data[0]))\r\nprint(vars(test_data[0]))\r\nprint(f\"训练集的大小为{len(train_data)}\")\r\nprint(f\"测试集的大小为{len(test_data)}\")\r\n\r\nMAX_VOCAB_SIZE = 30000\r\n\r\nLABEL.build_vocab(train_data)\r\nSENTENCE1.build_vocab(train_data,max_size=MAX_VOCAB_SIZE, vectors='glove.6B.100d', unk_init=torch.Tensor.normal_)\r\nSENTENCE2.build_vocab(train_data,max_size=MAX_VOCAB_SIZE, vectors='glove.6B.100d', unk_init=torch.Tensor.normal_)\r\n\r\nprint(SENTENCE1.vocab.itos[0],SENTENCE1.vocab)\r\nprint(SENTENCE1.vocab.itos[1],SENTENCE1.vocab[1])\r\nprint(f\"LABEL词表的大小为:{len(LABEL.vocab)}\")\r\n\r\nprint(f\"SENTENCE1词表的大小为:{len(SENTENCE1.vocab)}\")\r\nprint(f\"SENTENCE2词表的大小为:{len(SENTENCE2.vocab)}\")\r\n\r\nprint(\"LABEL词表包括那些东西::\",LABEL.vocab.stoi)\r\n\r\n####建立完词表后 定义batch_size和device(为什么??因为Iterator里面参数要用到batch_size 和device) 然后建立Iterator\r\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\nBATCH_SIZE =128\r\ntrain_iter , test_iter = data.BucketIterator.splits((train_data,test_data),sort=False,batch_size=BATCH_SIZE,device=device)\r\n\r\nfor batch in train_iter:\r\n print (batch)\r\n break\r\n\r\nclass ESIM(nn.Module):\r\n def __init__(self, args):\r\n super(ESIM, self).__init__()\r\n self.args = args\r\n self.dropout = 0.5\r\n self.hidden_size = args.hidden_size\r\n self.embeds_dim = args.embeds_dim\r\n self.pad_idx = args.pad_idx\r\n self.num_word = args.num_word\r\n\r\n self.embeds = nn.Embedding(self.num_word, self.embeds_dim,padding_idx=self.pad_idx)\r\n self.bn_embeds = nn.BatchNorm1d(self.embeds_dim)\r\n self.lstm1 = nn.LSTM(self.embeds_dim, self.hidden_size, batch_first=True, bidirectional=True)\r\n self.lstm2 = nn.LSTM(self.hidden_size * 8, self.hidden_size, batch_first=True, bidirectional=True)\r\n\r\n self.fc = nn.Sequential(\r\n nn.BatchNorm1d(self.hidden_size * 8),\r\n nn.Linear(self.hidden_size * 8, args.linear_size),\r\n nn.ELU(inplace=True),\r\n # nn.BatchNorm1d(args.linear_size),\r\n # nn.Dropout(self.dropout),\r\n # nn.Linear(args.linear_size, args.linear_size),\r\n # nn.ELU(inplace=True),\r\n nn.BatchNorm1d(args.linear_size),\r\n nn.Dropout(self.dropout),\r\n nn.Linear(args.linear_size,4)\r\n # nn.Softmax(dim=-1)\r\n )\r\n\r\n def soft_attention_align(self, x1, x2, mask1, mask2):\r\n '''\r\n x1: batch_size * seq_len * dim\r\n x2: batch_size * seq_len * dim\r\n '''\r\n # attention: batch_size * seq_len * seq_len\r\n attention = torch.matmul(x1, x2.transpose(1, 2))\r\n mask1 = mask1.float().masked_fill_(mask1, float('-inf'))\r\n mask2 = mask2.float().masked_fill_(mask2, float('-inf')) ###为什么叫mask,就像面具一样,把原来的值全部用 -inf覆盖了,这样softmax出来就都是0 ,也就是attention中和相关的注意力都是0\r\n #mask batch_size *seq_len unsqueeze之后变成batch_size *1 *seq_len\r\n\r\n # weight: batch_size * seq_len * seq_len\r\n\r\n weight1 = F.softmax(attention + mask2.unsqueeze(1), dim=-1) #batch_size *(seq_len)*seq_len 注意矩阵维度不一样的时候的加法\r\n # '''[2,3,3]+[2,1,3]\r\n # torch.Size([2, 3, 3])\r\n # tensor([[[-0.3740, 1.0252, 0.5291],\r\n # [-0.2367, 2.1526, -0.2691],\r\n # [-1.6116, -1.5094, 0.2614]],\r\n #\r\n # [[-0.8805, 1.8062, 0.2487],\r\n # [-0.0205, 0.1859, -0.5070],\r\n # [0.2409, 0.5222, 1.0360]]])\r\n # tensor([[[1.3760, 0.6039, 0.2657]],\r\n #\r\n # [[0.6044, 0.7289, -0.6047]]])\r\n # tensor([[[1.0020, 1.6291, 0.7947],\r\n # [1.1394, 2.7565, -0.0035],\r\n # [-0.2356, -0.9055, 0.5270]],\r\n #\r\n # [[-0.2760, 2.5351, -0.3560],\r\n # [0.5839, 0.9148, -1.1117],\r\n # [0.8453, 1.2511, 0.4312]]])\r\n # '''\r\n x1_align = torch.matmul(weight1, x2)\r\n weight2 = F.softmax(attention.transpose(1, 2) + mask1.unsqueeze(1), dim=-1)\r\n x2_align = torch.matmul(weight2, x1) #batch_size*seq_len *seq_len batch_size * seq_len * hidden_size\r\n # x_align: batch_size * seq_len * hidden_size\r\n return x1_align, x2_align\r\n\r\n\r\n def submul(self, x1, x2):\r\n mul = x1 * x2 ###############element-wise 相应元素相乘,论文中是这么写的吗????\r\n sub = x1 - x2\r\n return torch.cat([sub, mul], -1) ####按最后一个维度进行拼接\r\n\r\n def apply_multiple(self, x):\r\n # input: batch_size * seq_len * (2 * hidden_size)\r\n p1 = F.avg_pool1d(x.transpose(1, 2), x.size(1)).squeeze(-1)\r\n p2 = F.max_pool1d(x.transpose(1, 2), x.size(1)).squeeze(-1)\r\n # output: batch_size * (4 * hidden_size)\r\n return torch.cat([p1, p2], 1)\r\n\r\n def forward(self, sentence1,sentence2):\r\n # batch_size * seq_len\r\n sent1, sent2 = sentence1, sentence2\r\n\r\n\r\n mask1, mask2 = sent1.eq(0), sent2.eq(0) ####这里的mask其实就是原始句子中的标签把\r\n\r\n # embeds: batch_size * seq_len => batch_size * seq_len * dim\r\n x1 = self.bn_embeds(self.embeds(sent1).transpose(1, 2).contiguous()).transpose(1, 2) #batch_size *seq_len * 2*embedding_dim\r\n x2 = self.bn_embeds(self.embeds(sent2).transpose(1, 2).contiguous()).transpose(1, 2)\r\n\r\n # batch_size * seq_len * dim => batch_size * seq_len * hidden_size\r\n o1, _ = self.lstm1(x1)\r\n o2, _ = self.lstm1(x2)\r\n\r\n # Attention\r\n # batch_size * seq_len * hidden_size\r\n q1_align, q2_align = self.soft_attention_align(o1, o2, mask1, mask2)\r\n\r\n # Compose\r\n # batch_size * seq_len * (8 * hidden_size)\r\n q1_combined = torch.cat([o1, q1_align, self.submul(o1, q1_align)], -1)\r\n q2_combined = torch.cat([o2, q2_align, self.submul(o2, q2_align)], -1)\r\n\r\n # batch_size * seq_len * (2 * hidden_size)\r\n q1_compose, _ = self.lstm2(q1_combined)\r\n q2_compose, _ = self.lstm2(q2_combined)\r\n\r\n # Aggregate\r\n # input: batch_size * seq_len * (2 * hidden_size)\r\n # output: batch_size * (4 * hidden_size)\r\n q1_rep = self.apply_multiple(q1_compose)\r\n q2_rep = self.apply_multiple(q2_compose)\r\n\r\n # Classifier\r\n x = torch.cat([q1_rep, q2_rep], -1)\r\n similarity = self.fc(x)\r\n\r\n return similarity\r\n\r\n#使用传统的双向LSTM 好像也可以试试\r\n\r\n\r\n# class RNN(nn.Module):\r\n#\r\n# def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers,\r\n# bidirectional, dropout, pad_idx):\r\n# super().__init__()\r\n#\r\n# self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=pad_idx)\r\n#\r\n# self.rnn = nn.LSTM(embedding_dim,\r\n# hidden_dim,\r\n# num_layers=n_layers,\r\n# bidirectional=bidirectional,\r\n# dropout=dropout)\r\n#\r\n# self.fc = nn.Linear(hidden_dim * 2, output_dim)\r\n#\r\n# self.dropout = nn.Dropout(dropout)\r\n#\r\n# def forward(self, text, text_lengths):\r\n# # text = [sent len, batch size]\r\n# embedded = self.dropout(self.embedding(text))\r\n# # embedded = [sent len, batch size, emb dim]\r\n# # pack sequence\r\n# packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, text_lengths)\r\n# packed_output, (hidden, cell) = self.rnn(packed_embedded)\r\n# # unpack sequence\r\n# output, output_lengths = nn.utils.rnn.pad_packed_sequence(packed_output)\r\n# # output = [sent len, batch size, hid dim * num directions]\r\n# # output over padding tokens are zero tensors\r\n# # hidden = [num layers * num directions, batch size, hid dim]\r\n# # cell = [num layers * num directions, batch size, hid dim]\r\n# # concat the final forward (hidden[-2,:,:]) and backward (hidden[-1,:,:]) hidden layers\r\n# # and apply dropout\r\n# hidden = self.dropout(torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1))\r\n# # hidden = [batch size, hid dim * num directions]\r\n# return self.fc(hidden)\r\n#\r\n#\r\n\r\n\r\n\r\n#####################初始化需要哪些东西??? hidden_size embeds_dim linear_size\r\n\r\nINPUT_DIM1 = len(SENTENCE1.vocab)\r\nINPUT_DIM2 = len(SENTENCE2.vocab)\r\nEMBEDS_DIM = 100\r\nHIDDEN_SIZE = 128\r\nLINEAR_SIZE = 50\r\nOUTPUT_DIM = 3\r\nDROPOUT = 0.5\r\n\r\nPAD_IDX =SENTENCE1.vocab.stoi[SENTENCE1.pad_token]\r\n\r\n# PAD_IDX2 =SENTENCE2.vocab.stoi[SENTENCE1.pad_token]\r\n#\r\n# print(\"pad_idx1:\",PAD_IDX1)\r\n#\r\n# print(\"pad_idx2:\",PAD_IDX2)\r\n\r\nclass arg:\r\n def __init__(self,a,b,c,d,e):\r\n self.hidden_size = a\r\n self.embeds_dim = b\r\n self.linear_size = c\r\n self.pad_idx = d\r\n self.num_word =e\r\n\r\nNUM_WORD = len(SENTENCE1.vocab)\r\nARG = arg(HIDDEN_SIZE,EMBEDS_DIM,LINEAR_SIZE,PAD_IDX,NUM_WORD)\r\n\r\nmodel = ESIM(ARG)\r\n\r\n\r\ndef count_parameters(model):\r\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\r\nprint(f'The model has {count_parameters(model):,} trainable parameters')\r\n\r\n################################准 备 训 练#####################################\r\n\r\n\r\npretrained_embedding = SENTENCE1.vocab.vectors\r\n# pretrained_embedding2 = SENTENCE2.vocab.vectors\r\n# print(pretrained_embedding.shape)\r\n# print(pretrained_embedding2.shape)\r\nmodel.embeds.weight.data.copy_(pretrained_embedding)\r\nUNK_IDX = SENTENCE1.vocab.stoi[SENTENCE1.unk_token]\r\nPAD_IDX = SENTENCE1.vocab.stoi[SENTENCE1.pad_token]\r\n\r\nmodel.embeds.weight.data[UNK_IDX] = torch.zeros(EMBEDS_DIM)\r\nmodel.embeds.weight.data[PAD_IDX] = torch.zeros(EMBEDS_DIM)\r\n\r\n# print(model.embeds.weight.data)\r\n\r\n##########################定义优化器 损失函数 ###################################################\r\n\r\nimport torch.optim as optim\r\noptimizer = optim.Adam(model.parameters())\r\n\r\ncriterion =nn.CrossEntropyLoss()\r\n\r\nmodel = model.to(device)\r\ncriterion = criterion.to(device)\r\n\r\n#############################################################################\r\n########################################################################\r\n\r\n\r\ndef get_result(preds): ################输入[batchsize C ] 返回[batchsize]大小的list\r\n ######################################用来和Sentiment比较计算准确率\r\n result = []\r\n for i in preds:\r\n i = i.cpu().detach().numpy()\r\n result.append(int(np.argmax(i)))\r\n return result\r\n\r\ndef get_accuracy(preds, y):\r\n ###多分类这个不知道怎么写!!!!\r\n \"\"\"\"return accuracy per batch , i.e.\"\"\"\r\n result = []\r\n for i in preds:\r\n# i = i.cpu().detach().numpy()\r\n# result.append(int(np.argmax(i))) ###torch有自己的argmax函数\r\n result.append(int(torch.argmax(i)))\r\n sum = 0\r\n for i in range(len(y)):\r\n if result[i] == y[i]:\r\n sum = sum + 1\r\n acc = sum / len(y)\r\n return acc\r\n\r\n# for batch in train_iter:\r\n# print(batch)\r\n\r\n\r\ndef train(model, iterator, optimizer, criterion):\r\n epoch_loss = 0\r\n epoch_acc = 0\r\n model.train()\r\n count = 0\r\n for batch in iterator:\r\n optimizer.zero_grad()\r\n st1 = batch.st1\r\n st2 = batch.st2\r\n st1 = st1.transpose(0, 1)\r\n st2 = st2.transpose(0, 1)\r\n predictions = model(st1, st2)\r\n batch.label = batch.label - 2 # 类别下标只能从0开始 不然各种报错\r\n # print(\"Label\", batch.label[0])\r\n # print(\"prediction\",get_result(predictions))\r\n # print(get_accuracy(predictions,batch.label[0]))\r\n loss = criterion(predictions, batch.label[0])\r\n acc = get_accuracy(predictions, batch.label[0])\r\n loss.backward()\r\n optimizer.step()\r\n epoch_loss += loss.item()\r\n epoch_acc += acc\r\n count+=1\r\n if(count%1000==0):\r\n print(epoch_acc/count)\r\n epoch_acc = 0\r\n count = 0\r\n\r\n return epoch_loss / len(iterator), epoch_acc / len(iterator)\r\n\r\n\r\ndef evaluate(model, iterator, criterion):\r\n epoch_loss = 0\r\n epoch_acc = 0\r\n model.eval()\r\n count = 0\r\n with torch.no_grad():\r\n for batch in iterator:\r\n st1, st2 = batch.st1,batch.st2\r\n st1 = st1.transpose(0, 1)\r\n st2 = st2.transpose(0, 1)\r\n predictions = model(st1, st2)\r\n batch.label = batch.label - 2\r\n # print(batch.label)\r\n # print(\"prediceions:\",predictions)\r\n # print(\"Label\",batch.label[0])\r\n loss = criterion(predictions, batch.label[0])\r\n acc = get_accuracy(predictions, batch.label[0])\r\n epoch_loss += loss.item()\r\n epoch_acc += acc\r\n count += 1\r\n if (count % 1000 == 0):\r\n print(epoch_acc / count)\r\n epoch_acc = 0\r\n count = 0\r\n\r\n return epoch_loss / len(iterator), epoch_acc / len(iterator)\r\n\r\n\r\nimport time\r\n\r\n\r\ndef epoch_time(start_time, end_time):\r\n elapsed_time = end_time - start_time\r\n elapsed_mins = int(elapsed_time / 60)\r\n elapsed_secs = int(elapsed_time - (elapsed_mins * 60))\r\n return elapsed_mins, elapsed_secs\r\n\r\n\r\nN_EPOCHS = 5\r\n\r\nbest_valid_loss = float('inf')\r\n\r\nfor epoch in range(N_EPOCHS):\r\n start_time = time.time()\r\n train_loss, train_acc = train(model, train_iter, optimizer, criterion)\r\n valid_loss, valid_acc = evaluate(model, test_iter, criterion)\r\n end_time = time.time()\r\n epoch_mins, epoch_secs = epoch_time(start_time, end_time)\r\n if valid_loss < best_valid_loss:\r\n best_valid_loss = valid_loss\r\n torch.save(model.state_dict(), 'tut2-model.pt')\r\n print(f'Epoch: {epoch + 1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s')\r\n print(f'\\tTrain Loss: {train_loss:.3f}| Train Acc: {train_acc * 100:.2f}%')\r\n print(f'\\t Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc * 100:.2f}%')\r\n","sub_path":"任务3.py","file_name":"任务3.py","file_ext":"py","file_size_in_byte":16096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"135146473","text":"'''\r\nCreated on 2019年1月13日\r\n\r\n@author: Le\r\n'''\r\nimport requests\r\nfrom lxml import etree\r\n\r\nheaders = {'Refere': 'https://blog.csdn.net/u012843873/article/details/73558064/',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'}\r\nurl = 'https://movie.douban.com/cinema/nowplaying/hangzhou/'\r\nresponse = requests.get(url, headers=headers)\r\n# print(response.text)#返回经过解码后的字符串str\r\n# print(response.contents)#返回原生字节串,byte\r\nparse = etree.HTML(response.text)\r\nul = parse.xpath(\"//ul[@class = 'lists']\")[0]\r\nlis = ul.xpath(\"./li\")\r\n#print(etree.tostring(lis[0], encoding='utf-8').decode('utf-8'))\r\nmovies = []\r\nfor li in lis:\r\n try:\r\n title = li.xpath('@data-title')[0]\r\n score = li.xpath(\"@data-score\")[0]\r\n duration = li.xpath(\"@data-duration\")[0]\r\n region = li.xpath(\"@data-region\")[0]\r\n actor = li.xpath(\"@data-actors\")[0]\r\n thumbnail = li.xpath(\".//img/@src\")[0]\r\n except IndexError:\r\n print(\"error\")\r\n continue\r\n movie = {\r\n \"title\": title,\r\n \"score\": score,\r\n \"duration\": duration,\r\n \"region\": region,\r\n \"actor\": actor,\r\n \"thumbnail\": thumbnail\r\n }\r\n movies.append(movie)\r\nprint(movies)","sub_path":"spider/xpathfordouban.py","file_name":"xpathfordouban.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"327986892","text":"class Solution:\n def uniquePaths(self, m:int, n:int):\n dp = [[1] * n] + [[1] + [0] * (n - 1) for _ in range(m - 1)]\n for i in range(1, m):\n for j in range(1, n):\n dp[i][j] = dp[i - 1][j] + dp[i][j - 1]\n\n return dp[-1][-1]\n\n\nif __name__ == '__main__':\n n = 3\n m = 2\n cls = Solution()\n print(cls.uniquePaths(n, m))","sub_path":"hot100/62. 不同路径.py","file_name":"62. 不同路径.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"428706004","text":"from pandas_datareader import data as pdr\nimport yfinance as yf\nimport matplotlib.pyplot as plt\n\nyf.pdr_override()\n\n#데이터 불러오기 //\nsec = pdr.get_data_yahoo('005930.KS', start='2018-05-04')\nmsft = pdr.get_data_yahoo(\"MSFT\", start='2018-05-04')\nskhy = pdr.get_data_yahoo('000660.KS', start='2018-05-04')\nnaver = pdr.get_data_yahoo('035420.KS', start='2018-05-04')\nkakao = pdr.get_data_yahoo('035720.KS', start='2018-05-04')\n\n#변동률\nsec_dpc = ((sec['Close'] - sec['Close'].shift(1)) / sec['Close'].shift(1)) * 100\nmsft_dpc = ((msft['Close'] - msft['Close'].shift(1)) / msft['Close'].shift(1)) * 100\nskhy_dpc = ((skhy['Close'] - skhy['Close'].shift(1)) / skhy['Close'].shift(1)) * 100\nnaver_dpc = ((naver['Close'] - naver['Close'].shift(1)) / naver['Close'].shift(1)) * 100\nkakao_dpc = ((kakao['Close'] - kakao['Close'].shift(1)) / kakao['Close'].shift(1)) * 100\n\n# NaN값 0으로 변경\nsec_dpc.iloc[0] = 0\nmsft_dpc.iloc[0] = 0\nskhy_dpc.iloc[0] = 0\nnaver_dpc.iloc[0] = 0\nkakao_dpc.iloc[0] = 0\n\n#일간 변동률 누적합\nsec_dpc_cs = sec_dpc.cumsum() #18년 5월 ~ 20년 9월 19.6% 이익률\nmsft_dpc_cs = msft_dpc.cumsum() #18년 5월 ~ 20년 9월 92% 이익률\nskhy_dpc_cs = skhy_dpc.cumsum() #18년 5월 ~ 20년 9월 13% 이익률\nnaver_dpc_cs = naver_dpc.cumsum() #18년 5월 ~ 20년 9월 84% 이익률\nkakao_dpc_cs = kakao_dpc.cumsum() #18년 5월 ~ 20년 9월 130% 이익률\n#문제점 // 하락한 부분에서 반등한 부분까지 총합이므로 결과값이 이상하게 나온다..\n\n#첫날 대비 현재가에 증가율을 구해야 하므로 오늘 종가 - 구매 첫날 종가/구매 첫날 종가 * 100을 해야한다.\nsec_dpc2 = ((sec['Close'][-1] - sec['Close'][0]) / sec['Close'][0]) * 100\nmsft_dpc2 = ((msft['Close'][-1] - msft['Close'][0]) / msft['Close'][0]) * 100\n\n\n\n#두개 기업 비교 // 삼성 vs ms\nplt.plot(sec.index, sec_dpc_cs2, 'b', label=\"Samsung Electronic\")\nplt.plot(msft.index, msft_dpc_cs, 'r--', label=\"MicroSoft\")\nplt.ylabel('Change %')\nplt.grid(True)\nplt.show()\n\n#네이버 카카오\nplt.plot(naver.index, naver_dpc_cs, 'b', label=\"Naver\")\nplt.plot(kakao.index, kakao_dpc_cs, 'r--', label=\"KaKao\")\nplt.ylabel('Change %')\nplt.grid(True)\nplt.show()\n\n\n","sub_path":"price_earnigs_ratio.py","file_name":"price_earnigs_ratio.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"67316810","text":"# from lib.openfood_env import MULTI_1X\n# from lib.openfood_env import MULTI_2X\n# from lib.openfood_env import MULTI_3X\n# from lib.openfood_env import MULTI_4X\n# from lib.openfood_env import MULTI_5X\nfrom .openfood_env import KOMODO_NODE\nfrom .openfood_env import RPC_USER\nfrom .openfood_env import RPC_PASSWORD\nfrom .openfood_env import RPC_PORT\nfrom .openfood_env import KV1_NODE\nfrom .openfood_env import KV1_RPC_USER\nfrom .openfood_env import KV1_RPC_PASSWORD\nfrom .openfood_env import KV1_RPC_PORT\nfrom .openfood_env import EXPLORER_URL\nfrom .openfood_env import THIS_NODE_RADDRESS\nfrom .openfood_env import THIS_NODE_WIF\nfrom .openfood_env import BLOCKNOTIFY_CHAINSYNC_LIMIT\nfrom .openfood_env import HOUSEKEEPING_RADDRESS\nfrom .openfood_env import IMPORT_API_BASE_URL\nfrom .openfood_env import DEV_IMPORT_API_RAW_REFRESCO_REQUIRE_INTEGRITY_PATH\nfrom .openfood_env import DEV_IMPORT_API_RAW_REFRESCO_INTEGRITY_PATH\nfrom .openfood_env import DEV_IMPORT_API_RAW_REFRESCO_TSTX_PATH\nfrom .openfood_env import openfood_API_BASE_URL\nfrom .openfood_env import openfood_API_ORGANIZATION\nfrom .openfood_env import openfood_API_ORGANIZATION_CERTIFICATE_NORADDRESS\nfrom .openfood_env import openfood_API_ORGANIZATION_CERTIFICATE\nfrom .openfood_env import openfood_API_ORGANIZATION_BATCH\nfrom .openfood_env import FUNDING_AMOUNT_CERTIFICATE\nfrom .openfood_env import FUNDING_AMOUNT_TIMESTAMPING_START\nfrom .openfood_env import FUNDING_AMOUNT_TIMESTAMPING_END\nfrom .openfood_env import DEV_IMPORT_API_RAW_REFRESCO_PATH\nfrom .openfood_env import WALLET_DELIVERY_DATE\nfrom .openfood_env import WALLET_DELIVERY_DATE_THRESHOLD_BALANCE\nfrom .openfood_env import WALLET_DELIVERY_DATE_THRESHOLD_UTXO\nfrom .openfood_env import WALLET_DELIVERY_DATE_THRESHOLD_UTXO_VALUE\nfrom .openfood_env import WALLET_PON\nfrom .openfood_env import WALLET_PON_THRESHOLD_BALANCE\nfrom .openfood_env import WALLET_PON_THRESHOLD_UTXO\nfrom .openfood_env import WALLET_PON_THRESHOLD_UTXO_VALUE\n\nfrom .openfood_env import WALLET_TIN\nfrom .openfood_env import WALLET_TIN_THRESHOLD_BALANCE\nfrom .openfood_env import WALLET_TIN_THRESHOLD_UTXO\nfrom .openfood_env import WALLET_TIN_THRESHOLD_UTXO_VALUE\nfrom .openfood_env import WALLET_PROD_DATE\nfrom .openfood_env import WALLET_PROD_DATE_THRESHOLD_BALANCE\nfrom .openfood_env import WALLET_PROD_DATE_THRESHOLD_UTXO\nfrom .openfood_env import WALLET_PROD_DATE_THRESHOLD_UTXO_VALUE\nfrom .openfood_env import WALLET_JULIAN_START\nfrom .openfood_env import WALLET_JULIAN_START_THRESHOLD_BALANCE\nfrom .openfood_env import WALLET_JULIAN_START_THRESHOLD_UTXO\nfrom .openfood_env import WALLET_JULIAN_START_THRESHOLD_UTXO_VALUE\nfrom .openfood_env import WALLET_JULIAN_STOP\nfrom .openfood_env import WALLET_JULIAN_STOP_THRESHOLD_BALANCE\nfrom .openfood_env import WALLET_JULIAN_STOP_THRESHOLD_UTXO\nfrom .openfood_env import WALLET_JULIAN_STOP_THRESHOLD_UTXO_VALUE\nfrom .openfood_env import WALLET_BB_DATE\nfrom .openfood_env import WALLET_BB_DATE_THRESHOLD_BALANCE\nfrom .openfood_env import WALLET_BB_DATE_THRESHOLD_UTXO\nfrom .openfood_env import WALLET_BB_DATE_THRESHOLD_UTXO_VALUE\nfrom .openfood_env import WALLET_ORIGIN_COUNTRY\nfrom .openfood_env import WALLET_ORIGIN_COUNTRY_THRESHOLD_BALANCE\nfrom .openfood_env import WALLET_ORIGIN_COUNTRY_THRESHOLD_UTXO\nfrom .openfood_env import WALLET_ORIGIN_COUNTRY_THRESHOLD_UTXO_VALUE\n\nfrom dotenv import load_dotenv\nfrom . import transaction, bitcoin\nfrom . import rpclib\nfrom .transaction import Transaction\nfrom slickrpc import Proxy\nimport subprocess\nimport requests\nimport json\nload_dotenv(verbose=True)\nSCRIPT_VERSION = 0.00012111\n\nRPC = \"\"\nKV1RPC = \"\"\nURL_IMPORT_API_RAW_REFRESCO_INTEGRITY_PATH = IMPORT_API_BASE_URL + DEV_IMPORT_API_RAW_REFRESCO_INTEGRITY_PATH\nURL_IMPORT_API_RAW_REFRESCO_TSTX_PATH = IMPORT_API_BASE_URL + DEV_IMPORT_API_RAW_REFRESCO_TSTX_PATH\nURL_openfood_API_ORGANIZATION = openfood_API_BASE_URL + openfood_API_ORGANIZATION\nURL_openfood_API_ORGANIZATION_BATCH = openfood_API_BASE_URL + openfood_API_ORGANIZATION_BATCH\n\n\n# helper mothods\ndef is_json(myjson):\n try:\n json_object = json.loads(myjson)\n except ValueError as e:\n return False\n return True\n\n\n# test done\ndef connect_node():\n global RPC\n print(\"Connecting to: \" + KOMODO_NODE + \":\" + RPC_PORT)\n RPC = Proxy(\"http://\" + RPC_USER + \":\" + RPC_PASSWORD + \"@\" + KOMODO_NODE + \":\" + RPC_PORT)\n return True\n\n\n# test done\ndef connect_kv1_node():\n global KV1RPC\n print(\"Connecting KV to: \" + KV1_NODE + \":\" + KV1_RPC_PORT)\n KV1RPC = Proxy(\"http://\" + KV1_RPC_USER + \":\" + KV1_RPC_PASSWORD + \"@\" + KV1_NODE + \":\" + KV1_RPC_PORT)\n return True\n\n\n#no test\ndef kvupdate_wrapper(kv_key, kv_value, kv_days, kv_passphrase):\n if(type(kv_value) == type({\"this\": \"is\", \"a\": \"json\"})):\n kv_value = json.dumps(kv_value)\n txid = rpclib.kvupdate(RPC, kv_key, kv_value, kv_days, kv_passphrase)\n return txid\n\n#no test\ndef kvsearch_wrapper(kv_key):\n kv_response = rpclib.kvsearch(RPC, kv_key)\n return kv_response\n\n\n#no test\ndef oracle_create(name, description, data_type):\n or_responce = rpclib.oracles_create(RPC, name, description, data_type)\n return or_responce\n\n#no test\ndef oracle_fund(or_id):\n or_responce = rpclib.oracles_fund(RPC, or_id)\n return or_responce\n\n#no test\ndef oracle_register(or_id, data_fee):\n or_responce = rpclib.oracles_register(RPC, or_id, data_fee)\n return or_responce\n\n#no test\ndef oracle_subscribe(or_id, publisher_id, data_fee):\n or_responce = rpclib.oracles_subscribe(RPC, or_id, publisher_id, data_fee)\n return or_responce\n\n#no test\ndef oracle_info(or_id):\n or_responce = rpclib.oracles_info(RPC, or_id)\n return or_responce\n\n#no test\ndef oracle_data(or_id, hex_string):\n or_responce = rpclib.oracles_data(RPC, or_id, hex_string)\n return or_responce\n\n#no test\ndef oracle_list():\n or_responce = rpclib.oracles_list(RPC)\n return or_responce\n\n#no test\ndef oracle_samples(oracletxid, batonutxo, num):\n or_responce = rpclib.oracles_samples(RPC, oracletxid, batonutxo, num)\n return or_responce\n\ndef find_oracleid_with_pubkey(pubkey):\n\tor_responce = oracle_list()\n\tfor oracle in or_responce:\n\t\toracle = oracle_info(oracle)\n\t\tfor registered in oracle['registered']:\n\t\t\tif registered['publisher'] == pubkey:\n\t\t\t\treturn oracle['txid']\n# test done\ndef sendtoaddress_wrapper(to_address, amount):\n send_amount = round(amount, 10)\n txid = rpclib.sendtoaddress(RPC, to_address, send_amount)\n return txid\n\n\n# test done\ndef sendmany_wrapper(from_address, recipients_json):\n txid = rpclib.sendmany(RPC, from_address, recipients_json)\n return txid\n\n\n# test done\ndef signmessage_wrapper(data):\n signed_data = rpclib.signmessage(RPC, THIS_NODE_RADDRESS, data)\n return signed_data\n\n\n# test done\ndef housekeeping_tx():\n return sendtoaddress_wrapper(HOUSEKEEPING_RADDRESS, SCRIPT_VERSION)\n\n\n# test done\ndef sendtoaddressWrapper(address, amount, amount_multiplier):\n print(\"Deprecated: use sendtoaddress_wrapper\")\n send_amount = round(amount * amount_multiplier, 10) # rounding 10??\n txid = rpclib.sendtoaddress(RPC, address, send_amount)\n return txid\n\n\n# test done\ndef check_sync():\n general_info = rpclib.getinfo(RPC)\n sync = general_info['longestchain'] - general_info['blocks']\n\n print(\"Chain info. Longest chain, blocks, sync diff\")\n print(general_info['longestchain'])\n\n print(general_info['blocks'])\n\n print(sync)\n\n if sync >= BLOCKNOTIFY_CHAINSYNC_LIMIT:\n print('the chain is not synced, try again later')\n exit()\n\n print(\"Chain is synced\")\n return sync\n\n\n# test done\ndef check_node_wallet():\n # check wallet management\n try:\n print(\"Validating node wallet with \" + THIS_NODE_RADDRESS)\n is_mine = rpclib.validateaddress(RPC, THIS_NODE_RADDRESS)['ismine']\n print(is_mine)\n if is_mine is False:\n rpclib.importprivkey(RPC, THIS_NODE_WIF)\n is_mine = rpclib.validateaddress(RPC, THIS_NODE_RADDRESS)['ismine']\n return is_mine\n except Exception as e:\n print(e)\n print(\"## CHECK NODE WALLET ERROR ##\")\n print(\"# Things that could be wrong:\")\n print(\"# Wallet is not imported on this node or wallet mismatch to env\")\n print(\"# Node is not available. Check debug.log for details\")\n print(\"# If node is rescanning, will take a short while\")\n print(\"# If changing wallet & env, rescan will occur\")\n print(\"# Exiting.\")\n print(\"##\")\n exit()\n\n\ndef check_kv1_wallet():\n # check wallet management\n try:\n print(\"Validating kv1 wallet with \" + THIS_NODE_RADDRESS)\n is_mine = rpclib.validateaddress(KV1RPC, THIS_NODE_RADDRESS)['ismine']\n print(is_mine)\n if is_mine is False:\n rpclib.importprivkey(KV1RPC, THIS_NODE_WIF)\n is_mine = rpclib.validateaddress(KV1RPC, THIS_NODE_RADDRESS)['ismine']\n return is_mine\n except Exception as e:\n print(e)\n print(\"## CHECK KV1 WALLET ERROR ##\")\n print(\"# Things that could be wrong:\")\n print(\"# Wallet is not imported on this node or wallet mismatch to env\")\n print(\"# Node is not available. Check debug.log for details\")\n print(\"# If node is rescanning, will take a short while\")\n print(\"# If changing wallet & env, rescan will occur\")\n print(\"# Exiting.\")\n print(\"##\")\n exit()\n\n\n# test done\ndef fund_offline_wallet(offline_wallet_raddress):\n json_object = {\n offline_wallet_raddress: 11.2109\n }\n sendmany_txid = sendmany_wrapper(THIS_NODE_RADDRESS, json_object)\n return sendmany_txid\n\n# test done\ndef is_below_threshold_balance(check_this, balance_threshold):\n if( check_this < balance_threshold * 100000000 ):\n return True\n\n\ndef check_offline_wallets():\n print(\"Check offline wallets: getXXXWallet, getBalance (if low then fund), getUTXOCount\")\n wallet_delivery_date = getOfflineWalletByName(WALLET_DELIVERY_DATE)\n wallet_pon = getOfflineWalletByName(WALLET_PON)\n wallet_tin = getOfflineWalletByName(WALLET_TIN)\n wallet_prod_date = getOfflineWalletByName(WALLET_PROD_DATE)\n wallet_julian_start = getOfflineWalletByName(WALLET_JULIAN_START)\n wallet_julian_stop = getOfflineWalletByName(WALLET_JULIAN_STOP)\n wallet_origin_country = getOfflineWalletByName(WALLET_ORIGIN_COUNTRY)\n wallet_bb_date = getOfflineWalletByName(WALLET_BB_DATE)\n\n # print(\"Checking delivery date wallet: \" + wallet_delivery_date['address'])\n # check balance\n wallet_delivery_date_balance = int(explorer_get_balance(wallet_delivery_date['address']))\n print(wallet_delivery_date_balance)\n if is_below_threshold_balance(wallet_delivery_date_balance, WALLET_DELIVERY_DATE_THRESHOLD_BALANCE):\n print(\"FUND the \" + WALLET_DELIVERY_DATE + \" wallet because balance low\")\n funding_txid = fund_offline_wallet(wallet_delivery_date['address'])\n print(funding_txid)\n\n wallet_pon_balance = int(explorer_get_balance(wallet_pon['address']))\n print(wallet_pon_balance)\n if is_below_threshold_balance(wallet_pon_balance, WALLET_PON_THRESHOLD_BALANCE):\n print(\"FUND the \" + WALLET_PON + \" wallet because balance low\")\n funding_txid = fund_offline_wallet(wallet_pon['address'])\n print(funding_txid)\n\n wallet_tin_balance = int(explorer_get_balance(wallet_tin['address']))\n print(wallet_tin_balance)\n if is_below_threshold_balance(wallet_tin_balance, WALLET_TIN_THRESHOLD_BALANCE):\n print(\"FUND the \" + WALLET_TIN + \" wallet because balance low\")\n funding_txid = fund_offline_wallet(wallet_tin['address'])\n print(funding_txid)\n\n wallet_prod_date_balance = int(explorer_get_balance(wallet_prod_date['address']))\n print(wallet_prod_date_balance)\n if is_below_threshold_balance(wallet_prod_date_balance, WALLET_PROD_DATE_THRESHOLD_BALANCE):\n print(\"FUND the \" + WALLET_PROD_DATE + \" wallet because balance low\")\n funding_txid = fund_offline_wallet(wallet_prod_date['address'])\n print(funding_txid)\n\n wallet_julian_start_balance = int(explorer_get_balance(wallet_julian_start['address']))\n print(wallet_julian_start_balance)\n if is_below_threshold_balance(wallet_julian_start_balance, WALLET_JULIAN_START_THRESHOLD_BALANCE):\n print(\"FUND the \" + WALLET_JULIAN_START + \" wallet because balance low\")\n funding_txid = fund_offline_wallet(wallet_julian_start['address'])\n print(funding_txid)\n\n wallet_julian_stop_balance = int(explorer_get_balance(wallet_julian_stop['address']))\n print(wallet_julian_stop_balance)\n if is_below_threshold_balance(wallet_julian_stop_balance, WALLET_JULIAN_STOP_THRESHOLD_BALANCE):\n print(\"FUND the \" + WALLET_JULIAN_STOP + \" wallet because balance low\")\n funding_txid = fund_offline_wallet(wallet_julian_stop['address'])\n print(funding_txid)\n\n wallet_origin_country_balance = int(explorer_get_balance(wallet_origin_country['address']))\n print(wallet_origin_country_balance)\n if is_below_threshold_balance(wallet_origin_country_balance, WALLET_ORIGIN_COUNTRY_THRESHOLD_BALANCE):\n print(\"FUND the \" + WALLET_ORIGIN_COUNTRY + \" wallet because balance low\")\n funding_txid = fund_offline_wallet(wallet_origin_country['address'])\n print(funding_txid)\n\n wallet_bb_date_balance = int(explorer_get_balance(wallet_bb_date['address']))\n print(wallet_bb_date_balance)\n if is_below_threshold_balance(wallet_bb_date_balance, WALLET_BB_DATE_THRESHOLD_BALANCE):\n print(\"FUND the \" + WALLET_BB_DATE + \" wallet because balance low\")\n funding_txid = fund_offline_wallet(wallet_bb_date['address'])\n print(funding_txid)\n\n # check utxo count\n utxo_count = explorer_get_utxos(wallet_delivery_date['address'])\n print(utxo_count)\n # next needs to be manual tx, sendmany does not function like this\n # if low, fund with sendmany by adding threshold balance x3 utxo threshold\n # if( len(utxo_count) < WALLET_DELIVERY_DATE_THRESHOLD_UTXO):\n # print(\"FUND the wallet because low utxo count\")\n # fund_offline_wallet(wallet_delivery_date['address'])\n\ndef organization_certificate_noraddress(url, org_id, THIS_NODE_RADDRESS):\n try:\n res = requests.get(url)\n except Exception as e:\n raise Exception(e)\n\n certs_no_addy = res.text\n certs_no_addy = json.loads(certs_no_addy)\n # the issuer, issue date, expiry date, identifier (not the db id, the certificate serial number / identfier)\n\n for cert in certs_no_addy:\n raw_json = {\n \"issuer\": cert['issuer'],\n \"issue_date\": cert['date_issue'],\n \"expiry_date\": cert['date_expiry'],\n \"identfier\": cert['identifier']\n }\n raw_json = json.dumps(raw_json)\n addy = gen_wallet(raw_json)\n # id = str(cert['id'])\n # url = IMPORT_API_BASE_URL + openfood_API_ORGANIZATION_CERTIFICATE + id + \"/\"\n\n try:\n data = {\"raddress\": addy['address'], \"pubkey\": addy['pubkey']}\n res = requests.patch(url, data=data)\n except Exception as e:\n raise Exception(e)\n\n\n# test done\ndef explorer_get_utxos(querywallet):\n print(\"Get UTXO for wallet \" + querywallet)\n # INSIGHT_API_KOMODO_ADDRESS_UTXO = \"insight-api-komodo/addrs/{querywallet}/utxo\"\n INSIGHT_API_KOMODO_ADDRESS_UTXO = \"insight-api-komodo/addrs/\" + querywallet + \"/utxo\"\n try:\n res = requests.get(EXPLORER_URL + INSIGHT_API_KOMODO_ADDRESS_UTXO)\n except Exception as e:\n raise Exception(e)\n # vouts = json.loads(res.text)\n # for vout in vouts:\n # print(vout['txid'] + \" \" + str(vout['vout']) + \" \" + str(vout['amount']) + \" \" + str(vout['satoshis']))\n return res.text\n\n# test done\ndef explorer_get_balance(querywallet):\n print(\"Get balance for wallet: \" + querywallet)\n INSIGHT_API_KOMODO_ADDRESS_BALANCE = \"insight-api-komodo/addr/\" + querywallet + \"/balance\"\n try:\n res = requests.get(EXPLORER_URL + INSIGHT_API_KOMODO_ADDRESS_BALANCE)\n except Exception as e:\n raise Exception(e)\n return res.text\n\n\n# test done\ndef createrawtx_wrapper(txids, vouts, to_address, amount):\n return rpclib.createrawtransaction(RPC, txids, vouts, to_address, amount)\n\n\n# test done\ndef createrawtxwithchange(txids, vouts, to_address, amount, change_address, change_amount):\n print(\"Create raw tx with change\")\n print(to_address)\n print(amount)\n print(change_address)\n print(change_amount)\n return rpclib.createrawtransactionwithchange(RPC, txids, vouts, to_address, amount, change_address, change_amount)\n\n\n# test done\ndef createrawtx(txids, vouts, to_address, amount):\n print(\"Deprecated: use createrawtx_wrapper\")\n return rpclib.createrawtransaction(RPC, txids, vouts, to_address, amount)\n\n\ndef createrawtx6(utxos_json, num_utxo, to_address, to_amount, fee, change_address):\n print(to_amount)\n rawtx_info = [] # return this with rawtx & amounts\n utxos = json.loads(utxos_json)\n # utxos.reverse()\n count = 0\n\n txids = []\n vouts = []\n amounts = []\n amount = 0\n\n for objects in utxos:\n if (objects['amount'] > 0.2 and objects['confirmations'] > 2) and count < num_utxo:\n count = count + 1\n easy_typeing2 = [objects['vout']]\n easy_typeing = [objects['txid']]\n txids.extend(easy_typeing)\n vouts.extend(easy_typeing2)\n amount = amount + objects['amount']\n amounts.extend([objects['satoshis']])\n\n # check this file in commit https://github.com/The-New-Fork/blocknotify-python/commit/f91a148b18840aaf08d7c7736045a8c924bd236b\n # for to_amount. When a wallet had no utxos, the resulting change was -0.00123, some sort of mis-naming maybe?\n #to_amount = 0.00123\n # change_tmp = 0\n if( amount > to_amount ):\n change_amount = round(amount - fee - to_amount, 10)\n else:\n # TODO\n print(\"### ERROR ### Needs to be caught, the to_amount is larger than the utxo amount, need more utxos\")\n change_amount = round(to_amount - amount - fee, 10)\n print(\"AMOUNTS: amount, #to_amount, change_amount, fee\")\n print(amount)\n print(to_amount)\n print(float(change_amount))\n print(fee)\n rawtx = \"\"\n if( change_amount < 0.01 ):\n print(\"Change too low, sending as miner fee \" + str(change_amount))\n change_amount = 0\n rawtx = createrawtx(txids, vouts, to_address, round(amount - fee, 10))\n\n else:\n rawtx = createrawtxwithchange(txids, vouts, to_address, to_amount, change_address, float(change_amount))\n\n rawtx_info.append({'rawtx': rawtx})\n rawtx_info.append({'amounts': amounts})\n return rawtx_info\n\n\n# test done\ndef createrawtx5(utxos_json, num_utxo, to_address, fee, change_address):\n rawtx_info = [] # return this with rawtx & amounts\n utxos = json.loads(utxos_json)\n # utxos.reverse()\n count = 0\n\n txids = []\n vouts = []\n amounts = []\n amount = 0\n\n for objects in utxos:\n if (objects['amount'] > 0.00005 and objects['confirmations'] > 2) and count < num_utxo:\n count = count + 1\n easy_typeing2 = [objects['vout']]\n easy_typeing = [objects['txid']]\n txids.extend(easy_typeing)\n vouts.extend(easy_typeing2)\n amount = amount + objects['amount']\n amounts.extend([objects['satoshis']])\n\n # check this file in commit https://github.com/The-New-Fork/blocknotify-python/commit/f91a148b18840aaf08d7c7736045a8c924bd236b\n # for to_amount. When a wallet had no utxos, the resulting change was -0.00123, some sort of mis-naming maybe?\n #to_amount = 0.00123\n change_tmp = 0\n change_amount = round(amount - fee - change_tmp, 10)\n print(\"AMOUNTS: amount, #to_amount, change_amount, fee\")\n print(amount)\n # print(to_amount)\n print(change_amount)\n print(fee)\n\n # rawtx = createrawtxwithchange(txids, vouts, to_address, to_amount, change_address, change_amount)\n rawtx = createrawtxwithchange(txids, vouts, to_address, change_tmp, change_address, change_amount)\n rawtx_info.append({'rawtx': rawtx})\n rawtx_info.append({'amounts': amounts})\n return rawtx_info\n\n\n# test done\ndef createrawtx4(utxos_json, num_utxo, to_address, fee):\n rawtx_info = [] # return this with rawtx & amounts\n utxos = json.loads(utxos_json)\n utxos.reverse()\n count = 0\n\n txids = []\n vouts = []\n amounts = []\n amount = 0\n\n for objects in utxos:\n if (objects['amount'] > 0.00005) and count < num_utxo:\n count = count + 1\n easy_typeing2 = [objects['vout']]\n easy_typeing = [objects['txid']]\n txids.extend(easy_typeing)\n vouts.extend(easy_typeing2)\n amount = amount + objects['amount']\n amounts.extend([objects['satoshis']])\n\n amount = round(amount, 10)\n print(\"AMOUNT\")\n print(amount)\n\n rawtx = createrawtx(txids, vouts, to_address, round(amount - fee, 10))\n rawtx_info.append({'rawtx': rawtx})\n rawtx_info.append({'amounts': amounts})\n return rawtx_info\n\n\n# test done\ndef decoderawtx_wrapper(tx):\n return rpclib.decoderawtransaction(RPC, tx)\n\n\n# test done\ndef decoderawtx(tx):\n print(\"Deprecated: use decoderawtx_wrapper(tx)\")\n return rpclib.decoderawtransaction(RPC, tx)\n\n\n# test done\ndef signtx(kmd_unsigned_tx_serialized, amounts, wif):\n txin_type, privkey, compressed = bitcoin.deserialize_privkey(wif)\n pubkey = bitcoin.public_key_from_private_key(privkey, compressed)\n\n jsontx = transaction.deserialize(kmd_unsigned_tx_serialized)\n inputs = jsontx.get('inputs')\n outputs = jsontx.get('outputs')\n locktime = jsontx.get('lockTime', 0)\n outputs_formatted = []\n # print(\"\\n###### IN SIGNTX FUNCTION #####\\n\")\n # print(jsontx)\n # print(inputs)\n # print(outputs)\n # print(locktime)\n\n for txout in outputs:\n outputs_formatted.append([txout['type'], txout['address'], (txout['value'])])\n print(\"Value of out before miner fee: \" + str(txout['value']))\n print(\"Value of out: \" + str(txout['value']))\n\n # print(\"\\nOutputs formatted:\\n\")\n # print(outputs_formatted)\n\n for txin in inputs:\n txin['type'] = txin_type\n txin['x_pubkeys'] = [pubkey]\n txin['pubkeys'] = [pubkey]\n txin['signatures'] = [None]\n txin['num_sig'] = 1\n txin['address'] = bitcoin.address_from_private_key(wif)\n txin['value'] = amounts[inputs.index(txin)] # required for preimage calc\n\n tx = Transaction.from_io(inputs, outputs_formatted, locktime=locktime)\n # print(\"### TX before signing###\")\n # print(tx)\n # print(\"### END TX ###\")\n tx.sign({pubkey: (privkey, compressed)})\n\n # print(\"\\nSigned tx:\\n\")\n # print(tx.serialize())\n # print(\"Return from signtx\")\n return tx.serialize()\n\n\ndef broadcast_via_explorer(explorer_url, signedtx):\n INSIGHT_API_BROADCAST_TX = \"insight-api-komodo/tx/send\"\n params = {'rawtx': signedtx}\n url = explorer_url + INSIGHT_API_BROADCAST_TX\n print(\"Broadcast via \" + url)\n\n try:\n broadcast_res = requests.post(url, data=params)\n except Exception as e:\n print(e)\n\n print(broadcast_res.text)\n broadcast_res = json.loads(broadcast_res.text)\n return broadcast_res['txid']\n\n\n# test done\ndef gen_wallet(data, label='NoLabelOK'):\n print(\"Creating a %s address signing with %s and data %s\" % (label, THIS_NODE_RADDRESS, data))\n signed_data = rpclib.signmessage(RPC, THIS_NODE_RADDRESS, data)\n # print(\"Signed data is %s\" % (signed_data))\n new_wallet_json = subprocess.getoutput(\"php genwallet.php \" + signed_data)\n print(\"Created wallet %s\" % (new_wallet_json))\n\n new_wallet = json.loads(new_wallet_json)\n\n return new_wallet\n\n\n# test done\ndef getOfflineWalletByName(name):\n obj = {\n \"name\": name\n }\n raw_json = json.dumps(obj)\n log_label = name\n offline_wallet = gen_wallet(raw_json, log_label)\n return offline_wallet\n\n\ndef dateToSatoshi(date):\n return int(date.replace('-', ''))\n\n\ndef sendToBatchDeliveryDate(batch_raddress, delivery_date):\n # delivery date\n print(\"SEND DELIVERY DATE\")\n date_as_satoshi = dateToSatoshi(delivery_date)\n print(date_as_satoshi)\n delivery_date_wallet = getOfflineWalletByName(WALLET_DELIVERY_DATE)\n utxos_json = explorer_get_utxos(delivery_date_wallet['address'])\n print(utxos_json)\n # works sending 0\n # rawtx_info = createrawtx5(utxos_json, 1, batch_raddress, 0, delivery_date_wallet['address'])\n rawtx_info = createrawtx6(utxos_json, 1, batch_raddress, round(date_as_satoshi/100000000, 10), 0, delivery_date_wallet['address'])\n print(\"DELIVERY DATE RAWTX: \" + str(rawtx_info))\n signedtx = signtx(rawtx_info[0]['rawtx'], rawtx_info[1]['amounts'], delivery_date_wallet['wif'])\n deliverydate_txid = broadcast_via_explorer(EXPLORER_URL, signedtx)\n raddress = delivery_date_wallet['address']\n # txid = sendtoaddressWrapper(batch_raddress, date_as_satoshi/100000000, 1)\n return deliverydate_txid\n\n\ndef sendToBatchPON(batch_raddress, pon):\n # delivery date\n print(\"SEND PON, check PON is accurate\")\n pon_as_satoshi = dateToSatoshi(pon)\n print(pon_as_satoshi)\n pon_wallet = getOfflineWalletByName(WALLET_PON)\n utxos_json = explorer_get_utxos(pon_wallet['address'])\n print(utxos_json)\n # works sending 0\n # rawtx_info = createrawtx5(utxos_json, 1, batch_raddress, 0, delivery_date_wallet['address'])\n rawtx_info = createrawtx6(utxos_json, 1, batch_raddress, round(pon_as_satoshi/100000000, 10), 0, pon_wallet['address'])\n print(\"PON RAWTX: \" + str(rawtx_info))\n signedtx = signtx(rawtx_info[0]['rawtx'], rawtx_info[1]['amounts'], pon_wallet['wif'])\n pon_txid = broadcast_via_explorer(EXPLORER_URL, signedtx)\n raddress = pon_wallet['address']\n # txid = sendtoaddressWrapper(batch_raddress, date_as_satoshi/100000000, 1)\n return pon_txid\n\n\n# test done\ndef offlineWalletGenerator_fromObjectData_certificate(objectData):\n obj = {\n \"issuer\": objectData['issuer'],\n \"issue_date\": objectData['date_issue'],\n \"expiry_date\": objectData['date_expiry'],\n \"identfier\": objectData['identifier']\n }\n\n print(obj)\n log_label = objectData['identifier']\n raw_json = json.dumps(obj)\n \n print(\"libopenfood->offlineWalletGenerator object data as json: \" + raw_json)\n\n offline_wallet = gen_wallet(raw_json, log_label)\n\n return offline_wallet\n\n\n# test done\ndef utxo_bundle_amount(utxos_obj):\n count = 0\n list_of_ids = []\n list_of_vouts = []\n amount = 0\n\n for objects in utxos_obj:\n if (objects['amount']):\n count = count + 1\n easy_typeing2 = [objects['vout']]\n easy_typeing = [objects['txid']]\n list_of_ids.extend(easy_typeing)\n list_of_vouts.extend(easy_typeing2)\n amount = amount + objects['amount']\n\n amount = round(amount, 10)\n return amount\n\n\n# test done\ndef get_batches_no_timestamp():\n print(\"***** start import api timestamping integrity - raw/refresco/require_integrity/\")\n url = IMPORT_API_BASE_URL + DEV_IMPORT_API_RAW_REFRESCO_REQUIRE_INTEGRITY_PATH\n print(\"Trying: \" + url)\n\n try:\n res = requests.get(url)\n except Exception as e:\n print(\"###### REQUIRE INTEGRITY URL ERROR: \", e)\n print(\"20201020 - url not sending nice response \" + url)\n\n print(res.text)\n\n raw_json = res.text\n batches_no_timestamp = \"\"\n\n try:\n batches_no_timestamp = json.loads(raw_json)\n except Exception as e:\n print(\"10009 failed to parse to json because of\", e)\n\n print(\"***** New batch requires timestamping: \" + str(len(batches_no_timestamp)))\n return batches_no_timestamp\n\n\n# has test\ndef get_batches():\n print(\"10009 start import api - raw/refresco\")\n url = IMPORT_API_BASE_URL + DEV_IMPORT_API_RAW_REFRESCO_PATH\n print(\"Trying: \" + url)\n\n try:\n res = requests.get(url)\n except Exception as e:\n print(\"###### REQUIRE INTEGRITY URL ERROR: \", e)\n print(\"20201020 - url not sending nice response \" + url)\n\n print(res.text)\n\n raw_json = res.text\n batches = \"\"\n\n try:\n batches = json.loads(raw_json)\n except Exception as e:\n print(\"10009 failed to parse to json because of\", e)\n\n print(\"New batch requires timestamping: \" + str(len(batches)))\n return batches\n\n\n# has test function\ndef get_certificates_no_timestamp():\n url = openfood_API_BASE_URL + openfood_API_ORGANIZATION_CERTIFICATE_NORADDRESS\n try:\n res = requests.get(url)\n except Exception as e:\n raise Exception(e)\n\n certs_no_addy = json.loads(res.text)\n return certs_no_addy\n\n\ndef fund_certificate(certificate_address):\n txid = sendtoaddress_wrapper(certificate_address, FUNDING_AMOUNT_CERTIFICATE)\n return txid\n\n\n# test done\ndef postWrapper(url, data):\n res = requests.post(url, data=data)\n if(res.status_code == 200 | res.status_code == 201):\n return res.text\n else:\n obj = json.dumps({\"error\": res.reason})\n return obj\n\n\n# test done\ndef putWrapper(url, data):\n res = requests.put(url, data=data)\n\n if(res.status_code == 200):\n return res.text\n else:\n obj = json.dumps({\"error\": res.reason})\n return obj\n\n\n# has test function\ndef patchWrapper(url, data):\n res = requests.patch(url, data=data)\n\n if(res.status_code == 200):\n return res.text\n else:\n obj = json.dumps({\"error\": res.reason})\n return obj\n\n\n# has test function\ndef getWrapper(url):\n res = requests.get(url)\n\n if(res.status_code == 200):\n return res.text\n else:\n obj = json.dumps({\"error\": res.reason})\n return obj\n\n\n# test done\ndef get_jcapi_organization():\n print(\"GET openfood-api organization query: \" + URL_openfood_API_ORGANIZATION + \"?raddress=\" + THIS_NODE_RADDRESS)\n res = getWrapper(URL_openfood_API_ORGANIZATION + \"?raddress=\" + THIS_NODE_RADDRESS)\n print(res)\n organizations = json.loads(res)\n # TODO E721 do not compare types, use \"isinstance()\" pep8\n if type(organizations) == type(['d', 'f']):\n return organizations[0]\n return organizations\n\n\n# test done\ndef batch_wallets_generate_timestamping(batchObj, import_id):\n json_batch = json.dumps(batchObj)\n # anfp_wallet = gen_wallet(json_batch['anfp'], \"anfp\")\n # pon_wallet = gen_wallet(json_batch['pon'], \"pon\")\n bnfp_wallet = gen_wallet(batchObj['bnfp'], \"bnfp\")\n # pds_wallet = openfood.gen_wallet(data['pds'], \"pds\")\n # jds_wallet = openfood.gen_wallet(data['jds'], \"jds\")\n # jde_wallet = openfood.gen_wallet(data['jde'], \"jde\")\n # bbd_wallet = openfood.gen_wallet(data['bbd'], \"bbd\")\n # pc_wallet = openfood.gen_wallet(data['pc'], \"pc\")\n integrity_address = gen_wallet(json_batch, \"integrity address\")\n print(\"Timestamp-integrity raddress: \" + integrity_address['address'])\n data = {'name': 'timestamping',\n 'integrity_address': integrity_address['address'],\n 'batch': import_id,\n 'batch_lot_raddress': bnfp_wallet['address']\n }\n\n batch_wallets_update_response = postWrapper(URL_IMPORT_API_RAW_REFRESCO_INTEGRITY_PATH, data)\n print(\"POST response: \" + batch_wallets_update_response)\n return json.loads(batch_wallets_update_response)\n\n\n# test done\ndef batch_wallets_timestamping_update(batch_integrity):\n batch_integrity_url = URL_IMPORT_API_RAW_REFRESCO_INTEGRITY_PATH + batch_integrity['id'] + \"/\"\n print(batch_integrity)\n batch_integrity_response = putWrapper(batch_integrity_url, batch_integrity)\n return batch_integrity_response\n\n\n# test done\ndef batch_wallets_timestamping_start(batch_integrity, start_txid):\n batch_integrity_url = URL_IMPORT_API_RAW_REFRESCO_INTEGRITY_PATH + batch_integrity['id'] + \"/\"\n print(batch_integrity)\n batch_integrity['integrity_pre_tx'] = start_txid\n print(batch_integrity)\n # data = {'name': 'chris', 'integrity_address': integrity_address[\n # 'address'], 'integrity_pre_tx': integrity_start_txid, 'batch_lot_raddress': bnfp_wallet['address']}\n\n batch_integrity_start_response = putWrapper(batch_integrity_url, batch_integrity)\n return batch_integrity_start_response\n\n\n# test done\ndef batch_wallets_timestamping_end(batch_integrity, end_txid):\n batch_integrity['integrity_post_tx'] = end_txid\n print(batch_integrity)\n batch_integrity_end_response = batch_wallets_timestamping_update(batch_integrity)\n return batch_integrity_end_response\n\n\n# test done\ndef batch_wallets_fund_integrity_start(integrity_address):\n return sendtoaddress_wrapper(integrity_address, FUNDING_AMOUNT_TIMESTAMPING_START)\n\n\n# test done\ndef batch_wallets_fund_integrity_end(integrity_address):\n return sendtoaddress_wrapper(integrity_address, FUNDING_AMOUNT_TIMESTAMPING_END)\n\n\ndef organization_send_batch_links(batch_integrity):\n sample_pool_po = \"RWSVFtCJfRH5ErsXJCaz9YNVKx7PijxpoV\"\n sample_pool_batch_lot = \"R9X5CBJjmVmJe4a533hemBf6vCW2m3BAqH\"\n print(\"MAIN WALLET \" + THIS_NODE_RADDRESS + \" SENDMANY TO BATCH_LOT (bnfp), POOL_PO (pon), POOL_BATCH_LOT\")\n json_object = {sample_pool_po: SCRIPT_VERSION,\n sample_pool_batch_lot: SCRIPT_VERSION,\n batch_integrity['batch_lot_raddress']: SCRIPT_VERSION\n }\n sendmany_txid = sendmany_wrapper(THIS_NODE_RADDRESS, json_object)\n return sendmany_txid\n\n\ndef timestamping_save_batch_links(id, sendmany_txid):\n print(\"** txid ** (Main org wallet sendmany BATCH_LOT/POOL_PO/GTIN): \" + sendmany_txid)\n tstx_data = {'sender_raddress': THIS_NODE_RADDRESS,\n 'tsintegrity': id, 'sender_name': 'ORG WALLET', 'txid': sendmany_txid}\n ts_response = postWrapper(URL_IMPORT_API_RAW_REFRESCO_TSTX_PATH, tstx_data)\n print(\"POST ts_response: \" + ts_response)\n return ts_response\n\n\ndef timestamping_save_certificate(id, sender_name, sender_wallet, certificate_txid):\n print(\"** txid ** (Certificate to batch_lot): \" + certificate_txid)\n tstx_data = {'sender_raddress': sender_wallet['address'],\n 'tsintegrity': id, 'sender_name': sender_name, 'txid': certificate_txid}\n print(tstx_data)\n ts_response = postWrapper(URL_IMPORT_API_RAW_REFRESCO_TSTX_PATH, tstx_data)\n print(\"POST ts_response: \" + ts_response)\n return ts_response\n\n\n# test done\ndef get_certificate_for_test(url):\n return getWrapper(url)\n\n\n# test done\ndef get_certificate_for_batch():\n # TODO this is hardcoded, which is bad - needs to fetch by cert rules\n test_url = openfood_API_BASE_URL + openfood_API_ORGANIZATION_CERTIFICATE + \"8/\"\n certificate = json.loads(get_certificate_for_test(test_url))\n return certificate\n\n\ndef push_batch_data_consumer(jcapi_org_id, batch, batch_wallet):\n data = {'identifier': batch['bnfp'],\n 'jds': batch['jds'],\n 'jde': batch['jde'],\n 'date_production_start': batch['pds'],\n 'date_best_before': batch['bbd'],\n 'origin_country': batch['pc'],\n 'raddress': batch_wallet['address'],\n 'pubkey': batch_wallet['pubkey'],\n 'organization': jcapi_org_id}\n jcapi_response = postWrapper(URL_openfood_API_ORGANIZATION_BATCH, data=data)\n jcapi_batch_id = json.loads(jcapi_response)['id']\n print(\"BATCH ID @ openfood-API: \" + str(jcapi_batch_id))\n return jcapi_response\n","sub_path":"src/kvhelper/lib/openfood.py","file_name":"openfood.py","file_ext":"py","file_size_in_byte":35426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"627820563","text":"from collections import defaultdict\r\nfrom random import uniform\r\nfrom math import sqrt\r\nimport random\r\nimport time\r\n\r\nimport numpy as np\r\nnp.set_printoptions(suppress=True)\r\nnp.set_printoptions(precision=30)\r\nimport mvhe\r\n\r\n#读取待聚类数据集\r\ndef read_points(filename):\r\n # dataset = []\r\n # with open('data.txt', 'r') as file:\r\n # for line in file:\r\n # if line == '\\n':\r\n # continue\r\n # dataset.append(list(map(float, line.split(' '))))\r\n # file.close()\r\n # return dataset\r\n dataset = np.loadtxt(filename)\r\n return dataset\r\n\r\n#保存结果\r\ndef write_vhe_results(listResult, dataset, k):\r\n with open('vhe_result.txt', 'a') as file:\r\n for kind in range(k):\r\n file.write(\"CLASSINFO:%d\\n\" % (kind + 1))\r\n for j in listResult[kind]:\r\n file.write('%d\\n' % j)\r\n file.write('\\n')\r\n file.write('\\n\\n')\r\n file.close()\r\n\r\n#加密待聚类数据集\r\ndef data_enc(dataset):\r\n enc_dataset = np.zeros((row, col + K), dtype=object)\r\n for i in range(row):\r\n enc_dataset[i] = mvhe.encrypt(T, Mt, dataset[i])\r\n\r\n return enc_dataset\r\n\r\n#随机选取初始的k个聚类中心\r\ndef enc_generate_k(enc_dataset, k):\r\n # index = random.sample(range(0, len(enc_dataset)), k)\r\n index = [220, 306, 205, 78, 140]\r\n centers = [enc_dataset[i] for i in index]\r\n return centers\r\n\r\n#计算距离\r\ndef enc_disatance(a, b):\r\n # dimension = len(a)\r\n # sum = 0\r\n # for i in range(dimension):\r\n # sq = (a[i] - b[i]) ** 2\r\n # sum += sq\r\n # return sqrt(sum)\r\n # print((a-b).T)\r\n # print(H)\r\n # print(a-b)\r\n # print(((a-b).T.dot(H).dot(a-b))/(mvhe.w**2))\r\n return ((a-b).T.dot(H).dot(a-b))/(mvhe.w**2)\r\n\r\n#为每个点分配标签\r\ndef enc_assign_points(enc_dataset, centers):\r\n assignments = []\r\n for point in enc_dataset:\r\n shortest = float('inf')\r\n shortest_index = 0\r\n for i in range(len(centers)):\r\n value = enc_disatance(point, centers[i])\r\n if value < shortest:\r\n shortest = value\r\n shortest_index = i\r\n assignments.append(shortest_index)\r\n\r\n if len(set(assignments)) < len(centers):\r\n print(\"\\n--!!!产生随机数错误,请重新运行程序!!!--\\n\")\r\n exit()\r\n return assignments\r\n\r\n#计算k个聚类中点个数的最小公倍数,LCM=(n1,n2,...,nk), nj为每个聚类的点的个数\r\n# def LCM(num):\r\n# size = len(num)\r\n# idx = 1\r\n# i = num[0]\r\n# while idx < size:\r\n# j = num[idx]\r\n# # 用辗转相除法求i,j的最大公约数m\r\n# b = i if i < j else j # i,j中较小那个值\r\n# a = i if i > j else j # i,j中较大那个值\r\n# r = b # a除以b的余数\r\n# while(r != 0):\r\n# r = a % b\r\n# if r != 0:\r\n# a = b\r\n# b = r\r\n# lcm = i*j/b # 两个数的最小公倍数\r\n# i = lcm\r\n# idx += 1\r\n# return lcm\r\n\r\n#产生新的聚类中心\r\ndef enc_update_centers(enc_dataset, assignments, k):\r\n new_means = defaultdict(list)\r\n centers = []\r\n for assignment, point in zip(assignments, enc_dataset):\r\n new_means[assignment].append(point)\r\n\r\n # num = [0 for i in range(k)]\r\n # for j in range(k):\r\n # for i in range(len(enc_dataset)):\r\n # if assignments[i] == j:\r\n # num[j] += 1\r\n # lcm = LCM(num)\r\n\r\n for i in range(k):\r\n points = new_means[i]\r\n centers.append(point_avg(points))\r\n\r\n return centers\r\n\r\n#聚类中的点求均值\r\ndef point_avg(points):\r\n # enc_avg = np.zeros((1, col + K), dtype=object)\r\n # for p in points:\r\n # enc_avg = mvhe.addVector(enc_avg, p)\r\n # enc_avg = env_avg/len(points)\r\n # return enc_avg\r\n dimensions = len(points[0])\r\n new_center = []\r\n for dimension in range(dimensions):\r\n sum = 0\r\n for p in points:\r\n sum += p[dimension]\r\n new_center.append(float(\"%.8f\" % (sum / float(len(points)))))\r\n return new_center\r\n\r\ndef vhe_kmeans(dataset,k):\r\n enc_dataset = data_enc(dataset)\r\n k_point = enc_generate_k(enc_dataset, k)\r\n assignments = enc_assign_points(enc_dataset, k_point)\r\n print(assignments)\r\n print(k_point)\r\n old_assignments = None\r\n num = [0 for i in range(k)]\r\n iteration = 0\r\n while assignments != old_assignments:\r\n new_centers = enc_update_centers(enc_dataset, assignments, k)\r\n old_assignments = assignments\r\n assignments = enc_assign_points(enc_dataset, new_centers)\r\n iteration += 1\r\n\r\n dec_dataset = np.zeros((row, col), dtype=object)\r\n for i in range(row):\r\n dec_dataset[i] = mvhe.decrypt(S, enc_dataset[i])\r\n # print(dec_dataset[i])\r\n\r\n result = list(zip(assignments, dec_dataset))\r\n\r\n print('\\n\\n---------------------------------分类结果---------------------------------------\\n\\n')\r\n print('聚类中心:')\r\n new_centers = np.array(new_centers)\r\n dec_new_centers = np.zeros((k, col), dtype=object)\r\n for i in range(k):\r\n dec_new_centers[i] = mvhe.decrypt(S, new_centers[i])\r\n print(dec_new_centers)\r\n\r\n for j in range(k):\r\n for i in range(len(dataset)):\r\n if assignments[i] == j:\r\n num[j] += 1\r\n\r\n print('聚类点个数:')\r\n print(num)\r\n\r\n print('迭代次数:')\r\n print(iteration)\r\n\r\n print('\\n\\n---------------------------------标号简记---------------------------------------\\n\\n')\r\n for out in result:\r\n print(out, end='\\n')\r\n print('\\n\\n---------------------------------聚类结果---------------------------------------\\n\\n')\r\n listResult = [[] for i in range(k)]\r\n count = 0\r\n for i in assignments:\r\n listResult[i].append(count)\r\n count = count + 1\r\n write_vhe_results(listResult, dec_dataset, k)\r\n for kind in range(k):\r\n print(\"第%d类数据有:\" % (kind + 1))\r\n count = 0\r\n for j in listResult[kind]:\r\n print(j, end=' ')\r\n count = count + 1\r\n if count % 25 == 0:\r\n print('\\n')\r\n print('\\n')\r\n print('\\n\\n--------------------------------------------------------------------------------\\n\\n')\r\n\r\n\r\n# 读取数据集\r\nprint(\"Load dataset...\")\r\ndataset = read_points('data.txt')\r\ndataset = np.array(dataset)\r\nprint(\"Dataset has %d items and %d dims\" % (dataset.shape[0], dataset.shape[1]))\r\nprint(dataset[0])\r\n\r\n# 参数设置\r\nrow = dataset.shape[0]\r\ncol = dataset.shape[1]\r\nprint(row, col)\r\n\r\nK = 1\r\nN = col\r\nSt, Mt = mvhe.getinvertiblematrix(N + K)\r\nT = mvhe.getRandomMatrix(N, K, mvhe.tBound)\r\nS = mvhe.getSecretKey(T, St)\r\nH = np.dot(S.T, S)\r\n\r\ndef main():\r\n start = time.time()\r\n vhe_kmeans(dataset, 5)\r\n end = time.time()\r\n print(end-start)\r\n\r\n # k=5\r\n # print(dataset)\r\n # enc_dataset = data_enc(dataset)\r\n # print(enc_dataset)\r\n # k_point = enc_generate_k(enc_dataset, k)\r\n # print(k_point)\r\n # assignments = enc_assign_points(enc_dataset, k_point)\r\n # new_centers = enc_update_centers(enc_dataset, assignments, k)\r\n # print(len(new_centers[0]))\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n\r\n","sub_path":"kmeansvhe.py","file_name":"kmeansvhe.py","file_ext":"py","file_size_in_byte":7274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"591297698","text":"import requests\nimport time\nimport json\n\nfrom mlflow.pyfunc import scoring_server\nfrom mlflow.utils.proto_json_utils import _DateTimeEncoder\n\n\nclass ScoringServerClient:\n def __init__(self, host, port):\n self.url_prefix = f\"http://{host}:{port}\"\n\n def ping(self):\n ping_status = requests.get(url=self.url_prefix + \"/ping\")\n if ping_status.status_code != 200:\n raise Exception(f\"ping failed (error code {ping_status.status_code})\")\n\n def wait_server_ready(self, timeout=30, scoring_server_proc=None):\n begin_time = time.time()\n\n while True:\n time.sleep(0.3)\n try:\n self.ping()\n return\n except Exception:\n pass\n if time.time() - begin_time > timeout:\n break\n if scoring_server_proc is not None:\n return_code = scoring_server_proc.poll()\n if return_code is not None:\n raise RuntimeError(f\"Server process already exit with returncode {return_code}\")\n raise RuntimeError(\"Wait scoring server ready timeout.\")\n\n def invoke(self, data):\n \"\"\"\n Invoke inference on input data. The input data must be pandas dataframe or json instance.\n \"\"\"\n content_type = scoring_server.CONTENT_TYPE_JSON\n post_data = json.dumps(\n scoring_server._get_jsonable_obj(data, pandas_orient=\"split\"),\n cls=_DateTimeEncoder,\n )\n\n response = requests.post(\n url=self.url_prefix + \"/invocations\",\n data=post_data,\n headers={\"Content-Type\": content_type},\n )\n\n if response.status_code != 200:\n raise Exception(\n f\"Invocation failed (error code {response.status_code}, response: {response.text})\"\n )\n\n return scoring_server.infer_and_parse_json_input(response.text)\n","sub_path":"mlflow/pyfunc/scoring_server/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"361327714","text":"import socketserver\nimport os\nfrom subprocess import call\nimport time\nimport cv2\nimport pysftp\n\n\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nimport numpy as np\n\n\ndef predict_image():\n\timg_width, img_height = 160, 120\n\n\n\tmodel = load_model('./data/models/beispiel1.h5')\n\tmodel.compile(loss='binary_crossentropy',\n\t\t\t\t optimizer='rmsprop',\n\t\t\t\t metrics=['accuracy'])\n\n\n\timg = image.load_img('predict.png', target_size=(img_width, img_height))\n\tx = image.img_to_array(img)\n\tx = np.expand_dims(x, axis=0)\n\n\tclasses = model.predict_classes(x, batch_size=128)\n\tprint(classes)\n\n\n\n\nclass ChatRequestHandler(socketserver.BaseRequestHandler):\n\n\tdef handle(self):\n\n\t\taddr = self.client_address[0] \n\t\tprint(\"[%s] Verbindung hergestellt\" % addr)\n\t\twhile True: \n\t\t\ts = self.request.recv(1024)\n\t\t\tif s:\n\t\t\t\tprint(\"[%s] %s\" % (addr, s))\n\t\t\t\t\n\t\t\t\tprint(\"load model...\")\n\t\t\t\twith pysftp.Connection('192.168.178.103', username='pi', password='kevin') as sftp:\n\t\t\t\t\tsftp.get('/home/pi/Desktop/PiBits-master/ServoBlaster/user/picture.png')\n\t\t\t\t\t#predict_image()\n\t\t\t\t\t\t\n\n\t\t\telse: \n\t\t\t\tprint(\"[%s] Verbindung geschlossen\" % addr) \n\t\t\t\tbreak\n\n\nserver = socketserver.ThreadingTCPServer((\"\", 50001), ChatRequestHandler) \nserver.serve_forever()\n","sub_path":"ML_AP/bot/server_ryzen_AI.py","file_name":"server_ryzen_AI.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"319260702","text":"def validarNumero(prompt,min,max):\r\n while (True):\r\n try:\r\n x=int(input(prompt))\r\n assert x >= min and x <= max\r\n return x\r\n break\r\n except ValueError:\r\n print(\"Ingresar solo números\")\r\n except:\r\n print(\"El valor debe estar dentro del RANGO --> (-10..10) <--\")\r\n\r\nv = validarNumero(\"Ingrese un valor dentro de -10 a 10: 30\",-10,10)\r\n\r\nprint (\"El número es:\", v)\r\n \r\n","sub_path":"validarnumerorangos.py","file_name":"validarnumerorangos.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"501294617","text":"#!/usr/bin/env python3\n\nimport sys\n\n\"\"\"@package Action\nThis module defines the Action object, which is used, together with the ActionQueue class,\nto implement delayed function calls.\n\"\"\"\n\n# Note: Only currently supports Python3\n\n#############\n## Imports ##\n#############\nimport types\nfrom inspect import signature\n\n#############\n## Classes ##\n#############\n\n# Action Class\nclass Action :\n\t\"\"\"\n\tElement of an action queue\n\t\"\"\"\n\t\n\t# Constructors\n\t\n\tdef __init__( self , fn_to_be_called : types.FunctionType , fn_arg_list : list , ctr_val : int = 0 ) -> None :\n\t\t\"\"\"\n\t\tDefault constructor\n\t\tThe number of arguments is checked. It is fn_to_be_called's responsibility\n\t\tto check the types of the arguments.\n\n\t\t@param fn_to_be_called Function to be called (mandatory)\n\t\t@param fn_arg_list List of function arguments (mandatory)\n\t\t@param ctr_val Counter value (default to 0; optional)\n\t\t\"\"\"\n\t\tself.set_fn( fn_to_be_called , fn_arg_list )\n\t\tself.set_ctr( ctr_val )\n\n\t# Useful methods\n\n\tdef decrement( self , n : int = 1 ) -> None :\n\t\t\"\"\"\n\t\tDecrement the counter by n, defaulted to 1.\n\t\tIf the counter should be 0 or lower, it will not drop below 0.\n\t\tInstead, call the function with the associated arguments and\n\t\tset the counter to 0.\n\t\t@param n The amount by which the counter is decremented\n\t\t\"\"\"\n\t\tassert n >= 0\n\t\tself.__ctr_val -= n\n\t\tif self.__ctr_val <= 0 :\n\t\t\tself.__ctr_val = 0\n\t\t\tself.__fn_to_be_called( *self.__fn_arg_list )\n\n\t# Setter methods\n\n\tdef set_fn( self , fn_to_be_called : types.FunctionType , fn_arg_list : list ) -> None :\n\t\t\"\"\"\n\t\tAssigned function to be called and the argument list.\n\t\tNumber of args is checked. fn_to_be_called will need to check types of args.\n\t\t@param fn_to_be_called Function to be called\n\t\t@param fn_arg_list List of arguments passed to fn_to_be_called\n\t\t\"\"\"\n\t\tassert len( signature( fn_to_be_called ).parameters ) == len( fn_arg_list )\n\t\tself.__fn_to_be_called = fn_to_be_called\n\t\tself.__fn_arg_list = fn_arg_list\n\n\tdef set_ctr( self , ctr_val : int ) -> None :\n\t\t\"\"\"\n\t\tChecks that ctr_val is 0 or greater, and sets the counter value accordingly.\n\t\t@param ctr_val The new counter value\n\t\t\"\"\"\n\t\tassert ctr_val >= 0\n\t\tself.__ctr_val = ctr_val\n\n\t# Getter methods\n\n\tdef get_fn( self ) -> types.FunctionType :\n\t\t\"\"\"\n\t\tReturns the function associated with this action.\n\t\t\"\"\"\n\t\treturn self.__fn_to_be_called\n\n\tdef get_args( self ) -> list :\n\t\t\"\"\"\n\t\tReturns the function args associated with this action.\n\t\t\"\"\"\n\t\treturn self.__fn_arg_list\n\n\tdef get_ctr( self ) -> int :\n\t\t\"\"\"\n\t\tReturns the counter value associated with this action.\n\t\t\"\"\"\n\t\treturn self.__ctr_val\n\nif __name__ == \"__main__\" :\n\t# Unit Test\n\terrors = 0\n\t\n\t# Test function\n\tdef fn( n ) :\n\t\tprint( \"Current value of n: \" + str( n ) )\n\n\t# Initialize action object\n\ttest_obj = None\n\ttry :\n\t\ttest_obj = Action( )\n\t\tprint( \"Action doesn't break if instantiated with wrong number of args!\" )\n\t\terrors += 1\n\texcept TypeError :\n\t\tprint( \"Great! Action breaks if instantiated with wrong number of args!\" )\n\t# Set function args\n\ttest_obj = Action( fn , [ 1 ] )\n\t# Test decrement when ctr is 0\n\tprint( \"We should now see the function be called.\" )\n\ttest_obj.decrement( )\n\t# Test getters\n\tprint( \"Testing getters\" )\n\tprint( \"Function object: \" + str( test_obj.get_fn( ) ) )\n\tprint( \"Args: \" + str( test_obj.get_args( ) ) )\n\tif test_obj.get_args( ) != [ 1 ] :\n\t\tprint( \"Wrong args!\" )\n\t\terrors += 1\n\tprint( \"Ctr: \" + str( test_obj.get_ctr( ) ) )\n\tif test_obj.get_ctr( ) != 0 :\n\t\tprint( \"Wrong counter val!\" )\n\t\terrors += 1\n\t# Call setters and reset the counter\n\tdef fn2( x , y ) :\n\t\tprint( \"New string: \" + str( x + y ) )\n\ttest_obj.set_fn( fn2 , [ 1 , 3 ] )\n\tif test_obj.get_args( ) != [ 1 , 3 ] :\n\t\tprint( \"Wrong args!\" )\n\t\terrors += 1\n\ttest_obj.set_ctr( 3 )\n\tif test_obj.get_ctr( ) != 3 :\n\t\tprint( \"Wrong ctr!\" )\n\t\terrors += 1\n\t# Decrement a few times until function is called\n\ttest_obj.decrement( )\n\tprint( \"We should now see the function be called.\" )\n\ttest_obj.decrement( 5 )\n\tif test_obj.get_ctr( ) != 0 :\n\t\tprint( \"Wrong ctr!\" )\n\t\terrors += 1\n\t# Test constructor with optional argument\n\ttest_obj = Action( fn , [ 3 ] , 3 )\n\tif test_obj.get_ctr( ) != 3 :\n\t\tprint( \"Wrong ctr!\" )\n\t\terrors += 1\n\tif test_obj.get_args( ) != [ 3 ] :\n\t\tprint( \"Wrong args!\" )\n\t\terrors += 1\n\n\tprint( \"===================\" )\n\tprint( \"Unit test complete.\" )\n\tprint( \"Number of errors: \" + str( errors ) )\n\tprint( \"===================\" )\n\n\tsys.exit( errors )\n","sub_path":"src/simlib/src/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"179567225","text":"from flask import Blueprint, request as req, jsonify\nfrom selenium import webdriver\nfrom Server.utils import utils\nimport os\n\napp = Blueprint('image', __name__)\n\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument('headless')\nchrome_options.add_argument('no-sandbox')\n\ndriver = webdriver.Chrome(executable_path=os.getcwd()+\"/Server/utils/\"+utils.check_os_type()+\"_chromedriver\", chrome_options=chrome_options)\n\ndriver.implicitly_wait(3)\n\n@app.route('/', methods=['GET'])\ndef image_main():\n return \"

    Image Route

    \"\n\n\n@app.route('/check', methods=['POST'])\ndef image_check():\n images = []\n\n count = 0\n\n r_url = req.form['url']\n\n driver.get(r_url)\n\n print(\"URL :\",r_url)\n\n image_elements = driver.find_elements_by_tag_name('img')\n\n for element in image_elements:\n\n images.append(element.get_attribute('src'))\n\n print(\"Detected Images : \"+str(len(images)))\n\n print(images)\n\n check_data = utils.check_toto_banner(images)\n\n print(check_data)\n\n state_data = False\n\n for i in check_data:\n if i == True:\n state_data = True\n count = count+1\n\n # driver.quit()\n\n return_data = {\n \"check\" : state_data,\n \"count\" : count\n }\n\n return jsonify(return_data)\n\n\n\n\n\n\n\n\n","sub_path":"Server/routes/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"400915371","text":"#\n# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.\n#\n\n\"\"\"\nKubernetes network manager\n\"\"\"\n\nimport gevent\nfrom gevent.queue import Queue\n\nfrom vnc_api.vnc_api import *\n\nimport common.logger as logger\nimport common.args as kube_args\nimport vnc.vnc_kubernetes as vnc_kubernetes\nimport kube.kube_monitor as kube_monitor\nimport kube.namespace_monitor as namespace_monitor\nimport kube.pod_monitor as pod_monitor\nimport kube.service_monitor as service_monitor\nimport kube.network_policy_monitor as network_policy_monitor\nimport kube.endpoint_monitor as endpoint_monitor\nimport kube.ingress_monitor as ingress_monitor\n\nclass KubeNetworkManager(object):\n def __init__(self, args=None):\n self.args = args\n self.logger = logger.KubeManagerLogger(args)\n self.q = Queue()\n\n kube_api_connected = False\n while not kube_api_connected:\n try:\n self.kube = kube_monitor.KubeMonitor(\n args=self.args, logger=self.logger, q=self.q)\n\n self.namespace = namespace_monitor.NamespaceMonitor(\n args=self.args, logger=self.logger, q=self.q)\n\n self.pod = pod_monitor.PodMonitor(args=self.args,\n logger=self.logger, q=self.q)\n\n self.service = service_monitor.ServiceMonitor(\n args=self.args, logger=self.logger, q=self.q)\n\n self.network_policy =\\\n network_policy_monitor.NetworkPolicyMonitor(args=self.args,\n logger=self.logger, q=self.q)\n\n self.endpoint = \\\n endpoint_monitor.EndPointMonitor(args=self.args,\n logger=self.logger, q=self.q)\n\n self.ingress = \\\n ingress_monitor.IngressMonitor(args=self.args,\n logger=self.logger, q=self.q)\n\n kube_api_connected = True\n\n except Exception as e:\n time.sleep(5)\n\n self.vnc = vnc_kubernetes.VncKubernetes(args=self.args,\n logger=self.logger, q=self.q, kube=self.kube)\n\n def _kube_object_cache_enabled(self):\n return True if self.args.kube_object_cache == 'True' else False;\n\n def start_tasks(self):\n self.logger.info(\"Starting all tasks.\")\n\n gevent.joinall([\n gevent.spawn(self.vnc.vnc_process),\n gevent.spawn(self.namespace.namespace_callback),\n gevent.spawn(self.service.service_callback),\n gevent.spawn(self.pod.pod_callback),\n gevent.spawn(self.network_policy.network_policy_callback),\n gevent.spawn(self.endpoint.endpoint_callback),\n gevent.spawn(self.ingress.ingress_callback),\n ])\n\ndef main():\n args = kube_args.parse_args()\n kube_nw_mgr = KubeNetworkManager(args)\n kube_nw_mgr.start_tasks()\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/container/kube-manager/kube_manager/kube_manager.py","file_name":"kube_manager.py","file_ext":"py","file_size_in_byte":2901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"629643190","text":"# Copyright 2019 Wilhelm Putz\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom jinjamator.tools.xlsx_tools import XLSXReader, XLSXWriter\n\nimport os\n\n\ndef load(path, **kwargs):\n if not os.path.isabs(path):\n path = os.path.join(self._parent.task_base_dir, path)\n xlsx = XLSXReader(\n path, kwargs.get(\"work_sheet_name\", \"Sheet1\"), kwargs.get(\"cache\", True)\n )\n xlsx.parse_header(kwargs.get(\"header_lines\", 1))\n xlsx.parse_data()\n return xlsx.data\n","sub_path":"jinjamator/plugins/content/file/excel.py","file_name":"excel.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"636799014","text":"from abc import ABC, abstractmethod\nfrom numba.core.registry import TargetRegistry, CPUDispatcher\n\nfrom threading import local as tls\n\n_active_context = tls()\n_active_context_default = 'cpu'\n\n\nclass HardwareRegistry(TargetRegistry):\n\n def __getitem__(self, item):\n try:\n return super().__getitem__(item)\n except KeyError:\n msg = \"No target is registered against '{}', known targets:\\n{}\"\n known = '\\n'.join([f\"{k: <{10}} -> {v}\"\n for k, v in hardware_registry.items()])\n raise ValueError(msg.format(item, known)) from None\n\n\nhardware_registry = HardwareRegistry()\n\n\nclass hardware_target(object):\n def __init__(self, name):\n self._orig_target = getattr(_active_context, 'target',\n _active_context_default)\n self.target = name\n\n def __enter__(self):\n _active_context.target = self.target\n\n def __exit__(self, ty, val, tb):\n _active_context.target = self._orig_target\n\n\ndef current_target():\n \"\"\"Returns the current target\n \"\"\"\n return getattr(_active_context, 'target', _active_context_default)\n\n\ndef get_local_target(context):\n \"\"\"\n Gets the local target from the call stack if available and the TLS\n override if not.\n \"\"\"\n # TODO: Should this logic be reversed to prefer TLS override?\n if len(context.callstack._stack) > 0:\n target = context.callstack[0].target\n else:\n target = hardware_registry.get(current_target(), None)\n if target is None:\n msg = (\"The hardware target found is not registered.\"\n \"Given target was {}.\")\n raise ValueError(msg.format(target))\n else:\n return target\n\n\ndef resolve_target_str(target_str):\n \"\"\"Resolves a target specified as a string to its Target class.\"\"\"\n return hardware_registry[target_str]\n\n\ndef resolve_dispatcher_from_str(target_str):\n \"\"\"Returns the dispatcher associated with a target hardware string\"\"\"\n target_hw = resolve_target_str(target_str)\n return dispatcher_registry[target_hw]\n\n\nclass JitDecorator(ABC):\n\n @abstractmethod\n def __call__(self):\n return NotImplemented\n\n\nclass Target(ABC):\n \"\"\" Implements a hardware/pseudo-hardware target \"\"\"\n\n @classmethod\n def inherits_from(cls, other):\n \"\"\"Returns True if this target inherits from 'other' False otherwise\"\"\"\n return issubclass(cls, other)\n\n\nclass Generic(Target):\n \"\"\"Mark the hardware target as generic, i.e. suitable for compilation on\n any target. All hardware must inherit from this.\n \"\"\"\n\n\nclass CPU(Generic):\n \"\"\"Mark the hardware target as CPU.\n \"\"\"\n\n\nclass GPU(Generic):\n \"\"\"Mark the hardware target as GPU, i.e. suitable for compilation on a GPU\n target.\n \"\"\"\n\n\nclass CUDA(GPU):\n \"\"\"Mark the hardware target as CUDA.\n \"\"\"\n\n\nclass ROCm(GPU):\n \"\"\"Mark the hardware target as ROCm.\n \"\"\"\n\n\nclass NPyUfunc(Target):\n \"\"\"Mark the hardware target as a ufunc\n \"\"\"\n\n\nhardware_registry['generic'] = Generic\nhardware_registry['CPU'] = CPU\nhardware_registry['cpu'] = CPU\nhardware_registry['GPU'] = GPU\nhardware_registry['gpu'] = GPU\nhardware_registry['CUDA'] = CUDA\nhardware_registry['cuda'] = CUDA\nhardware_registry['ROCm'] = ROCm\nhardware_registry['npyufunc'] = NPyUfunc\n\ndispatcher_registry = TargetRegistry(key_type=Target)\ndispatcher_registry[hardware_registry['cpu']] = CPUDispatcher\n","sub_path":"numba/core/extending_hardware.py","file_name":"extending_hardware.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"514703196","text":"from __future__ import division\r\nimport calendar\r\nfrom calendar import Calendar\r\n \r\nCAPITALIZATION = {\"month\":12, \"day\":365, \"end\":1}\r\n\r\nclass Deposit:\r\n def __init__(self, saldo=0, interest=0, duration=0, tax=19, year=2010):\r\n self.saldo = saldo\r\n self.interest = interest\r\n self.duration = duration\r\n self.capitalisation_key=\"month\"\r\n self.capitalisation = CAPITALIZATION[self.capitalisation_key]\r\n self.tax = tax\r\n self.year = year\r\n \r\n def normalize_capitalisation(self, interest, capitalisation):\r\n return (interest/capitalisation)/100\r\n \r\n def calculate_profit(self, saldo):\r\n interest = self.normalize_capitalisation(self.interest, self.capitalisation)\r\n return (saldo*interest)\r\n \r\n def daily_profit(self, saldo):\r\n capitalisation_key=\"day\"\r\n capitalisation = CAPITALIZATION[capitalisation_key]\r\n interest = self.normalize_capitalisation(self.interest, capitalisation)\r\n profit = interest*saldo\r\n return profit\r\n \r\n def monthly_profit(self, days, saldo):\r\n profit = 0\r\n for i in range(0, days):\r\n profit += self.daily_profit(saldo)\r\n profit -= self.calculate_tax(profit)\r\n return profit\r\n \r\n def calculate_total_profit(self, saldo):\r\n if self.capitalisation_key==\"month\":\r\n for i in range(0,self.duration):\r\n saldo+=self.monthly_profit(30, saldo)\r\n elif self.capitalisation_key==\"end\":\r\n profit = 0\r\n for i in range(0,self.duration):\r\n profit+=self.monthly_profit(self.month_days(self.year,i+1), saldo)\r\n #profit+=self.monthly_profit(30, saldo)\r\n saldo+=profit\r\n return saldo\r\n \r\n def calculate_tax(self, value):\r\n result = value*(self.tax/100)\r\n return result\r\n \r\n def month_days(self, year, month):\r\n return calendar.mdays[month]\r\n \r\nclass SavingsAccount(Deposit):\r\n \r\n def __init__(self, saldo=0, interest=0, duration=0, tax=19, year=2010):\r\n Deposit.__init__(self, saldo, interest, duration,tax, year)\r\n self.capitalisation_key=\"month\"\r\n self.capitalisation=CAPITALIZATION[self.capitalisation_key]\r\n \r\n def calculate_for_monthly_income(self, transfers, saldo):\r\n transfes_overall = 0\r\n for i in range(0, self.duration):\r\n saldo += self.monthly_profit(self.month_days(self.year,i+1), saldo)\r\n #saldo += self.monthly_profit(30, saldo)\r\n if i < transfers.__len__():\r\n saldo += transfers[i]\r\n transfes_overall += transfers[i]\r\n return {\"total\":saldo, \"transfes_overall\":transfes_overall}\r\n \r\nif __name__ == '__main__':\r\n sa = SavingsAccount(saldo=5000,interest=4.1, duration=12, year=2010, tax=19)\r\n transfers= [1500,1500,1500,1500,1500,1500,0,0]\r\n result = sa.calculate_for_monthly_income(transfers, sa.saldo)\r\n #print \"income_no_profit= \" + str(result[\"income\"])\r\n #print \"income_saldo= \" + str(result[\"income_saldo\"])\r\n \r\n print (\"profit= \" + str(result[\"total\"]-sa.saldo-result[\"transfes_overall\"]))\r\n print(\"total= \"+str(result[\"total\"]))\r\n konto_profit = result[\"total\"]-sa.saldo-result[\"transfes_overall\"] \r\n sa = SavingsAccount(saldo=10000,interest=5.35, duration=12, tax=19, year=2010)\r\n sa.capitalisation_key=\"end\"\r\n sa.capitalisation=CAPITALIZATION[sa.capitalisation_key]\r\n result2 = sa.calculate_total_profit(sa.saldo)\r\n print (\"lokata= \"+str(result2-sa.saldo))\r\n print (\"lokata= \"+str(konto_profit+(result2-sa.saldo)))\r\n ","sub_path":"calculations/src/money/functions/profit.py","file_name":"profit.py","file_ext":"py","file_size_in_byte":3672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"175073906","text":"import os\n\nimport sys\nfrom PyQt4.QtGui import QApplication, QGridLayout, QSizePolicy\nfrom taurus.qt.qtgui.container import TaurusWidget\nfrom taurus.qt.qtgui.display import QLed, TaurusLabel, TaurusLed\n\n\nclass TestWidget(TaurusWidget):\n def __init__(self, parent=None):\n super(TestWidget, self).__init__(parent)\n self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)\n self.layout = QGridLayout(self)\n self.setModel('sys/tg_test/1')\n self.led = StateLED(self)\n self.status_widget = StatusWidget(self)\n self.layout.addWidget(self.led, 0, 0)\n self.layout.addWidget(self.status_widget, 0, 1)\n self.resize(self.layout.sizeHint())\n\n\nclass StateLED(TaurusLed):\n def __init__(self, parent):\n super(StateLED, self).__init__(parent)\n self.setModel('/State')\n self.useParentModel = True\n\n\n\nclass StatusWidget(TaurusLabel):\n def __init__(self, parent):\n super(StatusWidget, self).__init__(parent)\n self.useParentModel = True\n self.setModel('/Status')\n\n\nif __name__ == '__main__':\n os.environ[\"TANGO_HOST\"] = \"tango-dev.m.cps.uj.edu.pl:10000\"\n app = QApplication(sys.argv)\n widget = TestWidget()\n widget.show()\n sys.exit(app.exec_())\n","sub_path":"tests&snippets/taurus_tests/parent_model_tests.py","file_name":"parent_model_tests.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"244744611","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport os\nimport pickle\n\ndef create_uniform_sphere_xyz():\n while True:\n xyz = np.random.normal(\n loc = 0,\n scale = 1,\n size = 3)\n if abs(xyz[2]) < 0.001:\n continue\n norm = np.linalg.norm(xyz, ord=2)\n if abs(norm) < 0.001:\n continue\n x,y,z = xyz / norm\n return [x,y,z]\n\n\ndef create_Track_txt(track_ranges_micron, sigma_track_range, crystal_distance, prob_crystal_dev):\n n_track = 50\n thickness_boron = 0.200\n thickness_protection = 0.060\n depth_boron = thickness_boron + thickness_protection\n reaction_point= np.random.uniform(depth_boron, thickness_protection)\n\n file_output = f\"track_{track_ranges_micron}_sig_{sigma_track_range:.2f}_crystal_{crystal_distance:.2f}_prob_{prob_crystal_dev:.2f}_Track.txt\"\n\n # loop\n list_tracks = []\n for _ in range(n_track):\n track_base = random.choice([track_ranges_micron, track_ranges_micron*5.1/2.6])\n track_range_base = track_base + reaction_point\n track_range = track_range_base + random.gauss(0, sigma_track_range)\n\n n_crystal = int(track_range / crystal_distance)\n list_grain_position = []\n for c in range(n_crystal):\n p = (c + 0.5) * crystal_distance\n rand_number = random.uniform(0, 1)\n if rand_number < prob_crystal_dev:\n \n list_grain_position.append(p)\n #print(f\"track:{i}, crystal:{c}, random_number:{rand_number:.3f}, position{p:.3f}\")\n\n this_track = {\"track_range_base\":track_range_base,\n \"track_range\": track_range,\n \"list_grain_position\": list_grain_position}\n list_tracks.append(this_track)\n #print(list_tracks)\n\n\n list_str_out = []\n for t in list_tracks:\n if len(t[\"list_grain_position\"]) > 0:\n for g in t[\"list_grain_position\"]:\n list_str_out.append( f\"1 0.0 0.0 {g*0.6*(55.0/20.0):.3f}\\n\" )\n list_str_out.append( f\"1 0.0 0.0 0.0\\n\" )\n list_str_out.append( f\"1 0.0 0.0 0.0\\n\" )\n\n\n with open(file_output, mode='w') as f:\n f.writelines(list_str_out)\n\n\n\n\n\nif __name__ == '__main__':\n\n # output dir\n output_dir = 'monte_carlo_simulation_range_emulsion'\n os.makedirs(f\"{output_dir}\", exist_ok=True)\n #np.random.seed(0)\n\n # parameters \n track_range_micron = [2.4, 2.6, 2.8, 3.0, 3.2]\n sigma_track_range = [0.5, 0.6, 0.7, 0.8, 0.9]\n crystal_distance = [0.04, 0.06]\n prob_crystal_dev = [0.07, 0.15]\n \n\n for r in track_range_micron:\n for s in sigma_track_range:\n for d in crystal_distance:\n for p in prob_crystal_dev:\n print(r, s, d, p)\n create_Track_txt(r, s, d, p)\n","sub_path":"monte_carlo_simulation_range_emulsion_positiondfference.py","file_name":"monte_carlo_simulation_range_emulsion_positiondfference.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"381859713","text":"# A Program to determine employee eligability for advancement\n\n# Created by: \n\n# Copyright CTHS Engineering, Inc., 2021\n# This code or any portion fo this code can be be reused without \n# previous approval from the company CIO or CEO, in writing.\n\nempName = \"Sam\"\n\n#Project1(P1) - New school wing\n#TA - Task Accuracy\n#EstBud - Estimated Budget\n#ActBud - Actual Budget\n#EstMP - Estimated Manpower\n#ActMP - Actual Manpower\nempP1TA = 92\nempP1EstBud = 1285000\nempP1ActBud = 1301346\nempP1EstMP = 1625\nempP1EstMP = 1650\n\n#Project2 - Custom motorcycle company warehouse\nempP2TA = 98\nempP2EstBud = 650000\nempP2ActBud = 624000\nempP2EstMP = 525\nempP2ActMP = 515\n\n#Project3 - Minor Nascar training track\nempP3TA = 96\nempP3EstBud = 2500000\nempP3ActBud = 3231325\nempP3EstMP = 1050\nempP3ActMP = 1250\n\n#Project4 - Man cave warehouse and house\nempP4TA = 92\nempP4EstBud = 825000\nempP4ActBud = 830000\nempP4EstMP = 400\nempP4ActMP = 375\n\n#your code goes below\n\n","sub_path":"review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"242404750","text":"import re\n\nplayers = 0\nmax_marble = 0\n\npattern = '[0-9]{1,10}'\ncompiled = re.compile(pattern)\nwith open('d9-inputs') as txtfile:\n for row in txtfile:\n ans = compiled.findall(row)\n\n players = int(ans[0])\n max_marble = int(ans[1])*100\n\nprint(players, max_marble)\n\nmarbles = [0, 1]\ncurrent_marble = 1\n\ncurrent_marble_worth = 2\ncurrent_player = 2\n\nplayer_list = {}\nfor player in range(players):\n player_list[player+1] = 0\n\nwhile current_marble_worth <= max_marble:\n placement = current_marble + 2\n if placement > len(marbles):\n placement -= len(marbles)\n\n if current_marble_worth % 23 == 0:\n player_list[current_player] = player_list[current_player] + current_marble_worth\n\n extra_score = current_marble - 7\n if extra_score < 0:\n extra_score = current_marble - 7 + len(marbles)\n\n player_list[current_player] = player_list[current_player] + marbles[extra_score]\n\n if extra_score + 1 >= len(marbles):\n current_marble = marbles[extra_score + 1 - len(marbles)]\n else:\n current_marble = extra_score\n\n marbles.remove(marbles[extra_score])\n\n else:\n marbles.insert(placement, current_marble_worth)\n current_marble = placement\n\n\n current_marble_worth += 1\n current_player += 1\n if current_player > players:\n current_player = 1\n\n\nbest_score = 0\nwinner = 0\nfor k,v in player_list.items():\n if v > best_score:\n best_score = v\n winner = k\n\nprint(winner, best_score)\n","sub_path":"Day 9/Puzzle 2.py","file_name":"Puzzle 2.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"71383092","text":"import unittest\nimport requests\nimport json\nfrom Global_base import global_base\nfrom parameterized import parameterized\n\n\nclass GetMeInfo(unittest.TestCase):\n \"\"\"我的页面接口\"\"\"\n def setUp(self):\n self.url = global_base.DefTool.url(self, '/app/profile/getMeInfo.do')\n\n def tearDown(self):\n print(\"请求地址为{}\".format(self.url))\n print(\"请求参数为{}\".format(json.dumps(self.params, indent=2, sort_keys=False, ensure_ascii=False)))\n print(\"请求结果为:{}\".format(json.dumps(self.result, indent=2, sort_keys=False, ensure_ascii=False)))\n\n @parameterized.expand([\n (\"我的页面请求成功\", \"1\", \"5\", \"POST\", \"1\", \"false\", \"request1565592555859\", \"867910035562539\", \"2.6.0\", \"15\",\n \"1003\", \"sinaif\", \"ef70fb3178dccde19df9295a68aca0a3\", \"qsj\")\n ])\n def test_getMeInfo(self, name, deviceType, recommendSize, method, pageIndex, json, callbackName,\n deviceId, ver, verno, productId, channelId, deviceToken, mjbname):\n \"\"\"我的页面接口\"\"\"\n pa = {\"deviceType\": deviceType, \"recommendSize\": recommendSize, \"method\": method,\n \"pageIndex\": pageIndex, \"json\": json, \"callbackName\": callbackName, \"deviceId\": deviceId, \"ver\": ver,\n \"verno\": verno, \"productId\": productId,\n \"channelId\": channelId, \"deviceToken\": deviceToken, \"mjbname\": mjbname}\n self.params = global_base.DefTool().payload(**pa)\n self.result = requests.post(url=self.url, data=self.params).json()\n self.assertEqual(self.result['msg'], 'ok')\n self.assertEqual(self.result[\"code\"], '200')\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"interface/app/get_me_Info_test.py","file_name":"get_me_Info_test.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"590203057","text":"import os\nimport pandas as pd\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import messagebox\n\n\ndef info():\n infowindow = Toplevel()\n infolabel = Label(infowindow, text=\"This tool 'walks' through a directory and returns the filename, filepath and filesize for all files inside the directory and its subfolders.\")\n infolabel.grid(row=0, column=0)\n \n blank7 = Label(infowindow, text=\"\")\n blank7.grid(row=1, column=0)\n \n infodirectory = Label(infowindow, text=\"Choose directory if you want to fetch info for all files inside a directory. You can specify certain filetypes.\")\n infodirectory.grid(row=2, column=0)\n \n blank8 = Label(infowindow, text=\"\")\n blank8.grid(row=3, column=0)\n \n infocsv = Label(infowindow, text=\"Choose csv if you have a '.csv' file with the filenames. The tool will only return the filepath and filesize for the filenames provided in the csv.\")\n infocsv.grid(row=4, column=0)\n \n\ndef open_path():\n path = filedialog.askdirectory(title=\"Select directory!\")\n show_path = Label(fetchfilesize, text=\"You chose this path: \" + path, bg=\"#e4e5e5\")\n show_path.grid(column=0, row=11, columnspan=4)\n blank = Label(fetchfilesize, text=\"\", bg=\"#e4e5e5\")\n blank.grid(column=0, row=10, columnspan=4)\n return path\n\n\ndef openfile():\n file = filedialog.askopenfile(title=\"Select file!\")\n return file\n\n\ndef save_file():\n location = filedialog.askdirectory(title=\"Save File!\")\n show_location = Label(fetchfilesize, text=\"Your file (output.xlsx) can be found here: \" + location, bg=\"#e4e5e5\")\n show_location.grid(column=0, row=12, columnspan=4)\n return location\n\n\ndef choose():\n choice = [variable.get(), variable2.get()]\n if tuple(choice) == ('','directory'):\n def start():\n column = [\"filename\", 'path', \"filesize (MB)\"]\n _list = []\n totalsize = 0\n filetypes = [var1.get(), var2.get(), var3.get(), var4.get(), var5.get(), var6.get(), var7.get(), var8.get(),\n var9.get()]\n while \"\" in filetypes:\n filetypes.remove(\"\")\n messagebox.showinfo(\"You chose filetype(s): \", filetypes)\n\n for x, y, z in os.walk(open_path()):\n\n for a in z:\n if a.endswith(tuple(filetypes)):\n b = os.path.join(x, a)\n c = os.path.getsize(b)\n d = round(c / (1024 * 1024), 3)\n totalsize += d\n e = str(a) + '%£~' + str(b) + '%£~' + str(d)\n f = e.split('%£~')\n\n _list.append(f)\n df = pd.DataFrame(_list, columns=column)\n messagebox.showinfo(\"Choose location\", \"Please choose a location to store the result\")\n\n # Windows OS\n df.to_excel(str(save_file()) + \"\\output.xlsx\")\n\n # linux - MAC OS\n df.to_excel(str(save_file()) + \"/output.xlsx\")\n\n size = Label(fetchfilesize, text=\"The total size is: \" + str(round(totalsize / 1024, 2)) + \" GB\",\n bg=\"#e4e5e5\")\n size.grid(row=14, column=0, columnspan=4)\n\n if len(_list) > 0:\n averagesize = totalsize / len(_list)\n average = Label(fetchfilesize, text=\"The average size is: \" + str(round(averagesize, 2)) + \" MB\",\n bg=\"#e4e5e5\")\n average.grid(row=15, column=0, columnspan=4)\n else:\n average = Label(fetchfilesize, text='The average size is: 0.0 MB', bg=\"#e4e5e5\")\n average.grid(row=15, column=0, columnspan=4)\n\n var1 = StringVar()\n var2 = StringVar()\n var3 = StringVar()\n var4 = StringVar()\n var5 = StringVar()\n var6 = StringVar()\n var7 = StringVar()\n var8 = StringVar()\n var9 = StringVar()\n\n checktif = Checkbutton(fetchfilesize, text=\".tif\", bg=\"#e4e5e5\", onvalue=\".tif\", offvalue=\"\", variable=var1)\n checkjpg = Checkbutton(fetchfilesize, text=\".jpg\", bg=\"#e4e5e5\", onvalue=\".jpg\", offvalue=\"\", variable=var2)\n checkwav = Checkbutton(fetchfilesize, text=\".wav\", bg=\"#e4e5e5\", onvalue=\".wav\", offvalue=\"\", variable=var3)\n checkmov = Checkbutton(fetchfilesize, text=\".mov\", bg=\"#e4e5e5\", onvalue=\".mov\", offvalue=\"\", variable=var4)\n checkmp3 = Checkbutton(fetchfilesize, text=\".mp3\", bg=\"#e4e5e5\", onvalue=\".mp3\", offvalue=\"\", variable=var5)\n checkmp4 = Checkbutton(fetchfilesize, text=\".mp4\", bg=\"#e4e5e5\", onvalue=\".mp4\", offvalue=\"\", variable=var6)\n checktiff = Checkbutton(fetchfilesize, text=\".tiff\", bg=\"#e4e5e5\", onvalue=\".tiff\", offvalue=\"\", variable=var7)\n checkJPG = Checkbutton(fetchfilesize, text=\".JPG\", bg=\"#e4e5e5\", onvalue=\".JPG\", offvalue=\"\", variable=var8)\n checkTIF = Checkbutton(fetchfilesize, text=\".TIF\", bg=\"#e4e5e5\", onvalue=\".TIF\", offvalue=\"\", variable=var8)\n\n checktif.grid(row=5, column=0)\n checkjpg.grid(row=5, column=1)\n checkwav.grid(row=5, column=2)\n checkmov.grid(row=5, column=3)\n checkmp3.grid(row=6, column=0)\n checkmp4.grid(row=6, column=1)\n checktiff.grid(row=6, column=2)\n checkJPG.grid(row=6, column=3)\n checkTIF.grid(row=6, column=4)\n\n blank2 = Label(text=\"\", bg=\"#e4e5e5\")\n blank2.grid(row=4, column=1)\n \n blank3 = Label(text=\"\", bg=\"#e4e5e5\")\n blank3.grid(row=7, column=1)\n\n buttonstart = Button(fetchfilesize, text=\"Start\", padx=50, pady=10, borderwidth=4, bg=\"#04a37b\", command=start)\n buttonstart.grid(row=8, column=1, columnspan=2)\n\n else:\n def start():\n column = [\"filename\", 'path', \"filesize (MB)\"]\n lijst = []\n\n for x, y, z in os.walk(open_path()):\n\n for a in z:\n b = os.path.join(x, a)\n c = os.path.getsize(b)\n d = round(c / (1024 * 1024), 3)\n e = str(a) + '%£~' + str(b) + '%£~' + str(d)\n f = e.split('%£~')\n lijst.append(f)\n df = pd.DataFrame(lijst, columns=column)\n messagebox.showinfo(\"Choose file\", \"Please open file with filenames (one column with header 'filename')\")\n filenames = pd.read_csv(open_file())\n result = pd.merge(filenames, df, left_on='filename', right_on=\"filename\", how='left')\n messagebox.showinfo(\"Choose location\", \"Please choose a location to store the result\")\n result.to_excel(save_file() + r\"\\result.xlsx\")\n \n \n blank4 = Label(text=\"\", bg=\"#e4e5e5\")\n blank4.grid(row=4, column=1)\n \n _info = Label(text=\"Press Start\", bg=\"#e4e5e5\")\n _info.grid(row=5, column=1)\n \n blank5 = Label(text=\"\", bg=\"#e4e5e5\")\n blank5.grid(row=6, column=1)\n\n buttonstart = Button(fetchfilesize, text=\"Start\", padx=50, pady=10, borderwidth=4, bg=\"#04a37b\", command=start)\n buttonstart.grid(row=7, column=1, columnspan=4)\n\n\nfetchfilesize = Tk()\nfetchfilesize.title(\"fetch filesize\")\nfetchfilesize.configure(bg=\"#e4e5e5\")\nfetchfilesize.geometry(\"900x550\")\n\nInfo = Label(text=\"Please choose filesource and press start\")\nInfo.grid(row=0, column=1)\n\nblank6 = Label(text=\"\", bg=\"#e4e5e5\")\nblank6.grid(row=2, column=1)\n\nvariable = StringVar()\nvariable2 = StringVar()\n\nFilesource1 = Checkbutton(fetchfilesize, text=\"csv\", variable=variable, onvalue=\"csv\", offvalue=\"\", bg=\"#e4e5e5\")\nFilesource2 = Checkbutton(fetchfilesize, text=\"directory\", variable=variable2, onvalue=\"directory\", offvalue=\"\", bg=\"#e4e5e5\")\n\n\nFilesource1.grid(row=1, column=1)\nFilesource2.grid(row=1, column=2)\n\nbuttonchoose = Button(fetchfilesize, text=\"Start\", padx=50, pady=10, borderwidth=4, bg=\"#04a37b\", command=choose)\nbuttonchoose.grid(row=3, column=1, columnspan=2)\n\nbuttoninfo = Button(fetchfilesize, text=\"Info\", borderwidth=4, bg=\"#b9bcbb\", command=info)\nbuttoninfo.grid(row=1, column=0)\n\nfetchfilesize.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"524021231","text":"import codecs\nimport json\nimport matplotlib.pyplot as plt\nimport math\nimport matplotlib.ticker as ticker\nimport numpy as np\nimport os\nimport random\nimport time\nfrom time import sleep\nimport subprocess\nimport re\n\nimport torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\nimport torch.utils.data\n\ntorch.set_num_threads(1)\n\nMAX_LENGTH = 50\n\nclass EncoderRNN(nn.Module):\n def __init__(self, input_size, hidden_size, dropout_p=0.1):\n super(EncoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.dropout_p = dropout_p\n\n self.embedding = nn.Embedding(input_size, hidden_size)\n self.dropout = nn.Dropout(self.dropout_p)\n self.gru = nn.GRU(hidden_size, hidden_size)\n\n\n def forward(self, input, hidden):\n word_embedded = self.embedding(input).view(1, 1, -1)\n word_embedded = self.dropout(word_embedded)\n output, hidden = self.gru(word_embedded, hidden)\n return output, hidden\n\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size)\n\n\nclass EncoderPOS(nn.Module):\n def __init__(self, input_size, hidden_size, dropout_p=0.1):\n super(EncoderPOS, self).__init__()\n self.hidden_size = hidden_size\n self.dropout_p = dropout_p\n\n self.word_embedding = nn.Embedding(input_size, hidden_size)\n self.pos_embedding = nn.Embedding(MAX_LENGTH, hidden_size)\n self.dropout = nn.Dropout(self.dropout_p)\n self.linear = nn.Linear(hidden_size*2, hidden_size)\n\n def forward(self, input, hidden):\n index = input[0]\n word = input[1]\n word_embedded = self.word_embedding(word).view(1, 1, -1)\n pos_embedded = self.pos_embedding(torch.tensor([index], dtype=torch.long)).view(1, 1, -1)\n\n combined_embedding = torch.cat((word_embedded.squeeze(0), pos_embedded.squeeze(0)), 1)\n output = self.dropout(combined_embedding)\n output = self.linear(output)\n return output, hidden\n\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size)\n\n\n\nclass AttnDecoderRNN(nn.Module):\n def __init__(self, hidden_size, output_size, dropout_p=0.1, max_length=MAX_LENGTH):\n super(AttnDecoderRNN, self).__init__()\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.dropout_p = dropout_p\n self.max_length = max_length\n\n self.embedding = nn.Embedding(self.output_size, self.hidden_size)\n self.attn = nn.Linear(self.hidden_size * 2, self.max_length)\n self.attn_combine = nn.Linear(self.hidden_size * 2, self.hidden_size)\n self.dropout = nn.Dropout(self.dropout_p)\n self.gru = nn.GRU(self.hidden_size, self.hidden_size)\n self.out = nn.Linear(self.hidden_size, self.output_size)\n\n\n def forward(self, input, hidden, encoder_outputs):\n embedded = self.embedding(input).view(1, 1, -1)\n embedded = self.dropout(embedded)\n\n attn_weights = F.softmax(\n self.attn(torch.cat((embedded[0], hidden[0]), 1)), dim=1)\n attn_applied = torch.bmm(attn_weights.unsqueeze(0),\n encoder_outputs.unsqueeze(0))\n\n output = torch.cat((embedded[0], attn_applied[0]), 1)\n output = self.attn_combine(output).unsqueeze(0)\n\n output = F.relu(output)\n output, hidden = self.gru(output, hidden)\n\n output = F.log_softmax(self.out(output[0]), dim=1)\n return output, hidden, attn_weights\n\n\n def initHidden(self):\n return torch.zeros(1, 1, self.hidden_size)\n\n\nclass NMT(nn.Module):\n def __init__(self, i2w_english, i2w_french, hidden_size, positional, criterion):\n super(NMT, self).__init__()\n if positional:\n self.encoder = EncoderPOS(len(i2w_french), hidden_size)\n else:\n self.encoder = EncoderRNN(len(i2w_french), hidden_size)\n self.decoder = AttnDecoderRNN(hidden_size, len(i2w_english))\n self.positional = positional\n self.criterion = criterion\n\n\n def forward(self, input_tensor, target_tensor):\n loss = 0\n\n input_length = input_tensor.size(0)\n target_length = target_tensor.size(0)\n\n encoder_hidden = self.encoder.initHidden()\n encoder_outputs = torch.zeros(MAX_LENGTH, self.encoder.hidden_size)\n\n if input_length > MAX_LENGTH: input_length = MAX_LENGTH\n\n if self.positional:\n average_hidden = torch.zeros(1, self.encoder.hidden_size)\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = self.encoder((ei, input_tensor[ei]), encoder_hidden)\n average_hidden += encoder_output\n encoder_outputs[ei] = encoder_output[0, 0]\n encoder_hidden = (average_hidden/input_length).unsqueeze(0)\n else:\n for ei in range(input_length):\n encoder_output, encoder_hidden = self.encoder(input_tensor[ei], encoder_hidden)\n encoder_outputs[ei] = encoder_output[0, 0]\n\n decoder_input = torch.tensor([[SOS_token_en]])\n decoder_hidden = encoder_hidden\n\n # Use teacher forcing\n for di in range(target_length):\n decoder_output, decoder_hidden, decoder_attention = self.decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n loss += self.criterion(decoder_output, target_tensor[di])\n decoder_input = target_tensor[di]\n\n loss.backward()\n\n return loss.item()/target_length\n\n\n def evaluate(self, w2i_french, i2w_english, input_sentence, target_sentence):\n with torch.no_grad():\n input_tensor = sentence_to_tensor(w2i_french, input_sentence)\n target_tensor = sentence_to_tensor(w2i_english, target_sentence)\n\n input_length = input_tensor.size()[0]\n encoder_hidden = self.encoder.initHidden()\n\n encoder_outputs = torch.zeros(MAX_LENGTH, self.encoder.hidden_size)\n\n if input_length > MAX_LENGTH: input_length = MAX_LENGTH\n\n if self.positional:\n average_hidden = torch.zeros(1, self.encoder.hidden_size)\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = self.encoder((ei, input_tensor[ei]), encoder_hidden)\n average_hidden += encoder_output\n encoder_outputs[ei] += encoder_output[0, 0]\n encoder_hidden = (average_hidden/input_length).unsqueeze(0)\n else:\n for ei in range(input_length):\n encoder_output, encoder_hidden = self.encoder(input_tensor[ei], encoder_hidden)\n encoder_outputs[ei] += encoder_output[0, 0]\n\n decoder_input = torch.tensor([[SOS_token_en]]) # SOS\n\n decoder_hidden = encoder_hidden\n\n decoded_words = []\n decoder_attentions = torch.zeros(MAX_LENGTH, MAX_LENGTH)\n\n for di in range(MAX_LENGTH):\n decoder_output, decoder_hidden, decoder_attention = self.decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n decoder_attentions[di] = decoder_attention.data\n topv, topi = decoder_output.data.topk(1)\n if topi.item() == EOS_token_en:\n decoded_words.append(\"\")\n break\n else:\n decoded_words.append(i2w_english[topi.item()])\n\n decoder_input = topi.squeeze().detach()\n return decoded_words, decoder_attentions[:di + 1]\n\n\ndef read_data(file_name):\n \"\"\"\n Reads the data and returns it in a list.\n \"\"\"\n\n f = codecs.open(file_name, \"r\", encoding='utf-8')\n return [line.strip().split() for line in f.readlines()]\n\n\ndef word_to_index(file_name):\n \"\"\"\n Obtains the vocabulary of a file and returns it\n in a dictionary to be able to use w2i.\n \"\"\"\n\n file = codecs.open(file_name, \"r\", encoding='utf-8')\n w2i = json.load(file)\n w2i[\"\"] = len(w2i)\n return w2i\n\n\ndef index_to_word(dictionary):\n \"\"\"\n Reverses the dictionary such that i2w can be used.\n \"\"\"\n\n reversed_dict = {}\n\n for word, index in dictionary.items():\n reversed_dict[index] = word\n return reversed_dict\n\n\ndef sentence_to_indices(w2i, sentence):\n \"\"\"\n Returns the indices of the words in a sentence in a list.\n \"\"\"\n\n return [w2i[word] for word in sentence]\n\n\ndef sentence_to_tensor(w2i, sentence):\n \"\"\"\n Returns the tensor of a sentence.\n \"\"\"\n\n indices = sentence_to_indices(w2i, sentence)\n indices.append(w2i[\"\"])\n return torch.tensor(indices, dtype=torch.long).view(-1, 1)\n\n\ndef train(input_sentence, target_sentence, w2i_english,\n w2i_french, nmt, nmt_optimizer, criterion, max_length=MAX_LENGTH):\n \"\"\"\n Does one iteration of training.\n \"\"\"\n\n loss = 0\n output_sentence = []\n input_tensor = sentence_to_tensor(w2i_french, input_sentence)\n target_tensor = sentence_to_tensor(w2i_english, target_sentence)\n target_length = target_tensor.size(0)\n\n nmt_optimizer.zero_grad()\n loss = nmt.forward(input_tensor, target_tensor)\n\n nmt_optimizer.step()\n\n return loss\n\n\ndef train_dataset(w2i_english, w2i_french, train_english,\n train_french, nmt, learning_rate):\n \"\"\"\n Trains the Encoder-Decoder model for the entire data set.\n \"\"\"\n\n start = time.time()\n\n nmt_optimizer = optim.SGD(nmt.parameters(), lr=learning_rate)\n criterion = nn.NLLLoss()\n total_loss = 0\n\n for iter in range(1, len(train_english) + 1):\n input_sentence = train_french[iter-1]\n target_sentence = train_english[iter-1]\n loss = train(input_sentence, target_sentence, w2i_english,\n w2i_french, nmt, nmt_optimizer, criterion)\n total_loss += loss\n return total_loss\n\n\ndef evaluate_dataset(w2i_french, i2w_english, nmt, val_french, val_english):\n \"\"\"\n Evaluates the data set and returns the obtained predictions and loss.\n \"\"\"\n\n predictions = []\n\n for i, input_sentence in enumerate(val_french):\n target_sentence = val_english[i]\n\n predicted_words, attentions = nmt.evaluate(w2i_french, i2w_english,\n input_sentence, target_sentence)\n predicted_sentence = ' '.join(predicted_words)\n predictions.append(predicted_sentence)\n return predictions\n\n\ndef save_model(model, positional, epoch, lr, train_loss, val_score):\n \"\"\"\n Saves the NMT model to a file.\n \"\"\"\n\n model_type = \"rnn\"\n if positional: model_type = \"pos\"\n\n path = \"models/\" + model_type + \"_lr\" + str(lr) + \"_epoch\" + str(epoch) + \\\n \"_trainloss\" + str(train_loss) + \"_valscore\" + str(val_score)\n torch.save(model.state_dict(), path)\n\n\ndef save_predictions(predictions, epoch, lr, train_loss, positional):\n \"\"\"\n Saves the encoded predicted sentences decoded to a file.\n \"\"\"\n\n model_type = \"rnn\"\n if positional: model_type = \"pos\"\n\n path = \"results/predictions_\" + model_type + \"_lr\" + str(lr) + \\\n \"_epoch\" + str(epoch) + \"_trainloss\" + str(train_loss) + \".txt\"\n\n with codecs.open(\"temp_encoded.txt\", \"w\", encoding='utf-8') as f:\n for sentence in predictions:\n f.write(sentence.split(\"<\")[0] + \"\\n\")\n f.close()\n\n command = \"sed -r 's/(@@ )|(@@ ?$)//g' temp_encoded.txt > \" + path\n os.system(command)\n os.remove(\"temp_encoded.txt\")\n return path\n\n\ndef evaluate_predictions(predictions_path, val_path):\n \"\"\"\n Computes BLEU score for predictions file.\n \"\"\"\n command = \" \".join([\"perl\", \"multi-bleu.perl\", val_path, \"<\", predictions_path])\n\n try:\n BLEU_full = \"\".join(re.split(r'BLEU = |\\\\n\\'', str(subprocess.check_output(command, shell=True)))[1:])\n BLEU_score = re.split(r',', BLEU_full)[0].strip()\n except:\n BLEU_full = \"error\"\n BLEU_score = None\n\n return BLEU_score, BLEU_full\n\n\ndef save_losses(train_loss, val_score, learning_rate):\n \"\"\"\n Appends the obtained losses to a file.\n \"\"\"\n\n model_type = \"rnn\"\n if positional: model_type = \"pos\"\n path = model_type + \"_lr\" + str(learning_rate)\n\n with codecs.open(\"results/trainlosses_\" + path + \".txt\", \"a\", encoding='utf-8') as train_file:\n train_file.write(str(train_loss) + \"\\n\")\n train_file.close()\n\n with codecs.open(\"results/valscores_\" + path + \".txt\", \"a\", encoding='utf-8') as val_file:\n val_file.write(str(val_score) + \"\\n\")\n val_file.close()\n\n\ndef train_and_evaluate(w2i_english, w2i_french, train_english, train_french,\n nmt, positional, num_epochs, learning_rate=0.01):\n \"\"\"\n Trains the Encoder-Decoder for a certain amount of epochs.\n \"\"\"\n\n train_losses = []\n val_scores = []\n\n for iter in range(1, num_epochs + 1):\n print(\"Iteration\", iter, \"of\", num_epochs)\n train_loss = train_dataset(w2i_english, w2i_french,\n train_english, train_french,\n nmt, learning_rate)\n predictions = evaluate_dataset(w2i_french, i2w_english,\n nmt, val_french, val_english)\n\n predictions_path = save_predictions(predictions, iter, learning_rate, train_loss,\n positional)\n\n sleep(0.01)\n\n val_score, bleu_output = evaluate_predictions(predictions_path, \"val/val.en\")\n\n print(\"training loss:\", train_loss)\n print(\"validation bleu:\", bleu_output)\n train_losses.append(train_loss)\n val_scores.append(val_score)\n\n save_model(nmt, positional, iter, learning_rate, train_loss, val_score)\n save_losses(train_loss, val_score, learning_rate)\n\n\nif __name__ == \"__main__\":\n train_english = read_data(\"data/train_preprocessed.en\")\n train_french = read_data(\"data/train_preprocessed.fr\")\n\n val_english = read_data(\"data/val_preprocessed.en\")\n val_french = read_data(\"data/val_preprocessed.fr\")\n\n w2i_french = word_to_index(\"data/train_preprocessed.fr.json\")\n w2i_english = word_to_index(\"data/train_preprocessed.en.json\")\n\n i2w_french = index_to_word(w2i_french)\n i2w_english = index_to_word(w2i_english)\n\n EOS_token_en = w2i_english[\"\"]\n SOS_token_en = w2i_english[\"\"]\n\n EOS_token_fr = w2i_french[\"\"]\n SOS_token_fr = w2i_french[\"\"]\n\n positional = False\n num_epochs = 10\n learning_rate = 0.0001\n\n criterion = nn.NLLLoss()\n nmt = NMT(i2w_english, i2w_french, 256, positional, criterion)\n train_and_evaluate(w2i_english, w2i_french, train_english,\n train_french, nmt, positional, num_epochs,\n learning_rate)\n","sub_path":"assignment2/python_files/rnn_lr0.0001.py","file_name":"rnn_lr0.0001.py","file_ext":"py","file_size_in_byte":14739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"163764530","text":"# Copyright 2018 The LUCI Authors. All rights reserved.\n# Use of this source code is governed under the Apache License, Version 2.0\n# that can be found in the LICENSE file.\n\nDEPS = [\n 'tricium',\n 'properties'\n]\n\n\ndef RunSteps(api):\n for filename in api.tricium.paths:\n api.tricium.add_comment('test', 'test message', filename)\n # Check that duplicate comments aren't entered.\n api.tricium.add_comment('test', 'test message', filename)\n \n api.tricium.repository\n api.tricium.ref\n api.tricium.add_comment(\n 'another',\n 'another test message',\n 'path/to/file/2',\n start_char=10,\n end_char=20\n )\n\n api.tricium.write_comments()\n api.tricium.write_comments(dump=True)\n\n\ndef GenTests(api):\n yield (api.test('basic') + api.properties(\n repository='https://chromium.googlesource.com/luci/recipes-py',\n ref='refs/changes/99/999999/9',\n paths=['path/to/file']))\n","sub_path":"recipe_modules/tricium/examples/full.py","file_name":"full.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"164926035","text":"\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2021-present Benitz\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished 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\nOR IMPLIED, 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\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\"\"\"\n\nimport typing\nimport datetime\n\nfrom datetime import datetime\nfrom typing import TypeVar\n\n__all__ = (\n 'Timestamp'\n)\n\nT = TypeVar('T', bound='Timestamp')\n\nclass Timestamp:\n \"\"\"Represents timestamp embedded messages(not embeds).\n\n Attributes\n -----------\n convert_to_timestamp: :class:`str`\n Converts datetime into timestamp message.\n convert_to_datetime: :class:`str`\n Converts timestamp into datetime string. Datetime formate: '%d/%m/%Y - %H:%M:%S'\n now: :class:`str`\n The timestamp message of the current time.\n\n .. note::\n\n All datetimes are supposed to be in the formate '%d/%m/%Y - %H:%M:%S'\n\n These timestamps are made for messages that will be sent in discord, therefore '' is added\n to the message for discord's timestamps.\n\n This doesn't work as embed timestamps.\n\n .. versionadded:: 2.2\n \"\"\"\n\n @property\n async def convert_to_timestamp(date):\n \"\"\"\n convert_to_timestamp: :class:`str`\n Converts datetime into timestamp message.\n .. versionadded:: 2.2\n \"\"\"\n date = datetime.strptime(date, \"%d/%m/%Y - %H:%M:%S\")\n date = datetime.timestamp(date)\n return \"\"\n\n @property\n async def now():\n \"\"\"\n convert_to_datetime: :class:`str`\n Converts timestamp into datetime string. Datetime formate: '%d/%m/%Y - %H:%M:%S'\n .. versionadded:: 2.2\n \"\"\"\n date = datetime.timestamp(datetime.now())\n return \"\"\n\n @property\n async def convert_to_date(timestamp):\n \"\"\"\n now: :class:`str`\n The timestamp message of the current datetime.\n .. versionadded:: 2.2\n \"\"\"\n try:\n timestamp = str(timestamp)\n timestamp = timestamp.replace(\"\", \"\")\n try:\n if len(timestamp) != 10:\n raise TypeError(\"ERROR: provided 'timestamp' is not a valid timestamp.\")\n timestamp = int(timestamp)\n except:\n raise TypeError(f\"ERROR: provided 'timestamp' is not a valid timestamp.\")\n dt_obj = datetime.fromtimestamp(timestamp)\n dt_obj = str(dt_obj).replace(\"-\", \"/\")\n dt_obj = dt_obj.replace(\" \", \" - \")\n return dt_obj\n except Exception as e:\n raise RuntimeError(f\"ERROR: 'conver_to_date' function has failed to evaluate, Error:\\n{e}\")","sub_path":"discord/timestamp.py","file_name":"timestamp.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"455943241","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\nimport openerp.addons.decimal_precision as dp\n\n\nclass select_soline_wizard(osv.osv_memory):\n _name = 'select.soline.wizard'\n\n def get_default_so_id(self, cr, uid, context=None):\n if context is None:\n context = {}\n ids = context.get('active_ids')\n if ids:\n return_browse = self.pool.get('return.sale.order').browse(cr,uid,ids[0],context=context)\n sale_order_id = return_browse.so_id and return_browse.so_id.id or False\n return sale_order_id\n else:\n return False\n\n _columns = {\n 'patial_order_line_ids': fields.many2many('sale.order.line', 'partial_sale_order_line_ids', 'line_id', 'order_id', 'Sale Order Line'),\n 'sale_order': fields.many2one('sale.order','Sale order')\n }\n\n _defaults = {\n 'sale_order': get_default_so_id,\n }\n\n def generate_editable_so_line(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n wiz_browse = self.browse(cr,uid,ids[0],context=context)\n sale_obj = self.pool.get('sale.order')\n product_obj = self.pool.get('product.product')\n sale_line_obj = self.pool.get('sale.order.line')\n return_obj = self.pool.get('return.sale.order')\n active_id = context.get('active_id')\n record_list = []\n current_browse = self.browse(cr,uid,ids[0],context=context)\n partial_soline_ids = current_browse.patial_order_line_ids\n for so_line in partial_soline_ids:\n record_list+=[(0,0,{\n 'rso_order_id': context.get('active_id'),\n 'so_id': so_line.order_id and so_line.order_id.id,\n 'name': so_line.name or '',\n 'analytic_account_id':so_line.analytic_account_id and so_line.analytic_account_id.id or False,\n 'project_code': so_line.project_code or '',\n 'project_desc': so_line.project_desc or '',\n 'rubros_uom_id': so_line.rubros_uom_id and so_line.rubros_uom_id.id or False,\n 'extend_id': so_line.extend_id and so_line.extend_id.id or False,\n 'company_id': so_line.order_id.company_id and so_line.order_id.company_id.id or False,\n 'product_id': so_line.product_id and so_line.product_id.id or False ,\n 'product_qty': so_line.product_uom_qty or 0.0,\n 'purchase_price': so_line.purchase_price or 0.0,\n 'product_uom': so_line.product_uom and so_line.product_uom.id or False,\n 'name': so_line.product_id and so_line.product_id.name or False,\n 'state': 'draft',\n 'subtotal': so_line.sub_total,\n 'price_subtotal': so_line.subtotal_taxes,\n 'type': 'make_to_order',\n 'delay': 1.0,\n })]\n return return_obj.write(cr,uid, active_id,{'partial_return_line': record_list},context=context)\nselect_soline_wizard()\n\n\n\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"return_sales/wizard/select_so_line.py","file_name":"select_so_line.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"616210185","text":"#!/usr/bin/env python\n\nimport re\nimport requests\nimport timeit\n\nfrom functools import partial\nfrom multiprocessing.dummy import Pool as ThreadPool\n\n\ndef get_session_rate(host, port):\n url = ('http://%s:%s/database/stats/session.rate' % (host, port))\n result = requests.get(url, auth=('admin', 'netwitness'))\n return re.findall(r'(\\d+)', result.text)[0]\n\n\ndef get_session_cnt(host, port=50102):\n url = ('http://%s:%s/database/stats/session.total' % (host, port))\n result = requests.get(url, auth=('admin', 'netwitness'))\n return re.findall(r'(\\d+)', result.text)[0]\n\n\nstart_time = timeit.default_timer()\nprint(start_time)\n# Make the Pool of workers\npool = ThreadPool(6)\n# Open the urls in their own threads and return the results\nld_rates = pool.starmap(get_session_rate, [('10.101.59.237', 50102), ('10.101.59.238', 50102), ('10.101.59.239', 50102)])\nconc_rates = pool.starmap(get_session_rate, [('10.101.59.240', 50105), ('10.101.59.241', 50105), ('10.101.59.242', 50105)])\n#close the pool and wait for the work to finish\npool.close()\npool.join()\nprint(ld_rates)\nprint(conc_rates)\nprint(timeit.default_timer() - start_time)\n","sub_path":"ctf/multiprocess_trials.py","file_name":"multiprocess_trials.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"300198613","text":"import os\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.padding import PKCS7\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\n\n\nclass AESencryption():\n \"\"\"this class holds everything related to AES in this code.\"\"\"\n\n def __init__(self):\n \"\"\"constructor -- does nothing.\"\"\"\n\n def random_bytes_generator(self, size):\n \"\"\"generates random numbers needed by AES\n (symmetric key + initialization vector)\n :param int size -- the key size\n :returns a list contains the key + iv\n \"\"\"\n key = os.urandom(size)\n\n # AES block size = 128 bits -> iv length must be 16 bytes\n # 16 * 8 = 128\n initialization_vector = os.urandom(16)\n\n # Writing key to disk\n # with open('key.pem', 'wb') as key_file:\n # key_file.write(key)\n # key_file.write(b'_') # A separator to distinguish the key from iv\n # key_file.write(initialization_vector)\n\n return [key, initialization_vector]\n\n def key_generator(self):\n \"\"\"Creates a Cipher object after getting the random numbers.\n\n Cipher objects combine an algorithm such as AES\n with a mode like CBC.\n \"\"\"\n # Generating AES key + iv\n self.randoms = self.random_bytes_generator(size=32)\n\n # Specifying the desired algorithm and mode of operation\n self.cipher = Cipher(algorithms.AES(self.randoms[0]),\n modes.CBC(self.randoms[1]), default_backend())\n\n def pad(self, secret_message):\n \"\"\"Increases the length of a file to a multiple\n of the block size (128 bits).\n :param secret_message -- the file to be padded\n :returns the file after padding it\n \"\"\"\n # block_size - The size of the block in bits that the data is being padded to.\n padder = PKCS7(block_size=128).padder()\n padded_data = padder.update(secret_message) + padder.finalize()\n\n return padded_data\n\n def unpad(self, padded_data):\n \"\"\"Removes the padded data of the passed param.\n :param padded_data -- a padded file\n :returns the file after unpadding it\n \"\"\"\n # block_size - The size of the block in bits that the data is being padded to.\n unpadder = PKCS7(block_size=128).unpadder()\n unpadded_data = unpadder.update(padded_data) + unpadder.finalize()\n\n return unpadded_data\n\n def encrypt(self, secret_message):\n \"\"\"Encrypts the passed file.\n :param secret_message -- the file to be encrypted\n :returns the file after encrypting it\n \"\"\"\n\n # Keys will be generated only if encrypt() is called\n self.key_generator()\n\n # Padding the message\n padded_message = self.pad(secret_message)\n\n encryptor = self.cipher.encryptor()\n ciphertext = encryptor.update(padded_message) + encryptor.finalize()\n return [ciphertext, self.randoms]\n\n def decrypt(self, keys, ciphertext):\n \"\"\"Decrypts the passed ciphertext using the passed key.\n :param list keys -- AES symmetric key\n :param ciphertext -- the file to be decrypted\n :returns the file after decrypting it\n \"\"\"\n # Specifying the desired algorithm and mode of operation\n cipher = Cipher(algorithms.AES(keys[0]),\n modes.CBC(keys[1]), default_backend())\n\n decryptor = cipher.decryptor()\n decrypted_message = decryptor.update(ciphertext) + decryptor.finalize()\n\n # Unpadding the decrypted padded message\n plaintext = self.unpad(decrypted_message)\n\n return plaintext\n","sub_path":"AESencryption/AES.py","file_name":"AES.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"325823341","text":"from selenium.webdriver.common.keys import Keys\nfrom .base import FunctionalTest\n\n\nclass ItemValidationTest(FunctionalTest):\n def test_cannot_add_empty_list_items(self):\n # She goes to the home page\n self.browser.get(self.live_server_url)\n # Seach for inputbox and send empty item\n self.get_item_input_box().send_keys(Keys.ENTER)\n\n # The home pages refreshes, and there is an error message saying that\n # list items cannot be blank.\n self.wait_for(lambda: self.browser.find_elements_by_css_selector(\n '#id_text:invalid'\n ))\n\n # She tries again with some text for the item, which now works\n self.get_item_input_box().send_keys('Buy milk')\n self.wait_for(lambda: self.browser.find_elements_by_css_selector(\n '#id_text:invalid'\n ))\n\n self.get_item_input_box().send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: Buy milk')\n\n # Perversely, she now decides to submit a second balnk list item\n self.get_item_input_box().send_keys(Keys.ENTER)\n\n # She receives a similar warning on the list page\n self.wait_for(lambda: self.browser.find_elements_by_css_selector(\n '#id_text:invalid'\n ))\n\n # And she can correct it by filling some text in\n self.get_item_input_box().send_keys('Make tea')\n self.wait_for(lambda: self.browser.find_elements_by_css_selector(\n '#id_text:invalid'\n ))\n self.get_item_input_box().send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: Buy milk')\n self.wait_for_row_in_list_table('2: Make tea')\n\n def test_cannot_add_duplicate_items(self):\n # User goes to the home page and starts a new list\n self.browser.get(self.live_server_url)\n self.get_item_input_box().send_keys('Buy wellies')\n self.get_item_input_box().send_keys(Keys.ENTER)\n self.wait_for_row_in_list_table('1: Buy wellies')\n\n # User accidentally tries to enter a duplicate item\n self.get_item_input_box().send_keys('Buy wellies')\n self.get_item_input_box().send_keys(Keys.ENTER)\n\n # User sees a helpful error message\n self.wait_for(lambda: self.assertEqual(\n self.browser.find_element_by_css_selector('.has-error').text,\n \"You've already got this in your list\"\n ))\n\n\n","sub_path":"functional_tests/test_list_item_validation.py","file_name":"test_list_item_validation.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"595692317","text":"#Задачка с числами Фибоначчи\n#https://py.checkio.org/ru/mission/ghosts-age/\n#Числа фибоначи это то число, если сумма двух предыдущих чисел равна ему.\ndef checkio(opacity):\n age = 0\n newborn = 10000\n fib1 = 0\n fib2 = 1\n while newborn != opacity:\n age += 1\n if age == fib1 + fib2:\n newborn -= age\n fib1, fib2 = fib2, age\n else:\n newborn +=1\n return age\n\n# These \"asserts\" using only for self-checking and not necessary for auto-testing\nif __name__ == '__main__':\n assert checkio(10000) == 0, \"Newborn\"\n assert checkio(9999) == 1, \"1 year\"\n assert checkio(9997) == 2, \"2 years\"\n assert checkio(9994) == 3, \"3 years\"\n assert checkio(9995) == 4, \"4 years\"\n assert checkio(9990) == 5, \"5 years\"","sub_path":"ghosts-age.py","file_name":"ghosts-age.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"310403532","text":"#!/usr/bin/env python\n\"\"\"\nbasic request helper module\n\"\"\"\n\nfrom __future__ import print_function\nfrom contextlib import closing\nfrom requests import get\nfrom requests.exceptions import RequestException\n\ndef simple_get(url):\n \"\"\"\n Attempts to get the content at 'url' by making a HTTP GET request\n If the content-type of response is some kind of HTML/XML, return the\n text content, otherwise return None\n \"\"\"\n result = None\n try:\n # pylint: disable=no-member\n with closing(get(url, stream=True)) as resp:\n if is_good_response(resp):\n result = resp.content\n except RequestException as exc:\n log_error('Error during request to {0} : {1}'.format(url, str(exc)))\n return result\n\n\ndef is_good_response(resp):\n \"\"\"\n Returns True if the response seems to be HTML, False otherwise\n \"\"\"\n content_types = (\"html\", \"json\", \"csv\")\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200\n and content_type is not None\n and any(ct in content_type for ct in content_types))\n\ndef log_error(exc):\n \"\"\"\n It is always a good idea to log errors\n This function just prints them, but you can\n make it do anything\n \"\"\"\n print(exc)\n","sub_path":"app/basic_request.py","file_name":"basic_request.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"171835027","text":"#并不符合O(log(m+n))的复杂度的要求,但应该算最为便捷的解法\r\nclass Solution:\r\n def findMedianSortedArrays(self, nums1: list[int], nums2: list[int]) -> float:\r\n nums3 = nums1 + nums2\r\n nums3.sort()\r\n l = len(nums3)\r\n if l%2 == 0:\r\n b = l/2\r\n a = nums3[int(b)]+nums3[int(b-1)]\r\n a = float(a/2)\r\n return a\r\n else:\r\n b = l/2+1\r\n return float(nums3[int(b)])\r\n","sub_path":"寻找两个有序数组的中位数.py","file_name":"寻找两个有序数组的中位数.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"558322777","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\ntrain = pd.read_csv(\"train.csv\")\n#test = pd.read_csv(\"test.csv\")\n\n#split training into y and x\ny = train[\"label\"]\nx = train.drop(labels = [\"label\"],axis = 1)\n\n#print(y.head())\n#print(x.head())\n\ndel train\n\n#check for missing values\n#print(x.isnull().any().describe())\n#print(test.isnull().any().describe())\n\n#greyscale the images\nx = x / 255.0\n#test = test / 255.0\n\n#reshape values\nx = x.values.reshape(-1, 28, 28, 1)\n#test = test.values.reshape(-1, 28, 28, 1)\n#plt.imshow(x[0][:,:,0])\n#plt.show()\n\ny = to_categorical(y, num_classes = 10)\nrandom_seed = 2\n\n#split into train and validation set\nx_train, x_val, y_train, y_val = train_test_split(x,y, test_size = 0.1, random_state = random_seed)\n\n##plt.imshow(x_train[0][:,:,0])\n##plt.show()\n\ncnn = Sequential()\ncnn.add(Conv2D(filters = 32, kernel_size = (5,5), padding = 'Same', activation='relu', input_shape = (28,28,1)))\ncnn.add(MaxPool2D(pool_size = (2,2), strides = (2,2)))\ncnn.add(Dropout(0.25))\n\ncnn.add(Flatten())\ncnn.add(Dense(256, activation = 'relu'))\ncnn.add(Dropout(0.5))\ncnn.add(Dense(10, activation = 'softmax'))\n\noptimizer = RMSprop(lr = 0.001, rho = 0.9, epsilon = 1e-08, decay=0.0)\ncnn.compile(optimizer = optimizer, loss = 'categorical_crossentropy', metrics = ['accuracy'])\n\nlearning_rate_reduction = ReduceLROnPlateau(\n monitor = 'val_acc',\n patience = 3,\n verbose = 1,\n factor = 0.5,\n min_lr = 0.00001)\n\nepochs = 1\nbatch_size = 86\n\n#data augmentation\n#augmentation techniques:\n#grayscale, horizontal & vertical flips, random crops, color jitters, translations, rotations\ndatagen = ImageDataGenerator(\n featurewise_center=False, # set input mean to 0 over the dataset\n samplewise_center=False, # set each sample mean to 0\n featurewise_std_normalization=False, # divide inputs by std of the dataset\n samplewise_std_normalization=False, # divide each input by its std\n zca_whitening=False, # apply ZCA whitening\n rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)\n zoom_range = 0.10, # Randomly zoom image \n width_shift_range=0.10, # randomly shift images horizontally (fraction of total width)\n height_shift_range=0.10, # randomly shift images vertically (fraction of total height)\n horizontal_flip=False, # randomly flip images\n vertical_flip=False) # randomly flip images\n\ndatagen.fit(x_train)\n\nfinal_model = cnn.fit_generator(datagen.flow(x_train,y_train, batch_size = batch_size),\n epochs = epochs, validation_data= (x_val, y_val),\n verbose = 2, steps_per_epoch = x_train.shape[0] // batch_size,\n callbacks = [learning_rate_reduction])\n\n\n##fig, ax = plt.subplots(2,1)\n##ax[0].plot(final_model.history['loss'], color='b', label = 'Training Loss')\n##ax[0].plot(final_model.history['val_loss'], color='r', label = 'Validation Accuracy')\n##legend = ax[0].legend(loc = 'best', shadow = True)\n##ax[1].plot(final_model.history['acc'], color='b', label='Training accuracy')\n##ax[1].plot(final_model.history['val_acc'], color='r', label='Validation accuracy')\n##legend = ax[1].legend(loc = 'best', shadow = True)\n\n#plt.show()\nplt.clf()\n\ndef plot_c_mtx(c_mtx, classes, cmap=plt.cm.Blues):\n plt.imshow(c_mtx, interpolation='nearest', cmap=plt.cm.Blues)\n plt.title('Confusion Matrix')\n plt.colorbar()\n classes = range(10)\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n thresh = c_mtx.max() / 2.\n for i, j in itertools.product(range(c_mtx.shape[0]), range(c_mtx.shape[1])):\n plt.text(j, i, c_mtx[i,j],\n horizontalalignment = \"center\",\n color = \"white\" if c_mtx[i,j] > thresh else \"black\")\n\n plt.ylabel('True Label')\n plt.xlabel('Predicted Label')\n\npred = cnn.predict(x_val)\npred_classes = np.argmax(pred, axis = 1)\ny_true = np.argmax(y_val, axis = 1)\nc_mtx = confusion_matrix(y_true, pred_classes)\nplot_c_mtx(c_mtx, range(10))\nplt.show()\n#heat_map = sns.heatmap(c_mtx, annot=True, fmt='d')\n\n\n\n","sub_path":"digit-recognizer/digit-recognizer.py","file_name":"digit-recognizer.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"178002136","text":"import findspark\nfrom pyspark.sql import SparkSession\nfrom pyspark import SparkContext\nfrom pyspark.streaming import StreamingContext\n\nfrom riotwatcher import LolWatcher\nimport json\nimport random\nimport time\nfrom math import log,inf\n\ndef createGameList(watcher,region):\n # used to call multiple games at once\n gamelist=[]\n for i in range (500):\n gamelist.extend(watcher.spectator.featured_games(region)[\"gameList\"])\n return gamelist\n\ndef saveGameList(gamelist):\n with open('data', 'w') as f:\n for game in gamelist:\n f.write(json.dumps(game)+\"\\n\") \ndef getParticipantData(game):\n try:\n game=json.loads(game)\n participants=game[\"participants\"]\n return [{'summonerName':participant['summonerName'],\"championId\":participant[\"championId\"],\"teamId\":participant[\"teamId\"],\"gameId\":game[\"gameId\"] } for participant in participants if participant['bot']== False]\n except:\n pass\ndef getSummonerData(participants):\n from riotwatcher import LolWatcher\n watcher = LolWatcher(key)\n players=[]\n for player in participants:\n player_data=watcher.summoner.by_name(region,player[\"summonerName\"])\n player[\"accountId\"]=player_data[\"accountId\"]\n player[\"summonerId\"]=player_data[\"id\"]\n players.append(player)\n return players\ndef getChampMastery(participants):\n from riotwatcher import LolWatcher\n watcher = LolWatcher(key)\n players=[]\n for player in participants:\n \n player_champ_data=watcher.champion_mastery.by_summoner_by_champion(region,player[\"summonerId\"],player[\"championId\"])\n \n stats={\"championLevel\":player_champ_data['championLevel'],\n \"championPoints\":player_champ_data['championPoints']}\n champ_familiarity=(int(round(time.time() * 1000)) - player_champ_data[\"lastPlayTime\"])/1000 #converts it into seconds\n stats[\"champ_familiarity\"]=champ_familiarity\n player[\"stats\"]=stats\n \n players.append(player)\n return players\ndef getLoggedScore(participants):\n players=[]\n for player in participants:\n stats=player[\"stats\"]\n score=log(stats[\"championLevel\"]*stats[\"championPoints\"])/log(stats[\"champ_familiarity\"])\n player[\"score\"]=score\n players.append(player)\n return players\ndef getnoLoggedScore(participants):\n players=[]\n for player in participants:\n stats=player[\"stats\"]\n score=stats[\"championLevel\"]*stats[\"championPoints\"]/stats[\"champ_familiarity\"]\n player[\"score\"]=score\n players.append(player)\n return players\ndef getScore(participants):\n players=[]\n for player in participants:\n stats=player[\"stats\"]\n score=stats[\"championLevel\"]*stats[\"championPoints\"]/log(stats[\"champ_familiarity\"])\n player[\"score\"]=score\n players.append(player)\n return players\ndef splitTeams(participants):\n blue=[]\n red=[]\n for player in participants:\n if player[\"teamId\"]==100: blue.append(player)\n if player[\"teamId\"]==200: red.append(player)\n return {\"blue\":blue,\"red\":red}\ndef getGamePrediction(teams):\n game_predictions={}\n for team_name in teams.keys():\n team=teams[team_name]\n total_score=0\n max={\"score\":-inf,\"summonerName\":\"\"}\n for player in team:\n total_score+=player[\"score\"] \n if player[\"score\"] >max[\"score\"]:\n max[\"score\"]=player[\"score\"]\n max[\"summonerName\"]=player[\"summonerName\"]\n game_predictions[f\"{team_name}TotalScore\"]=total_score\n game_predictions[f\"{team_name}ThreatName\"]=max[\"summonerName\"]\n game_predictions[f\"{team_name}ThreatScore\"]=max[\"score\"]\n \n game_predictions[f\"redThreatScore\"]=game_predictions[f\"redThreatScore\"]/(game_predictions[f\"redThreatScore\"]+game_predictions[f\"blueThreatScore\"])\n game_predictions[f\"blueThreatScore\"]=game_predictions[f\"blueThreatScore\"]/(game_predictions[f\"redThreatScore\"]+game_predictions[f\"blueThreatScore\"])\n \n total_score=game_predictions[\"blueTotalScore\"]+game_predictions[f\"redTotalScore\"]\n game_predictions[\"redWinProbability\"]=100*game_predictions[f\"redTotalScore\"]/total_score\n game_predictions[\"blueWinProbability\"]=100*game_predictions[f\"blueTotalScore\"]/total_score\n \n game_predictions[\"gameId\"]=teams[\"blue\"][0][\"gameId\"]\n return game_predictions\n \ndef saveToFile(game_score):\n with open(\"results\",\"r+\") as f:\n json.dump(game_score,f)\n \n \nif __name__ == \"__main__\":\n \n findspark.init()\n spark = SparkSession.builder.master(\"local[*]\").getOrCreate()\n sc=spark.sparkContext\n ssc = StreamingContext(sc, 1)\n key='RGAPI-bf9365f8-34d6-45d1-b2dc-ca530963d7ca'\n watcher = LolWatcher(key)\n region = 'EUN1'\n \n games = ssc.socketTextStream(\"localhost\", 9999)\n predictions=games.map(getParticipantData)\\\n .map(getSummonerData)\\\n .map(getChampMastery)\\\n .map(getnoLoggedScore)\\\n .map(splitTeams)\\\n .map(getGamePrediction)\n predictions.saveAsTextFiles(\"output2/\")\n # score=participants_per_game.map(getScore)\n predictions.pprint()\n \n ssc.start()\n ssc.awaitTermination()","sub_path":"streaming/lol.py","file_name":"lol.py","file_ext":"py","file_size_in_byte":5229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"96346668","text":"import gym\nfrom gym import spaces\nimport numpy as np\nfrom shapely.geometry import Polygon, Point, LinearRing\nimport shapely.affinity as affinity\nimport math\n\nfrom .config import ROOM_DIM_X, ROOM_DIM_Y, MAX_SENSOR_DETECT, WHEEL_DIAMETER, RC_ROBOT_DIAMETER, MIN_TIME_PER_ROTATION, MAX_ANGULAR_VELOCITY, WHEEL_DISTANCE, FRAMES_PER_SECOND\n\n\ndef create_hexagon(center_x, center_y, radius):\n side30 = radius / 2\n side60 = math.sqrt(3) * side30\n point1 = (center_x + radius, center_y)\n point2 = (center_x + side30, center_y + side60)\n point3 = (center_x - side30, center_y + side60)\n point4 = (center_x - radius, center_y)\n point5 = (center_x - side30, center_y - side60)\n point6 = (center_x + side30, center_y - side60)\n \n return [point1, point2, point3, point4, point5, point6]\n\nclass RCCar:\n def __init__(self, start_x, start_y):\n self.cur_x = start_x\n self.cur_y = start_y\n\n self.next_x = self.cur_x\n self.next_y = self.cur_y\n\n self.prev_x = self.cur_x\n self.prev_y = self.cur_y\n\n self.cur_theta = math.pi / 2\n self.next_theta = self.cur_theta\n\n robot_hex = create_hexagon(self.cur_x, self.cur_y, RC_ROBOT_DIAMETER / 2)\n robot_shell = create_hexagon(self.cur_x, self.cur_y, RC_ROBOT_DIAMETER / 2 + MAX_SENSOR_DETECT)\n\n self.poly = Polygon(robot_hex)\n\n self.sensor_fields = []\n # make 5 of the sensor fields\n for i in range(5):\n trap = Polygon([robot_shell[i], robot_hex[i], robot_hex[i + 1], robot_shell[i + 1]])\n self.sensor_fields.append(trap)\n # last 6\n trap = Polygon([robot_shell[5], robot_hex[5], robot_hex[0], robot_shell[0]])\n self.sensor_fields.append(trap)\n\n self.penalties = 0\n\n def find_next_frame_data(self, action):\n wheel_angular_velocities = self.action_to_rotational_velocity(action)\n wheel_linear_velocities = wheel_angular_velocities * WHEEL_DIAMETER / 2\n\n w = (wheel_linear_velocities[1] - wheel_linear_velocities[0]) / WHEEL_DISTANCE\n if (wheel_linear_velocities[1] - wheel_linear_velocities[0]) < 0.01:\n self.next_x = self.cur_x + wheel_linear_velocities[0] * 1/FRAMES_PER_SECOND * math.cos(self.cur_theta)\n self.next_y = self.cur_y + wheel_linear_velocities[0] * 1/FRAMES_PER_SECOND * math.sin(self.cur_theta)\n self.next_theta = self.cur_theta\n return\n # turning in place, use one motor\n elif (wheel_linear_velocities[1] + wheel_linear_velocities[0]) < 0.01:\n wheel_linear_velocities[1] = 0\n\n r = WHEEL_DISTANCE / 2 * ((wheel_linear_velocities[1] + wheel_linear_velocities[0]) / (wheel_linear_velocities[1] - wheel_linear_velocities[0]))\n icc = [self.cur_x - r * math.sin(self.cur_theta), self.cur_y + r * math.cos(self.cur_theta)]\n\n w_t = w * 1/FRAMES_PER_SECOND\n mod_x, mod_y = self.cur_x - icc[0], self.cur_y - icc[1]\n self.next_x = math.cos(w_t) * mod_x - math.sin(w_t) * mod_y\n self.next_y = math.sin(w_t) * mod_x + math.cos(w_t) * mod_y\n self.next_x += icc[0]\n self.next_y += icc[1]\n self.next_theta = w_t + self.cur_theta\n\n def apply_transform(self, dx, dy):\n for i in range(len(self.sensor_fields)):\n trap = self.sensor_fields[i]\n # apply dx, dy\n trap = affinity.translate(trap, dx, dy)\n self.sensor_fields[i] = trap\n # update robot polygon\n self.poly = affinity.translate(self.poly, dx, dy)\n\n self.cur_x += dx\n self.cur_y += dy\n \n def apply_rotation(self, dtheta):\n for i in range(len(self.sensor_fields)):\n trap = self.sensor_fields[i]\n # apply dtheta\n trap = affinity.rotate(trap, dtheta * 180/(math.pi), 'center')\n self.sensor_fields[i] = trap\n self.poly = affinity.rotate(self.poly, dtheta * 180/(math.pi), 'center')\n\n def update_robot_bounds(self, objects):\n self.prev_x = self.cur_x\n self.prev_y = self.cur_y\n\n # update sensor fields\n dx = self.next_x - self.cur_x\n dy = self.next_y - self.cur_y\n dtheta = self.next_theta - self.cur_theta\n self.apply_transform(dx, dy)\n self.apply_rotation(dtheta)\n\n # absolutes\n self.cur_x = self.next_x\n self.cur_y = self.next_y\n self.cur_theta = self.next_theta\n\n for obj in objects[1:]: # ignore car at index 0\n if self.poly.contains(obj.poly) or self.poly.intersects(obj.poly):\n self.penalties += 1\n \n # keep robot in bounds\n if self.cur_x > ROOM_DIM_X - RC_ROBOT_DIAMETER / 2:\n dx = ROOM_DIM_X - RC_ROBOT_DIAMETER / 2 - self.cur_x\n self.apply_transform(dx, 0)\n self.next_x = self.cur_x\n \n elif self.cur_x < 0 + RC_ROBOT_DIAMETER / 2:\n dx = (0 + RC_ROBOT_DIAMETER / 2) - self.cur_x\n self.apply_transform(dx, 0)\n self.next_x = self.cur_x\n \n if self.cur_y > ROOM_DIM_Y - RC_ROBOT_DIAMETER / 2:\n dy = (ROOM_DIM_Y - RC_ROBOT_DIAMETER / 2) - self.cur_y\n self.apply_transform(0, dy)\n self.next_y = self.cur_y\n\n elif self.cur_y < 0 + RC_ROBOT_DIAMETER / 2:\n dy = (0 + RC_ROBOT_DIAMETER / 2) - self.cur_y\n self.apply_transform(0, dy)\n self.next_y = self.cur_y\n \n def get_penalties(self):\n penalties = self.penalties\n self.penalties = 0\n return penalties\n\n def action_to_rotational_velocity(self, action):\n return MAX_ANGULAR_VELOCITY * (action / 1.0)\n\n def update(self, action, objects): \n self.update_robot_bounds(objects)\n self.find_next_frame_data(action)\n\n def get_sensor_data(self, objects):\n \"\"\" Scans environment and determines if objects are in radar and if so to which sensor and the distance \"\"\"\n to_ret = [100 for _ in range(6)]\n for i, trap in enumerate(self.sensor_fields):\n for obj in objects[1:]: # ignore car at index 0\n if trap.contains(obj.poly) or trap.intersects(obj.poly):\n dist = self.poly.distance(obj.poly)\n if dist < to_ret[i]:\n to_ret[i] = dist\n \n return to_ret\n \n\n ","sub_path":"Reinforcement-Learning-Tutorial/ddpg walker/rc_car_env/rc_car_env/envs/car_dynamics.py","file_name":"car_dynamics.py","file_ext":"py","file_size_in_byte":6362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"3961536","text":"import mysql.connector\r\nimport time\r\nimport json\r\nfrom collections import Counter\r\n\r\nimport csv\r\n\r\nmydb = mysql.connector.connect(\r\n host='localhost',\r\n user='root',\r\n password='root',\r\n database='cy'\r\n)\r\ncursor = mydb.cursor()\r\n# 红汤绝配\r\nHt = ['巴庄脆毛肚', '本色千层肚', '鲜切牛上脑', '德清虾滑', '无骨鲜鸭掌', '巴庄鲜鸭血', '冰鲜鸭肠', '藤椒小酥肉',\r\n '天然黑豆面筋', '富硒紫薯川粉', '鲜打牛肉丸']\r\n# 酒水\r\nJs = ['牛栏山陈酿42°500ML', '江小白100ML', '江小白300ML', '劲酒125ML', '百威啤酒', '青岛崂山', '青岛纯生', '青岛经典',\r\n '金桔茉莉', '红柚乳酸菌', '秘制青梅汁', '蔓越莓绿茶', '桂花布丁奶',\r\n '果粒橙1.25L', '加多宝', '可乐听装330ml', '雪碧听装330ml', '花花牛酸奶', '椰冻爽',\r\n '农夫山泉', '皮带面', '绿豆面', '方便面', '水果拼盘', '香油蒜泥', '麻酱', '餐巾纸']\r\n# 锅底\r\nGd = ['牛油辣+野山菌汤+骨汤', '青椒辣+野山菌汤+骨汤', '番茄+牛油辣+野山菌汤']\r\n# 赠送相关\r\nZs = ['新版小料', '长寿面', '芙蓉蛋', '辣椒圈']\r\n\r\ndef Fl():\r\n for p in range(1, 15):\r\n # 这个是啥来着\r\n c_li = []\r\n p2 = \"select 消费明细,消费金额 from cpd where 就餐人数={} and 消费明细 like '%野山菌汤%'\".format(p)\r\n cursor.execute(p2)\r\n info = cursor.fetchall()\r\n print(p, len(info))\r\n # for index.html, i in zip(range(0, len(info)), info[0]):\r\n for i in info:\r\n mx = json.loads(i[0])\r\n # all,这个是点的菜\r\n dl = []\r\n # 菜品\r\n i_l = []\r\n for k in mx['cp']:\r\n # print(k.keys())\r\n i_l.append(list(k.keys())[0])\r\n # print(i_l)\r\n # 剔除酒水什么的, 差集\r\n dl = list(set(i_l).difference(set(Js), set(Gd), set(Zs)))\r\n # print(dl)\r\n # 红汤绝配交集\r\n ret = list(set(dl).intersection(set(Ht)))\r\n # print(ret)\r\n r = ','.join(ret)\r\n ot = list(set(dl).difference(set(ret)))\r\n # print(ot)\r\n o = ','.join(ot)\r\n # print(o)\r\n sql = \"insert into zj(就餐人数, 消费金额, 红汤绝配数, 全部菜品数, 红汤绝配, 其他) values({0},{1},{2},{3},'{4}','{5}')\"\r\n if len(ret):\r\n # print('%s人台,%s个红汤绝配,红汤绝配占比%s,占所点菜品%s' % (p, len(ret), (len(ret)/len(Ht) *100), len(ret)/len(dl)))\r\n cursor.execute(sql.format(p, i[1], len(ret), len(dl), r, o))\r\n mydb.commit()\r\n else:\r\n cursor.execute(sql.format(p, i[1], 0, len(dl), r, o))\r\n mydb.commit()\r\n # print('%s人台,%s个红汤绝配,红汤绝配占比%s,占所点菜品%s' % (p, 0, 0, 0))\r\n # 个数、占比\r\n\r\n # d = {index.html: mx['cp']}\r\n # # print(d)\r\n # c_li.append(d)\r\n # ss = {p: c_li}\r\n # print(ss)\r\n\r\ndef count():\r\n for p in range(1, 15):\r\n hl =[]\r\n ql = []\r\n sql1 = \"select 红汤绝配 from zj where 就餐人数={}\"\r\n sql2 = \"select 其他 from zj where 就餐人数={}\"\r\n sql3 = \"select 消费金额 from zj where 就餐人数={}\"\r\n cursor.execute(sql1.format(p))\r\n a = cursor.fetchall()\r\n cursor.execute(sql2.format(p))\r\n b = cursor.fetchall()\r\n cursor.execute(sql3.format(p))\r\n c = cursor.fetchall()\r\n for i, j in zip(a, b):\r\n h = i[0].split(',')\r\n q = j[0].split(',')\r\n # print(h, q)\r\n for x, y in zip(h, q):\r\n hl.append(x)\r\n ql.append(y)\r\n # print(ql)\r\n result1 = Counter(hl).most_common()\r\n result2 = Counter(ql).most_common()\r\n print(result2)\r\n for r1 in result1:\r\n hName, hNum = r1[0], r1[1]\r\n rowt = [p, hName]\r\n rowz = [len(c), hNum]\r\n with open('ht.csv', 'a', encoding='utf8')as f:\r\n f_csv = csv.writer(f)\r\n f_csv.writerow(rowt)\r\n f_csv.writerow(rowz)\r\n for r2 in result2:\r\n qName, qNum = r2[0], r2[1]\r\n # for r1, r2 in zip(result1, result2):\r\n # hName, hNum = r1[0], r1[1]\r\n # qName, qNum = r2[0], r2[1]\r\n # print(p, len(c), hName, hNum, qName, qNum)\r\n row1 = [p, qName]\r\n row2 = [len(c), qNum]\r\n with open('qt.csv', 'a', encoding='utf8')as f:\r\n f_csv = csv.writer(f)\r\n f_csv.writerow(row1)\r\n f_csv.writerow(row2)\r\n\r\n\r\nif __name__ == '__main__':\r\n count()","sub_path":"Info/modle.py","file_name":"modle.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"354287728","text":"import matplotlib.pyplot as plt\n\nx=[1,2,3,4,5,6,7,8]\ny=[0,1,0,2,0,5,0,6]\nplt.title('Title')\nplt.plot(x,y)\nplt.xlabel('Time')\n\n\nx=[1,2,3,4,5,6,5,8]\ny=[0,1,0,4,0,5,0,6]\nplt.title('RST')\nplt.plot(x,y)\nplt.xlabel('Time')\nplt.show()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"59202525","text":"from setuptools import setup\n\nfrom os import path\n\nthis_directory = path.abspath(path.dirname(__file__))\nwith open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n\nsetup(\n name = 'pyids',\n packages = ['pyids', \"pyids.data_structures\", \"pyids.model_selection\", \"pyids.rule_mining\", \"pyids.test\",\"pyids.visualization\"],\n install_requires=['pandas', 'numpy', 'sklearn','pyarc', 'pyfim'],\n version = '0.0.1'\n \n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"41478132","text":"\"\"\"\nResearch Note: Proper Motion Test (2014-06)\nWorking Directory: /u/jlu/data/Wd1/hst/reduce_2014_06_17/\n\"\"\"\nimport math\nimport pylab as py\nimport numpy as np\nfrom hst_flystar import reduce as flystar\nfrom jlu import photometry as photo\nimport glob\nfrom matplotlib import colors\nfrom jlu.util import statsIter\nfrom jlu.util import fileUtil\nimport pdb\nimport os\nimport shutil\nimport subprocess\nfrom hst_flystar import astrometry as ast\nfrom hst_flystar import photometry\nfrom hst_flystar import reduce as flystar\nfrom hst_flystar import starlists\nfrom hst_flystar import completeness as comp\nimport astropy.table\nfrom astropy import table\nfrom astropy.table import Table\nfrom astropy.table import Column\nfrom jlu.astrometry import align\nfrom jlu.gc.gcwork import starset\nfrom scipy.stats import binned_statistic\nfrom matplotlib import colors as mcolors\nfrom matplotlib import colorbar\n\nwork_dir = '/u/jlu/data/wd1/hst/reduce_2015_01_05/'\ncode_dir = '/u/jlu/code/fortran/hst/'\n\n# Load this variable with outputs from calc_years()\nyears = {'2005_F814W': 2005.485,\n '2010_F125W': 2010.652,\n '2010_F139M': 2010.652,\n '2010_F160W': 2010.652,\n '2013_F160W': 2013.199,\n '2013_F160Ws': 2013.202}\n\ntopStars = [{'name':'wd1_00001', 'x': 1838.81, 'y': 568.98, 'm160': -10.2},\n {'name':'wd1_00002', 'x': 3396.91, 'y': 1389.27, 'm160': -10.1},\n {'name':'wd1_00003', 'x': 3824.63, 'y': 3347.88, 'm160': -10.4},\n {'name':'wd1_00004', 'x': 717.67, 'y': 3033.63, 'm160': -9.9},\n {'name':'wd1_00005', 'x': 2030.72, 'y': 2683.57, 'm160': -9.7},\n {'name':'wd1_00006', 'x': 676.98, 'y': 663.25, 'm160': -9.6}]\n\n\ndef run_img2xym_acswfc(directory):\n \"\"\"\n Run img2xym on ACS WFC data in the specified directory, . There is a specific\n directory structure that is expected within :\n\n 00.DATA/\n 01.XYM/\n \"\"\"\n os.chdir(directory + '/01.XYM')\n\n program = 'img2xymrduv'\n\n ## Arguments include:\n # hmin - dominance of peak. Something like the minimum SNR of a peak w.r.t. background.\n hmin = 5\n # fmin - minumum peak flux above the background\n fmin = 500\n # pmax - maximum flux allowed (absolute)\n pmax = 99999\n # psf - the library\n psf = code_dir + 'PSFs/PSFSTD_ACSWFC_F814W_4SM3.fits'\n\n ## Files to operate on:\n dataDir = '../00.DATA/*flt.fits'\n\n cmd_tmp = '{program} {hmin} {fmin} {pmax} {psf} {dataDir}'\n cmd = cmd_tmp.format(program=program, hmin=hmin, fmin=fmin, pmax=pmax, psf=psf,\n dataDir=dataDir)\n\n try:\n os.system(cmd)\n finally:\n os.chdir('../../')\n \n\ndef xym_acswfc_pass1():\n \"\"\"\n Match and align the 3 exposures. Make a new star list (requiring 2 out of\n 3 images). Also make sure the new starlist has only positive pxel values.\n \"\"\"\n year = '2005'\n filt = 'F814W'\n\n xym_dir = '{0}_{1}/01.XYM/'.format(year, filt)\n\n flystar.xym2mat('ref1', year, filt, camera='f5 c5', mag='m-13.5,-10', clobber=True)\n flystar.xym2bar('ref1', year, filt, camera='f5 c5', Nepochs=2, clobber=True)\n\n starlists.make_matchup_positive(xym_dir + 'MATCHUP.XYMEEE.ref1')\n \ndef xym_acswfc_pass2():\n \"\"\"\n Re-do the alignment with the new positive master file. Edit IN.xym2mat to \n change 00 epoch to use the generated matchup file with f5, c0 \n (MATCHUP.XYMEEE.01.all.positive). Make sure to remove all the old MAT.* and \n TRANS.xym2mat files because there is a big shift in the transformation from \n the first time we ran it.\n \"\"\"\n year = '2005'\n filt = 'F814W'\n\n xym_dir = '{0}_{1}/01.XYM/'.format(year, filt)\n\n flystar.xym2mat('ref2', year, filt, camera='f5 c5', mag='m-13.5,-10',\n ref='MATCHUP.XYMEEE.ref1.positive', ref_mag='m-13.5,-10',\n ref_camera='f5 c0', clobber=True)\n flystar.xym2bar('ref2', year, filt, Nepochs=2, zeropoint='', \n camera='f5 c5', clobber=True)\n\ndef plot_cmd_one_pass(reread=False):\n \"\"\"\n Plot CMDs for all filter combinations from the one-pass analysis.\n This is just to get a sense of the magnitude differences.\n \"\"\"\n if reread:\n # Read in the text files and save as FITS tables for speed.\n t2005_814 = starlists.read_matchup('MATCHUP.XYMEEE.F814W.2005.ref5')\n t2010_160 = starlists.read_matchup('MATCHUP.XYMEEE.F160W.2010.ref5')\n t2010_139 = starlists.read_matchup('MATCHUP.XYMEEE.F139M.2010.ref5')\n t2010_125 = starlists.read_matchup('MATCHUP.XYMEEE.F125W.2010.ref5')\n t2013_160 = starlists.read_matchup('MATCHUP.XYMEEE.F160W.2013.ref5')\n t2013_160s = starlists.read_matchup('MATCHUP.XYMEEE.F160Ws.2013.ref5')\n\n t2005_814.write('MATCHUP.XYMEEE.F814W.2005.ref5.fits', overwrite=True)\n t2010_160.write('MATCHUP.XYMEEE.F160W.2010.ref5.fits', overwrite=True)\n t2010_139.write('MATCHUP.XYMEEE.F139M.2010.ref5.fits', overwrite=True)\n t2010_125.write('MATCHUP.XYMEEE.F125W.2010.ref5.fits', overwrite=True)\n t2013_160.write('MATCHUP.XYMEEE.F160W.2013.ref5.fits', overwrite=True)\n t2013_160s.write('MATCHUP.XYMEEE.F160Ws.2013.ref5.fits', overwrite=True)\n else:\n # Read in the FITS versions of the tables.\n t2005_814 = Table.read('MATCHUP.XYMEEE.F814W.2005.ref5.fits')\n t2010_160 = Table.read('MATCHUP.XYMEEE.F160W.2010.ref5.fits')\n t2010_139 = Table.read('MATCHUP.XYMEEE.F139M.2010.ref5.fits')\n t2010_125 = Table.read('MATCHUP.XYMEEE.F125W.2010.ref5.fits')\n t2013_160 = Table.read('MATCHUP.XYMEEE.F160W.2013.ref5.fits')\n t2013_160s = Table.read('MATCHUP.XYMEEE.F160Ws.2013.ref5.fits')\n\n # Trim down to only those stars with well measured positions. \n good = np.where((t2005_814['xe'] < 0.1) & (t2005_814['ye'] < 0.1) &\n (t2010_160['xe'] < 0.1) & (t2010_160['ye'] < 0.1) & \n (t2010_139['xe'] < 0.1) & (t2010_139['ye'] < 0.1) & \n (t2010_125['xe'] < 0.1) & (t2010_125['ye'] < 0.1) & \n (t2013_160['xe'] < 0.1) & (t2013_160['ye'] < 0.1) & \n (t2013_160s['xe'] < 0.1) & (t2013_160s['ye'] < 0.1))[0]\n\n t2005_814 = t2005_814[good]\n t2010_160 = t2010_160[good]\n t2010_139 = t2010_139[good]\n t2010_125 = t2010_125[good]\n t2013_160 = t2013_160[good]\n t2013_160s = t2013_160s[good]\n\n # Put all the tables in a list so that we can loop through\n # the different combinations.\n t_all = [t2005_814, t2010_125, t2010_139, t2010_160, t2013_160, t2013_160s]\n label = ['F814W 2005', 'F125W 2010', 'F139M 2010', 'F160W 2010',\n 'F160W 2013', 'F160Ws 2013']\n \n ##########\n # CMDs\n ##########\n for ii in range(len(t_all)):\n for jj in range(ii+1, len(t_all)):\n t1 = t_all[ii]\n t2 = t_all[jj]\n \n py.clf()\n py.plot(t1['m'] - t2['m'], t1['m'], 'k.')\n py.xlabel(label[ii] + ' - ' + label[jj])\n py.ylabel(label[ii])\n ax = py.gca()\n ax.invert_yaxis()\n\n outfile = 'cmd_'\n outfile += label[ii].replace(' ', '_')\n outfile += '_vs_'\n outfile += label[jj].replace(' ', '_')\n outfile += '.png'\n py.savefig(outfile)\n\n return\n\n\ndef plot_quiver_one_pass(reread=False):\n \"\"\"\n Plot a quiver vector plot between F814W in 2005 and F160W in 2010 and 2013.\n This is just to check that we don't hae any gross flows between the two cameras.\n \"\"\"\n if reread:\n t2005 = starlists.read_matchup('MATCHUP.XYMEEE.F814W.2005.ref5')\n t2010 = starlists.read_matchup('MATCHUP.XYMEEE.F160W.2010.ref5')\n t2013 = starlists.read_matchup('MATCHUP.XYMEEE.F160W.2013.ref5')\n\n t2005.write('MATCHUP.XYMEEE.F814W.2005.ref5.fits')\n t2010.write('MATCHUP.XYMEEE.F160W.2010.ref5.fits')\n t2013.write('MATCHUP.XYMEEE.F160W.2013.ref5.fits')\n else:\n t2005 = Table.read('MATCHUP.XYMEEE.F814W.2005.ref5.fits')\n t2010 = Table.read('MATCHUP.XYMEEE.F160W.2010.ref5.fits')\n t2013 = Table.read('MATCHUP.XYMEEE.F160W.2013.ref5.fits')\n\n good = np.where((t2005['m'] < -8) & (t2010['m'] < -8) & (t2013['m'] < -8) &\n (t2005['xe'] < 0.05) & (t2010['xe'] < 0.05) & (t2013['xe'] < 0.05) & \n (t2005['ye'] < 0.05) & (t2010['ye'] < 0.05) & (t2013['ye'] < 0.05) & \n (t2005['me'] < 0.05) & (t2010['me'] < 0.05) & (t2013['me'] < 0.05))[0]\n\n g2005 = t2005[good]\n g2010 = t2010[good]\n g2013 = t2013[good]\n\n dx_05_10 = (g2010['x'] - g2005['x']) * ast.scale['WFC'] * 1e3\n dy_05_10 = (g2010['y'] - g2005['y']) * ast.scale['WFC'] * 1e3\n\n dx_05_13 = (g2013['x'] - g2005['x']) * ast.scale['WFC'] * 1e3\n dy_05_13 = (g2013['y'] - g2005['y']) * ast.scale['WFC'] * 1e3\n\n dx_10_13 = (g2013['x'] - g2010['x']) * ast.scale['WFC'] * 1e3\n dy_10_13 = (g2013['y'] - g2010['y']) * ast.scale['WFC'] * 1e3\n\n small = np.where((np.abs(dx_05_10) < 20) & (np.abs(dy_05_10) < 20) & \n (np.abs(dx_05_13) < 20) & (np.abs(dy_05_13) < 20) & \n (np.abs(dx_10_13) < 20) & (np.abs(dy_10_13) < 20))[0]\n\n print(len(g2005), len(small), len(dx_05_10))\n g2005 = g2005[small]\n g2010 = g2010[small]\n g2013 = g2013[small]\n dx_05_10 = dx_05_10[small]\n dx_05_13 = dx_05_13[small]\n dx_10_13 = dx_10_13[small]\n dy_05_10 = dy_05_10[small]\n dy_05_13 = dy_05_13[small]\n dy_10_13 = dy_10_13[small]\n print(len(g2005), len(small), len(dx_05_10))\n\n qscale = 1e2\n \n py.clf()\n q = py.quiver(g2005['x'], g2005['y'], dx_05_10, dy_05_10, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2010 - 2005')\n py.savefig('vec_diff_ref5_05_10.png')\n\n py.clf()\n q = py.quiver(g2005['x'], g2005['y'], dx_05_13, dy_05_13, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2013 - 2005')\n py.savefig('vec_diff_ref5_05_13.png')\n\n py.clf()\n q = py.quiver(g2005['x'], g2005['y'], dx_10_13, dy_10_13, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2013 - 2010')\n py.savefig('vec_diff_ref5_10_13.png')\n\n py.clf()\n py.plot(dx_05_10, dy_05_10, 'k.', ms=2)\n lim = 10\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2010 - 2005')\n py.savefig('pm_diff_ref5_05_10.png')\n\n py.clf()\n py.plot(dx_05_13, dy_05_13, 'k.', ms=2)\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2013 - 2005')\n py.savefig('pm_diff_ref5_05_13.png')\n\n py.clf()\n py.plot(dx_10_13, dy_10_13, 'k.', ms=2)\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2013 - 2010')\n py.savefig('pm_diff_ref5_10_13.png')\n\n print('2010 - 2005')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_10.mean(), dxe=dx_05_10.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_10.mean(), dye=dy_05_10.std()))\n\n print('2013 - 2005')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_13.mean(), dxe=dx_05_13.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_13.mean(), dye=dy_05_13.std()))\n\n print('2013 - 2010')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_10_13.mean(), dxe=dx_10_13.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_10_13.mean(), dye=dy_10_13.std()))\n\ndef make_refClust_catalog():\n \"\"\"\n Make mat_all_good.fits where we matchup all the refClust starlists and\n get a preliminary look at the VPD and CMD. Do this on a per-position basis.\n \"\"\"\n for ii in range(1, 4+1):\n pos_dir = 'match_refClust_pos{0}'.format(ii)\n os.chdir(work_dir + '03.MAT_POS/')\n \n fileUtil.mkdir(pos_dir)\n shutil.copy('2005_F814W/01.XYM/MATCHUP.XYMEEE.F814W.2005.refClust', pos_dir)\n os.chdir(work_dir + '03.MAT_POS/' + pos_dir)\n \n # Call xym1mat to match against F814W for all combos\n f814w = 'MATCHUP.XYMEEE.F814W.2005.refClust'\n\n years = ['2010', '2010', '2010', '2013']\n filts = ['F160W', 'F139M', 'F125W', 'F160W']\n\n for jj in range(len(years)):\n match = 'MATCHUP.XYMEEE.'\n match += '{0}.{1}.pos{2}.refClust'.format(filts[jj], years[jj], ii)\n out_root = 'mat_2005_{0}_{1}_pos{2}'.format(years[jj], filts[jj], ii)\n\n match_dir = '../{0}_{1}_pos{2}/01.XYM/'.format(years[jj], filts[jj], ii)\n shutil.copy(match_dir + match, './')\n \n cmd = ['xym1mat', f814w, match,\n out_root + '.mat', out_root + '.xym1', out_root + '.lnk',\n '14', '0.99']\n subprocess.call(cmd)\n\n # Process the output.\n fmt = '{name:8s} {x:10.4f} {y:10.4f} {m:8.4f} '\n fmt += '{xe:7.4f} {ye:7.4f} {me:7.4f} '\n fmt += '{n:2d}\\n'\n \n # First 2005 (treated differently)\n tab = starlists.read_matchup(f814w)\n _final_2005 = open('final_2005_814_pos{0}.txt'.format(ii), 'w')\n for tt in tab:\n _final_2005.write(fmt.format(name=tt[13], x=tt[0], y=tt[1], m=tt[2],\n xe=tt[3], ye=tt[4], me=tt[5], n=tt[10]))\n _final_2005.close()\n\n # All 2010 and 2013 data\n for jj in range(len(years)):\n suffix = '{0}_{1}_pos{2}'.format(years[jj], filts[jj], ii)\n _final = open('final_' + suffix + '.txt', 'w')\n tab = Table.read('mat_2005_' + suffix + '.lnk', format='ascii')\n\n for tt in tab:\n _final.write(fmt.format(name=tt[30], x=tt[19], y=tt[20], m=tt[21],\n xe=tt[22], ye=tt[23], me=tt[24], n=tt[29]))\n _final.close()\n \n return\n\ndef plot_quiver_one_pass_refClust():\n \"\"\"\n Plot a quiver vector plot between F814W in 2005 and F160W in 2010 and 2013.\n This is just to check that we don't hae any gross flows between the two cameras.\n\n See notes from \"HST Data Reduction (2014-06) for creation of the FITS table.\n \"\"\"\n t = Table.read('mat_all_good.fits')\n t.rename_column('col05', 'x_2005')\n t.rename_column('col06', 'y_2005')\n t.rename_column('col07', 'm_2005')\n\n t.rename_column('col11', 'x_2010')\n t.rename_column('col12', 'y_2010')\n t.rename_column('col13', 'm_2010')\n t.rename_column('col23', 'xe_2010')\n t.rename_column('col24', 'ye_2010')\n t.rename_column('col25', 'me_2010')\n\n t.rename_column('col44', 'x_2013')\n t.rename_column('col45', 'y_2013')\n t.rename_column('col46', 'm_2013')\n t.rename_column('col56', 'xe_2013')\n t.rename_column('col57', 'ye_2013')\n t.rename_column('col58', 'me_2013')\n \n good = np.where((t['m_2005'] < -8) & (t['m_2010'] < -8) & (t['m_2013'] < -8) &\n (t['xe_2010'] < 0.05) & (t['xe_2013'] < 0.05) & \n (t['ye_2010'] < 0.05) & (t['ye_2013'] < 0.05) & \n (t['me_2010'] < 0.05) & (t['me_2013'] < 0.05))[0]\n\n g = t[good]\n\n dx_05_10 = (g['x_2010'] - g['x_2005']) * ast.scale['WFC'] * 1e3\n dy_05_10 = (g['y_2010'] - g['y_2005']) * ast.scale['WFC'] * 1e3\n\n dx_05_13 = (g['x_2013'] - g['x_2005']) * ast.scale['WFC'] * 1e3\n dy_05_13 = (g['y_2013'] - g['y_2005']) * ast.scale['WFC'] * 1e3\n\n dx_10_13 = (g['x_2013'] - g['x_2010']) * ast.scale['WFC'] * 1e3\n dy_10_13 = (g['y_2013'] - g['y_2010']) * ast.scale['WFC'] * 1e3\n\n small = np.where((np.abs(dx_05_10) < 20) & (np.abs(dy_05_10) < 20) & \n (np.abs(dx_05_13) < 20) & (np.abs(dy_05_13) < 20) & \n (np.abs(dx_10_13) < 20) & (np.abs(dy_10_13) < 20))[0]\n\n print(len(g), len(small), len(dx_05_10))\n g = g[small]\n dx_05_10 = dx_05_10[small]\n dx_05_13 = dx_05_13[small]\n dx_10_13 = dx_10_13[small]\n dy_05_10 = dy_05_10[small]\n dy_05_13 = dy_05_13[small]\n dy_10_13 = dy_10_13[small]\n print(len(g), len(small), len(dx_05_10))\n\n qscale = 2e2\n \n py.clf()\n q = py.quiver(g['x_2005'], g['y_2005'], dx_05_10, dy_05_10, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2010 - 2005')\n py.savefig('vec_diff_ref5_05_10.png')\n\n py.clf()\n q = py.quiver(g['x_2005'], g['y_2005'], dx_05_13, dy_05_13, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2013 - 2005')\n py.savefig('vec_diff_ref5_05_13.png')\n\n py.clf()\n q = py.quiver(g['x_2005'], g['y_2005'], dx_10_13, dy_10_13, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2013 - 2010')\n py.savefig('vec_diff_ref5_10_13.png')\n\n py.clf()\n py.plot(dx_05_10, dy_05_10, 'k.', ms=2)\n lim = 10\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2010 - 2005')\n py.savefig('pm_diff_ref5_05_10.png')\n\n py.clf()\n py.plot(dx_05_13, dy_05_13, 'k.', ms=2)\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2013 - 2005')\n py.savefig('pm_diff_ref5_05_13.png')\n\n py.clf()\n py.plot(dx_10_13, dy_10_13, 'k.', ms=2)\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2013 - 2010')\n py.savefig('pm_diff_ref5_10_13.png')\n\n print('2010 - 2005')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_10.mean(), dxe=dx_05_10.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_10.mean(), dye=dy_05_10.std()))\n\n print('2013 - 2005')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_13.mean(), dxe=dx_05_13.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_13.mean(), dye=dy_05_13.std()))\n\n print('2013 - 2010')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_10_13.mean(), dxe=dx_10_13.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_10_13.mean(), dye=dy_10_13.std()))\n\ndef plot_quiver_align(pos, orig=''):\n \"\"\"\n Set orig='orig' to plot xorig and yorig (straight from ks2) rather than\n x and y from align output.\n \"\"\"\n t = Table.read(work_dir + '50.ALIGN_KS2/align_a4_t.fits')\n \n good = np.where((t['m_2005_F814W'] < 17.5) &\n (t['m_2010_F160W_' + pos] < 18) &\n (t['m_2013_F160W_' + pos] < 18) &\n (t['x_2005_F814W'] > -1) &\n (t['x_2010_F160W_' + pos] > -1) &\n (t['x_2013_F160W_' + pos] > -1) &\n (t['y_2005_F814W'] > -1) &\n (t['y_2010_F160W_' + pos] > -1) &\n (t['y_2013_F160W_' + pos] > -1) &\n (t['xe_2010_F160W_' + pos] < 0.05) &\n (t['xe_2013_F160W_' + pos] < 0.05) &\n (t['ye_2010_F160W_' + pos] < 0.05) &\n (t['ye_2013_F160W_' + pos] < 0.05) & \n (t['me_2010_F160W_' + pos] < 0.05) &\n (t['me_2013_F160W_' + pos] < 0.05))[0]\n print('Good = ', len(good))\n g = t[good]\n\n dx_05_10 = (g['x'+orig+'_2010_F160W_' + pos] - g['x'+orig+'_2005_F814W']) * ast.scale['WFC'] * 1e3\n dy_05_10 = (g['y'+orig+'_2010_F160W_' + pos] - g['y'+orig+'_2005_F814W']) * ast.scale['WFC'] * 1e3\n\n dx_05_13 = (g['x'+orig+'_2013_F160W_' + pos] - g['x'+orig+'_2005_F814W']) * ast.scale['WFC'] * 1e3\n dy_05_13 = (g['y'+orig+'_2013_F160W_' + pos] - g['y'+orig+'_2005_F814W']) * ast.scale['WFC'] * 1e3\n\n dx_10_13 = (g['x'+orig+'_2013_F160W_' + pos] - g['x'+orig+'_2010_F160W_' + pos]) * ast.scale['WFC'] * 1e3\n dy_10_13 = (g['y'+orig+'_2013_F160W_' + pos] - g['y'+orig+'_2010_F160W_' + pos]) * ast.scale['WFC'] * 1e3\n\n small = np.where((np.abs(dx_05_10) < 20) & (np.abs(dy_05_10) < 20) & \n (np.abs(dx_05_13) < 20) & (np.abs(dy_05_13) < 20) & \n (np.abs(dx_10_13) < 20) & (np.abs(dy_10_13) < 20))[0]\n print('Small = ', len(small))\n\n g = g[small]\n dx_05_10 = dx_05_10[small]\n dx_05_13 = dx_05_13[small]\n dx_10_13 = dx_10_13[small]\n dy_05_10 = dy_05_10[small]\n dy_05_13 = dy_05_13[small]\n dy_10_13 = dy_10_13[small]\n\n qscale = 2e2\n\n plot_dir = work_dir + '50.ALIGN_KS2/plots/'\n \n py.clf()\n q = py.quiver(g['x_2005_F814W'], g['y_2005_F814W'], dx_05_10, dy_05_10, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2010 - 2005')\n py.savefig(plot_dir + 'quiver_align_05_10_' + pos + orig + '.png')\n\n py.clf()\n q = py.quiver(g['x_2005_F814W'], g['y_2005_F814W'], dx_05_13, dy_05_13, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2013 - 2005')\n py.savefig(plot_dir + 'quiver_align_05_13_' + pos + orig + '.png')\n\n py.clf()\n q = py.quiver(g['x_2005_F814W'], g['y_2005_F814W'], dx_10_13, dy_10_13, scale=qscale)\n py.quiverkey(q, 0.95, 0.95, 5, '5 mas', color='red', labelcolor='red')\n py.title('2013 - 2010')\n py.savefig(plot_dir + 'quiver_align_10_13_' + pos + orig + '.png')\n\n py.clf()\n py.plot(dx_05_10, dy_05_10, 'k.', ms=2)\n lim = 10\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2010 - 2005')\n py.savefig(plot_dir + 'quiver_align_vpd_05_10_' + pos + orig + '.png')\n \n py.clf()\n py.plot(dx_05_13, dy_05_13, 'k.', ms=2)\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2013 - 2005')\n py.savefig(plot_dir + 'quiver_align_vpd_05_13_' + pos + orig + '.png')\n\n py.clf()\n py.plot(dx_10_13, dy_10_13, 'k.', ms=2)\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas)')\n py.ylabel('Y Proper Motion (mas)')\n py.title('2013 - 2010')\n py.savefig(plot_dir + 'quiver_align_vpd_10_13_' + pos + orig + '.png')\n\n print('2010 - 2005')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_10.mean(), dxe=dx_05_10.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_10.mean(), dye=dy_05_10.std()))\n\n print('2013 - 2005')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_05_13.mean(), dxe=dx_05_13.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_05_13.mean(), dye=dy_05_13.std()))\n\n print('2013 - 2010')\n print(' dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx_10_13.mean(), dxe=dx_10_13.std()))\n print(' dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy_10_13.mean(), dye=dy_10_13.std()))\n\n _out = open(plot_dir + 'quiver_align_stats_' + pos + orig + '.txt', 'w')\n _out.write('2010 - 2005\\n')\n _out.write(' dx = {dx:6.2f} +/- {dxe:6.2f} mas\\n'.format(dx=dx_05_10.mean(), dxe=dx_05_10.std()))\n _out.write(' dy = {dy:6.2f} +/- {dye:6.2f} mas\\n'.format(dy=dy_05_10.mean(), dye=dy_05_10.std()))\n\n _out.write('2013 - 2005\\n')\n _out.write(' dx = {dx:6.2f} +/- {dxe:6.2f} mas\\n'.format(dx=dx_05_13.mean(), dxe=dx_05_13.std()))\n _out.write(' dy = {dy:6.2f} +/- {dye:6.2f} mas\\n'.format(dy=dy_05_13.mean(), dye=dy_05_13.std()))\n\n _out.write('2013 - 2010\\n')\n _out.write(' dx = {dx:6.2f} +/- {dxe:6.2f} mas\\n'.format(dx=dx_10_13.mean(), dxe=dx_10_13.std()))\n _out.write(' dy = {dy:6.2f} +/- {dye:6.2f} mas\\n'.format(dy=dy_10_13.mean(), dye=dy_10_13.std()))\n _out.close()\n\n \n\n \n return\n\ndef plot_vpd_across_field(nside=4, interact=False):\n \"\"\"\n Plot the VPD at different field positions so we can see if there are\n systematic discrepancies due to residual distortions.\n \"\"\"\n # Read in matched and aligned star lists from the *.ref5 analysis.\n # Recall these data sets are in the F814W reference frame with a 50 mas plate scale.\n t2005 = starlists.read_matchup(work_dir + '02.MAT/MATCHUP.XYMEEE.F814W.ref5')\n t2010 = starlists.read_matchup(work_dir + '02.MAT/MATCHUP.XYMEEE.F125W.ref5')\n\n scale = 50.0 # mas per pixel\n \n\n # Trim down to only those stars that are detected in both epochs.\n # Also make cuts on astrometric/photometric errors, etc.\n # We only want the well measured stars in this analysis.\n perrLim814 = 1.0 / scale\n perrLim125 = 4.0 / scale\n merrLim814 = 0.05\n merrLim125 = 0.1\n \n cond = ((t2005.m != 0) & (t2010.m != 0) &\n (t2005.xe < perrLim814) & (t2005.ye < perrLim814) &\n (t2010.xe < perrLim125) & (t2010.ye < perrLim125) &\n (t2005.me < merrLim814) & (t2010.me < merrLim125))\n\n t2005 = t2005.where(cond)\n t2010 = t2010.where(cond)\n\n # Calculate proper motions\n dt = years['2010_F125W'] - years['2005_F814W']\n dx = t2010.x - t2005.x\n dy = t2010.y - t2005.y\n pmx = dx * scale / dt\n pmy = dy * scale / dt\n pm = np.hypot(pmx, pmy)\n\n t2005.add_column('pmx', pmx)\n t2005.add_column('pmy', pmy)\n t2005.add_column('pm', pm)\n\n\n # Divide up the region into N x N boxes and plot up the VPD for each.\n xlo = math.floor(t2005.x.min())\n xhi = math.ceil(t2005.x.max())\n ylo = math.floor(t2005.y.min())\n yhi = math.ceil(t2005.y.max())\n xboxsize = round((xhi - xlo) / nside)\n yboxsize = round((yhi - ylo) / nside)\n\n # Setup colors\n jet = py.get_cmap('jet')\n cNorm = colors.Normalize(vmin=0, vmax=nside**2)\n colorMap = py.cm.ScalarMappable(norm=cNorm, cmap=jet)\n\n # Save the average proper motions in each box\n pmx = np.zeros((nside, nside), dtype=float)\n pmy = np.zeros((nside, nside), dtype=float)\n pmxe = np.zeros((nside, nside), dtype=float)\n pmye = np.zeros((nside, nside), dtype=float)\n xcen = np.zeros((nside, nside), dtype=float)\n ycen = np.zeros((nside, nside), dtype=float)\n\n pmCut = 1.0\n\n # Calculate the global mean proper motion\n # Start by trimming down to a 1 mas/yr radius\n idx2 = np.where(pm < pmCut)[0]\n pmx_all = np.median( t2005.pmx[idx2] )\n pmy_all = np.median( t2005.pmy[idx2] )\n \n out = 'All X:{0:5.0f}-{1:5.0f} Y:{2:5.0f}-{3:5.0f} '\n out += 'PMX:{4:5.2f} +/- {5:5.2f} PMY:{6:5.2f} +/- {7:5.2f} '\n out += 'N:{8:5d}'\n print((out.format(xlo, xhi, ylo, yhi, pmx_all, 0.0, pmy_all, 0.0, len(idx2))))\n\n # Make a global proper motion diagram of star with a proper motion within\n # 1 mas/yr. This is mainly to see systematic flows due to residual distortion.\n pmTot = np.hypot(t2005.pmx, t2005.pmy)\n clust = np.where(pmTot < pmCut)[0]\n py.clf()\n q = py.quiver(t2005.x[clust], t2005.y[clust], t2005.pmx[clust], t2005.pmy[clust],\n scale=18)\n py.quiverkey(q, 0.5, 0.98, 1, '1 mas/yr', color='red', labelcolor='red')\n py.xlabel('X Position (pixels)')\n py.ylabel('Y Position (pixels)')\n py.xlim(xlo, xhi)\n py.ylim(ylo, yhi)\n out = '{0}/plots/vec_proper_motion_all.png'\n py.savefig(out.format(work_dir))\n \n py.clf()\n for xx in range(nside):\n for yy in range(nside):\n xlo_box = xlo + xx * xboxsize\n ylo_box = ylo + yy * yboxsize\n xhi_box = xlo + (1+xx) * xboxsize\n yhi_box = ylo + (1+yy) * yboxsize\n\n idx = np.where((t2005.x > xlo_box) & (t2005.x <= xhi_box) &\n (t2005.y > ylo_box) & (t2005.y <= yhi_box))[0]\n\n\n if interact:\n color = colorMap.to_rgba(yy + xx * nside)\n lim = 5\n\n py.plot(t2005.pmx[idx], t2005.pmy[idx], 'k.', ms=2, color=color)\n py.axis([-lim, lim, -lim, lim])\n\n py.xlabel('X Proper Motion (mas/yr)')\n py.ylabel('Y Proper Motion (mas/yr)')\n\n # Lets get the mean and std-dev (iterative) for the box.\n # Start by trimming down to a 1 mas/yr circle.\n idx2 = np.where(t2005.pm[idx] < pmCut)[0]\n xmean = np.median( t2005.pmx[idx][idx2] )\n ymean = np.median( t2005.pmy[idx][idx2] )\n xstd = t2005.pmx[idx][idx2].std()\n ystd = t2005.pmy[idx][idx2].std()\n xmean_err = xstd / np.sqrt(len(idx2))\n ymean_err = ystd / np.sqrt(len(idx2))\n\n xcen[xx, yy] = xlo_box + (xboxsize / 2.0)\n ycen[xx, yy] = ylo_box + (yboxsize / 2.0)\n pmx[xx, yy] = xmean - pmx_all\n pmy[xx, yy] = ymean - pmx_all\n pmxe[xx, yy] = xmean_err\n pmye[xx, yy] = ymean_err\n\n out = 'Box X:{0:5.0f}-{1:5.0f} Y:{2:5.0f}-{3:5.0f} '\n out += 'PMX:{4:5.2f} +/- {5:5.2f} PMY:{6:5.2f} +/- {7:5.2f} '\n out += 'N:{8:5d} '\n\n if interact:\n out += 'Continue?'\n input(out.format(xlo_box, xhi_box, ylo_box, yhi_box,\n xmean, xmean_err, ymean, ymean_err, len(idx2)))\n else:\n print((out.format(xlo_box, xhi_box, ylo_box, yhi_box,\n xmean, xmean_err, ymean, ymean_err, len(idx2))))\n\n\n if interact:\n out = '{0}/plots/vpd_grid_nside{1}.png'\n py.savefig(out.format(work_dir, nside))\n\n py.clf()\n q = py.quiver(xcen, ycen, pmx, pmy)\n py.quiverkey(q, 0.5, 0.98, 0.1, '0.1 mas/yr', color='red', labelcolor='red')\n py.xlabel('X Position (pixels)')\n py.ylabel('Y Position (pixels)')\n py.xlim(xlo, xhi)\n py.ylim(ylo, yhi)\n for xx in range(nside+1):\n py.axvline(xlo + xx * xboxsize, linestyle='--', color='grey')\n for yy in range(nside+1):\n py.axhline(ylo + yy * yboxsize, linestyle='--', color='grey')\n out = '{0}/plots/vec_proper_motion_grid_nside{1}.png'\n py.savefig(out.format(work_dir, nside))\n\n py.clf()\n q = py.quiver(xcen, ycen, pmx/pmxe, pmy/pmye)\n py.quiverkey(q, 0.5, 0.98, 3, '3 sigma', color='red', labelcolor='red')\n py.xlabel('X Position (pixels)')\n py.ylabel('Y Position (pixels)')\n py.xlim(xlo, xhi)\n py.ylim(ylo, yhi)\n for xx in range(nside+1):\n py.axvline(xlo + xx * xboxsize, linestyle='--', color='grey')\n for yy in range(nside+1):\n py.axhline(ylo + yy * yboxsize, linestyle='--', color='grey')\n out = '{0}/plots/vec_proper_motion_grid_sig_nside{1}.png'\n py.savefig(out.format(work_dir, nside))\n\ndef calc_years():\n \"\"\"\n Calculate the epoch for each data set.\n \"\"\"\n years = ['2005', '2010', '2010', '2010', '2013', '2013']\n filts = ['F814W', 'F125W', 'F139M', 'F160W', 'F160W', 'F160Ws']\n \n for ii in range(len(years)):\n dataDir = '{0}/{1}_{2}/00.DATA/'.format(work_dir, years[ii], filts[ii])\n\n epoch = flystar.calc_mean_year(glob.glob(dataDir + '*_flt.fits'))\n\n print(('{0}_{1} at {2:8.3f}'.format(years[ii], filts[ii], epoch)))\n \n \ndef make_master_lists():\n \"\"\"\n Trim the ref5 master lists for each filter down to just stars with\n proper motions within 1 mas/yr of the cluster motion.\n \"\"\"\n # Read in matched and aligned star lists from the *.ref5 analysis.\n # Recall these data sets are in the F814W reference frame with a 50 mas plate scale.\n print('Loading Data')\n t2005_814 = starlists.read_matchup(work_dir + '02.MAT/MATCHUP.XYMEEE.F814W.2005.ref5')\n t2010_125 = starlists.read_matchup(work_dir + '02.MAT/MATCHUP.XYMEEE.F125W.2010.ref5')\n t2010_139 = starlists.read_matchup(work_dir + '02.MAT/MATCHUP.XYMEEE.F139M.2010.ref5')\n t2010_160 = starlists.read_matchup(work_dir + '02.MAT/MATCHUP.XYMEEE.F160W.2010.ref5')\n t2013_160 = starlists.read_matchup(work_dir + '02.MAT/MATCHUP.XYMEEE.F160W.2013.ref5')\n t2013_160s = starlists.read_matchup(work_dir + '02.MAT/MATCHUP.XYMEEE.F160Ws.2013.ref5')\n\n scale = 50.0 # mas per pixel\n\n # Trim down to only those stars that are detected in all epochs.\n # Also make cuts on astrometric/photometric errors, etc.\n # We only want the well measured stars in this analysis.\n perrLim2005 = 3.0 / scale\n perrLim2010 = 4.0 / scale\n perrLim2013 = 5.0 / scale\n merrLim2005 = 0.05\n merrLim2010 = 0.1\n merrLim2013 = 0.1\n \n print('Trimming Data')\n cond = ((t2005_814['m'] != 0) & (t2010_125['m'] != 0) &\n (t2010_139['m'] != 0) & (t2010_160['m'] != 0) &\n (t2013_160['m'] != 0) &\n (t2005_814['xe'] < perrLim2005) & (t2005_814['ye'] < perrLim2005) &\n (t2010_125['xe'] < perrLim2010) & (t2010_125['ye'] < perrLim2010) &\n (t2010_139['xe'] < perrLim2010) & (t2010_139['ye'] < perrLim2010) &\n (t2010_160['xe'] < perrLim2010) & (t2010_160['ye'] < perrLim2010) &\n (t2013_160['xe'] < perrLim2013) & (t2013_160['ye'] < perrLim2013) &\n (t2005_814['me'] < merrLim2005) & (t2010_125['me'] < merrLim2010) &\n (t2010_139['me'] < merrLim2010) & (t2010_160['me'] < merrLim2010) &\n (t2013_160['me'] < merrLim2013))\n print(' Cutting down to {0} from {1}'.format(cond.sum(), len(t2005_814)))\n\n t2005_814 = t2005_814[cond]\n t2010_125 = t2010_125[cond]\n t2010_139 = t2010_139[cond]\n t2010_160 = t2010_160[cond]\n t2013_160 = t2013_160[cond]\n t2013_160s = t2013_160s[cond]\n\n # Calculate proper motions\n print('Calculating velocities')\n t = np.array([years['2005_F814W'], years['2010_F160W'], years['2013_F160W']])\n x = np.array([t2005_814['x'], t2010_160['x'], t2013_160['x']]).T\n y = np.array([t2005_814['y'], t2010_160['y'], t2013_160['y']]).T\n xe = np.array([t2005_814['xe'], t2010_160['xe'], t2013_160['xe']]).T\n ye = np.array([t2005_814['ye'], t2010_160['ye'], t2013_160['ye']]).T\n\n def linefit2(time, pos, pos_err):\n epochs = np.tile(time, (pos_err.shape[1], 1)).T\n\n # t_w = epochs / (pos_err ** 2)\n # p_w = pos / (pos_err ** 2)\n\n w = 1.0 / (pos_err ** 2)\n\n w_sum = w.sum(axis=0)\n\n wxy = (w * epochs * pos).sum(axis=0)\n wx = (w * epochs).sum(axis=0)\n wy = (w * pos).sum(axis=0)\n wxx = (w * epochs ** 2).sum(axis=0)\n\n denom = (w_sum * wxx) - (wx ** 2)\n \n vel = (w_sum * wxy - wx * wy) / denom\n pos0 = (wxx * wy - wx * wxy) / denom\n\n vel_err = np.sqrt( w_sum / denom )\n pos0_err = np.sqrt( wxx / denom )\n\n return pos0, vel, pos0_err, vel_err\n \n \n # Lets set a t0 value:\n t0 = 2010.0\n x0, vx, x0e, vxe = linefit2(t - t0, x.T, xe.T)\n y0, vy, y0e, vye = linefit2(t - t0, y.T, ye.T)\n vx *= scale\n vy *= scale\n vxe *= scale\n vye *= scale\n\n # Add the velocity fits to the 2005 table\n t2005_814['vx'] = vx\n t2005_814['vy'] = vy\n t2005_814['vxe'] = vxe\n t2005_814['vye'] = vye\n\n # Get rid of stars without velocities\n good = ((np.isnan(vx) == False) & (np.isnan(vy) == False))\n print(' Cutting down to {0} from {1}'.format(good.sum(), len(t2005_814)))\n t2005_814 = t2005_814[good]\n t2010_125 = t2010_125[good]\n t2010_139 = t2010_139[good]\n t2010_160 = t2010_160[good]\n t2013_160 = t2013_160[good]\n t2013_160s = t2013_160s[good]\n\n vx = vx[good]\n vy = vy[good]\n vxe = vxe[good]\n vye = vye[good]\n\n # Trim down to a 1 mas/yr radius\n # vx_mean = statsIter.mean(vx, lsigma=4, hsigma=4, iter=10, verbose=True)\n # vy_mean = statsIter.mean(vy, lsigma=4, hsigma=4, iter=10, verbose=True)\n vx_mean = 0.0\n vy_mean = 0.0 \n velCut = 0.7\n velErrCut = 0.2\n\n # Make a couple of plots to decide on (and show) the cuts\n py.clf()\n py.plot(vx, vy, 'k.', alpha=0.2)\n circ = py.Circle([vx_mean, vy_mean], radius=velCut, color='red', fill=False)\n py.gca().add_artist(circ)\n py.xlabel('X Velocity (mas/yr)')\n py.ylabel('Y Velocity (mas/yr)')\n py.axis([-2, 2, -2, 2])\n py.savefig('plots/make_master_vpd_cuts.png')\n\n py.clf()\n py.plot(t2005_814['m'], vxe, 'r.', alpha=0.2, label='X')\n py.plot(t2005_814['m'], vye, 'b.', alpha=0.2, label='Y')\n py.axhline(velErrCut, color='black')\n py.xlabel('F814W Magnitude')\n py.ylabel('Velocity Error (mas/yr)')\n py.legend()\n py.savefig('plots/make_master_verr_cuts.png')\n\n dv = np.hypot(vx - vx_mean, vy - vy_mean)\n idx2 = ((dv < velCut) & (vxe < velErrCut) & (vye < velErrCut))\n print('Making Velocity Cuts: v < {0:3.1f} mas/yr and verr < {1:3.1f} mas/yr'.format(velCut, velErrCut))\n print(' Cutting down to {0} from {1}'.format(idx2.sum(), len(t2005_814)))\n\n t2005_814 = t2005_814[idx2]\n t2010_125 = t2010_125[idx2]\n t2010_139 = t2010_139[idx2]\n t2010_160 = t2010_160[idx2]\n t2013_160 = t2013_160[idx2]\n t2013_160s = t2013_160s[idx2]\n\n _o814_05 = open(work_dir + '02.MAT/MASTER.F814W.2005.ref5', 'w')\n _o125_10 = open(work_dir + '02.MAT/MASTER.F125W.2010.ref5', 'w')\n _o139_10 = open(work_dir + '02.MAT/MASTER.F139M.2010.ref5', 'w')\n _o160_10 = open(work_dir + '02.MAT/MASTER.F160W.2010.ref5', 'w')\n _o160_13 = open(work_dir + '02.MAT/MASTER.F160W.2013.ref5', 'w')\n _o160s_13 = open(work_dir + '02.MAT/MASTER.F160Ws.2013.ref5', 'w')\n\n ofmt = '{0:10.4f} {1:10.4f} {2:8.4f} {3:10.4f} {4:10.4f} {5:8.4f} {6}\\n'\n for ii in range(len(t2005_814)):\n _o814_05.write(ofmt.format(t2005_814['x'][ii], t2005_814['y'][ii], t2005_814['m'][ii],\n t2005_814['xe'][ii], t2005_814['ye'][ii], t2005_814['me'][ii],\n t2005_814['name'][ii]))\n _o125_10.write(ofmt.format(t2010_125['x'][ii], t2010_125['y'][ii], t2010_125['m'][ii],\n t2010_125['xe'][ii], t2010_125['ye'][ii], t2010_125['me'][ii],\n t2010_125['name'][ii]))\n _o139_10.write(ofmt.format(t2010_139['x'][ii], t2010_139['y'][ii], t2010_139['m'][ii],\n t2010_139['xe'][ii], t2010_139['ye'][ii], t2010_139['me'][ii],\n t2010_139['name'][ii]))\n _o160_10.write(ofmt.format(t2010_160['x'][ii], t2010_160['y'][ii], t2010_160['m'][ii],\n t2010_160['xe'][ii], t2010_160['ye'][ii], t2010_160['me'][ii],\n t2010_160['name'][ii]))\n _o160_13.write(ofmt.format(t2013_160['x'][ii], t2013_160['y'][ii], t2013_160['m'][ii],\n t2013_160['xe'][ii], t2013_160['ye'][ii], t2013_160['me'][ii],\n t2013_160['name'][ii]))\n _o160s_13.write(ofmt.format(t2013_160s['x'][ii], t2013_160s['y'][ii], t2013_160s['m'][ii],\n t2013_160s['xe'][ii], t2013_160s['ye'][ii], t2013_160s['me'][ii],\n t2013_160s['name'][ii]))\n\n _o814_05.close()\n _o125_10.close()\n _o139_10.close()\n _o160_10.close()\n _o160_13.close()\n _o160s_13.close()\n\n\ndef make_pos_directories():\n \"\"\"\n Make the individual position directories. The structure is complicated\n enough that it is worth doing in code. All of this goes under\n\n 03.MAT_POS/\n\n \"\"\"\n os.chdir(work_dir + '/03.MAT_POS')\n\n years = ['2005', '2010', '2013']\n\n filts = {'2005': ['F814W'],\n '2010': ['F125W', 'F139M', 'F160W'],\n '2013': ['F160W', 'F160Ws']}\n\n pos4_exceptions = ['2005_F814W', '2013_F160Ws']\n old_mat_dir = '../02.MAT'\n\n for year in years:\n filts_in_year = filts[year]\n\n for filt in filts_in_year:\n epoch_filt = '{0}_{1}'.format(year, filt)\n\n if epoch_filt in pos4_exceptions:\n posits = ['']\n else:\n posits = ['pos1', 'pos2', 'pos3', 'pos4']\n\n # Define the master file for this combo\n master_file = '{0}/MASTER.{1}.{2}.ref5'.format(old_mat_dir, filt, year)\n \n for pos in posits:\n ep_filt_pos = epoch_filt\n if pos != '':\n ep_filt_pos += '_{0}'.format(pos)\n\n # Make the directory\n fileUtil.mkdir(ep_filt_pos)\n fileUtil.mkdir(ep_filt_pos + '/01.XYM')\n\n # Copy over the master file\n shutil.copy(master_file, ep_filt_pos + '/01.XYM/')\n\n return\n\ndef calc_pos_number():\n \"\"\"\n Calculate the position number (in 2005 ACS coordinate system) of all the\n MAT.*** files in 02.MAT directory. This can then be used to separate out\n which files are in pos1/ pos2/ pos3/ and pos4/. The schematic for the\n positions is:\n\n pos4 pos1\n pos3 pos2\n\n Just read in the MAT.*** file, take the average of columns 3 and 4 and use\n rough, hard-coded quadrant separations to pick out the position. \n \"\"\"\n mat_files = glob.glob(work_dir + '02.MAT/MAT.*')\n epoch_filt = np.zeros(len(mat_files), dtype='S12')\n pos = np.zeros(len(mat_files), dtype='S4')\n mat_root = np.zeros(len(mat_files), dtype='S8')\n xavg = np.zeros(len(mat_files), dtype=float)\n yavg = np.zeros(len(mat_files), dtype=float)\n\n for mm in range(len(mat_files)):\n tab = starlists.read_mat(mat_files[mm])\n\n # Get the average X and average Y position for this file\n xavg[mm] = tab['xref'].mean()\n yavg[mm] = tab['yref'].mean()\n\n # Get the MAT root file name and number for printing\n mat_root[mm] = os.path.split(mat_files[mm])[1]\n mat_num = os.path.splitext(mat_root[mm])[1]\n mat_num = int(mat_num[1:])\n\n # Decide the epoch and the filter.\n if (mat_num >= 0) and (mat_num <= 99):\n epoch_filt[mm] = '2005_F814W'\n if (mat_num >= 100) and (mat_num <= 129):\n epoch_filt[mm] = '2010_F125W'\n if (mat_num >= 130) and (mat_num <= 161):\n epoch_filt[mm] = '2010_F139M'\n if (mat_num >= 162) and (mat_num <= 199):\n epoch_filt[mm] = '2010_F160W'\n if (mat_num >= 200) and (mat_num <= 259):\n epoch_filt[mm] = '2013_F160W'\n if (mat_num >= 270) and (mat_num <= 299):\n epoch_filt[mm] = '2013_F160Ws'\n \n # Decide the position\n if (xavg[mm] > 2000) and (yavg[mm] > 2000):\n pos[mm] = 'pos1'\n if (xavg[mm] > 2000) and (yavg[mm] < 2000):\n pos[mm] = 'pos2'\n if (xavg[mm] < 2000) and (yavg[mm] < 2000):\n pos[mm] = 'pos3'\n if (xavg[mm] < 2000) and (yavg[mm] > 2000):\n pos[mm] = 'pos4'\n\n\n\n # Print output\n efilt_unique = np.unique(epoch_filt)\n pos_unique = np.unique(pos)\n fmt = '{0:s} {1:s} {2:s} {3:4.0f} {4:4.0f}'\n\n for ee in efilt_unique:\n for pp in pos_unique:\n idx = np.where((epoch_filt == ee) & (pos == pp))[0]\n\n print() \n for ii in idx:\n print(fmt.format(mat_root[ii], epoch_filt[ii], pos[ii],\n xavg[ii], yavg[ii]))\n \n return mat_root, epoch_filt, pos\n\ndef setup_xym_by_pos():\n \"\"\"\n Something\n \"\"\"\n os.chdir(work_dir + '/03.MAT_POS')\n\n pos4_exceptions = ['2005_F814W', '2013_F160Ws']\n old_mat_dir = '../02.MAT/'\n\n # Get the MAT file names and positions.\n mat_root, epoch_filt, pos = calc_pos_number()\n\n # Read the old IN.xym2bar file to match MAT.??? to the *.xym files\n mat_xym_files = read_in_xym2mat(old_mat_dir + 'IN.xym2mat')\n \n open_logs = {}\n \n for ii in range(len(mat_root)):\n # copy stuff to this directory\n to_dir = epoch_filt[ii]\n\n if epoch_filt[ii] not in pos4_exceptions:\n to_dir += '_' + pos[ii]\n\n to_dir += '/01.XYM/'\n print('Copying to {0} for {1}'.format(to_dir, mat_root[ii]))\n \n # Get rid of the filter-related letters for the 02.MAT/ sub-dir.\n efilt_strip = epoch_filt[ii].replace('W', '').replace('F', '').replace('M', '')\n\n # Copy the old MAT file\n from_file = old_mat_dir + efilt_strip + '/' + mat_root[ii]\n shutil.copy(from_file, to_dir)\n print(' Copy ' + from_file)\n\n # Copy the xym file\n mat_num = mat_root[ii].split('.')[1]\n\n xym_file = mat_xym_files[mat_num]\n \n shutil.copy(xym_file, to_dir)\n print(' Copy ' + xym_file)\n\n # Keep a record of the match between XYM and MAT files\n logfile = to_dir + 'xym_mat.txt'\n\n if logfile not in list(open_logs.keys()):\n _log = open(logfile, 'w')\n open_logs[logfile] = _log\n else:\n _log = open_logs[logfile]\n\n # Just save the xym_file file name... not the path.\n xym_file_base = os.path.split(xym_file)[1]\n _log.write('{0} {1}\\n'.format(mat_num, xym_file_base))\n\n # Close all the log files\n for key in open_logs:\n open_logs[key].close()\n \n return\n\n\ndef read_in_xym2mat(in_file):\n _in = open(in_file, \"r\")\n lines = _in.readlines()\n _in.close()\n \n cnt_mat = len(lines) - 1\n\n mat_num = np.zeros(cnt_mat, dtype='S3')\n xym_files = np.zeros(cnt_mat, dtype='S80')\n\n # Skip the first line\n jj = 0\n for ii in range(1, len(lines)):\n # Split the line by spaces\n line_split = lines[ii].split()\n \n # First entry is the MAT file number\n mat_num[jj] = line_split[0]\n xym_files[jj] = line_split[1][1:-1]\n\n jj += 1\n\n mat_xym_files = dict(list(zip(mat_num, xym_files)))\n\n return mat_xym_files\n\n\n \ndef xym_by_pos(year, filt, pos, Nepochs):\n \"\"\"\n Re-do the alignment with the ref5 master frames (cluster members only);\n but do the alignments on each position separately.\n\n Doesn't work for 2005_F814W or 2013_F160Ws.\n \"\"\"\n mat_dir = '{0}/03.MAT_POS/{1}_{2}_{3}/01.XYM/'.format(work_dir, year, filt, pos)\n\n master_file = 'MASTER.{0}.{1}.ref5'.format(filt, year)\n\n # Read in the xym_mat.txt file that maps the MAT and XYM files together.\n tab = Table.read(mat_dir + 'xym_mat.txt', format='ascii')\n \n # Make IN.xym2mat and IN.xym2bar file\n _mat = open(mat_dir + 'IN.xym2mat', 'w')\n _bar = open(mat_dir + 'IN.xym2bar', 'w')\n \n _mat.write('000 ' + master_file + ' c0\\n')\n\n for ii in range(len(tab)):\n _mat.write('{0} {1} c9\\n'.format(tab[ii][0], tab[ii][1]))\n _bar.write('{0} {1} c9\\n'.format(tab[ii][0], tab[ii][1]))\n\n _mat.close()\n _bar.close()\n\n # Run xym2mat\n os.chdir(mat_dir)\n subprocess.call(['xym2mat', '22'])\n subprocess.call(['xym2mat', '24'])\n subprocess.call(['xym2mat', '25'])\n\n # Make IN.xym2bar file\n subprocess.call(['xym2bar', str(Nepochs)])\n\n # Copy final output files\n suffix = '.{0}.{1}.{2}.refClust'.format(filt, year, pos)\n shutil.copy('MATCHUP.XYMEEE', 'MATCHUP.XYMEEE' + suffix)\n shutil.copy('TRANS.xym2mat', 'TRANS.xym2mat' + suffix)\n shutil.copy('TRANS.xym2bar', 'TRANS.xym2bar' + suffix)\n shutil.copy('IN.xym2mat', 'IN.xym2mat' + suffix)\n shutil.copy('IN.xym2bar', 'IN.xym2bar' + suffix)\n\n return\n \ndef make_brite_list_2010():\n \"\"\"\n Copy over the MATCHUP ref5 files from the 02.MAT directory. It has to be ref5\n because we want the starlists to be matched. The difference between ref5 and\n refClust is very small.\n \n Take an input list of MATCHUP files (assumes they have the same stars, and the\n same length) and trim out only the bright stars. The resulting output file contains\n the X and Y position (from the first file) and the list of all magnitudes for each star.\n\n trimMags is a list of brightness criteria for each of the matchup files. Any star\n that satisfies this criteria in any one of the filters will be added to the global\n bright list.\n\n This is a modified version of the code that is in hst_flystar. The modifications\n include:\n - for bright stars, detection in only 1 filter is required.\n - a set of hand selected brite stars are validated and added to the list.\n \"\"\"\n matchup_file = ['MATCHUP.XYMEEE.F160W.2010.ref5',\n 'MATCHUP.XYMEEE.F139M.2010.ref5',\n 'MATCHUP.XYMEEE.F125W.2010.ref5']\n trimMags = [-8, -7, -8]\n\n os.chdir(work_dir + '12.KS2_2010')\n shutil.copy('{0}02.MAT/{1}'.format(work_dir, matchup_file[0]), './')\n shutil.copy('{0}02.MAT/{1}'.format(work_dir, matchup_file[1]), './')\n shutil.copy('{0}02.MAT/{1}'.format(work_dir, matchup_file[2]), './')\n\n # Read in the matchup files.\n list_160 = starlists.read_matchup(matchup_file[0])\n list_139 = starlists.read_matchup(matchup_file[1])\n list_125 = starlists.read_matchup(matchup_file[2])\n\n stars = astropy.table.hstack([list_160, list_139, list_125])\n print('Loaded {0} stars'.format(len(stars)))\n\n # Trim down based on the magnitude cuts. Non-detections will pass\n # through as long as there is a valid detection in at least one filter.\n good1 = np.where((stars['m_1'] < trimMags[0]) |\n (stars['m_2'] < trimMags[1]) |\n (stars['m_3'] < trimMags[2]))[0]\n\n stars = stars[good1]\n print('Keeping {0} stars that meet brightness cuts'.format(len(stars)))\n\n # For sources fainter than [-10, -9, -10], they must be in\n # all three epochs.\n keep = np.zeros(len(stars), dtype=bool)\n\n mag_rng = [-10, -9, -10]\n good2 = np.where((stars['m_1'] > mag_rng[0]) & (stars['m_1'] < 0) &\n (stars['m_2'] > mag_rng[1]) & (stars['m_2'] < 0) &\n (stars['m_3'] > mag_rng[2]) & (stars['m_3'] < 0))[0]\n keep[good2] = True\n\n # For sources between [-14, -13, -14] and [-10, -9, -10], they must be in\n # at least two epochs.\n mag_lo = [-10, -9, -10]\n mag_hi = [-14, -13, -14]\n in12 = np.where((stars['m_1'] > mag_hi[0]) & (stars['m_1'] < mag_lo[0]) &\n (stars['m_2'] > mag_hi[1]) & (stars['m_2'] < mag_lo[1]))[0]\n in13 = np.where((stars['m_1'] > mag_hi[0]) & (stars['m_1'] < mag_lo[0]) &\n (stars['m_3'] > mag_hi[2]) & (stars['m_3'] < mag_lo[2]))[0]\n in23 = np.where((stars['m_2'] > mag_hi[1]) & (stars['m_2'] < mag_lo[1]) &\n (stars['m_3'] > mag_hi[2]) & (stars['m_3'] < mag_lo[2]))[0]\n\n keep[in12] = True\n keep[in13] = True\n keep[in23] = True\n\n # For sources brighter than [-14, -13, -14], they must be detected in\n # at least one epoch.\n mag_lim = [-14, -13, -14]\n good3 = np.where((stars['m_1'] < mag_lim[0]) |\n (stars['m_2'] < mag_lim[1]) |\n (stars['m_3'] < mag_lim[2]))[0]\n keep[good3] = True\n\n stars = stars[keep]\n\n # Save the matchup stars to a file (with errors). Later on,\n # these will be appended to the ks2 output if ks2 doesn't find\n # the bright source. In other wordes, trust the one pass output\n # at the brightest stars.\n brite_obs_125 = open('BRITE_F125W.XYMEEE', 'w')\n brite_obs_139 = open('BRITE_F139M.XYMEEE', 'w')\n brite_obs_160 = open('BRITE_F160W.XYMEEE', 'w')\n \n for ii in range(len(stars)):\n fmt = '{x:10.4f} {y:10.4f} {m:10.4f} {me:10.4f} {ye:10.4f} {ye:10.4f}\\n'\n\n brite_obs_160.write(fmt.format(x=stars['x_1'][ii],\n y=stars['y_1'][ii],\n m=stars['m_1'][ii],\n xe=stars['xe_1'][ii],\n ye=stars['ye_1'][ii],\n me=stars['me_1'][ii]))\n brite_obs_139.write(fmt.format(x=stars['x_2'][ii],\n y=stars['y_2'][ii],\n m=stars['m_2'][ii],\n xe=stars['xe_2'][ii],\n ye=stars['ye_2'][ii],\n me=stars['me_2'][ii]))\n brite_obs_125.write(fmt.format(x=stars['x_3'][ii],\n y=stars['y_3'][ii],\n m=stars['m_3'][ii],\n xe=stars['xe_3'][ii],\n ye=stars['ye_3'][ii],\n me=stars['me_3'][ii]))\n \n brite_obs_125.close()\n brite_obs_139.close()\n brite_obs_160.close()\n \n\n # Now we need to fix the magnitudes for the non detections amongst the\n # bright sources. I know the rough relationships between brightnesses\n # between these 3 filters, so I will just use those:\n # F160W = F125W\n # F139M = F160W + 1.5\n #\n # 1. detected in F160W but not in F125W\n idx = np.where((stars['m_1'] != 0) & (stars['m_3'] == 0))[0]\n stars['m_3'][idx] = stars['m_1'][idx]\n stars['x_3'][idx] = stars['x_1'][idx]\n stars['y_3'][idx] = stars['y_1'][idx]\n\n # 2. detected in F160W but not in F139M\n idx = np.where((stars['m_1'] != 0) & (stars['m_2'] == 0))[0]\n stars['m_2'][idx] = stars['m_1'][idx] + 1.5\n stars['x_2'][idx] = stars['x_1'][idx]\n stars['y_2'][idx] = stars['y_1'][idx]\n\n # 3. detected in F125W but not in F160W\n idx = np.where((stars['m_3'] != 0) & (stars['m_1'] == 0))[0]\n stars['m_1'][idx] = stars['m_3'][idx]\n stars['x_1'][idx] = stars['x_3'][idx]\n stars['y_1'][idx] = stars['y_3'][idx]\n\n # 4. detected in F125W but not in F139M\n idx = np.where((stars['m_3'] != 0) & (stars['m_2'] == 0))[0]\n stars['m_2'][idx] = stars['m_3'][idx] + 1.5\n stars['x_2'][idx] = stars['x_3'][idx]\n stars['y_2'][idx] = stars['y_3'][idx]\n\n # 5. detected in F139M but not in F160W\n idx = np.where((stars['m_2'] != 0) & (stars['m_1'] == 0))[0]\n stars['m_1'][idx] = stars['m_2'][idx] - 1.5\n stars['x_1'][idx] = stars['x_2'][idx]\n stars['y_1'][idx] = stars['y_2'][idx]\n\n # 6. detected in F139M but not in F125W\n idx = np.where((stars['m_2'] != 0) & (stars['m_3'] == 0))[0]\n stars['m_3'][idx] = stars['m_2'][idx] - 1.5\n stars['x_3'][idx] = stars['x_2'][idx]\n stars['y_3'][idx] = stars['y_2'][idx]\n\n # Double check that everything has a valid magnitude\n idx = np.where((stars['m_1'] < 0) &\n (stars['m_2'] < 0) &\n (stars['m_3'] < 0) &\n (stars['x_1'] != 0) &\n (stars['y_1'] != 0))[0]\n if len(idx) != len(stars):\n print('FAILED: finding some bright stars with ')\n print('no magnitudes in some filters')\n pdb.set_trace()\n\n brite = open('BRITE.XYM', 'w')\n \n for ii in range(len(stars)):\n fmt = '{x:10.4f} {y:10.4f} {m1:10.4f} {m2:10.4f} {m3:10.4f}\\n'\n\n brite.write(fmt.format(x=stars['x_1'][ii],\n y=stars['y_1'][ii],\n m1=stars['m_1'][ii],\n m2=stars['m_2'][ii],\n m3=stars['m_3'][ii]))\n \n brite.close()\n\n return\n\ndef find_top_stars(reread=False):\n \"\"\"\n Select some stars to be our topStars named sources.\n Verify that they are detected in all of the\n epochs and all of the filters.\n \"\"\"\n root_2005_814 = work_dir + '11.KS2_2005/nimfo2bar.xymeee.ks2.F1'\n root_2010_160 = work_dir + '12.KS2_2010/nimfo2bar.xymeee.F1'\n root_2010_139 = work_dir + '12.KS2_2010/nimfo2bar.xymeee.F2'\n root_2010_125 = work_dir + '12.KS2_2010/nimfo2bar.xymeee.F3'\n root_2013_160 = work_dir + '13.KS2_2013/nimfo2bar.xymeee.F1'\n root_2013_160s = work_dir + '13.KS2_2013/nimfo2bar.xymeee.F2'\n\n print('Reading data')\n if reread == True:\n t_2005_814 = starlists.read_nimfo2bar(root_2005_814)\n t_2010_160 = starlists.read_nimfo2bar(root_2010_160)\n t_2010_139 = starlists.read_nimfo2bar(root_2010_139)\n t_2010_125 = starlists.read_nimfo2bar(root_2010_125)\n t_2013_160 = starlists.read_nimfo2bar(root_2013_160)\n t_2013_160s = starlists.read_nimfo2bar(root_2013_160s)\n\n t_2005_814.write(root_2005_814 + '.fits', overwrite=True)\n t_2010_160.write(root_2010_160 + '.fits', overwrite=True)\n t_2010_139.write(root_2010_139 + '.fits', overwrite=True)\n t_2010_125.write(root_2010_125 + '.fits', overwrite=True)\n t_2013_160.write(root_2013_160 + '.fits', overwrite=True)\n t_2013_160s.write(root_2013_160s + '.fits', overwrite=True)\n else:\n t_2005_814 = Table.read(root_2005_814 + '.fits')\n t_2010_160 = Table.read(root_2010_160 + '.fits')\n t_2010_139 = Table.read(root_2010_139 + '.fits')\n t_2010_125 = Table.read(root_2010_125 + '.fits')\n t_2013_160 = Table.read(root_2013_160 + '.fits')\n t_2013_160s = Table.read(root_2013_160s + '.fits')\n \n\n # Trim them all down to some decent magnitude ranges. These\n # were chosen by a quick look at the CMD from the one-pass analysis.\n print('Cutting out faint stars')\n lo814 = -13 #+ 3\n lo160 = -9 #+ 3\n lo139 = -7.35 #+ 3\n lo125 = -9.2 #+ 3\n\n # First pass, cuts are courser so that we can measure crowding.\n g_2005_814 = np.where(t_2005_814['m'] < lo814)[0]\n g_2010_125 = np.where(t_2010_125['m'] < lo125)[0]\n g_2010_139 = np.where(t_2010_139['m'] < lo139)[0]\n g_2010_160 = np.where(t_2010_160['m'] < lo160)[0]\n g_2013_160 = np.where(t_2013_160['m'] < lo160)[0]\n g_2013_160s = np.where(t_2013_160s['m'] < lo160)[0]\n\n t_2005_814 = t_2005_814[g_2005_814]\n t_2010_125 = t_2010_125[g_2010_125]\n t_2010_139 = t_2010_139[g_2010_139]\n t_2010_160 = t_2010_160[g_2010_160]\n t_2013_160 = t_2013_160[g_2013_160]\n t_2013_160s = t_2013_160s[g_2013_160s]\n\n # Cross match all the sources. All positions should agree to within\n # a pixel. Do this consecutively so that you build up the good matches.\n print('Matching 2010_160 and 2010_125')\n r1 = align.match(t_2010_160['x'], t_2010_160['y'], t_2010_160['m'],\n t_2010_125['x'], t_2010_125['y'], t_2010_125['m'] - 0.2,\n dr_tol=0.5, dm_tol=1.0)\n print(' found {0:d} matches'.format(len(r1[0])))\n t_2010_160 = t_2010_160[r1[0]]\n t_2010_125 = t_2010_125[r1[1]]\n \n print('Matching 2010_160 and 2010_139')\n r2 = align.match(t_2010_160['x'], t_2010_160['y'], t_2010_160['m'],\n t_2010_139['x'], t_2010_139['y'], t_2010_139['m'] - 1.65,\n dr_tol=0.5, dm_tol=1.0)\n print(' found {0:d} matches'.format(len(r2[0])))\n t_2010_160 = t_2010_160[r2[0]]\n t_2010_125 = t_2010_125[r2[0]]\n t_2010_139 = t_2010_139[r2[1]]\n \n print('Matching 2010_160 and 2013_160')\n r3 = align.match(t_2010_160['x'], t_2010_160['y'], t_2010_160['m'],\n t_2013_160['x'], t_2013_160['y'], t_2013_160['m'],\n dr_tol=0.5, dm_tol=1.0)\n print(' found {0:d} matches'.format(len(r3[0])))\n t_2010_160 = t_2010_160[r3[0]]\n t_2010_125 = t_2010_125[r3[0]]\n t_2010_139 = t_2010_139[r3[0]]\n t_2013_160 = t_2013_160[r3[1]]\n\n print('Matching 2010_160 and 2013_160s')\n r4 = align.match(t_2010_160['x'], t_2010_160['y'], t_2010_160['m'],\n t_2013_160s['x'], t_2013_160s['y'], t_2013_160s['m'],\n dr_tol=0.5, dm_tol=1.0)\n print(' found {0:d} matches'.format(len(r4[0])))\n t_2010_160 = t_2010_160[r4[0]]\n t_2010_125 = t_2010_125[r4[0]]\n t_2010_139 = t_2010_139[r4[0]]\n t_2013_160 = t_2013_160[r4[0]]\n t_2013_160s = t_2013_160s[r4[1]]\n\n print('Matching 2010_160 and 2005_814')\n r5 = align.match(t_2010_160['x'], t_2010_160['y'], t_2010_160['m'],\n t_2005_814['x'], t_2005_814['y'], t_2005_814['m'] + 4.2,\n dr_tol=0.5, dm_tol=1.0)\n print(' found {0:d} matches'.format(len(r5[0])))\n t_2010_160 = t_2010_160[r5[0]]\n t_2010_125 = t_2010_125[r5[0]]\n t_2010_139 = t_2010_139[r5[0]]\n t_2013_160 = t_2013_160[r5[0]]\n t_2013_160s = t_2013_160s[r5[0]]\n t_2005_814 = t_2005_814[r5[1]]\n\n # Sort by brightness and print\n sdx = t_2010_160['m'].argsort()\n \n fmt = '{name:10s} {x:8.2f} {y:8.2f} '\n fmt += '{m160:5.1f} {m139:5.1f} {m125:5.1f} {m814:5.1f}'\n\n nameIdx = 1\n\n _out = open('wd1_named_stars.txt', 'w')\n for ii in sdx:\n name = 'wd1_{0:05d}'.format(nameIdx)\n print(fmt.format(name = name,\n x = t_2010_160['x'][ii],\n y = t_2010_160['y'][ii],\n m160 = t_2010_160['m'][ii],\n m139 = t_2010_139['m'][ii],\n m125 = t_2010_125['m'][ii],\n m814 = t_2005_814['m'][ii]))\n _out.write(fmt.format(name = name,\n x = t_2010_160['x'][ii],\n y = t_2010_160['y'][ii],\n m160 = t_2010_160['m'][ii],\n m139 = t_2010_139['m'][ii],\n m125 = t_2010_125['m'][ii],\n m814 = t_2005_814['m'][ii]))\n _out.write('\\n')\n \n nameIdx += 1\n\n _out.close()\n\n return\n\ndef combine_nimfo2bar_brite():\n \"\"\"\n For all the data, we need to add back in the missing bright stars\n from the one-pass analysis.\n \"\"\"\n epochs = ['2005_F814W', \n '2010_F125W_pos1', '2010_F125W_pos2', '2010_F125W_pos3', '2010_F125W_pos4',\n '2010_F139M_pos1', '2010_F139M_pos2', '2010_F139M_pos3', '2010_F139M_pos4',\n '2010_F160W_pos1', '2010_F160W_pos2', '2010_F160W_pos3', '2010_F160W_pos4',\n '2013_F160W_pos1', '2013_F160W_pos2', '2013_F160W_pos3', '2013_F160W_pos4',\n '2013_F160Ws']\n magCuts = [-13.5, \n -10, -10, -10, -10,\n -9, -9, -9, -9,\n -10, -10, -10, -10,\n -10, -10, -10, -10,\n -10, -10, -10, -10]\n \n \n for ee in range(len(epochs)):\n ep = epochs[ee]\n year = ep.split('_')[0]\n filt = ep.split('_')[1]\n\n mat_dir = work_dir + '03.MAT_POS/' + ep + '/01.XYM/'\n mat_file = 'MATCHUP.XYMEEE'\n ks2_dir = work_dir\n ks2_file = 'nimfo2bar.xymeee.F1'\n N_filter = 1\n if year == '2005':\n ks2_dir += '11.KS2_2005/'\n ks2_file = ks2_file.replace('.F1', '.ks2.F1')\n\n if year == '2010':\n ks2_dir += '12.KS2_2010/0{pos}.pos{pos}/'.format(pos=ep[-1])\n N_filter = 3\n if filt == 'F139M':\n ks2_file = ks2_file.replace('.F1', '.F2')\n if filt == 'F125W':\n ks2_file = ks2_file.replace('.F1', '.F3')\n\n if year == '2013':\n ks2_dir += '13.KS2_2013/'\n if ep.endswith('s'):\n ks2_dir += '05.F160Ws/'\n else:\n ks2_dir += '0{pos}.pos{pos}/'.format(pos=ep[-1])\n \n one = starlists.read_matchup(mat_dir + mat_file)\n ks2 = starlists.read_nimfo2bar(ks2_dir + ks2_file)\n\n if 'F160Ws' in ks2_dir:\n # In the short-exposure data, most sources only detected\n # in a single frame and has no errors. We still want them.\n idx = np.where(one['m'] <= magCuts[ee])[0]\n else:\n print('magCut = ', magCuts[ee], ' for ', ep)\n idx = np.where((one['m'] <= magCuts[ee]) & (one['me'] < 1))[0]\n\n # Trim down to just the brite sources in the MATCHUP\n one_brite = one[idx]\n\n # Get the last ks2 star name. \n last_name = int(ks2[-1]['name'])\n\n # Loop through each brite star and see if it \n # was detected in ks2.\n cnt_add = 0\n cnt_replace = 0\n\n for ii in range(len(one_brite)):\n dx = one_brite[ii]['x'] - ks2['x']\n dy = one_brite[ii]['y'] - ks2['y']\n dm = one_brite[ii]['m'] - ks2['m']\n dr = np.hypot(dx, dy)\n\n rdx = dr.argmin()\n\n dr_min = dr[rdx]\n dm_min = dm[rdx]\n\n # Decide whether to add or replace this star in KS2\n add = False\n replace = False\n\n # Star doesn't exist in KS2 - add it.\n if (dr_min > 1):\n add = True\n else:\n # There is a star, but it has a wildly different\n # magnitude. Replace it.\n if (dm_min > 1):\n replace = True\n\n # There is a star in KS2; but it doesn't have errors\n # and the one-pass analysis does. Replace it.\n if ((ks2[rdx]['xe'] == 1) and (one_brite[ii]['xe'] != 1)):\n replace = True\n \n\n\n if add:\n new_name = last_name + 1\n\n ks2.add_row([one_brite[ii]['x'], one_brite[ii]['y'],\n one_brite[ii]['m'], one_brite[ii]['xe'],\n one_brite[ii]['ye'], one_brite[ii]['me'],\n one_brite[ii]['N_fnd'], one_brite[ii]['N_xywell'],\n str(new_name).zfill(6)])\n last_name += 1\n\n cnt_add += 1\n\n if replace:\n ks2[rdx]['x'] = one_brite[ii]['x']\n ks2[rdx]['y'] = one_brite[ii]['y']\n ks2[rdx]['m'] = one_brite[ii]['m']\n ks2[rdx]['xe'] = one_brite[ii]['xe']\n ks2[rdx]['ye'] = one_brite[ii]['ye']\n ks2[rdx]['me'] = one_brite[ii]['me']\n ks2[rdx]['N_fnd'] = one_brite[ii]['N_fnd']\n ks2[rdx]['N_xywell'] = one_brite[ii]['N_xywell']\n\n cnt_replace += 1\n \n fmt = '{0:s}: Added {1:d}, replace {2:d} out of {3:d} brite stars'\n print(fmt.format(ks2_dir + ks2_file, cnt_add, cnt_replace, len(one_brite)))\n ks2.write(ks2_dir + ks2_file.replace('2bar', '2bar_brite'), \n format='ascii.fixed_width_no_header', delimiter=' ',\n formats={'x': '%10.4f', 'y': '%10.4f', 'm': '%10.3f', \n 'xe': '%10.4f', 'ye': '%10.4f', 'me': '%10.3f',\n 'N_find': '%3d', 'N_xywell': '%3d', 'name': lambda n: n.zfill(6)})\n\n \n return\n \ndef align_to_fits(align_root):\n \"\"\"\n Given starlist output from align, returns to MATCHUP format. Inputs are the\n align *.pos, *.err, *.mag, *.param, and *.name files. Will return 3 MATCHUP\n files, one for each epoch. Align run order:\n\n 2005_F814W, 2010_F125W, 2010_F139M, 2010_F160W, 2013_F160W, 2013_f160Ws\n\n \"\"\"\n s = starset.StarSet(work_dir + '50.ALIGN_KS2/' + align_root)\n\n name = s.getArray('name')\n\n # Setup the mapping between epoch, filter, pos and the align index.\n align_idx = {0: '2005_F814W',\n 1: '2010_F125W_pos1',\n 2: '2010_F125W_pos2',\n 3: '2010_F125W_pos3',\n 4: '2010_F125W_pos4',\n 5: '2010_F139M_pos1',\n 6: '2010_F139M_pos2',\n 7: '2010_F139M_pos3',\n 8: '2010_F139M_pos4',\n 9: '2010_F160W_pos1',\n 10: '2010_F160W_pos2',\n 11: '2010_F160W_pos3',\n 12: '2010_F160W_pos4',\n 13: '2013_F160W_pos1',\n 14: '2013_F160W_pos2',\n 15: '2013_F160W_pos3',\n 16: '2013_F160W_pos4',\n 17: '2013_F160Ws'}\n\n num_epochs = len(align_idx)\n\n # Construct a list of columns and column names\n columns = []\n col_names = []\n\n # For each epoch, add all the columns we want to keep.\n for ii in range(num_epochs):\n columns.append(s.getArrayFromEpoch(ii, 'xpix'))\n col_names.append('x_' + align_idx[ii])\n \n columns.append(s.getArrayFromEpoch(ii, 'ypix'))\n col_names.append('y_' + align_idx[ii])\n\n columns.append(s.getArrayFromEpoch(ii, 'mag'))\n col_names.append('m_' + align_idx[ii])\n\n columns.append(s.getArrayFromEpoch(ii, 'xpixerr_p'))\n col_names.append('xe_' + align_idx[ii])\n\n columns.append(s.getArrayFromEpoch(ii, 'ypixerr_p'))\n col_names.append('ye_' + align_idx[ii])\n\n columns.append(s.getArrayFromEpoch(ii, 'snr'))\n col_names.append('me_' + align_idx[ii])\n\n columns.append(s.getArrayFromEpoch(ii, 'nframes'))\n col_names.append('n_' + align_idx[ii])\n \n columns.append(s.getArrayFromEpoch(ii, 'xorig'))\n col_names.append('xorig_' + align_idx[ii])\n\n columns.append(s.getArrayFromEpoch(ii, 'yorig'))\n col_names.append('yorig_' + align_idx[ii])\n \n t = Table(columns, names=col_names)\n\n t.table_name = align_root\n t.write(work_dir + '50.ALIGN_KS2/' + align_root + '.fits', overwrite=True)\n\n return\n\ndef combine_mosaic_pos():\n t = Table.read(work_dir + '50.ALIGN_KS2/align_a4_t.fits')\n \n # First we need to combine all the positions of the mosaic together.\n mosaic_epochs = ['2010_F125W', '2010_F139M', '2010_F160W', '2013_F160W']\n pos = ['pos1', 'pos2', 'pos3', 'pos4']\n\n n_epochs = len(mosaic_epochs)\n n_stars = len(t)\n x_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n y_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n f_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n m_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n xe_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n ye_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n fe_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n me_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n wx_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n wy_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n wf_wavg = np.zeros((n_epochs, n_stars), dtype=float)\n nframes = np.zeros((n_epochs, n_stars), dtype=float)\n\n # Loop through each year+filter combination \n for ee in range(n_epochs):\n print('Working on: ' + mosaic_epochs[ee])\n \n for pp in range(len(pos)):\n suffix = '_' + mosaic_epochs[ee] + '_' + pos[pp]\n \n x = t['x' + suffix]\n y = t['y' + suffix]\n m = t['m' + suffix]\n xe = t['xe' + suffix]\n ye = t['ye' + suffix]\n me = t['me' + suffix]\n n = t['n' + suffix]\n \n # Identify the stars with detections in this list.\n det = np.where((x > -1e4) & (xe > 0) &\n (y > -1e4) & (ye > 0) &\n (m > 0) & (me > 0))[0]\n\n # Convert the magnitudes to fluxes\n f_det, fe_det = photo.mag2flux(m[det], me[det])\n \n # Calculate the weights\n w_x = 1.0 / xe[det]**2\n w_y = 1.0 / ye[det]**2\n # w_f = 1.0 / fe_det**2 - Too big... mags are good enough.\n w_f = 1.0 / me[det]**2\n\n # Adding to the weighted average calculation\n x_wavg[ee, det] += x[det] * w_x\n y_wavg[ee, det] += y[det] * w_y\n f_wavg[ee, det] += f_det * w_f\n fe_wavg[ee, det] += fe_det * w_f\n\n wx_wavg[ee, det] += w_x\n wy_wavg[ee, det] += w_y\n wf_wavg[ee, det] += w_f\n\n nframes[ee, det] += n[det]\n\n # Finished this epoch, finish the weighted average calculation\n x_wavg[ee, :] /= wx_wavg[ee, :]\n xe_wavg[ee, :] = (1.0 / wx_wavg[ee, :])**0.5\n \n y_wavg[ee, :] /= wy_wavg[ee, :]\n ye_wavg[ee, :] = (1.0 / wy_wavg[ee, :])**0.5\n \n f_wavg[ee, :] /= wf_wavg[ee, :]\n # fe_wavg[ee, :] = (1.0 / wf_wavg[ee, :])**0.5\n fe_wavg[ee, :] /= wf_wavg[ee, :] # Spe\n\n m_wavg[ee, :], me_wavg[ee, :] = photo.flux2mag(f_wavg[ee, :], fe_wavg[ee, :])\n\n # Add new columns to the table\n t.add_column(Column(x_wavg[ee, :], name='x_' + mosaic_epochs[ee]))\n t.add_column(Column(y_wavg[ee, :], name='y_' + mosaic_epochs[ee]))\n t.add_column(Column(m_wavg[ee, :], name='m_' + mosaic_epochs[ee]))\n\n t.add_column(Column(xe_wavg[ee, :], name='xe_' + mosaic_epochs[ee]))\n t.add_column(Column(ye_wavg[ee, :], name='ye_' + mosaic_epochs[ee]))\n t.add_column(Column(me_wavg[ee, :], name='me_' + mosaic_epochs[ee]))\n \n t.add_column(Column(nframes[ee, :], name='n_' + mosaic_epochs[ee]))\n\n \n # Table Clean Up:\n # Remove the position dependent columns from the table.\n for ee in range(n_epochs):\n for pp in range(len(pos)):\n suffix = '_' + mosaic_epochs[ee] + '_' + pos[pp]\n\n # Identify the stars with detections in this list.\n # Used for checking zeropoint offsets.\n x = t['x' + suffix]\n y = t['y' + suffix]\n m = t['m' + suffix]\n xe = t['xe' + suffix]\n ye = t['ye' + suffix]\n me = t['me' + suffix]\n n = t['n' + suffix]\n \n det = np.where((x > -1e4) & (xe > 0) &\n (y > -1e4) & (ye > 0) &\n (m > 0) & (me > 0))[0]\n\n dx = x[det] - t['x_' + mosaic_epochs[ee]][det]\n dy = y[det] - t['y_' + mosaic_epochs[ee]][det]\n dm = m[det] - t['m_' + mosaic_epochs[ee]][det]\n\n print('Stats for: ' + mosaic_epochs[ee] + ' ' + pos[pp])\n print(' dx = {0:7.3f} +/- {1:7.3f}'.format(dx.mean(), dx.std()))\n print(' dy = {0:7.3f} +/- {1:7.3f}'.format(dy.mean(), dy.std()))\n print(' dm = {0:7.3f} +/- {1:7.3f}'.format(dm.mean(), dm.std()))\n \n t.remove_column('x' + suffix)\n t.remove_column('y' + suffix)\n t.remove_column('m' + suffix)\n t.remove_column('xe' + suffix)\n t.remove_column('ye' + suffix)\n t.remove_column('me' + suffix)\n t.remove_column('n' + suffix)\n t.remove_column('xorig' + suffix)\n t.remove_column('yorig' + suffix)\n\n # Remove the xorig and yorig for the other epochs\n t.remove_column('xorig_2005_F814W')\n t.remove_column('yorig_2005_F814W')\n t.remove_column('xorig_2013_F160Ws')\n t.remove_column('yorig_2013_F160Ws')\n\n t.write(work_dir + '50.ALIGN_KS2/align_a4_t_combo_pos.fits',\n format='fits', overwrite=True)\n\n \ndef make_catalog(use_RMSE=True, vel_weight=None):\n \"\"\"\n Read the align FITS table from all three epochs and fit a velocity to the\n positions.\n\n use_RMSE - If True, use RMS error (standard deviation) for the positional error.\n If False, convert the positional errors in \"error on the mean\" and\n save to a different catalog name.\n vel_weight - None, 'error', 'variance'\n None = no weighting by errors in the velocity fit.\n 'error' = Weight by 1.0 / positional error in the velocity fit.\n 'variance' = Weight by 1.0 / (positional error)^2 in the velocity fit. \n \"\"\"\n \n final = None\n good = None\n\n d_all = Table.read(work_dir + '50.ALIGN_KS2/align_a4_t_combo_pos.fits')\n\n # TRIM out all stars that aren't detected in all 3 epochs:\n # 2005_814\n # 2010_160\n # 2013_160\n idx = np.where((d_all['x_2005_F814W'] > -999) &\n (d_all['x_2010_F160W'] > -999) &\n (d_all['x_2013_F160W'] > -999) &\n (d_all['n_2005_F814W'] > 1) &\n (d_all['n_2010_F160W'] > 1) &\n (d_all['n_2013_F160W'] > 1) &\n (d_all['xe_2005_F814W'] > 0) &\n (d_all['xe_2010_F160W'] > 0) &\n (d_all['xe_2013_F160W'] > 0) &\n (d_all['ye_2005_F814W'] > 0) &\n (d_all['ye_2010_F160W'] > 0) &\n (d_all['ye_2013_F160W'] > 0))[0]\n\n tmp_2005 = np.where((d_all['x_2005_F814W'] > -999) &\n (d_all['n_2005_F814W'] > 1) &\n (d_all['xe_2005_F814W'] > 0) &\n (d_all['ye_2005_F814W'] > 0))[0]\n tmp_2010 = np.where((d_all['x_2010_F160W'] > -999) &\n (d_all['n_2010_F160W'] > 1) &\n (d_all['xe_2010_F160W'] > 0) &\n (d_all['ye_2010_F160W'] > 0))[0]\n tmp_2013 = np.where((d_all['x_2013_F160W'] > -999) &\n (d_all['n_2013_F160W'] > 1) &\n (d_all['xe_2013_F160W'] > 0) &\n (d_all['ye_2013_F160W'] > 0))[0]\n print('Found {0:3} in 2005 F814W'.format(len(tmp_2005)))\n print('Found {0:3} in 2010 F160W'.format(len(tmp_2010)))\n print('Found {0:3} in 2013 F160W'.format(len(tmp_2013)))\n print('')\n print('Kept {0:d} of {1:d} stars in all 3 epochs.'.format(len(idx), len(d_all)))\n \n d = d_all[idx]\n \n #Changing rms errors into standard errors for the f153m data\n xeom_2005_814 = d['xe_2005_F814W'] / np.sqrt(d['n_2005_F814W'])\n yeom_2005_814 = d['ye_2005_F814W'] / np.sqrt(d['n_2005_F814W'])\n xeom_2010_160 = d['xe_2010_F160W'] / np.sqrt(d['n_2010_F160W'])\n yeom_2010_160 = d['ye_2010_F160W'] / np.sqrt(d['n_2010_F160W'])\n xeom_2013_160 = d['xe_2013_F160W'] / np.sqrt(d['n_2013_F160W'])\n yeom_2013_160 = d['ye_2013_F160W'] / np.sqrt(d['n_2013_F160W'])\n \n # Fit velocities. Will use an error-weighted t0, specified to each object\n t = np.array([years['2005_F814W'], years['2010_F160W'], years['2013_F160W']])\n\n if use_RMSE:\n # Shape = (nepochs, nstars)\n xerr = np.array([d['xe_2005_F814W'], d['xe_2010_F160W'], d['xe_2013_F160W']])\n yerr = np.array([d['ye_2005_F814W'], d['ye_2010_F160W'], d['ye_2013_F160W']])\n else:\n xerr = np.array([xeom_2005_814, xeom_2010_160, xeom_2013_160])\n yerr = np.array([yeom_2005_814, yeom_2010_160, yeom_2013_160])\n\n w = 1.0 / (xerr**2 + yerr**2)\n w = np.transpose(w) #Getting the dimensions of w right\n numerator = np.sum(t * w, axis = 1)\n denominator = np.sum(w, axis = 1)\n t0_arr = numerator / denominator\n\n nstars = len(d)\n nepochs = len(t)\n \n # 2D arrays Shape = (nepochs, nstars)\n t = np.tile(t, (nstars, 1)).T\n t0 = np.tile(t0_arr, (nepochs, 1))\n\n #Calculating dt for each object\n dt = t - t0\n\n d.add_column(Column(data=t[0],name='t_2005_F814W'))\n d.add_column(Column(data=t[1],name='t_2010_F160W'))\n d.add_column(Column(data=t[2],name='t_2013_F160W'))\n d.add_column(Column(data=t0[0],name='fit_t0'))\n\n d.add_column(Column(data=np.ones(nstars),name='fit_x0'))\n d.add_column(Column(data=np.ones(nstars),name='fit_vx'))\n d.add_column(Column(data=np.ones(nstars),name='fit_y0'))\n d.add_column(Column(data=np.ones(nstars),name='fit_vy'))\n\n d.add_column(Column(data=np.ones(nstars),name='fit_x0e'))\n d.add_column(Column(data=np.ones(nstars),name='fit_vxe'))\n d.add_column(Column(data=np.ones(nstars),name='fit_y0e'))\n d.add_column(Column(data=np.ones(nstars),name='fit_vye'))\n\n for ii in range(len(d)):\n x = np.array([d['x_2005_F814W'][ii], d['x_2010_F160W'][ii], d['x_2013_F160W'][ii]])\n y = np.array([d['y_2005_F814W'][ii], d['y_2010_F160W'][ii], d['y_2013_F160W'][ii]])\n xe = xerr[:, ii]\n ye = yerr[:, ii]\n\n if (vel_weight != 'error') and (vel_weight != 'variance'):\n vxOpt, vxCov = np.polyfit(dt[:, ii], x, 1, cov=True)\n vyOpt, vyCov = np.polyfit(dt[:, ii], y, 1, cov=True)\n if vel_weight == 'error':\n vxOpt, vxCov = np.polyfit(dt[:, ii], x, 1, w=1/xe, cov=True)\n vyOpt, vyCov = np.polyfit(dt[:, ii], y, 1, w=1/ye, cov=True)\n if vel_weight == 'variance':\n vxOpt, vxCov = np.polyfit(dt[:, ii], x, 1, w=1/xe**2, cov=True)\n vyOpt, vyCov = np.polyfit(dt[:, ii], y, 1, w=1/ye**2, cov=True)\n \n vxErr = np.sqrt(-1.0 * vxCov.diagonal())\n vyErr = np.sqrt(-1.0 * vyCov.diagonal())\n\n d['fit_x0'][ii] = vxOpt[1]\n d['fit_vx'][ii] = vxOpt[0]\n d['fit_x0e'][ii] = vxErr[1]\n d['fit_vxe'][ii] = vxErr[0]\n\n d['fit_y0'][ii] = vyOpt[1]\n d['fit_vy'][ii] = vyOpt[0]\n d['fit_y0e'][ii] = vyErr[1]\n d['fit_vye'][ii] = vyErr[0]\n\n\n # Fix the F814W magnitudes (adjust for integration time)\n fix_magnitudes(d)\n \n catalog_name = 'wd1_catalog'\n if use_RMSE:\n catalog_name += '_RMSE'\n else:\n catalog_name += '_EOM'\n\n if vel_weight == None:\n catalog_name += '_wvelNone'\n else:\n if vel_weight == 'error':\n catalog_name += '_wvelErr'\n if vel_weight == 'variance':\n catalog_name += '_wvelVar'\n catalog_name += '.fits'\n\n d.write(work_dir + '50.ALIGN_KS2/' + catalog_name, format='fits', overwrite=True)\n \n return\n\ndef art_set_detected(use_obs_align=False):\n \"\"\"\n Create the \"detected\" columsn in the artificial star list.\n \n Apply a set of criteria to call a star detected based on on how\n closely the input and output position/flux match.\n \"\"\"\n in_file = work_dir + '51.ALIGN_ART/art_align'\n if use_obs_align:\n in_file += '_obs'\n else:\n in_file += '_art'\n in_file += '_combo_pos.fits'\n \n d = Table.read(in_file)\n\n # Make a \"detected\" column for each epoch/filter.\n # Set detected = True for all sources that are detected and whose\n # positions/fluxes match within certain criteria. These are loose criteria.\n epochs = ['2005_F814W', '2010_F125W', '2010_F139M', '2010_F160W', '2013_F160W']\n dr_cuts = [1.0, 0.5, 0.5, 0.5, 0.5] # pixels\n dm_cuts = [0.5, 0.5, 0.5, 0.5, 0.5] # magnitudes\n n_cut = 1\n\n for ee in range(len(epochs)):\n epoch = epochs[ee]\n det = np.zeros(len(d), dtype=bool)\n\n n = d['n_' + epoch]\n dx = d['x_' + epoch] - d['xin_' + epoch]\n dy = d['y_' + epoch] - d['yin_' + epoch]\n dm = d['m_' + epoch] - d['min_' + epoch]\n dr = np.hypot(dx, dy)\n\n idx = np.where((n > n_cut) & (dr < dr_cuts[ee]) & (dm < dm_cuts[ee]))\n det[idx] = True\n\n # Add this column to the table.\n d.add_column(Column(det, name='det_' + epoch))\n\n catalog_name = work_dir + '51.ALIGN_ART/art_align' \n if use_obs_align:\n catalog_name += '_obs'\n else:\n catalog_name += '_art'\n catalog_name += '_combo_pos_det.fits'\n d.write(catalog_name, format='fits', overwrite=True)\n\n return\n \ndef fix_artstar_errors(use_obs_align=False):\n \"\"\"\n Little snippet of code to compare the artificial star errors with the\n observed star errors to determine if a constant offset exists between\n the two. Reports the value of that offset.\n\n Specialized to work with Wd1 data (filter sets, etc)\n\n art_obs mags assumed to be instrumental\n \"\"\"\n real_obs = work_dir + '50.ALIGN_KS2/align_a4_t_combo_pos.fits'\n art_obs = work_dir + '51.ALIGN_ART/art_align'\n if use_obs_align:\n art_obs += '_obs'\n else:\n art_obs += '_art'\n art_obs += '_combo_pos_det.fits'\n binsize = 0.5\n \n\n # Read the catalogs, create new artificial star lists for\n # each filter/epoch only containing the recovered stars\n print('Reading input')\n obs = Table.read(real_obs, format='fits')\n art = Table.read(art_obs, format='fits')\n print('Done')\n\n # Fix F814W mag in observed data temporariliy\n fix_magnitudes(obs)\n \n epochs = ['2005_F814W', '2010_F125W', '2010_F139M', '2010_F160W', '2013_F160W']\n\n def mean_clip(vals):\n val_mean, val_std, n = statsIter.mean_std_clip(vals,\n clipsig=3.0,\n maxiter=10,\n converge_num=0.01,\n verbose=False,\n return_nclip=True)\n return val_mean\n\n def plot_pos_errors(epoch, obs_mag, obs_err, art_mag, art_err, mag_cent,\n obs_pos_err_mean, art_pos_err_mean, suffix=''):\n \n py.figure(1, figsize = (10,10))\n py.clf()\n py.semilogy(art_mag, art_err, 'k.', ms=4, label='Artificial', alpha=0.2)\n py.semilogy(obs_mag, obs_err, 'r.', ms=4, label='Observed', alpha=0.5)\n py.plot(mag_cent, obs_pos_err_mean, 'b-', linewidth=2,\n label='Observed Median')\n py.plot(mag_cent, art_pos_err_mean, 'g-', linewidth=2,\n label='Artificial Median')\n py.xlabel('Observed Mag')\n py.ylabel('Positional Error (pix)')\n py.title('Positional Errors,' + epoch)\n py.legend(loc=2, numpoints=1)\n py.xlim(13, max(art_mag))\n py.ylim(1e-4, 1)\n plot_file = work_dir + 'plots/Pos_errcomp' + suffix + '_' + epoch\n if use_obs_align:\n plot_file += '_obs'\n else:\n plot_file += '_art'\n plot_file += '.png'\n py.savefig(plot_file)\n\n return\n\n def plot_mag_errors(epoch, obs_mag, obs_err, art_mag, art_err, mag_cent,\n obs_mag_err_mean, art_mag_err_mean, suffix=''):\n \n py.figure(2, figsize=(10,10))\n py.clf()\n py.semilogy(art_mag, art_merr, 'k.', ms=4, label='Artificial', alpha=0.2)\n py.semilogy(obs_mag, obs_merr, 'r.', ms=4, label='Observed', alpha=0.5)\n py.plot(mag_cent, obs_mag_err_mean, 'b-', linewidth=2,\n label='Observed Median')\n py.plot(mag_cent, art_mag_err_mean, 'g-', linewidth=2,\n label='Artificial Median')\n py.xlabel('Observed Mag')\n py.ylabel('Photometric Error (mag)')\n py.title('Photometric Errors,' + epoch)\n py.legend(loc=2, numpoints=1)\n py.xlim(13, max(art_mag))\n py.ylim(1e-4, 1)\n plot_file = work_dir + 'plots/Mag_errcomp' + suffix + '_' + epoch\n if use_obs_align:\n plot_file += '_obs'\n else:\n plot_file += '_art'\n plot_file += '.png'\n py.savefig(plot_file)\n\n return\n \n for epoch in epochs:\n # Convert art star mags from instrumental to apparent\n filt = epoch.split('_')[-1]\n art['m_' + epoch] += photometry.ZP[filt]\n art['min_' + epoch] += photometry.ZP[filt]\n\n det = np.where(art['det_' + epoch] == True)\n \n # Extract observed/artificial errors for each filter.\n # X and Y errors are added in quadrature.\n obs_err = np.hypot(obs['xe_' + epoch], obs['ye_' + epoch])\n obs_mag = obs['m_' + epoch]\n obs_merr = obs['me_' + epoch]\n\n art_err = np.hypot(art['xe_' + epoch], art['ye_' + epoch])\n art_mag = art['m_' + epoch]\n art_merr = art['me_' + epoch]\n\n art_err = art_err[det]\n art_mag = art_mag[det]\n art_merr = art_merr[det]\n\n # For each epoch/filter, calculate the median position and\n # magnitude error in each magbin for both observed and artificial.\n mag_bins = np.arange(min(art_mag), max(art_mag) + binsize, binsize)\n mag_cent = mag_bins[:-1] + (np.diff(mag_bins) / 2.0)\n\n obs_pos_err_mean, f1, f2 = binned_statistic(obs_mag, obs_err,\n bins=mag_bins,\n statistic=mean_clip)\n obs_mag_err_mean, f1, f2 = binned_statistic(obs_mag, obs_merr,\n bins=mag_bins,\n statistic=mean_clip)\n art_pos_err_mean, f1, f2 = binned_statistic(art_mag, art_err,\n bins=mag_bins,\n statistic=mean_clip)\n art_mag_err_mean, f1, f2 = binned_statistic(art_mag, art_merr,\n bins=mag_bins,\n statistic=mean_clip)\n\n plot_pos_errors(epoch, obs_mag, obs_err, art_mag, art_err, mag_cent,\n obs_pos_err_mean, art_pos_err_mean, suffix='_orig')\n plot_mag_errors(epoch, obs_mag, obs_err, art_mag, art_err, mag_cent,\n obs_mag_err_mean, art_mag_err_mean, suffix='_orig')\n\n \n # Now, calculate error floor of observations, add in quadrature to artificial errors\n # For WFC3IR, we are in the error floor for everything brighter than 16th mag\n # For ACS, we are in error floor for evertything brighter than 14th mag\n\n if epoch == '2005_F814W':\n brite_obs = np.where((obs_mag > 10) & (obs_mag < 21))[0]\n brite_art = np.where((art_mag > 10) & (art_mag < 21))[0]\n else:\n brite_obs = np.where((obs_mag > 0) & (obs_mag < 16))[0]\n brite_art = np.where((art_mag > 0) & (art_mag < 16))[0]\n \n # Take the median error for all the bright bins.\n perr_obs = np.median(obs_err[brite_obs])\n merr_obs = np.median(obs_merr[brite_obs])\n perr_art = np.median(art_err[brite_art])\n merr_art = np.median(art_merr[brite_art])\n\n # Calculate the final \"floor\" errors that will get\n # added in quadrature.\n pos_err = 0.0\n mag_err = 0.0\n pos_err_1d = 0.0\n if perr_obs > perr_art:\n pos_err = np.sqrt(perr_obs**2 - perr_art**2)\n pos_err_1d = pos_err / np.sqrt(2.0)\n if merr_obs > merr_art:\n mag_err = np.sqrt(merr_obs**2 - merr_art**2)\n\n print('**********************************')\n fmt = 'The {0:s} error floor of {1:s} is {2:5.4f} {3:s} vs. obs of {4:5.4f} {3:s}'\n print(fmt.format('1D positional', epoch, pos_err_1d, '(pix)', perr_obs))\n print(fmt.format(' photometric', epoch, mag_err, '(mag)', merr_obs))\n print('**********************************')\n\n # Adding error floors in quadrature to artificial errors\n art_err = np.hypot(art_err, pos_err)\n art_merr = np.hypot(art_merr, mag_err)\n \n # Recalculate median pos and mag errors for the artificial stars\n art_pos_err_mean, f1, f2 = binned_statistic(art_mag, art_err,\n bins=mag_bins,\n statistic=mean_clip)\n art_mag_err_mean, f1, f2 = binned_statistic(art_mag, art_merr,\n bins=mag_bins,\n statistic=mean_clip)\n \n plot_pos_errors(epoch, obs_mag, obs_err, art_mag, art_err, mag_cent,\n obs_pos_err_mean, art_pos_err_mean, suffix='_corr')\n plot_mag_errors(epoch, obs_mag, obs_err, art_mag, art_err, mag_cent,\n obs_mag_err_mean, art_mag_err_mean, suffix='_corr')\n\n # Update the original artificial star table with the error floors,\n # write new table. Only update errors for stars detected in that\n # particular filter.\n art['me_' + epoch][det] = art_merr\n\n # Will split pos error floor evenly among X,Y\n art['xe_' + epoch][det] = np.hypot(art['xe_' + epoch][det], pos_err_1d)\n art['ye_' + epoch][det] = np.hypot(art['ye_' + epoch][det], pos_err_1d)\n\n # Find any detected stars with zero errors. Set them to 0.1 * obs floor.\n det_zero_merr = np.where(art['me_' + epoch][det] == 0)[0]\n det_zero_xerr = np.where(art['xe_' + epoch][det] == 0)[0]\n det_zero_yerr = np.where(art['ye_' + epoch][det] == 0)[0]\n art['me_' + epoch][det][det_zero_merr] = 0.1 * merr_obs\n art['xe_' + epoch][det][det_zero_xerr] = 0.1 * perr_obs\n art['ye_' + epoch][det][det_zero_yerr] = 0.1 * perr_obs\n\n \n out_file = work_dir + '51.ALIGN_ART/art_align'\n if use_obs_align:\n out_file += '_obs'\n else:\n out_file += '_art'\n out_file += '_combo_pos_det_newerr.fits'\n art.write(out_file, format='fits', overwrite=True)\n\n return\n\n\ndef make_artificial_catalog(use_RMSE=True, vel_weight=None, use_obs_align=False):\n \"\"\"\n Read the align FITS table from the artificial star catalog and fit a\n velocity to the positions.\n\n use_RMSE - If True, use RMS error (standard deviation) for the positional error.\n If False, convert the positional errors in \"error on the mean\" and\n save to a different catalog name.\n vel_weight - None, 'error', 'variance'\n None = no weighting by errors in the velocity fit.\n 'error' = Weight by 1.0 / positional error in the velocity fit.\n 'variance' = Weight by 1.0 / (positional error)^2 in the velocity fit. \n \"\"\"\n \n final = None\n good = None\n\n in_file = work_dir + '51.ALIGN_ART/art_align'\n if use_obs_align:\n in_file += '_obs'\n else:\n in_file += '_art'\n in_file += '_combo_pos_det_newerr.fits'\n \n d = Table.read(in_file)\n \n # Fetch all stars that are in all 3 epochs.\n # 2005_814\n # 2010_160\n # 2013_160\n idx = np.where((d['det_2005_F814W'] == True) &\n (d['det_2010_F160W'] == True) &\n (d['det_2013_F160W'] == True))[0]\n \n print('Found {0:d} of {1:d} stars in all 3 epochs.'.format(len(idx), len(d)))\n \n # Changing rms errors into standard errors for the f153m data\n xeom_2005_814 = d['xe_2005_F814W'][idx] / np.sqrt(d['n_2005_F814W'][idx])\n yeom_2005_814 = d['ye_2005_F814W'][idx] / np.sqrt(d['n_2005_F814W'][idx])\n xeom_2010_160 = d['xe_2010_F160W'][idx] / np.sqrt(d['n_2010_F160W'][idx])\n yeom_2010_160 = d['ye_2010_F160W'][idx] / np.sqrt(d['n_2010_F160W'][idx])\n xeom_2013_160 = d['xe_2013_F160W'][idx] / np.sqrt(d['n_2013_F160W'][idx])\n yeom_2013_160 = d['ye_2013_F160W'][idx] / np.sqrt(d['n_2013_F160W'][idx])\n \n # Fit velocities. Will use an error-weighted t0, specified to each object\n t = np.array([years['2005_F814W'], years['2010_F160W'], years['2013_F160W']])\n\n if use_RMSE:\n # Shape = (nepochs, nstars)\n xerr = np.array([d['xe_2005_F814W'][idx],\n d['xe_2010_F160W'][idx],\n d['xe_2013_F160W'][idx]])\n yerr = np.array([d['ye_2005_F814W'][idx],\n d['ye_2010_F160W'][idx],\n d['ye_2013_F160W'][idx]])\n else:\n xerr = np.array([xeom_2005_814**2, xeom_2010_160**2, xeom_2013_160**2])\n yerr = np.array([yeom_2005_814**2, yeom_2010_160**2, yeom_2013_160**2])\n\n w = 1.0 / (xerr**2 + yerr**2)\n w = np.transpose(w) #Getting the dimensions of w right\n numerator = np.sum(t * w, axis = 1)\n denominator = np.sum(w, axis = 1)\n\n nstars = len(d)\n nepochs = len(t)\n \n t0_arr = np.zeros(nstars, dtype=float)\n t0_arr[idx] = numerator / denominator\n \n # 2D arrays Shape = (nepochs, nstars)\n t = np.tile(t, (nstars, 1)).T\n t0 = np.tile(t0_arr, (nepochs, 1))\n\n #Calculating dt for each object\n dt = t - t0\n \n d.add_column(Column(data=t[0], name='t_2005_F814W'))\n d.add_column(Column(data=t[1], name='t_2010_F160W'))\n d.add_column(Column(data=t[2], name='t_2013_F160W'))\n d.add_column(Column(data=t0[0], name='fit_t0'))\n\n d.add_column(Column(data=np.ones(nstars), name='fit_x0'))\n d.add_column(Column(data=np.ones(nstars), name='fit_vx'))\n d.add_column(Column(data=np.ones(nstars), name='fit_y0'))\n d.add_column(Column(data=np.ones(nstars), name='fit_vy'))\n\n d.add_column(Column(data=np.ones(nstars), name='fit_x0e'))\n d.add_column(Column(data=np.ones(nstars), name='fit_vxe'))\n d.add_column(Column(data=np.ones(nstars), name='fit_y0e'))\n d.add_column(Column(data=np.ones(nstars), name='fit_vye'))\n\n for i_idx in range(len(idx)):\n # Note i_idx is the index into the \"idx\" array.\n # Note ii is the index into the original table arrays.\n ii = idx[i_idx]\n\n if (ii % 1e4) == 0:\n print('Working on ', i_idx, ii)\n x = np.array([d['x_2005_F814W'][ii], d['x_2010_F160W'][ii], d['x_2013_F160W'][ii]])\n y = np.array([d['y_2005_F814W'][ii], d['y_2010_F160W'][ii], d['y_2013_F160W'][ii]])\n xe = xerr[:, i_idx]\n ye = yerr[:, i_idx]\n\n if (vel_weight != 'error') and (vel_weight != 'variance'):\n vxOpt, vxCov = np.polyfit(dt[:, ii], x, 1, cov=True)\n vyOpt, vyCov = np.polyfit(dt[:, ii], y, 1, cov=True)\n if vel_weight == 'error':\n vxOpt, vxCov = np.polyfit(dt[:, ii], x, 1, w=1/xe, cov=True)\n vyOpt, vyCov = np.polyfit(dt[:, ii], y, 1, w=1/ye, cov=True)\n if vel_weight == 'variance':\n vxOpt, vxCov = np.polyfit(dt[:, ii], x, 1, w=1/xe**2, cov=True)\n vyOpt, vyCov = np.polyfit(dt[:, ii], y, 1, w=1/ye**2, cov=True)\n\n # if (ii == 35391):\n # pdb.set_trace()\n \n vxErr = np.sqrt(-1.0 * vxCov.diagonal())\n vyErr = np.sqrt(-1.0 * vyCov.diagonal())\n\n d['fit_x0'][ii] = vxOpt[1]\n d['fit_vx'][ii] = vxOpt[0]\n d['fit_x0e'][ii] = vxErr[1]\n d['fit_vxe'][ii] = vxErr[0]\n\n d['fit_y0'][ii] = vyOpt[1]\n d['fit_vy'][ii] = vyOpt[0]\n d['fit_y0e'][ii] = vyErr[1]\n d['fit_vye'][ii] = vyErr[0]\n\n catalog_name = work_dir + '51.ALIGN_ART/wd1_art_catalog'\n if use_RMSE:\n catalog_name += '_RMSE'\n else:\n catalog_name += '_EOM'\n\n if vel_weight == None:\n catalog_name += '_wvelNone'\n else:\n if vel_weight == 'error':\n catalog_name += '_wvelErr'\n if vel_weight == 'variance':\n catalog_name += '_wvelVar'\n \n if use_obs_align:\n catalog_name += '_aln_obs'\n else:\n catalog_name += '_aln_art'\n \n catalog_name += '.fits'\n\n d.write(catalog_name, format='fits', overwrite=True)\n \n return\n\n\ndef plot_vpd(use_RMSE=False, vel_weight=None):\n \"\"\"\n Check the VPD and quiver plots for our KS2-extracted, re-transformed astrometry.\n \"\"\"\n catalog_name = 'wd1_catalog'\n catalog_suffix = ''\n if use_RMSE:\n catalog_suffix += '_RMSE'\n else:\n catalog_suffix += '_EOM'\n\n if vel_weight == None:\n catalog_suffix += '_wvelNone'\n else:\n if vel_weight == 'error':\n catalog_suffix += '_wvelErr'\n if vel_weight == 'variance':\n catalog_suffix += '_wvelVar'\n catalog_name += catalog_suffix + '.fits'\n \n catFile = work_dir + '50.ALIGN_KS2/' + catalog_name\n tab = Table.read(catFile)\n\n good = (tab['fit_vxe'] < 0.01) & (tab['fit_vye'] < 0.01) & \\\n (tab['me_2005_F814W'] < 0.1) & (tab['me_2010_F160W'] < 0.1)\n\n tab2 = tab[good]\n\n vx = tab2['fit_vx'] * ast.scale['WFC'] * 1e3\n vy = tab2['fit_vy'] * ast.scale['WFC'] * 1e3\n\n py.figure(1)\n py.clf()\n q = py.quiver(tab2['x_2005_F814W'], tab2['y_2005_F814W'], vx, vy, scale=1e2)\n py.quiverkey(q, 0.95, 0.85, 5, '5 mas/yr', color='red', labelcolor='red')\n py.savefig(work_dir + '50.ALIGN_KS2/plots/vec_diffs' + catalog_suffix + '.png')\n\n py.close(3)\n py.figure(3, figsize=(8,6))\n py.clf()\n nz = mcolors.Normalize()\n nz.autoscale(tab2['m_2005_F814W'])\n q = py.quiver(tab2['x_2005_F814W'], tab2['y_2005_F814W'], vx, vy, scale=1e2,\n color=py.cm.gist_stern(nz(tab2['m_2005_F814W'])))\n py.quiverkey(q, 0.95, 0.85, 5, '5 mas/yr', color='black', labelcolor='black')\n py.axis('equal')\n cax, foo = colorbar.make_axes(py.gca(), orientation='vertical', fraction=0.2, pad=0.04)\n cb = colorbar.ColorbarBase(cax, cmap=py.cm.gist_stern, norm=nz,\n orientation='vertical')\n cb.set_label('F814W')\n py.savefig(work_dir + '50.ALIGN_KS2/plots/vec_diffs_color' + catalog_suffix + '.png')\n\n \n py.figure(2)\n py.clf()\n py.plot(vx, vy, 'k.', ms=2)\n lim = 5\n py.axis([-lim, lim, -lim, lim])\n py.xlabel('X Proper Motion (mas/yr)')\n py.ylabel('Y Proper Motion (mas/yr)')\n py.savefig(work_dir + '50.ALIGN_KS2/plots/vpd' + catalog_suffix + '.png')\n\n py.figure(3)\n py.clf()\n nz = mcolors.Normalize()\n nz.autoscale(tab2['m_2005_F814W'])\n py.scatter(vx, vy, c=nz(tab2['m_2005_F814W']), s=5, edgecolor='',\n cmap=py.cm.gist_stern)\n py.xlabel('X Proper Motion (mas/yr)')\n py.ylabel('Y Proper Motion (mas/yr)')\n py.axis('equal')\n lim = 3.5\n py.axis([-lim, lim, -lim, lim])\n \n cax, foo = colorbar.make_axes(py.gca(), orientation='vertical', fraction=0.2, pad=0.04)\n cb = colorbar.ColorbarBase(cax, cmap=py.cm.gist_stern, norm=nz,\n orientation='vertical')\n cb.set_label('F814W')\n py.savefig(work_dir + '50.ALIGN_KS2/plots/vpd_color' + catalog_suffix + '.png')\n \n\n idx = np.where((np.abs(vx) < 3) & (np.abs(vy) < 3))[0]\n print('Cluster Members (within vx < 10 mas/yr and vy < 10 mas/yr)')\n print((' vx = {vx:6.2f} +/- {vxe:6.2f} mas/yr'.format(vx=vx[idx].mean(),\n vxe=vx[idx].std())))\n print((' vy = {vy:6.2f} +/- {vye:6.2f} mas/yr'.format(vy=vy[idx].mean(),\n vye=vy[idx].std())))\n \n return\n\ndef setup_artstar_info():\n comp_dirs = {'21.KS2_2005_ART': ['01.ks2', '02.ks2', '03.ks2',\n '04.ks2', '05.ks2', '06.ks2', '07.ks2',\n '08.ks2', '09.ks2', '10.ks2',\n '11.ks2', '12.ks2', '13.ks2', '14.ks2'],\n '22.KS2_2010_ART': ['01.pos1_a', '01.pos1_b', '01.pos1_c',\n '02.pos2_a', '02.pos2_b', '02.pos2_c',\n '03.pos3_a', '03.pos3_b', '03.pos3_c',\n '04.pos4_a', '04.pos4_b', '04.pos4_c',\n '01.pos1_d', '01.pos1_e', '01.pos1_f', \n '02.pos2_d', '02.pos2_e', '02.pos2_f', \n '03.pos3_d', '03.pos3_e', '03.pos3_f', \n '04.pos4_d', '04.pos4_e', '04.pos4_f'],\n '23.KS2_2013_ART': ['01.pos1_a', '01.pos1_b', '01.pos1_c',\n '02.pos2_a', '02.pos2_b', '02.pos2_c',\n '03.pos3_a', '03.pos3_b', '03.pos3_c',\n '04.pos4_a', '04.pos4_b', '04.pos4_c',\n '01.pos1_d', '01.pos1_e', '01.pos1_f',\n '02.pos2_d', '02.pos2_e', '02.pos2_f',\n '03.pos3_d', '03.pos3_e', '03.pos3_f',\n '04.pos4_d', '04.pos4_e', '04.pos4_f']}\n art_lists = {'21.KS2_2005_ART': ['Artstarlist_2005_1.txt',\n 'Artstarlist_2005_2.txt',\n 'Artstarlist_2005_3.txt',\n 'Artstarlist_2005_4.txt',\n 'Artstarlist_2005_5.txt',\n 'Artstarlist_2005_6.txt',\n 'Artstarlist_2005_7.txt',\n 'Artstarlist_2005_8.txt',\n 'Artstarlist_2005_9.txt',\n 'Artstarlist_2005_10.txt',\n 'Artstarlist_2005_11.txt',\n 'Artstarlist_2005_12.txt',\n 'Artstarlist_2005_13.txt',\n 'Artstarlist_2005_14.txt'],\n '22.KS2_2010_ART': ['Artstarlist_2010_pos1_a.txt',\n 'Artstarlist_2010_pos1_b.txt',\n 'Artstarlist_2010_pos1_c.txt',\n 'Artstarlist_2010_pos2_a.txt',\n 'Artstarlist_2010_pos2_b.txt',\n 'Artstarlist_2010_pos2_c.txt',\n 'Artstarlist_2010_pos3_a.txt',\n 'Artstarlist_2010_pos3_b.txt',\n 'Artstarlist_2010_pos3_c.txt',\n 'Artstarlist_2010_pos4_a.txt',\n 'Artstarlist_2010_pos4_b.txt',\n 'Artstarlist_2010_pos4_c.txt',\n 'Artstarlist_2010_pos1_d.txt',\n 'Artstarlist_2010_pos1_e.txt',\n 'Artstarlist_2010_pos1_f.txt',\n 'Artstarlist_2010_pos2_d.txt',\n 'Artstarlist_2010_pos2_e.txt',\n 'Artstarlist_2010_pos2_f.txt',\n 'Artstarlist_2010_pos3_d.txt',\n 'Artstarlist_2010_pos3_e.txt',\n 'Artstarlist_2010_pos3_f.txt',\n 'Artstarlist_2010_pos4_d.txt',\n 'Artstarlist_2010_pos4_e.txt',\n 'Artstarlist_2010_pos4_f.txt'],\n '23.KS2_2013_ART': ['Artstarlist_2013_pos1_a.txt',\n 'Artstarlist_2013_pos1_b.txt',\n 'Artstarlist_2013_pos1_c.txt',\n 'Artstarlist_2013_pos2_a.txt',\n 'Artstarlist_2013_pos2_b.txt',\n 'Artstarlist_2013_pos2_c.txt',\n 'Artstarlist_2013_pos3_a.txt',\n 'Artstarlist_2013_pos3_b.txt',\n 'Artstarlist_2013_pos3_c.txt',\n 'Artstarlist_2013_pos4_a.txt',\n 'Artstarlist_2013_pos4_b.txt',\n 'Artstarlist_2013_pos4_c.txt',\n 'Artstarlist_2013_pos1_d.txt',\n 'Artstarlist_2013_pos1_e.txt',\n 'Artstarlist_2013_pos1_f.txt',\n 'Artstarlist_2013_pos2_d.txt',\n 'Artstarlist_2013_pos2_e.txt',\n 'Artstarlist_2013_pos2_f.txt',\n 'Artstarlist_2013_pos3_d.txt',\n 'Artstarlist_2013_pos3_e.txt',\n 'Artstarlist_2013_pos3_f.txt',\n 'Artstarlist_2013_pos4_d.txt',\n 'Artstarlist_2013_pos4_e.txt',\n 'Artstarlist_2013_pos4_f.txt']}\n \n filters = {'21.KS2_2005_ART': [1],\n '22.KS2_2010_ART': [1, 2, 3],\n '23.KS2_2013_ART': [1]}\n\n return comp_dirs, art_lists, filters\n\n\ndef call_process_ks2_artstar():\n comp_dirs, art_lists, filters = setup_artstar_info()\n\n # Loop through each year\n for epoch in list(comp_dirs.keys()):\n art_dirs = comp_dirs[epoch]\n \n # Loop through each position, sublist combo\n for ii in range(len(art_dirs)):\n directory = work_dir + epoch + '/' + art_dirs[ii]\n os.chdir(directory)\n\n filt = filters[epoch]\n\n # Loop through each filter \n for ff in range(len(filt)):\n filt_string = 'F{0:d}'.format(filt[ff])\n print('Working on {0}, filter F{1}'.format(directory, filt_string))\n \n art_star_list = art_lists[epoch][ii]\n\n if '2005' in epoch:\n nimfo2bar_file = 'nimfo2bar.xymeee.ks2.' + filt_string\n else:\n nimfo2bar_file = 'nimfo2bar.xymeee.' + filt_string\n comp.process_ks2_artstar(art_star_list, nimfo2bar_file,\n filter_num=filt[ff])\n\n \n return\n\ndef recombine_artstar_subsets():\n \"\"\"\n Take the subsets of the artificial star lists and put them\n back together again. We will only work with the final output\n catalogs form call_process_ks2_artstar().\n\n Last step is top save the catalogs in 51.ALIGN_ART/.\n \"\"\"\n comp_dirs, art_lists, filters = setup_artstar_info()\n\n ##################################################\n #\n # Process 21.KS2_2005_ART -- combine everything (single filter)\n #\n ##################################################\n epoch = '21.KS2_2005_ART'\n t_2005_F814W = None\n subdirs = comp_dirs[epoch]\n alists = art_lists[epoch]\n\n N_largest = 0\n for ii in range(len(subdirs)):\n table_file = work_dir + epoch + '/' + subdirs[ii] + '/'\n table_file += alists[ii].replace('.txt', '')\n table_file += '_F1_joined.fits'\n\n t = Table.read(table_file)\n\n if ii == 0:\n t_2005_F814W = t\n else:\n # Modify the names (which are actually indices).\n t['name'] += N_largest\n t_2005_F814W = table.vstack((t_2005_F814W, t), join_type='exact')\n \n N_largest = t_2005_F814W['name'][-1]\n\n # Save output to file.\n outfile = 'artstar_2005_F814W.fits'\n outfile = work_dir + '51.ALIGN_ART/' + outfile\n t_2005_F814W.write(outfile, overwrite=True)\n\n\n\n ##################################################\n #\n # Process 22.KS2_2010_ART -- combine each position (three filters)\n #\n ##################################################\n epoch = '22.KS2_2010_ART'\n positions = ['pos1_1', 'pos2_1', 'pos3_1', 'pos4_1', 'pos1_2', 'pos2_2', 'pos3_2', 'pos4_2']\n subsets = {'pos1_1': ['a', 'b', 'c'],\n 'pos2_1': ['a', 'b', 'c'],\n 'pos3_1': ['a', 'b', 'c'],\n 'pos4_1': ['a', 'b', 'c'],\n 'pos1_2': ['d', 'e', 'f'],\n 'pos2_2': ['d', 'e', 'f'],\n 'pos3_2': ['d', 'e', 'f'],\n 'pos4_2': ['d', 'e', 'f']}\n filter_names = {1: 'F160W', 2: 'F139M', 3: 'F125W'}\n\n for pp in range(len(positions)):\n # The name of this mosaic position.\n pos_out = positions[pp]\n pos = positions[pp].split('_')[0]\n pos_idx = int(pos[-1])\n \n # List of subset directory suffixes for this mosaic position.\n subs = subsets[pos_out]\n\n for filt in filters[epoch]:\n t_2010 = None\n N_largest = 0\n\n for ii in range(len(subs)):\n table_file = work_dir + epoch\n table_file += '/{0:02d}.{1:s}_{2:s}/'.format(pos_idx, pos, subs[ii])\n table_file += 'Artstarlist_2010_{0:s}_{1:s}'.format(pos, subs[ii])\n table_file += '_F{0:d}'.format(filt)\n table_file += '_joined.fits'\n \n t = Table.read(table_file)\n\n if ii == 0:\n t_2010 = t\n else:\n # Modify the names (which are actually indices).\n t['name'] += N_largest\n t_2010 = table.vstack((t_2010, t), join_type='exact')\n \n N_largest = t_2010['name'][-1]\n\n # Save output to file.\n outfile = 'artstar_2010_{0}_{1}.fits'.format(filter_names[filt], pos_out)\n outfile = work_dir + '51.ALIGN_ART/' + outfile\n t_2010.write(outfile, overwrite=True)\n\n ##################################################\n #\n # Process 23.KS2_2013_ART -- combine each position (three filters)\n #\n ##################################################\n epoch = '23.KS2_2013_ART'\n positions = ['pos1_1', 'pos2_1', 'pos3_1', 'pos4_1', 'pos1_2', 'pos2_2', 'pos3_2', 'pos4_2']\n subsets = {'pos1_1': ['a', 'b', 'c'],\n 'pos2_1': ['a', 'b', 'c'],\n 'pos3_1': ['a', 'b', 'c'],\n 'pos4_1': ['a', 'b', 'c'],\n 'pos1_2': ['d', 'e', 'f'],\n 'pos2_2': ['d', 'e', 'f'],\n 'pos3_2': ['d', 'e', 'f'],\n 'pos4_2': ['d', 'e', 'f']}\n filter_names = {1: 'F160W'}\n\n for pp in range(len(positions)):\n # The name of this mosaic position.\n pos_out = positions[pp]\n pos = positions[pp].split('_')[0]\n pos_idx = int(pos[-1])\n \n # List of subset directory suffixes for this mosaic position.\n subs = subsets[pos_out]\n\n for filt in filters[epoch]:\n t_2013 = None\n N_largest = 0\n\n for ii in range(len(subs)):\n table_file = work_dir + epoch\n table_file += '/{0:02d}.{1:s}_{2:s}/'.format(pos_idx, pos, subs[ii])\n table_file += 'Artstarlist_2013_{0:s}_{1:s}'.format(pos, subs[ii])\n table_file += '_F{0:d}'.format(filt)\n table_file += '_joined.fits'\n \n t = Table.read(table_file)\n\n if ii == 0:\n t_2013 = t\n else:\n # Modify the names (which are actually indices).\n t['name'] += N_largest\n t_2013 = table.vstack((t_2013, t), join_type='exact')\n \n N_largest = t_2013['name'][-1]\n\n # Save output to file.\n outfile = 'artstar_2013_{0}_{1}.fits'.format(filter_names[filt], pos_out)\n outfile = work_dir + '51.ALIGN_ART/' + outfile\n t_2013.write(outfile, overwrite=True)\n\n return\n\ndef align_artstars(use_obs_align=False):\n \"\"\"\n Read in the artificial star catalogs, transform them using the\n alignments derived from the observed data, cross-match the stars across\n epochs, and apply trim_align cuts in a similar manner to the observed data.\n\n Deliver a FITS catalog that parallels the one delivered from\n align_to_fits()\n combine_mosaic_pos()\n This will have the mosaic positions combined together. \n \"\"\"\n mosaic_epochs = ['2005_F814W', '2010_F125W', '2010_F139M',\n '2010_F160W', '2013_F160W']\n pos_for_epoch = {'2005_F814W': [''],\n '2010_F125W': ['pos1_1', 'pos2_1', 'pos3_1', 'pos4_1', \n 'pos1_2', 'pos2_2', 'pos3_2', 'pos4_2'],\n '2010_F139M': ['pos1_1', 'pos2_1', 'pos3_1', 'pos4_1',\n 'pos1_2', 'pos2_2', 'pos3_2', 'pos4_2'],\n '2010_F160W': ['pos1_1', 'pos2_1', 'pos3_1', 'pos4_1',\n 'pos1_2', 'pos2_2', 'pos3_2', 'pos4_2'],\n '2013_F160W': ['pos1_1', 'pos2_1', 'pos3_1', 'pos4_1',\n 'pos1_2', 'pos2_2', 'pos3_2', 'pos4_2']}\n \n # WARNING Hard-coding the order -- arrays above need to be matched to\n # the align.list file from the observed data. No checks!!\n align_indices = {'2005_F814W': [0], \n '2010_F125W': [1, 2, 3, 4, 1, 2, 3, 4], \n '2010_F139M': [5, 6, 7, 8, 5, 6, 7, 8], \n '2010_F160W': [9, 10, 11, 12, 9, 10, 11, 12],\n '2013_F160W': [13, 14, 15, 16, 13, 14, 15, 16]}\n\n if use_obs_align:\n align_root = 'align_a4_t'\n align_dir = work_dir + '50.ALIGN_KS2/'\n else:\n align_root = 'align_a4_t'\n align_dir = work_dir + '51.ALIGN_ART/align_a4_t/'\n\n # This table contains the transformations that will be applied.\n trans = Table.read(align_dir + align_root + '.trans',\n format='ascii')\n\n # This will be used to validate that we are working on the right list. \n align_list_file = open(align_dir + align_root + '.list', 'r')\n align_list = align_list_file.readlines()\n\n def transform(xin, yin, tr):\n \"\"\"\n xin - array\n yin - array\n tr - row from an align.trans file\n \"\"\"\n xout = tr['a0']\n xout += (tr['a1'] * xin) + (tr['a2'] * yin)\n xout += (tr['a3'] * xin**2) + (tr['a4'] * xin * yin) + (tr['a5'] * yin**2)\n \n yout = tr['b0']\n yout += (tr['b1'] * yin) + (tr['b2'] * yin)\n yout += (tr['b3'] * yin**2) + (tr['b4'] * yin * xin) + (tr['b5'] * xin**2)\n\n return (xout, yout)\n\n def transform_error(xin, yin, xin_e, yin_e, tr):\n \"\"\"\n xin - array\n yin - array\n tr - row from an align.trans file\n \"\"\"\n xe_term1 = (tr['a1'] * xin_e)\n xe_term1 += (tr['a3'] * 2 * xin * xin_e) + (tr['a4'] * yin * xin_e)\n\n xe_term2 = (tr['a2'] * yin_e)\n xe_term2 += (tr['a5'] * 2 * yin * yin_e) + (tr['a4'] * xin * yin_e)\n \n xout_e = np.hypot(xe_term1, xe_term2)\n\n ye_term1 = (tr['b1'] * yin_e)\n ye_term1 += (tr['b3'] * 2 * yin * yin_e) + (tr['b4'] * xin * yin_e)\n\n ye_term2 = (tr['b2'] * xin_e)\n ye_term2 += (tr['b5'] * 2 * xin * xin_e) + (tr['b4'] * yin * xin_e)\n \n yout_e = np.hypot(ye_term1, ye_term2)\n \n return (xout_e, yout_e)\n \n # This will be the final table\n t_out = Table()\n t_out.table_name = 'art_align'\n\n if use_obs_align:\n t_out.table_name = t_out.table_name + '_obs'\n else:\n t_out.table_name = t_out.table_name + '_art'\n\n # Loop through each epoch (2005, 2010, 2013)\n for ee in range(len(mosaic_epochs)):\n epoch = mosaic_epochs[ee]\n positions = pos_for_epoch[epoch]\n print('')\n print('Combining all positions from epoch = ', epoch)\n \n\n # Define the final output arrays \n x = np.array([], dtype=float)\n y = np.array([], dtype=float)\n m = np.array([], dtype=float)\n xe = np.array([], dtype=float)\n ye = np.array([], dtype=float)\n me = np.array([], dtype=float)\n n = np.array([], dtype=int)\n x_in = np.array([], dtype=float)\n y_in = np.array([], dtype=float)\n m_in = np.array([], dtype=float)\n name = np.array([], dtype='S10')\n\n # Loop through the mosaic positions (pos1, pos2, pos3, pos4)\n for pp in range(len(positions)):\n # Get the current position\n pos = positions[pp]\n align_idx = align_indices[epoch][pp]\n pos_only = pos.split('_')[0]\n\n # Get the transformation for this epoch\n tr = trans[align_idx]\n\n # Make a suffix string from the current position\n if pos != '':\n pos_suffix = '_' + pos\n else:\n pos_suffix = pos\n\n # Read in the table\n artstar_list = 'artstar_{0}{1}.fits'.format(epoch, pos_suffix)\n\n print(' ks2 list = ', artstar_list, ' align list = ', align_list[align_idx].split()[0])\n\n t = Table.read(work_dir + '51.ALIGN_ART/' + artstar_list)\n\n # Transfrom the stars' input positions.\n x_in_t, y_in_t = transform(t['x_in'], t['y_in'], tr)\n\n # Identify the detected stars and only transform them.\n det = np.where(t['n_out'] > 0)[0]\n x_out_t = t['x_out']\n y_out_t = t['y_out']\n xe_out_t = t['xe_out']\n ye_out_t = t['ye_out']\n \n x_out_t[det], y_out_t[det] = transform(t['x_out'][det], t['y_out'][det],\n tr)\n xe_out_t[det], ye_out_t[det] = transform_error(t['x_out'][det],\n t['y_out'][det],\n t['xe_out'][det],\n t['ye_out'][det],\n tr)\n\n # Append input values to the final arrays\n x_in = np.append(x_in, x_in_t)\n y_in = np.append(y_in, y_in_t)\n m_in = np.append(m_in, t['m_in'])\n\n # Append detected values to the final arrays\n x = np.append(x, x_out_t)\n y = np.append(y, y_out_t)\n m = np.append(m, t['m_out'])\n n = np.append(n, t['n_out'])\n\n xe = np.append(xe, xe_out_t)\n ye = np.append(ye, ye_out_t)\n me = np.append(me, t['me_out'])\n\n new_name = [str(nn) + pos_suffix for nn in t['name']]\n\n name = np.append(name, new_name)\n\n print(' position = {0}, added {1} star'.format(pos, len(x_out_t)))\n print('')\n\n # Add new columns to the table\n t_out.add_column(Column(x, name='x_' + epoch))\n t_out.add_column(Column(y, name='y_' + epoch))\n t_out.add_column(Column(m, name='m_' + epoch))\n\n t_out.add_column(Column(xe, name='xe_' + epoch))\n t_out.add_column(Column(ye, name='ye_' + epoch))\n t_out.add_column(Column(me, name='me_' + epoch))\n \n t_out.add_column(Column(n, name='n_' + epoch))\n\n t_out.add_column(Column(x_in, name='xin_' + epoch))\n t_out.add_column(Column(y_in, name='yin_' + epoch))\n t_out.add_column(Column(m_in, name='min_' + epoch))\n\n t_out.add_column(Column(name, name='name_' + epoch))\n\n \n #fix_art_magnitudes(t_out)\n\n file_name = work_dir + '51.ALIGN_ART/art_align'\n if use_obs_align:\n file_name += '_obs'\n else:\n file_name += '_art'\n file_name += '_combo_pos.fits'\n\n print(file_name)\n \n t_out.write(file_name, overwrite=True)\n\n return\n\n\ndef fix_art_magnitudes(t):\n t['m_2005_F814W'] -= -2.5 * np.log10(2407. / 3.)\n t['min_2005_F814W'] -= -2.5 * np.log10(2407. / 3.)\n\n return\n \ndef fix_magnitudes(t):\n t['m_2005_F814W'] -= -2.5 * np.log10(2407. / 3.)\n\n return\n\n","sub_path":"jlu/wd1/analysis/reduce_2015_01_05.py","file_name":"reduce_2015_01_05.py","file_ext":"py","file_size_in_byte":121656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"425718546","text":"\nimport csv\n\ndef save_data(tx, ty, tz, obs, filename='data/data.csv'):\n data = [tx, ty, tz]\n for ob in obs:\n data.append(ob[1][0])\n data.append(ob[1][1])\n\n with open(filename, 'a', newline='') as f_data:\n wr = csv.writer(f_data, quoting=csv.QUOTE_ALL)\n wr.writerow(data)\n\ndef save_labels(pitch, yaw, f, filename='data/labels.csv'):\n with open(filename, 'a', newline='') as f_labels:\n wr = csv.writer(f_labels, quoting=csv.QUOTE_ALL)\n wr.writerow([pitch, yaw, f])\n","sub_path":"Zach/Missions/util/data_collection.py","file_name":"data_collection.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"271351688","text":"\"\"\"\n\nGoes to site sent from Page_Processor.py and returns titles and summaries.\n\n\"\"\"\n\n##Imports##\nfrom __main__ import *\nimport csv\nfrom requests import get\nfrom requests.exceptions import RequestException\nfrom contextlib import closing\nfrom bs4 import Comment\nfrom bs4 import BeautifulSoup\nfrom itertools import zip_longest\n\nheaders = {\n 'User-Agent': 'Michael, student',\n 'From': 'mpc238@nau.edu'\n}\n\n\ndef simple_get(YahooArticleURL):\n try:\n with closing(get(YahooArticleURL, stream=True)) as resp:\n if is_good_response(resp):\n return resp.content\n else:\n return None\n\n except RequestException as e:\n log_error('Error during requests to {0} : {1}'.format(YahooArticleURL, str(e)))\n return None\n\n\ndef is_good_response(resp):\n content_type = resp.headers['Content-Type'].lower()\n return (resp.status_code == 200 \n and content_type is not None \n and content_type.find('html') > -1)\n\n\ndef log_error(e):\n print(e)\n\n\n\ndef get_articles(YahooArticleURL):\n \n response = simple_get(YahooArticleURL)\n\n if response is not None:\n soup = BeautifulSoup(response, features='html.parser')\n articles = soup.find('ul', class_=\"My(0) Ov(h) P(0) Wow(bw)\")\n\n \n list_of_titles = []\n list_of_summaries = []\n #list_of_articles = []\n garbages = [\"’\",\"‘\"]\n for article in articles.find_all('li'):\n\n ##Clean Up Articles a bit##\n wastes = article.find_all(\"u\", class_=\"StretchedBox\") \n waste_comments = article.find_all(string=lambda text: isinstance(text, Comment))\n\n for waste in wastes:\n waste.decompose() \n for waste_comment in waste_comments:\n waste_comment.extract()\n\n ##Find Titles and Summaries##\n for title in article.find('a', class_=\"Fw(b) Fz(20px) Lh(23px) Fz(17px)--sm1024 Lh(19px)--sm1024 Td(n) C(#0078ff):h C(#000) LineClamp(2,46px) LineClamp(2,38px)--sm1024\"): \n for garbage in garbages:\n title.replace(garbage, '')\n return title\n list_of_titles.append(title)\n \n for summary in article.find('p', class_=\"Fz(14px) Lh(19px) Fz(13px)--sm1024 Lh(17px)--sm1024 LineClamp(2,38px) LineClamp(2,34px)--sm1024 M(0)\"):\n for garbage in garbages:\n summary.replace(garbage, '')\n return summary\n list_of_summaries.append(summary)\n\n list_of_articles = [list_of_titles, list_of_summaries]\n export_data = zip_longest(*list_of_articles, fillvalue = '')\n FinData = (open(\"./articles.csv\", \"w\", newline=''))\n with FinData:\n writer = csv.writer(FinData)\n writer.writerow([\"Titles\", \"Summaries\"])\n writer.writerows(export_data)\n FinData.close()\n\n\n else:\n log_error(\"Something went wrong.\")\n \n #raise Exception('Error retrieving contents at {}'.format(YahooArticleURL))\n","sub_path":"Page_Filer.py","file_name":"Page_Filer.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"151198124","text":"from flask import Flask, render_template\nimport cgi, cgitb\nform = cgi.FieldStorage()\n\ndef getForm():\n ans = {}\n for element in form:\n ans[element] = form[element].value\n return ans\n\nform = getForm()\n\nf=open('data1.csv',\"r\")\ndata = f.read()\ndatabackup = f.read()\nf.close()\n\n##assigns ordering\nif 'order' not in form:\n form['order'] = 'Performance Points'\nif 'direction' not in form:\n form['direction'] = 'up'\n \n##assigns interval, default=25\nif 'interval' not in form:\n form['interval'] = 25\n\n##changes ordering, order will be a string\ndef order(column, direction):\n least2big = []\n head = data.split(\"\\n\")[0]\n head = head.split(', ')\n index = head.index(column)\n lines = data.split(\"\\n\")[1:-1]\n for x in range(len(lines)):\n lines[x] = lines[x].split(',')\n for x in lines:\n for element in range(len(x)):\n x[element] = x[element].strip(' ')\n #now in format [ [a] [b] [c] ]\n for x in range(len(lines)):\n least = lines[-1]\n for element in lines:\n if column== \"Score Rank\":\n if int(least[index]) > int(element[index]):\n least = element\n elif column==\"SS\":\n if int(least[index]) > int(element[index]):\n least = element\n elif column == \"Performance Points\":\n if int(least[index][:-2]) > int(element[index][:-2]):\n least = element\n least2big.append(least)\n lines.pop(lines.index(least))\n if direction == 'up':\n\n least2big.insert(0,head)\n else:\n least2big.reverse()\n least2big.insert(0,head)\n return least2big\n\napp = Flask(__name__)\n\n@app.route(\"/home\")\n@app.route(\"/\")\ndef home():\n return render_template(\"home.html\")\n\ntablestring = \"Temporary Table String\"\n@app.route(\"/table\")\ndef makeTablePage():\n return render_template(\"table.html\",tablestr=tablestring)\n\nif __name__ == \"__main__\":\n app.debug=True\n app.run()\n","sub_path":"6/intro-proj1/ELiaoTLiang/dataproject.py","file_name":"dataproject.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"438417771","text":"import matplotlib.pyplot as plt \nimport numpy as np \nfrom matplotlib import style\nstyle.use('ggplot')\nfrom sklearn.cluster import KMeans\nfrom sklearn import preprocessing\nimport pandas as pd\nimport xlrd\n\n'''\nData being used: titanic dataset (titanic.xls)\n========================================\nPclass passenger's class (1st-3rd)\nsurvival Survive (0 = no, 1 = yes)\nname Name\nsex Sex\nage Age\nsibsp Num of Silings/Spouses aboard\nparch Num of parents/children aboard\nticket Ticket Num\nfare Passenger's Fare (BPS)\ncabin Cabin\nembarked Port of Embarkation(C = Cherbourg, Q = Queenstown, S = Southampton)\nboat Lifeboat\nbody Body ID Num\nhome.dest Home/Destination \n'''\ndf = pd.read_excel('titanic.xls')\ndf.drop(['body','name'], 1, inplace=True) #this data might taint the outcome \ndf.apply(pd.to_numeric, errors='coerce') #coerce / ignore for errors=''\ndf.fillna(0, inplace=True)\n\ndef handle_non_numerical(df):\n\tcolumns = df.columns.values\n\n\tfor column in columns:\n\t\ttext_digit_vals = {} #ex. {'female', 0}\n\t\tdef convert_to_int(val):\n\t\t\treturn text_digit_vals[val]\n\t\t\n\t\tif df[column].dtype != np.int64 and df[column].dtype != np.float64:\n\t\t\tcolumn_contents = df[column].values.tolist() # all just converting data to numerical\n\t\t\tunique_elements = set(column_contents)\n\t\t\tx = 0\n\t\t\tfor unique in unique_elements:\n\t\t\t\tif unique not in text_digit_vals:\n\t\t\t\t\ttext_digit_vals[unique] = x\n\t\t\t\t\tx += 1\n\t\t\tdf[column] = list(map(convert_to_int, df[column]))\n\n\treturn df\n\ndf = handle_non_numerical(df)\n\ndf.drop(['boat'], 1, inplace=True) #you can tweak the dataset to see what variabes have an impact\n\nX = np.array(df.drop(['survived'], 1).astype(float))\nX = preprocessing.scale(X)\ny = np.array(df['survived'])\n\nclf = KMeans(n_clusters=2)\nclf.fit(X)\n\ncorrect = 0\nfor i in range(len(X)):\n\tpredict_me = np.array(X[i].astype(float))\n\tpredict_me = predict_me.reshape(-1, len(predict_me))\n\tprediction = clf.predict(predict_me) # only for unspervised learning\n\tif prediction[0] == y[i]:\n\t\tcorrect += 1\n\nprint(df.head())\nprint(correct/len(X))\n\n'''\nSince the algorithm is identifying random/arbitary centroids for the clusters,\nthe accuracy of the model will bounce between 2 numbers.\n\nFor Example: accuracy could be 30%, which might sound bad but its really (100-30%) = 70%\nand if you run the same model multiple times, the accuracy will hover between 30 and 70, \nbecause of the randomness in centroid choosing, it might pick 'the wrong centroid' for \neach cluster but the overall algorithm is accurate.\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":"Unsupervised ML/K Means Clustering/K_means_titanic.py","file_name":"K_means_titanic.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"147910117","text":"import hashlib\n\nimport markup.csstester as testendpoint_css\nimport markup.markuptester as testendpoint_markup\nimport scripting as testendpoint_js\nfrom . import register_test\nfrom .. import unicodehelper\nfrom ..constants import *\n\n\nFLAGGED_FILES = set([\".DS_Store\", \"Thumbs.db\", \"desktop.ini\",\n \"_vti_cnf\"])\nFLAGGED_EXTENSIONS = set([\".orig\", \".old\", \".tmp\", \"~\"])\n\n\nwith open(os.path.join(os.path.dirname(__file__), \"hashes.txt\")) as f:\n hashes_whitelist = set([s.strip().split(None, 1)[0] for s in f])\n\n\n@register_test(tier=2)\ndef test_packed_packages(err, package=None):\n\n if not package:\n return\n\n processed_files = 0\n garbage_files = 0\n\n # Iterate each item in the package.\n for name in package:\n file_info = package.info(name)\n file_name = file_info[\"name_lower\"]\n file_size = file_info[\"size\"]\n\n if \"__MACOSX\" in name or file_name[0] in (\".\", \"_\", ):\n err.warning(\n err_id=(\"testcases_content\", \"test_packed_packages\",\n \"hidden_files\"),\n warning=\"Unused files or directories flagged.\",\n description=\"Hidden files and folders can make the review process \"\n \"difficult and may contain sensitive information \"\n \"about the system that generated the zip. Please \"\n \"modify the packaging process so that these files \"\n \"aren't included.\",\n filename=name)\n garbage_files += file_size\n continue\n elif (any(name.endswith(ext) for ext in FLAGGED_EXTENSIONS) or\n name in FLAGGED_FILES):\n err.warning(\n err_id=(\"testcases_content\", \"test_packaged_packages\",\n \"flagged_files\"),\n warning=\"Garbage file detected\",\n description=\"Files were found that are either unnecessary \"\n \"or have been included unintentionally. They \"\n \"should be removed.\",\n filename=name)\n garbage_files += file_size\n continue\n\n # Read the file from the archive if possible.\n file_data = u\"\"\n try:\n file_data = package.read(name)\n except KeyError:\n pass\n\n # Skip over whitelisted hashes - only applies to .js files for now.\n if name.endswith('.js'):\n file_data = file_data.replace(\"\\r\\n\", \"\\n\")\n if hashlib.sha256(file_data).hexdigest() in hashes_whitelist:\n continue\n\n # Process the file.\n processed = _process_file(err, package, name, file_data)\n # If the file is processed, it will return True. If the process goes\n # badly, it will return False. If the processing is skipped, it returns\n # None. We should respect that.\n if processed is None:\n continue\n\n # This aids in creating unit tests.\n processed_files += 1\n\n if garbage_files >= MAX_GARBAGE:\n err.error(\n err_id=(\"testcases_content\", \"garbage\"),\n error=\"Too much garbage in package\",\n description=\"Your app contains too many unused or garbage files. \"\n \"These include temporary files, 'dot files', IDE and \"\n \"editor backup and configuration, and operating \"\n \"system hidden files. They must be removed before \"\n \"your app can be submitted.\")\n\n return processed_files\n\n\ndef _process_file(err, package, name, file_data):\n \"\"\"Process a single file's content tests.\"\"\"\n\n name_lower = name.lower()\n\n if not name_lower.endswith((\".css\", \".js\", \".xml\", \".html\", \".xhtml\")):\n return False\n\n if not file_data:\n return None\n\n # Convert the file data to unicode\n file_data = unicodehelper.decode(file_data)\n\n if name_lower.endswith(\".css\"):\n testendpoint_css.test_css_file(err, name, file_data)\n\n elif name_lower.endswith(\".js\"):\n testendpoint_js.test_js_file(err, name, file_data)\n\n elif name_lower.endswith((\".xml\", \".html\", \".xhtml\")):\n p = testendpoint_markup.MarkupParser(err)\n p.process(name, file_data, package.info(name)[\"extension\"])\n\n return True\n\n\n@register_test(tier=2)\ndef test_cordova(err, package=None):\n\n if not package:\n return\n\n err.metadata[\"cordova\"] = \"www/cordova.js\" in package\n","sub_path":"appvalidator/testcases/content.py","file_name":"content.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"641693741","text":"# complete rxn from metabolites in metabolite dict\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport re\r\nimport numpy as np\r\nfrom mpact import get_kegg_compound_information\r\nfrom mpact import get_bigg_metabolite_information\r\nfrom mpact import define_metabolite_charge\r\nfrom mpact import get_element_coeff\r\nfrom mpact import get_charged_formula\r\nfrom mpact import get_list_of_met_bigg_ids_in_db\r\nfrom mpact import find_met_name_from_bigg_id_in_db\r\nfrom mpact import retrieve_metabolite_info_from_db\r\n\r\n\r\n#compounds = [\"ethanol\",\"acetaldehyde\"]\r\n#[selected_kegg_rxn, selected_bigg_rxn, bigg_string, bigg_name, bigg_mets, kegg_name, kegg_mets, kegg_string, metabolite_dict] = get_reaction(compounds)\r\n\r\ndef display_compound_length_warning(compounds):\r\n if len(compounds) != 2:\r\n print('\\n WARNING! \\n')\r\n print('This code only works for finding reactions between TWO compounds \\n')\r\n return \r\n\r\ndef get_rxn_info(compounds,metabolite_dict,bigg2kegg_rxn_db, bigg2kegg_db,mmdb_path):\r\n r1 = metabolite_dict[compounds[0]]['kegg_reactions']\r\n r2 = metabolite_dict[compounds[1]]['kegg_reactions']\r\n common_rxns = [value for value in r1 if value in r2]\r\n display_rxns = display_common_rxns(common_rxns)\r\n display_rxns = np.vstack(display_rxns)\r\n print(\"The following KEGG reactions were returned. Please select the correct reaction.\")\r\n print(display_rxns)\r\n user_input = input(\"Enter the number of the desired KEGG reaction: \")\r\n kegg_rxn = common_rxns[int(user_input)]\r\n [kegg_name, kegg_mets, kegg_string, kegg_ec,kegg_eqn] = get_kegg_rxn_info(kegg_rxn)\r\n bigg_ids = [s for s in bigg2kegg_rxn_db if kegg_rxn in s[1]]\r\n if bigg_ids == []:\r\n [bigg_rxn,bigg_name,bigg_mets,bigg_string,metabolite_dict] = create_BIGG_rxn_from_KEGG_rxn(kegg_rxn,kegg_name,kegg_mets,kegg_eqn,bigg2kegg_db,metabolite_dict,mmdb_path) \r\n else:\r\n display_rxn_strings = display_bigg_rxn_strings(bigg_ids)\r\n print(\"The following BIGG reactions were returned. Please select the correct reaction.\")\r\n print(display_rxn_strings)\r\n print('//////////////////')\r\n print('NOTE: IF DESIRED RXN IS NOT IN LIST, ENTER: \"n\"')\r\n print('//////////////////')\r\n user_input = input(\"Enter the number of the desired BIGG reaction: \")\r\n if user_input is 'n':\r\n [bigg_rxn,bigg_name,bigg_mets,bigg_string,metabolite_dict] = create_BIGG_rxn_from_KEGG_rxn(kegg_rxn,kegg_name,kegg_mets,kegg_eqn,bigg2kegg_db,metabolite_dict,mmdb_path) \r\n else:\r\n bigg_rxn = bigg_ids[int(user_input)][0]\r\n [bigg_string, bigg_name, bigg_mets] = get_bigg_rxn_info(bigg_rxn)\r\n metabolite_dict = add_rxn_mets_to_metabolite_dict(metabolite_dict,bigg_mets,bigg2kegg_db,mmdb_path)\r\n return bigg_rxn,kegg_rxn,bigg_string,bigg_name,bigg_mets,kegg_name,kegg_mets,kegg_string,kegg_eqn, kegg_ec\r\n \r\ndef add_to_reaction_dict(reaction_dict,compounds,metabolite_dict,bigg2kegg_rxn_db, bigg2kegg_db,mmdb_path):\r\n display_compound_length_warning(compounds)\r\n [bigg_rxn,kegg_rxn,bigg_string,bigg_name,bigg_mets,kegg_name,kegg_mets,kegg_string,kegg_eqn,kegg_ec] = get_rxn_info(compounds,metabolite_dict,bigg2kegg_rxn_db, bigg2kegg_db,mmdb_path)\r\n reaction_dict['reactions'].append(bigg_rxn)\r\n reaction_dict[bigg_rxn] = {}\r\n reaction_dict[bigg_rxn]['bigg_rxn'] = bigg_rxn\r\n reaction_dict[bigg_rxn]['kegg_rxn'] = kegg_rxn\r\n reaction_dict[bigg_rxn]['bigg_string'] = bigg_string\r\n reaction_dict[bigg_rxn]['bigg_name'] = bigg_name\r\n reaction_dict[bigg_rxn]['bigg_mets'] = bigg_mets\r\n reaction_dict[bigg_rxn]['kegg_name'] = kegg_name\r\n #reaction_dict[bigg_rxn]['kegg_mets'] = kegg_mets\r\n reaction_dict[bigg_rxn]['kegg_definition'] = kegg_string\r\n reaction_dict[bigg_rxn]['kegg_eqn'] = kegg_eqn\r\n reaction_dict[bigg_rxn]['BRENDA_enzymes'] = kegg_ec\r\n reaction_dict[bigg_rxn]['nodes'] = [metabolite_dict[i]['bigg_id'] for i in compounds]\r\n return reaction_dict, metabolite_dict\r\n\r\ndef create_BIGG_rxn_from_KEGG_rxn(kegg_rxn,kegg_name,kegg_mets,kegg_eqn,bigg2kegg_db,metabolite_dict,mmdb_path):\r\n print(' \\n ///// WARNING ///////')\r\n print('No BiGG reactions found for the selected KEGG reaction!')\r\n print('Creating a BIGG-like reaction ...')\r\n bigg_name = kegg_name\r\n bigg_mets = get_bigg_mets_from_kegg_mets(kegg_mets,bigg2kegg_db)\r\n metabolite_dict = add_rxn_mets_to_metabolite_dict(metabolite_dict,bigg_mets,bigg2kegg_db,mmdb_path)\r\n bigg_string = kegg2bigg_rxn_string(kegg_eqn,kegg_mets,bigg_mets)\r\n print('Please name the following BIGG reaction for',kegg_name)\r\n bigg_rxn = input('Enter BIGG ID:')\r\n return bigg_rxn,bigg_name,bigg_mets,bigg_string,metabolite_dict\r\n\r\ndef kegg2bigg_rxn_string(kegg_eqn,kegg_mets,bigg_mets):\r\n bigg_string = kegg_eqn\r\n for i in range(0,len(kegg_mets)):\r\n km = kegg_mets[i]\r\n bm = bigg_mets[i]+'_c'\r\n bigg_string = bigg_string.replace(km,bm)\r\n return bigg_string\r\n\r\ndef get_bigg_mets_from_kegg_mets(kegg_mets,bigg2kegg_db):\r\n bigg_mets = []\r\n for km in kegg_mets:\r\n bigg_ids = [s[0] for s in bigg2kegg_db if km in s[1]]\r\n if bigg_ids == []:\r\n print('///// WARNING //////')\r\n print('The KEGG compound,',km,'could be identified with any BIGG metabolite.')\r\n bigg_mets.append('NA')\r\n else:\r\n bigg_id = decide_compartment(bigg_ids)[0][:-2]\r\n bigg_mets.append(bigg_id)\r\n return bigg_mets\r\n \r\ndef decide_compartment(bigg_ids):\r\n bigg_id = []\r\n for ids in bigg_ids:\r\n if ids[-1] is 'c':\r\n bigg_id.append(ids)\r\n return bigg_id\r\n\r\ndef create_local_metabolite_conversion_table(metabolite_dict):\r\n local_met_conversion_table = []\r\n for met in metabolite_dict['metabolites']:\r\n local_met_conversion_table.append([met,metabolite_dict[met]['kegg_id'],metabolite_dict[met]['bigg_id']])\r\n return np.vstack(local_met_conversion_table)\r\n\r\ndef add_rxn_mets_to_metabolite_dict(metabolite_dict,bigg_mets,bigg2kegg_db,mmdb_path):\r\n bigg_ids_in_met_dict = get_bigg_ids_in_metabolite_dict(metabolite_dict)\r\n mets = list(set(bigg_mets) - set(bigg_ids_in_met_dict))\r\n db_met_ids = get_list_of_met_bigg_ids_in_db(mmdb_path)\r\n db_met_ids_wo_c = remove_compartments_from_a_list_of_bigg_ids(db_met_ids)\r\n for met in mets:\r\n if met in db_met_ids_wo_c:\r\n print(', \\n ',met,' already has an entry in your local database.')\r\n print('Would you like to retrieve information from your database?')\r\n user_input = input('Enter \"y\" for yes or \"n\" for no: ')\r\n if user_input == \"y\":\r\n met_name = find_met_name_from_bigg_id_in_db(met+'_c',mmdb_path)\r\n metabolite_dict = retrieve_metabolite_info_from_db(met_name,mmdb_path,metabolite_dict)\r\n elif user_input == \"n\":\r\n print('adding',met,'to the metabolite dictionary')\r\n [bigg_charges,bigg_formula] = get_bigg_metabolite_information(met+'_c')\r\n kegg_id = [s for s in bigg2kegg_db if s[0] == met+'_c'][0][1]\r\n [cpd_id, kegg_formula, kegg_rxns, name,kegg_dblinks] = get_kegg_compound_information([kegg_id])\r\n charge = define_metabolite_charge(bigg_charges)\r\n charged_formula = get_charged_formula(kegg_formula,charge)\r\n metabolite_dict['metabolites'].append(name)\r\n metabolite_dict[name] = {}\r\n metabolite_dict[name]['kegg_id'] = kegg_id\r\n metabolite_dict[name]['neutral_formula'] = kegg_formula\r\n metabolite_dict[name]['kegg_reactions'] = kegg_rxns\r\n metabolite_dict[name]['bigg_id'] = met+'_c'\r\n metabolite_dict[name]['bigg_charges'] = bigg_charges\r\n metabolite_dict[name]['bigg_formula'] = bigg_formula\r\n metabolite_dict[name]['charge'] = charge\r\n metabolite_dict[name]['kegg_dblinks'] = kegg_dblinks\r\n metabolite_dict[name]['formula'] = charged_formula\r\n else:\r\n print('adding',met,'to the metabolite dictionary')\r\n [bigg_charges,bigg_formula] = get_bigg_metabolite_information(met+'_c')\r\n kegg_id = [s for s in bigg2kegg_db if s[0] == met+'_c'][0][1]\r\n [cpd_id, kegg_formula, kegg_rxns, name,kegg_dblinks] = get_kegg_compound_information([kegg_id])\r\n charge = define_metabolite_charge(bigg_charges)\r\n charged_formula = get_charged_formula(kegg_formula,charge)\r\n metabolite_dict['metabolites'].append(name)\r\n metabolite_dict[name] = {}\r\n metabolite_dict[name]['kegg_id'] = kegg_id\r\n metabolite_dict[name]['neutral_formula'] = kegg_formula\r\n metabolite_dict[name]['kegg_reactions'] = kegg_rxns\r\n metabolite_dict[name]['bigg_id'] = met+'_c'\r\n metabolite_dict[name]['bigg_charges'] = bigg_charges\r\n metabolite_dict[name]['bigg_formula'] = bigg_formula\r\n metabolite_dict[name]['charge'] = charge\r\n metabolite_dict[name]['kegg_dblinks'] = kegg_dblinks\r\n metabolite_dict[name]['formula'] = charged_formula\r\n return metabolite_dict\r\n\r\ndef get_bigg_ids_in_metabolite_dict(metabolite_dict):\r\n metabolites = metabolite_dict['metabolites']\r\n bigg_ids_in_met_dict = []\r\n for met in metabolites:\r\n bigg_ids_in_met_dict.append(metabolite_dict[met]['bigg_id'][:-2])\r\n return bigg_ids_in_met_dict\r\n\r\ndef get_kegg_rxn_info(kegg_rxn):\r\n # get name, mets, string, enzyme class\r\n base = \"http://rest.kegg.jp/get/\"\r\n url = base + kegg_rxn\r\n response = requests.get(url)\r\n tsv_data = response.text\r\n data = re.split('\\n',tsv_data)\r\n name = re.split('NAME| ',data[1])\r\n name = [s for s in name if s][0]\r\n defn_index = [i for i, s in enumerate(data) if 'DEFINITION' in s][0]\r\n defn = data[defn_index]\r\n defn = re.split('DEFINITION ',defn)\r\n defn = [s for s in defn if s][0]\r\n eqn_index = [i for i, s in enumerate(data) if 'EQUATION' in s][0]\r\n eqn = data[eqn_index]\r\n eqn = re.split('EQUATION| ',eqn)\r\n eqn = [s for s in eqn if s][0]\r\n mets = eqn.replace(' <=> ',',')\r\n mets = mets.replace(' + ',',')\r\n mets = re.split(',| ',mets)\r\n mets = [i for i in mets if len(i) == 6]\r\n ec = [s for s in data if 'ENZYME' in s][0]\r\n ec = re.split('ENZYME| ',ec)\r\n ec = [s for s in ec if s]\r\n return name, mets, defn, ec, eqn\r\n\r\ndef get_bigg_rxn_info(selected_bigg_rxn):\r\n # get name, string, metabolites, EC numbers\r\n base = 'http://bigg.ucsd.edu/api/v2/universal/reactions/'\r\n url = base + selected_bigg_rxn\r\n response = requests.get(url)\r\n tsv_data = response.text\r\n data = re.split('\"reaction_string\": |\"metabolites\": |\"database_links\": |\"old_identifiers: ',tsv_data)\r\n rxn_string = re.split(',',data[1])[0]\r\n rxn_string = rxn_string.strip('\"')\r\n rxn_string = rxn_string.replace('⇌','<=>')\r\n mets = re.split('\"bigg_id\": |, \"name\": ',data[2])\r\n name = re.split('\"name\": |, \"pseudoreaction\":',data[3])[1]\r\n name = name.strip('\"')\r\n metabolites = []\r\n for num in range(1,len(mets)-1,2):\r\n metabolites = metabolites + [mets[num].strip('\"')]\r\n return rxn_string, name, metabolites\r\n\r\ndef display_bigg_rxn_strings(bigg_ids):\r\n base = 'http://bigg.ucsd.edu/api/v2/universal/reactions/'\r\n i = 0\r\n display_rxn_strings = []\r\n for b in bigg_ids:\r\n url = base + b[0]\r\n response = requests.get(url)\r\n tsv_data = response.text\r\n data = re.split('\"reaction_string\":',tsv_data)\r\n rxn_string = re.split(',',data[1])\r\n display_rxn_strings.append([i,b[0],rxn_string[0]])\r\n i = i + 1\r\n return np.vstack(display_rxn_strings)\r\n\r\ndef display_common_rxns(common_rxns):\r\n base = \"http://rest.kegg.jp/get/\"\r\n i = 0\r\n display_rxns = []\r\n for rxn in common_rxns:\r\n url = base + rxn\r\n response = requests.get(url)\r\n tsv_data = response.text\r\n data = re.split('\\n',tsv_data)\r\n defn = [s for s in data if \"DEFINITION\" in s]\r\n defn = re.split('DEFINITION ',defn[0])\r\n defn = [s for s in defn if s][0]\r\n display_rxns.append([i,defn])\r\n i = i + 1\r\n return display_rxns\r\n\r\ndef remove_compartments_from_a_list_of_bigg_ids(list_of_bigg_ids):\r\n ids_wo_c = []\r\n for bigg_id in list_of_bigg_ids:\r\n ids_wo_c.append(bigg_id[:-2])\r\n return ids_wo_c\r\n \r\n\r\n\r\n \r\n","sub_path":"mpact/mpact/get_reaction.py","file_name":"get_reaction.py","file_ext":"py","file_size_in_byte":12530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"498293964","text":"import sys\nimport magic\nimport hashlib\nimport os\nimport configparser\n\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nimport sqlalchemy\n\nclass Sequencer:\n\tdef factory(payload_path, ref=False):\n\t\tfrom plugins import pe\n\t\tfrom plugins import strings\n\t\tplugins = {\n\t\t\t'application/x-dosexec' : pe.Sequencer\n\t\t}\n\t\tpayload_mime = magic.from_file(payload_path, mime=True)\n\t\twith open(payload_path, 'rb') as f:\n\t\t\tpayload_data = f.read()\n\t\tpayload_sha256 = hashlib.sha256(payload_data).digest()\n\t\tconst = plugins.get(payload_mime, strings.Sequencer)\n\t\treturn const(payload_sha256, payload_mime, payload_path, ref=False)\n\n\tdef commit(self):\n\t\tconfig = configparser.ConfigParser()\n\t\tconfig_paths = [\n\t\t\tos.path.expanduser(\"~\") + \"/.s2db/s2db.ini\",\n\t\t\t'/etc/s2db/s2db.ini',\n\t\t\t'/etc/s2db.ini',\n\t\t\t'./s2db.ini'\n\t\t]\n\t\tfor config_path in config_paths:\n\t\t\tif config.read(config_path) != []:\n\t\t\t\tbreak\n\t\tdb_base = automap_base()\n\t\tdb_engine = sqlalchemy.create_engine(config['db']['insert'])\n\t\tdb_base.prepare(db_engine, reflect=True)\n\t\tdb_bin = db_base.classes.bin\n\t\tdb_bin2seq = db_base.classes.bin2seq\n\t\tdb_seq = db_base.classes.seq\n\t\t\n\t\tdb_session = Session(db_engine)\n\t\t\n\t\tdb_session.merge(db_bin(bin=self.payload_sha256,name=self.payload_name,ref=self.ref))\n\t\t\n\t\tfor s in self.seq:\n\t\t\tdb_session.merge(db_bin2seq(bin=self.payload_sha256,seq=s['seq']))\n\t\t\tdb_session.merge(db_seq(seq=s['seq'],type=s['type'],rep=s['rep']))\n\n\t\tdb_session.commit()\n\nif __name__ == '__main__':\n\ts = Sequencer.factory(sys.argv[1])\n\tprint(s.NAME)\n\tprint(s.payload_name)\n\tprint(\"Sequencing...\")\n\tseq = s.sequence()\n\tprint(\"Committing...\")\n\ts.commit()\n#\tfor s in seq:\n#\t\tprint(s['type']+':'+s['rep'])\n\n","sub_path":"sequencer/sequencer.py","file_name":"sequencer.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"168574010","text":"from datetime import datetime\n#import time\n\nHour = 15\nMin = 9\n\ndef now():\n import Email\n\nwhile True:\n now = datetime.now()\n H = now.strftime(\"%H\")\n M = now.strftime(\"%M\")\n if int(H) == Hour:\n if int(M) == Min:\n now()\n #time.sleep(65)\n","sub_path":"FoodBot/mailTime.py","file_name":"mailTime.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"325037557","text":"#!usr/bin/env python3\n\n\n# function that returns the joint entropy of two discrete random variables\ndef joint_entropy(pmf): # pdf is the joint p.d.f. of the discrete random variables\n\n from numpy import log2 as log2\n import numpy as np\n\n joint_ent = 0\n dimensions = np.shape(pmf) # Number of rows and columns of the joint pdf matrix\n\n for i in range(0, dimensions[0]): # Rows of matrix\n for j in range(0, dimensions[1]): # Columns of matrix\n if pmf[i][j] != 0: # If joint probability is zero there is no need to calculate\n joint_ent -= pmf[i][j] * log2(pmf[i][j])\n\n return joint_ent\n\n\n","sub_path":"joint.py","file_name":"joint.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"381068214","text":"# 40(10+20+10)个像素为蛇的宽度\n# 每一节为20*20 = 400 个像素\n# 每吃一个食物 增加 20*20\n# 地图边长:600*600 = 360000\n# 当前方向:\n# 0:水平向右\n# 1:水平向左\n# 3:竖直向上\n# 4:竖直向下\n\n# 绘制与消除\n# 0: 绘制\n# 1:消除\n\nimport cv2\nimport time\nimport numpy as np\nimport random\nfrom operator import itemgetter\n\n\nbody_section_width = 20\nbody_section_height = 20\nwin_back = np.zeros((200, 200), np.uint8)\ndirection_snake = 0\nflag = True\nflag_food = False\nfood_direction = []\nflag_get_food = False\npoint = 0\ndistance_list = []\nflag_tail_cut = True\n\nsnake_body = [(10, 10), (10, 30), (10, 50)]\n\n\ndef draw_snake_init():\n\n for center in snake_body:\n clear_and_draw_body(center, 0)\n\n\ndef draw_snake():\n\n global snake_body\n clear_and_draw_body(snake_body[-1], 0)\n\n\ndef clear_and_draw_food(center, isDraw):\n\n global body_section_height, body_section_width, win_back\n\n center_x = center[0]\n center_y = center[1]\n\n for x in range(int(center_x - body_section_width / 2), int(center_x + body_section_width / 2)):\n for y in range(int(center_y - body_section_height / 2), int(center_y + body_section_height / 2)):\n if isDraw == 0:\n win_back[x][y] = 255\n elif isDraw == 1:\n win_back[x][y] = 0\n\n\ndef clear_and_draw_body(center, isDraw):\n\n global body_section_height, body_section_width, win_back, flag, food_direction, flag_get_food, flag_food, point, \\\n flag_tail_cut\n\n center_x = center[0]\n center_y = center[1]\n\n for x in range(int(center_x - body_section_width / 2), int(center_x + body_section_width / 2)):\n for y in range(int(center_y - body_section_height / 2), int(center_y + body_section_height / 2)):\n if isDraw == 0:\n if x == -1 or x >= 200 or y == -1 or y >= 200 or tail_meet():\n flag = False\n break\n else:\n if abs(food_direction[0]-x) < 10 and abs(food_direction[1]-y) < 10:\n flag_get_food = True\n flag_food = False\n clear_and_draw_food(food_direction, 1)\n clear_and_draw_food(center, 0)\n win_back[x][y] = 255\n elif isDraw == 1:\n win_back[x][y] = 0\n if not flag:\n break\n\n\ndef tail_meet():\n\n global snake_body\n\n x_pos = snake_body[-1][0]\n y_pos = snake_body[-1][1]\n\n for sec in snake_body[:-2]:\n if abs(sec[0]-x_pos) < 18 and abs(sec[1]-y_pos) < 18:\n return True\n return False\n\n\ndef update(snake):\n\n global direction_snake, body_section_height, body_section_width, flag_get_food, flag_tail_cut\n\n if flag_tail_cut:\n clear_and_draw_body(snake[0], 1)\n del snake[0]\n\n if direction_snake == 0: # right\n snake.append((snake[-1][0], snake[-1][1]+body_section_width))\n elif direction_snake == 1: # left\n snake.append((snake[-1][0], snake[-1][1]-body_section_width))\n elif direction_snake == 3: # up\n snake.append((snake[-1][0]-body_section_height, snake[-1][1]))\n elif direction_snake == 4: # down\n snake.append((snake[-1][0]+body_section_height, snake[-1][1]))\n\n\ndef check_input_effect(input_key):\n\n global direction_snake\n\n key = sign_change(input_key)\n\n if abs(direction_snake - key) == 1 or direction_snake - key == 0:\n return False\n else:\n return True\n\n\ndef check_food_effect(center):\n\n global snake_body\n\n for i in range(len(snake_body)):\n if center in snake_body:\n return False\n return True\n\n\ndef food_create():\n\n global flag_food, food_direction, flag_get_food, point, snake_body\n\n is_effect = False\n\n if not flag_food:\n while not is_effect:\n food_x = random.randrange(10, 200, 20)\n food_y = random.randrange(10, 200, 20)\n is_effect = check_food_effect((food_x, food_y))\n\n clear_and_draw_food((food_x, food_y), 0)\n flag_food = True\n # if food_direction:\n # snake_body.append(food_direction)\n food_direction = [food_x, food_y]\n if flag_get_food:\n point += 1\n print(point)\n flag_get_food = False\n\n\ndef sign_change(key):\n if key == ord('d'): # right\n return 0\n elif key == ord('a'): # left\n return 1\n elif key == ord('w'): # up\n return 3\n elif key == ord('s'): # down\n return 4\n\n\ndef fail_sign():\n\n global snake_body, win_back, flag, direction_snake\n\n if direction_snake == 0: # right\n if snake_body[-1][1] == 190:\n flag = False\n elif direction_snake == 1: # left\n if snake_body[-1][1] == 10:\n flag = False\n elif direction_snake == 3: # up\n if snake_body[-1][0] == 10:\n flag = False\n elif direction_snake == 4: # down\n if snake_body[-1][0] == 190:\n flag = False\n\n\ndef ai_scanning(head_pos, direction):\n x_pos = head_pos[0]\n y_pos = head_pos[1]\n if y_pos == 190 and direction == 0:\n return ord('s')\n elif y_pos == 190 and direction == 4:\n return ord('a')\n elif y_pos == 30 and direction == 1 and x_pos < 170:\n return ord('s')\n elif y_pos == 30 and direction == 4:\n return ord('d')\n elif x_pos >= 170 and y_pos <= 20 and direction == 1:\n return ord('w')\n elif x_pos == 10 and y_pos == 10 and direction == 3:\n return ord('d')\n\n\ndef direction_find(food_pos, check_pos, dimension):\n if food_pos[0]-check_pos[0][dimension] == 0:\n return 0\n elif food_pos[dimension]-check_pos[0][dimension] > 0:\n return 1\n else:\n return -1\n\n\ndef pos_effect_check(pos):\n if 0 <= pos[0] <= 9 and 0 <= pos[1] <= 9:\n return True\n else:\n return False\n\n\ndef find_three_direction(snake, food):\n pos_may = []\n if (snake[-1][0], snake[-1][1]+20) not in snake and 10 <= snake[-1][1]+20 <= 190:\n pos_may.append((snake[-1][0], snake[-1][1]+20, 'r',\n (snake[-1][0] - food[0])**2 + (snake[-1][1]+20 - food[1])**2))\n if (snake[-1][0]+20, snake[-1][1]) not in snake and 10 <= snake[-1][0]+20 <= 190:\n pos_may.append((snake[-1][0]+20, snake[-1][1], 'd',\n (snake[-1][0]+20 - food[0])**2 + (snake[-1][1] - food[1])**2))\n if (snake[-1][0], snake[-1][1]-20) not in snake and 10 <= snake[-1][1]-20 <= 190:\n pos_may.append((snake[-1][0], snake[-1][1]-20, 'l',\n (snake[-1][0] - food[0])**2 + (snake[-1][1]-20 - food[1])**2))\n if (snake[-1][0]-20, snake[-1][1]) not in snake and 10 <= snake[-1][1]-20 <= 190:\n pos_may.append((snake[-1][0]-20, snake[-1][1], 'u',\n (snake[-1][0]-20 - food[0])**2 + (snake[-1][1] - food[1])**2))\n return pos_may\n\n\ndef fictitious_snake(snake, pos, food):\n fic_snake = []\n for i in range(len(snake)):\n fic_snake.append(snake[i])\n fic_snake.append(pos)\n del fic_snake[0]\n if not find_three_direction(fic_snake, food):\n return False\n else:\n return True\n\n\ndef find_best(pos_list, snake_, food_pos):\n # if not pos_list:\n # cv2.waitKey(0)\n\n pos_list = sorted(pos_list, key=itemgetter(3))\n pos_best = pos_list[0]\n for pos in pos_list:\n if fictitious_snake(snake_, pos, food_pos):\n pos_best = pos\n break\n\n return pos_best\n\n\ndef find_return_key(next_pos):\n if next_pos[2] == 'r':\n return ord('d')\n elif next_pos[2] == 'l':\n return ord('a')\n elif next_pos[2] == 'u':\n return ord('w')\n elif next_pos[2] == 'd':\n return ord('s')\n\n\ndef ai_path_search(snake, food_pos):\n\n pos_choice_list = find_three_direction(snake, food_pos)\n pos_best = find_best(pos_choice_list, snake, food_pos)\n\n return find_return_key(pos_best)\n\n\ndef can_straight_go(snake, food):\n head_x = snake[-1][0]\n head_y = snake[-1][1]\n food_x = food[0]\n food_y = food[1]\n num = 0\n if head_x != food_x:\n line_k = (head_y-food_y)/(head_x-food_x)\n line_b = (head_y*food_x-food_y*head_x)/(food_x-head_x)\n for x in range(head_x, food_x):\n y = line_k * x + line_b\n for i in range(len(snake)-1):\n if pow(x-snake[i][0], 2) + pow(y-snake[i][1], 2) < 100:\n num += 1\n else:\n for y in range(head_y, food_y):\n for i in range(len(snake)-1):\n if pow(head_x-snake[i][0], 2) + pow(y-snake[i][1], 2) < 100:\n num += 1\n\n if num == 0:\n return True\n else:\n return False\n\n\ndef find_distance(food):\n\n global distance_list\n\n distance_list.clear()\n food_pos_standard = (food[0] // 20, food[1] // 20)\n for x in range(10):\n for y in range(10):\n distance = abs(food_pos_standard[0]-x) + abs(food_pos_standard[1]-y)\n distance_list.append((x, y, distance))\n\n\ndef find_near(pos, snake):\n list_all = []\n if 0 <= pos[0]-1 <= 8 and (pos[0]-1, pos[1]) not in snake:\n list_all.append((pos[0]-1, pos[1]))\n if 0 <= pos[0]+1 <= 9 and (pos[0]+1, pos[1]) not in snake:\n list_all.append((pos[0]+1, pos[1]))\n if 0 <= pos[1]+1 <= 9 and (pos[0], pos[1]+1) not in snake:\n list_all.append((pos[0], pos[1]+1))\n if 0 <= pos[1]-1 <= 8 and (pos[0], pos[1]-1) not in snake:\n list_all.append((pos[0], pos[1]-1))\n return list_all\n\n\ndef output_list(final_pos, searched_list, head, food):\n output = [find_key(final_pos)]\n output_path = [final_pos]\n search_node = final_pos\n flag_run = True\n if final_pos[0] == food and final_pos[1] == head:\n return [find_key((food, head))]\n while flag_run:\n for node in searched_list:\n if node[0] == search_node[1]:\n output_path.append(node)\n output.append(find_key(node))\n if node[1] == head:\n flag_run = False\n search_node = node\n break\n return output\n\n\ndef find_key(list_son_father):\n head = list_son_father[1]\n next_pos = list_son_father[0]\n if head[0] == next_pos[0]:\n if head[1] > next_pos[1]:\n return ord('a')\n else:\n return ord('d')\n else:\n if head[0] > next_pos[0]:\n return ord('w')\n else:\n return ord('s')\n\n\n# def whether_searched(check_node, searched_list):\n\n\ndef bfs_search_path(snake, food, senter):\n search_list = []\n snake_standard = []\n searched = []\n food_standard = (food[0]//20, food[1]//20)\n for body in range(len(snake)):\n snake_standard.append((snake[body][0]//20, snake[body][1]//20))\n if senter == 1:\n del snake_standard[0]\n near = find_near(snake_standard[-1], snake_standard)\n for i in near:\n node = [i, snake_standard[-1]]\n search_list.append(node)\n while search_list:\n check_pos = search_list[0]\n if check_pos[0] == food_standard:\n searched.append(check_pos)\n output_ = output_list(check_pos, searched, snake_standard[-1], food_standard)\n return output_\n else:\n near = find_near(check_pos[0], snake_standard)\n for i in near:\n node = [i, check_pos[0]]\n if node not in searched and node not in search_list:\n search_list.append(node)\n del search_list[0]\n searched.append(check_pos)\n return []\n\n\ndef key_change(key):\n\n global direction_snake\n\n if key == ord('d'): # right\n if check_input_effect(key):\n direction_snake = sign_change(key)\n elif key == ord('a'): # left\n if check_input_effect(key):\n direction_snake = sign_change(key)\n elif key == ord('w'): # up\n if check_input_effect(key):\n direction_snake = sign_change(key)\n elif key == ord('s'): # down\n if check_input_effect(key):\n direction_snake = sign_change(key)\n\n\n'''\nfood_create()\ndraw_snake_init()\nloop = 0\nwhile flag:\n if loop != 0:\n draw_snake()\n cv2.imshow('win', win_back)\n update(snake_body)\n path = bfs_search_path(snake_body, food_direction)\n if not path:\n cv2.waitKey(0)\n path = [ord('s'), ord('s'), ord('s'), ord('s'), ord('s')]\n for i in range(-1, -len(path) - 1, -1):\n k = cv2.waitKey(1) & 0xFF\n if k == ord('q'):\n flag = False\n k = path[i]\n print(k)\n key_change(k)\n time.sleep(0.05)\n cv2.imshow('win', win_back)\n update(snake_body)\n loop += 1\n if loop != 0:\n draw_snake()\n cv2.imshow('win', win_back)\n update(snake_body)\n k = cv2.waitKey(1) & 0xFF\n if k == ord('q'):\n flag = False\n food_create()\n\n'''\n\n\ndef ai_logic_method_get_food(snake, food):\n food_standard = [food[0]//20, food[1]//20]\n snake_standard = []\n output_path = []\n flag_arrive_right = False\n flag_arrive_bottom = False\n flag_arrive_left = False\n flag_arrive_top = False\n for body in range(len(snake)):\n snake_standard.append((snake[body][0]//20, snake[body][1]//20))\n distance_to_right = 9 - snake_standard[-1][1]\n while not flag_arrive_right:\n if distance_to_right > 0:\n output_path.append(ord('d'))\n distance_to_right -= 1\n else:\n flag_arrive_right = True\n output_path.append(ord('s'))\n\n x_distance = food_standard[0] - 1\n y_distance = 9 - food_standard[1]\n if x_distance >= 0:\n for i in range(x_distance):\n output_path.append(ord('s'))\n for i in range(y_distance):\n output_path.append(ord('a'))\n else:\n for i in range(8):\n output_path.append(ord('s'))\n for i in range(9):\n output_path.append(ord('a'))\n for i in range(9):\n output_path.append(ord('w'))\n\n return output_path\n\n\ndef find_body_in_left_edge(snake):\n section_num = 0\n for i in range(len(snake)):\n if snake[i][1] == 0:\n break\n else:\n section_num += 1\n return section_num\n\n\ndef ai_logic_method_return_init(snake, direction):\n output_path = []\n section_num = 0\n snake_standard = []\n for body in range(len(snake)):\n snake_standard.append((snake[body][0]//20, snake[body][1]//20))\n begin_x = snake_standard[-1][0]\n begin_y = snake_standard[-1][1]\n check_pos = (begin_x, 0)\n\n for i in range(len(snake_standard)):\n if snake_standard[i] != check_pos:\n section_num += 1\n else:\n break\n\n if check_pos in snake_standard and section_num >= snake_standard[-1][1]-1 and direction == 1 and \\\n snake_standard[-1] != check_pos and section_num < len(snake_standard)-1:\n need_rows = (section_num-snake_standard[-1][1]+1)//7+1\n operate_num = 0\n print(need_rows)\n for i in range(snake_standard[-1][1]-1):\n output_path.append(ord('a'))\n\n for i in range(need_rows // 2+1):\n output_path.append(ord('s'))\n for q in range(7):\n output_path.append(ord('d'))\n output_path.append(ord('s'))\n for q in range(7):\n output_path.append(ord('a'))\n operate_num += 2\n # if need_rows % 2 != 0:\n # output_path.append(ord('s'))\n # for q in range(9):\n # output_path.append(ord('d'))\n # output_path.append(ord('s'))\n # output_path.append(ord('a'))\n # operate_num += 2\n output_path.append(ord('a'))\n for q in range(snake_standard[-1][0]+operate_num):\n output_path.append(ord('w'))\n elif snake_standard[0][0] < snake_standard[-1][0] and find_body_in_left_edge(snake_standard) > snake_standard[-1][1]:\n print('yes')\n for i in range(snake_standard[-1][1]):\n output_path.append(ord('a'))\n for i in range(snake_standard[-1][0]):\n output_path.append(ord('w'))\n else:\n for i in range(snake_standard[-1][1]):\n output_path.append(ord('a'))\n for i in range(snake_standard[-1][0]):\n output_path.append(ord('w'))\n return output_path\n\n\nfood_create()\ndraw_snake_init()\nloop = 0\nwhile flag:\n # if can_straight_go(snake_body, food_direction):\n # print(1)\n # path = bfs_search_path(snake_body, food_direction, 0)\n # else:\n # print(2)\n # path = bfs_search_path(snake_body, snake_body[0], 1)\n # if path:\n # print(path)\n # print(food_direction, snake_body[-1])\n path = ai_logic_method_get_food(snake_body, food_direction)\n path_num = len(path)\n # if path_num == 0:\n # print('path_num = 0')\n # print(food_direction, snake_body[-1])\n # cv2.waitKey(0)\n # flag = False\n while path_num > 0 and flag:\n cv2.imshow('win', win_back)\n k = cv2.waitKey(1) & 0xFF\n if k == ord('q'):\n flag = False\n # k = ai_scanning(snake_body[-1], direction_snake)\n # k = bfs_search_path(snake_body, food_direction)\n k = path[-path_num]\n key_change(k)\n update(snake_body)\n flag_tail_cut = True\n draw_snake()\n time.sleep(0.05)\n loop += 1\n path_num -= 1\n flag_tail_cut = False\n cv2.imshow('win', win_back)\n path = ai_logic_method_return_init(snake_body, direction_snake)\n path_num = len(path)\n while path_num > 0 and flag:\n cv2.imshow('win', win_back)\n k = cv2.waitKey(1) & 0xFF\n if k == ord('q'):\n flag = False\n # k = ai_scanning(snake_body[-1], direction_snake)\n # k = bfs_search_path(snake_body, food_direction)\n k = path[-path_num]\n key_change(k)\n update(snake_body)\n flag_tail_cut = True\n draw_snake()\n time.sleep(0.05)\n loop += 1\n path_num -= 1\n food_create()\ncv2.waitKey(0)\nprint('you are false!')\ncv2.destroyAllWindows()\n\n'''\ndef update_straight():\n global map_begin, center_pos_head, center_pos_tail, direct\n if direct == 0:\n for i in range(10):\n for q in range(20):\n map_begin[center_pos_head[0]-10+q][center_pos_head[1]+i] = [255, 255, 255]\n map_begin[center_pos_tail[0]-10+q][center_pos_tail[1]+i] = [0, 0, 0]\n center_pos_head = [center_pos_head[0], center_pos_head[1]+10]\n center_pos_tail = [center_pos_tail[0], center_pos_tail[1]+10]\n elif direct == 1:\n for i in range(10):\n for q in range(20):\n map_begin[center_pos_head[0]-10+q][center_pos_head[1]-i] = [255, 255, 255]\n map_begin[center_pos_tail[0]-10+q][center_pos_tail[1]-i] = [0, 0, 0]\n center_pos_head = [center_pos_head[0], center_pos_head[1]-10]\n center_pos_tail = [center_pos_tail[0], center_pos_tail[1]-10]\n elif direct == 2:\n for i in range(10):\n for q in range(20):\n map_begin[center_pos_head[0]-i][center_pos_head[1]-10+q] = [255, 255, 255]\n map_begin[center_pos_tail[0]-i][center_pos_tail[1]-10+q] = [0, 0, 0]\n center_pos_head = [center_pos_head[0]-10, center_pos_head[1]]\n center_pos_tail = [center_pos_tail[0]-10, center_pos_tail[1]]\n elif direct == 3:\n for i in range(10):\n for q in range(20):\n map_begin[center_pos_head[0]+i][center_pos_head[1]-10+q] = [255, 255, 255]\n map_begin[center_pos_tail[0]+i][center_pos_tail[1]-10+q] = [0, 0, 0]\n center_pos_head = [center_pos_head[0]+10, center_pos_head[1]]\n center_pos_tail = [center_pos_tail[0]+10, center_pos_tail[1]]\n\n\nmap_begin = cv2.imread('D:/map.jpg')\ncenter_pos_head = [20, 40]\ncenter_pos_tail = [20, 0]\ndirect = 0\nwhile 1:\n update_straight()\n cv2.imshow('map', map_begin)\n if cv2.waitKey(50) & 0xFF == ord('q'):\n break\n time.sleep(0.005)\ncv2.destroyAllWindows()\n'''","sub_path":"Retro_Snaker_win.py","file_name":"Retro_Snaker_win.py","file_ext":"py","file_size_in_byte":20041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"213675596","text":"import logging\nfrom normality import guess_file_encoding\n\nfrom ingestors.exc import ProcessingException\n\nlog = logging.getLogger(__name__)\n\n\nclass EncodingSupport(object):\n \"\"\"Decode the contents of the given file as plain text by guessing its\n encoding.\"\"\"\n\n DEFAULT_ENCODING = 'utf-8'\n\n def detect_stream_encoding(self, fh):\n return guess_file_encoding(fh, self.DEFAULT_ENCODING)\n\n def read_file_decoded(self, file_path):\n with open(file_path, 'rb') as fh:\n encoding = self.detect_stream_encoding(fh)\n body = fh.read()\n\n if encoding != self.DEFAULT_ENCODING:\n log.info(\"Decoding [%s] as: %s\", self.result, encoding)\n try:\n body = body.decode(encoding, 'replace')\n if not self.result.encoding:\n self.result.encoding = encoding\n return body\n except UnicodeDecodeError as ude:\n raise ProcessingException('Error decoding file [%s]: %s' %\n (encoding, ude))\n","sub_path":"ingestors/support/encoding.py","file_name":"encoding.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"135721245","text":"# coding: utf-8\ndef cond_probs(training_data):\n # c_probs will hold our conditional probabilities\n c_probs = collections.defaultdict(lambda: collections.defaultdict(float)) \n # docs_with_word is a mapping from a class to a mapping from a word to number of documents of that category the word appeared in \n docs_with_word = collections.defaultdict(lambda: collections.defaultdict(int)) \n # tot_words is a mapping from a class to the total number of words documents of that class\n tot_words = collections.defaultdict(int) \n \n # first get the counts of words in documents of a class and total word count per class\n for doc,c in training_data:\n for word in doc:\n docs_with_word[c][word] += 1\n tot_words[c] += 1\n \n # now compute the conditional probabilities\n for c in docs_with_word.keys(): \n for word in docs_with_word[c].keys():\n c_probs[c][word] = docs_with_word[c][word] / tot_words[c]\n return c_probs\n \nc_ps = cond_probs(train_data)\n\nc_ps[\"weather\"][\"today\"]\n","sub_path":"Workshops/Topic 2/solutions/cond_probs.py","file_name":"cond_probs.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"69898520","text":"from sockjs.tornado import handler\nfrom sockjs.tornado import transport\n\n\n__all__ = [\n 'get_urls',\n]\n\n\nSESSION_PREFIX_URL = r'/[^/.]+/(?P[^/.]+)'\n\n# no prefix required\nSTATIC_HANDLERS = (\n ('?', handler.GreetingsHandler),\n ('chunking_test', handler.ChunkingTestHandler),\n ('info', handler.InfoHandler),\n ('iframe[0-9-.a-z_]*.html', handler.IFrameHandler),\n ('websocket', transport.RawWebSocketTransport),\n)\n\n# requires the SESSION_PREFIX_URL prefix\nSEND_HANDLERS = (\n ('xhr_send', transport.XhrSendTransport),\n ('jsonp_send', transport.JSONPSendTransport),\n)\n\n# if enabled, requires the SESSION_PREFIX_URL prefix\nTRANSPORTS = {\n 'websocket': transport.WebSocketTransport,\n 'xhr': transport.XhrPollingTransport,\n 'xhr_streaming': transport.XhrStreamingTransport,\n 'jsonp': transport.JSONPTransport,\n 'eventsource': transport.EventSourceTransport,\n 'htmlfile': transport.HtmlFileTransport,\n}\n\n\ndef make_url(*args):\n return '/' + r'/'.join(args) + '$'\n\n\ndef get_urls(prefix, disabled_transports, **kwargs):\n prefix = prefix.lstrip('/')\n base = prefix + SESSION_PREFIX_URL\n\n urls = []\n\n for uri, handler_class in STATIC_HANDLERS:\n urls.append((\n make_url(prefix, uri),\n handler_class,\n kwargs\n ))\n\n for fragment, handler_class in SEND_HANDLERS:\n urls.append((\n make_url(base, fragment),\n handler_class,\n kwargs\n ))\n\n for transport_name, handler_class in TRANSPORTS.items():\n if transport_name in disabled_transports:\n continue\n\n urls.append((\n make_url(base, transport_name),\n handler_class,\n kwargs\n ))\n\n return urls\n","sub_path":"sockjs/tornado/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"420377432","text":"import glob as gb\nimport re\nfrom tqdm import tqdm\n\n\n\ndef set_data(dataset):\n dataset = dataset.upper()\n if dataset == \"SINASC\":\n path = \"/home/rodriguesms/Documents/Data_lake/Raw/Bancos_SINASC/CSV_format/\"\n pattern = \"DN*[A-Z][A-Z]\"\n elif dataset == \"SIM\":\n path = \"/home/rodriguesms/Documents/Data_lake/Raw/Bancos_SIM/CSV_format/\"\n pattern = \"DO*[A-Z][A-Z]\"\n elif dataset == \"AIH\":\n path = \"/home/rodriguesms/Documents/Data_lake/Raw/Bancos_AIH/CSV_format/\"\n pattern = \"RD*[A-Z][A-Z]\"\n return([path, pattern])\n\n\n#Define function to point files\ndef select_files(dataset, state = False, years = False, extension = \".csv\"):\n \"\"\"\n This function is used to create a list of datasets based on one of\n the brazilian information system e.g. AIH, SINASC, SINAN, SIM\n \"\"\"\n path = dataset[0]\n pattern = dataset[1]\n results = {}\n if re.search(r\"_AIH\", path):\n for year in years:\n if pattern:\n files = gb.glob(path + pattern + str(year)[2:4] + \"*\" + extension)\n results.update({year:files})\n return(results)\n else:\n try:\n for year in years:\n if pattern:\n files = gb.glob(path + pattern + \"*\" + str(year) + \"*\" + extension)\n else:\n files = gb.glob(path + \"*\" + extension)\n results.update({year:files})\n return(results)\n except:\n if pattern:\n files = gb.glob(path + pattern + \"*\" + extension)\n else:\n files = gb.glob(path + \"*\" + extension)\n return(files)","sub_path":"loadData.py","file_name":"loadData.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"80175483","text":"import os\r\nimport sys\r\n\r\nroot_directory = '/scratch/mtcraig_root/mtcraig1/shared_data/elccJobs/' + sys.argv[1]\r\n\r\ndef error_handling():\r\n\r\n global root_directory \r\n\r\n if root_directory[-1] != '/':\r\n root_directory += '/'\r\n\r\n if not os.path.exists(root_directory):\r\n raise RuntimeError('Invalid root directory\\n' + root_directory)\r\n\r\n if os.path.exists('elcc_job.txt'):\r\n os.system('rm elcc_job.txt')\r\n\r\ndef add_job(parameters):\r\n\r\n global root_directory\r\n\r\n parameter_string = root_directory\r\n\r\n for key in parameters:\r\n parameter_string = parameter_string + ' ' + str(key) + ' ' + str(parameters[key])\r\n \r\n with open('elcc_job.txt','a') as f:\r\n f.write('python -u elcc_master.py ' + parameter_string + '\\n')\r\n\r\ndef main():\r\n\r\n parameters = dict()\r\n\r\n # universal parameters\r\n\r\n parameters['year'] = 2018\r\n parameters['region'] = 'PACE'\r\n parameters['nameplate'] = 1000\r\n parameters['iterations'] = 10000\r\n parameters['generator_type'] = 'solar'\r\n parameters['generator_storage'] = True\r\n\r\n # variable parameters\r\n add_job(parameters)\r\n\r\n os.system('sbatch elcc_batch_job.sbat')\r\n\r\n print('Jobs submitted')\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n error_handling()\r\n main()","sub_path":"src/elcc.py","file_name":"elcc.py","file_ext":"py","file_size_in_byte":1272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"41252787","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2018/3/9 下午12:27\n# @Author : zhujinghui \n# @site : \n# @File : abc.py\n# @Software: PyCharm\nimport requests\nimport json\nfrom highcharts import Highstock\n\n\ndef creatChart(data,symbol='test'):\n filename = \"%s_dayk\" % symbol\n\n ohlc = data['volume_usd']\n volume = data['market_cap_by_available_supply']\n\n H = Highstock()\n\n groupingUnits = [\n ['day', [1]]\n ]\n\n\n\n options = {\n 'rangeSelector': {\n 'selected': 4\n },\n\n 'chart': {\n 'zoomType': 'x',\n 'reflow': True,\n 'height': 900\n },\n\n 'tooltip': {\n 'style': {'color': '#3E576F','fontSize': '30px'}\n },\n\n 'title': {\n 'text': 'Total Market Capitalization'\n },\n\n 'subtitle': {\n 'text': filename\n },\n\n 'xAxis': [\n {\n 'labels': {\n # 'align': 'left',\n # 'x': 3,\n 'style': {'color': '#3E576F', 'fontSize': '20px'}\n }\n # ,\n # 'title': {\n # 'text': 'Market Cap',\n #\n # },\n # 'height': '80%',\n # 'lineWidth': 2\n\n }\n ],\n\n\n 'yAxis': [\n {\n 'labels': {\n 'align': 'left',\n 'x': 3,\n 'style':{'color': '#3E576F','fontSize': '20px'}\n },\n 'title': {\n 'text': 'Market Cap',\n\n },\n 'height': '80%',\n 'lineWidth': 2\n\n }\n\n\n\n # ,\n\n # {\n # 'labels': {\n # 'align': 'right',\n # 'x': -3\n # },\n # 'title': {\n # 'text': ' 24h Vol'\n # },\n # 'top': '65%',\n # 'height': '40%',\n # 'offset': 0,\n # 'lineWidth': 2\n # }\n ],\n\n\n }\n\n H.add_data_set(ohlc, 'line', 'market_cap', dataGrouping = {\n 'units': groupingUnits\n }\n )\n\n # H.add_data_set(volume, 'column', 'Volume', yAxis = 1, dataGrouping = {\n # 'units': groupingUnits\n # }\n # )\n\n H.set_dict_options(options )\n\n H.save_file(filename)\n\n print(\"===--- Completed ---===\")\n\n\n\nurl = \"https://graphs2.coinmarketcap.com/global/marketcap-total/1367174820000/1520567220000/\"\n\ntext = requests.get(url).text\n\ndata_json = json.loads(text)\n\n# print(data_json)\n\ncreatChart(data_json)","sub_path":"ttt/abc.py","file_name":"abc.py","file_ext":"py","file_size_in_byte":2690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"416069639","text":"# import json\n# from pprint import pprint\n#\n# data = None\n# with open('test_json.json') as file:\n# data = json.load(file)\n# pprint(data, indent=4)\n# print(type(data))\n#\n# print(data['widget']['debug'])\n#\n# data['widget']['debug'] = 'off'\n# print(data['widget']['debug'])\n#\n# with open('test_json.json', 'w') as file:\n# json.dump(data, file, indent=4)\n\n\n# with open('test_json.json') as file:\n# print(file.read())\n# print(type(file.read()))\n# import yaml\n#\n# data = None\n# with open('test_yaml.yaml') as file:\n# data = yaml.safe_load(file)\n# print(data)\n#\n# data['laptop']['CPU'] = 16\n# with open('test_yaml.yaml', 'w') as file:\n# yaml.safe_dump(data, file)\n\n\n# CSV\n# import csv\n#\n# data_list = [[1, 2], 'kjsndkjcv', [3, 4]]\n# with open('test.csv', 'w') as file:\n# writer = csv.writer(file)\n# writer.writerows(data_list)\n\n# для exel xlsxwriter\nimport xlsxwriter\n\nheaders = ('ID', 'created_at', 'updated_at', 'vin', 'color', 'name', 'car_number', 'model', 'make',\n 'production_year', 'status')\nworkbook = xlsxwriter.Workbook('file.xlsx')\nwork_sheet = workbook.add_worksheet('list1')\ncell_format = workbook.add_format({'bold': True})\nworksheet = workbook.add_worksheet()\ncol = 0\nfor header in headers:\n worksheet.set_column(0, col, 30)\n worksheet.write(0, col, header, cell_format)\n col+=1\nworkbook.close()\n\n\n","sub_path":"lk5/class_work.py","file_name":"class_work.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"13411026","text":"import numpy as np\nimport scipy.interpolate as interpolate\nimport matplotlib.pyplot as plt\n\nclass imported_data(object):\n\n def verwerking(self,file):\n\n col = []\n cols = []\n lines = []\n with open('/home/jesse/Dropbox/projects/PropellerAnalysis/{0}.csv'.format(file)) as csvfile: # importeer data\n for row in csvfile:\n line = row.split(';')\n lines.append(line)\n for n in range(0,len(lines[0])):\n for line in lines[3:]:\n try:\n col.append(float(line[n]))\n except ValueError:\n continue\n cols.append(col)\n col = []\n J = []\n KT = []\n KQ = []\n k = 0\n for n in range(0,int(len(cols)/3)): # rangschik data\n J.append(cols[k])\n KT.append(cols[k+1])\n KQ.append(cols[k+2])\n k += 3\n J,KT,KQ = J[-1],KT[-1],KQ[-1]\n Interpol = []\n\n f_kt = interpolate.UnivariateSpline(J, KT, k = 1) # interpoleer data van J, KT\n f_kq = interpolate.UnivariateSpline(J, KQ, k = 1) # ' KQ\n Interpol.append(f_kt)\n Interpol.append(f_kq)\n\n j = np.linspace(J[0],J[-1],1000)\n\n def efficientie(j):\n return j/(np.pi*2)*f_kt(j)/f_kq(j)\n\n return efficientie\n\ninstance = imported_data()\nefficientie = instance.verwerking('data8')","sub_path":"strategy/propeff.py","file_name":"propeff.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"264896348","text":"from django.http import Http404, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom exchange.models import Item, Notification\nfrom stickies.models import Sticky\nfrom admin_extension.models import Info, Profile\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom string import strip\nimport settings\nfrom django.utils.html import strip_tags\n\n\n# site url, used for redirecting to homepage\nURL = 'http://replay-project.net/'\n\ndef home(request):\n \"\"\" \n loads the home page - a login screen\n if the user isn't logged in, or a page\n displaying all the items if they are \n \"\"\"\n errors = []\n # handle log-in form\n if request.method == 'POST':\n if not request.POST.get('pwd', ''):\n errors.append('Enter a password.')\n if not request.POST.get('identity', ''):\n errors.append('Enter a username.')\n # if no errors found, authenticate and log in user\n if not errors:\n username = request.POST['identity']\n password = request.POST['pwd']\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n else:\n errors.append('Disabled account')\n else:\n errors.append('Wrong username or password')\n if request.user.is_authenticated():\n # show only Notifications that should appear\n notes = Notification.objects.filter(sent_to=request.user)\n visible_notes = [n for n in notes if n.appears()] \n # return list of items with Notifications associated with them\n noted_items = [n.item for n in visible_notes]\n # filter out deleted items\n items = [i for i in Item.objects.all() if not i.deleted]\n return render(request, 'all.html', { 'id' : request.user.id, 'items' : items, 'noted_items': noted_items })\n else:\n\t return render(request, 'index.html', { 'errors' : errors })\n\ndef get_client_ip(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n if x_forwarded_for:\n ip = x_forwarded_for.split(',')[-1].strip()\n else:\n ip = request.META.get('REMOTE_ADDR')\n return ip\n\ndef get_item(num):\n \"\"\" \n helper function to attempt to retrieve \n an item of a given id string, \n returning false if item's not found, \n or returning the item if it is found \n \"\"\"\n try:\n id = int(num)\n except ValueError:\n raise Http404()\n try:\n item = Item.objects.get(id=id)\n except ObjectDoesNotExist:\n item = False\n return item\n\ndef item(request, num):\n \"\"\" \n displays an item if it can be found, \n checking whether the user currently\n owns the item or not\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n # make sure inputted id is an integer\n item = get_item(num)\n sent = False\n notes = False\n if item:\n user = User.objects.get(id=item.offered_by.id)\n yours = request.user == user\n if yours:\n # retrieve notifications that belong to this user and refer to this item\n notes = Notification.objects.filter(sent_to=request.user).filter(item=item)\n # show only visible notes\n notes = [n for n in notes if n.appears()] \n else:\n user = False\n yours = False\n return render(request, 'view_item.html', {'user' : user, 'item' : item, 'yours' : yours, 'sent' : sent, 'notes': notes })\n\ndef edit(request, id):\n \"\"\"\n handles a form to edit the fields of\n an item, after ensuring the user \n is the owner of the item\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n item = get_item(id)\n errors = []\n edited = False\n edit = True\n if item:\n owner= User.objects.get(id=item.offered_by.id)\n yours = request.user == owner\n if request.method == 'POST':\n # ensure inputted text is within length limits\n if len(request.POST['name']) > 40:\n errors.append(\"Please enter a shorter name\")\n else:\n item.name = strip_tags(request.POST['name'])\n if len(request.POST['desc']) > 500:\n errors.append(\"Please enter a shorter description\")\n else:\n item.description = strip_tags(request.POST['desc'])\n if 'image' in request.FILES:\n file = request.FILES['image']\n # make sure that the file has an image-associated ending and is < 4.5 mb\n errors = errors + invalid(file)\n if not errors:\n item.image = file\n if not errors:\n item.save()\n edited = not bool(errors)\n edit = bool(errors)\n else:\n owner = False\n yours = False\n\n return render(request, 'view_item.html', { 'edit' : edit, 'owner' : owner, 'item' : item, 'yours' : yours, 'errors' : errors, 'edited' : edited })\n\ndef notify(request, id):\n \"\"\"\n creates a Notification object\n indicating interest in the \n given object\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n item = get_item(id)\n if item:\n owner= User.objects.get(id=item.offered_by.id)\n yours = request.user == owner\n visible = True\n note = Notification(sent_to = owner, sent_from = request.user, item = item, visible = visible)\n note.save()\n sent = True\n else:\n owner = False\n yours = False\n sent = False\n return render(request, 'view_item.html', {'user' : owner, 'item' : item, 'yours' : yours, 'sent' : sent })\n\ndef delete(request, id):\n \"\"\" \n if the user owns the item,\n changes the deleted attribute\n to true, making it not appear\n in item listings on the site\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n msg = ''\n item = get_item(id)\n if(item):\n if request.user == item.offered_by:\n item.deleted = True\n item.save()\n msg = item.name + \" deleted succesfully!\"\n return render(request, 'items_mypage.html', { 'msg' : msg, 'deleted' : True })\n\ndef user(request, num): \n \"\"\"\n displays the items of a requested user,\n showing a slightly different page\n if that user is you\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n try:\n id = int(num)\n except ValueError:\n raise Http404()\n try:\n user = User.objects.get(id=id)\n # filter out deleted items\n items = [i for i in Item.objects.filter(offered_by_id=num) if not i.deleted]\n yours = request.user.id == user.id\n except ObjectDoesNotExist:\n user = False\n items = False\n yours = False\n if not yours:\n return render(request, 'community_friends_2.html', { 'user' : user, 'id': user.id, 'items' : items })\n else: \n notes = Notification.objects.filter(sent_to=request.user)\n # filter out expired notifications\n visible_notes = [n for n in notes if n.appears()] \n # return a list of items with Notifications associated with them\n noted_items = [n.item for n in visible_notes]\n return render(request, 'items_mypage.html', { 'user' : user, 'items' : items, 'id': user.id, 'noted_items' : noted_items })\n\n\ndef invalid(file):\n \"\"\"\n helper function for image handling views \n to check file type (image) and size (<4.5mb)\n \"\"\"\n errors = []\n file_type = file.content_type.split('/')[0]\n # check file type and size against parameters in settings file\n if file_type not in settings.TASK_UPLOAD_FILE_TYPES:\n errors.append('File type is not supported (try uploading a jpg, png, or gif file)')\n if file._size > settings.TASK_UPLOAD_FILE_MAX_SIZE:\n errors.append('Your image is too big (max 4.5mb)')\n return errors\n\ndef add(request):\n \"\"\"\n handles a form to add an item to the\n database, ensuring all fields have\n been filled out and the image is valid\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n errors = []\n item = False\n form = True\n msg = ''\n desc = False\n name = False\n file = False\n if request.method == 'POST':\n if not request.POST.get('name', ''):\n errors.append('Enter a name.')\n else:\n name = strip_tags(request.POST['name'])\n if len(name) > 40:\n errors.append('Enter a shorter name (max 40 characters)')\n if not request.POST.get('desc', ''):\n errors.append('Enter a description.')\n else:\n desc = strip_tags(request.POST['desc'])\n if len(desc) > 500:\n errors.append('Enter a shorter description (max 500 characters)')\n if 'image' not in request.FILES:\n errors.append('Please submit an image')\n else:\n file = request.FILES['image']\n errors = errors + invalid(file)\n if not errors:\n item = Item(name=name, description=desc, offered_by = request.user, image=file )\n item.save()\n form = bool(errors)\n return render(request, 'add.html', { 'item' : item, 'id' : request.user.id, 'errors' : errors, 'form' : form, 'msg' : msg, 'desc':desc, 'name':name})\n\n\ndef logout_user(request):\n \"\"\"\n calls the built-in logout\n function to log out a user\n and redirects them to the \n homepage\n \"\"\"\n logout(request)\n return HttpResponseRedirect(URL) \n\ndef account(request):\n \"\"\"\n displays the account settings form,\n filling out every field with information\n already associated with the account.\n Upon submission, user and profile\n models are updated appropriately\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n user = request.user\n errors = []\n changed = False\n # handle form submission\n if request.method == 'POST':\n try:\n profile = user.profile\n except ObjectDoesNotExist:\n profile = Profile(user = user)\n profile.save()\n # validate image\n if 'image' in request.FILES:\n image = request.FILES['image']\n errors = errors + invalid(image)\n if not errors: \n profile.picture = image\n # check which fields have been filled out,\n # set model field to their values\n if request.POST.get('name', ''):\n user.username = request.POST['name']\n if request.POST.get('phone', ''):\n profile.telephone = request.POST['phone']\n if request.POST.get('email', ''):\n user.email = request.POST['email']\n if request.POST.get('firstname', ''):\n user.first_name = request.POST['firstname']\n if request.POST.get('lastname', ''):\n user.last_name = request.POST['lastname']\n if request.POST.get('address', ''):\n profile.address = request.POST['address']\n # change password if confirmation field is correct\n if request.POST.get('pwd', ''):\n pwd = request.POST['pwd']\n if request.POST.get('pwd_conf', ''):\n if pwd == request.POST['pwd_conf']:\n user.set_password(pwd)\n else:\n errors.append('Enter your new password again in confirmation password')\n else:\n errors.append('Enter a confirmation password')\n # save the User and Profile models if no errors have been found\n if not errors:\n user.save()\n profile.save()\n changed = True\n return render(request, 'accounts.html', {'user' : user, 'errors' : errors, 'changed' : changed} )\n\ndef community(request):\n \"\"\"displays all users\n on the site, linking to \n their user pages\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n return render(request, 'community.html', {'users' : User.objects.all() })\n\ndef ask(request, id=False):\n \"\"\"\n Displays all stickies,\n allows users to edit\n and add new ones\n \"\"\"\n if not request.user.is_authenticated():\n return HttpResponseRedirect(URL)\n else:\n errors = []\n text = False\n # if a sticky id is passed to the view, delete it if the user is the owner\n if id:\n sticky = Sticky.objects.get(id=id)\n # check that the user owns this sticky\n if request.user == sticky.writer:\n sticky.deleted = True\n sticky.save()\n if request.method == 'POST':\n if not request.POST.get('sticktext', ''):\n errors.append('Enter some text for your sticky.')\n else:\n text = request.POST['sticktext']\n if strip(text) == \"I would like...\":\n errors.append('Enter some text for your sticky.')\n if strip(text) == \"I'm looking for...\":\n errors.append('Enter some text for your sticky.')\n if len(text) > 70:\n errors.append('Your text is too long (max 70 characters)')\n if not errors:\n sticky = Sticky(writer = request.user, message = text) \n sticky.save()\n # filter out all deleted stickies\n stickies = [n for n in Sticky.objects.all() if not n.deleted] \n return render(request, 'ask.html', {'stickies' : stickies, 'errors' : errors, 'your_stickies' : Sticky.objects.filter(writer=request.user)})\n\n# views for flatpages, pulled from the Info model\ndef about(request):\n text = Info.objects.get(name=\"about\").text\n return render(request, 'info.html', {'text' : text, 'title' : \"About\"})\n\ndef contact(request):\n text = Info.objects.get(name=\"contact\").text\n return render(request, 'info.html', {'text' : text, 'title' : \"Contact\" })\n","sub_path":"play/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"318659998","text":"\ndef solve():\n s = list(input())\n s_sort = sorted(s)\n print(\"YES\" if s == s_sort else \"NO\")\n\n\ndef main():\n test = 1\n test = int(input())\n while test >= 1:\n solve()\n test -= 1\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Python/sokhonggiam.py","file_name":"sokhonggiam.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"378920697","text":"#Alexandra Thompson\n#athompson77@gatech.edu\n#CS 1301-Section B01\n#I worked on the homework assignment alone using only this semester's course materials.\n\nfrom Myro import*\ninit()\n\ndef shake(): #helper function\n for t in timer(5):\n turnBy(20,\"deg\")\n turnBy(-20, \"deg\")\n\ndef rollOver(): #helper function\n forward(1,2)#backward, spins, forward, spins\n turnLeft(1,3.2)\n backward(1,2)\n turnRight(1,3.2)\n\ndef chaseTail(): #helper function\n import random\n for t in timer(10): #spins randomly\n turnBy(random.randint(-350,350),\"deg\")\n motors(1,.2)\n wait(2)\n stop()\n\ndef star(): #helper function\n for t in timer(10): #makes a criss cross star\n forward(1,2)\n turnBy(45,\"deg\")\n backward(1,2)\n turnBy(45,\"deg\")\n\ndef tune(): #helper function\n turnLeft(1)\n beep(.2,1318.51)#plays first measure of fur elise\n beep(.2,1244.51)\n beep(.2,1318.51)\n beep(.2,1244.51)\n beep(.2,1318.51)\n beep(.2,987.77)\n beep(.2,1174.66)\n beep(.2,1046.50)\n beep(.5,880)\n stop()\n\ndef morningRoutine(tricks):\n if tricks <1:\n return None\n elif tricks == 1:\n shake()\n elif tricks == 2:\n shake()\n rollOver()\n elif tricks == 3:\n shake()\n rollOver()\n chaseTail()\n elif tricks == 4:\n shake()\n rollOver()\n chaseTail()\n star()\n else:\n shake()\n rollOver()\n chaseTail()\n star()\n tune()\n\ndef potato(): #helper function\n forward(.5,1)\n backward(.5,1)\n beep(.5,523.25) #cbA#a\n beep(.5,493.88)\n beep(.5,466.16)\n beep(1,440)\n\ndef fish(): #helper function\n shake()\n beep(.3, 587.33) #low-pitch yellow submarine\n beep(.3, 587.33)\n beep(.3, 587.33)\n beep(.2, 587.33)\n beep(.2, 659.25)\n beep(.2, 440)\n beep(.1, 440)\n beep(.2, 440)\n beep(.1, 440)\n beep(.4, 440)\n\ndef scooby(): #helper function\n chaseTail()\n beep(.2, 1318.51) #scooby doo theme\n beep(.25, 1318.51)\n beep(.2, 1174.66)\n beep(.25, 1174.66)\n beep(.6, 1046.50)\n wait(.2)\n beep(.2, 1174.66)\n beep(.5, 1396.91)\n beep(.5, 880)\n\ndef cat(): #helper function\n rollOver()\n beep(.4, 783.99) #the lion sleeps tonight\n beep(.2, 880)\n beep(.4, 987.77)\n beep(.3, 880)\n beep(.2, 987.77)\n beep(.4, 1046.50)\n beep(.2, 987.77)\n beep(.3, 880)\n beep(.4, 783.99)\n\ndef dragon(): #helper function\n star()\n beep(.4, 1046.50) #puff the magic dragon\n beep(.2, 1046.50)\n beep(.3, 1046.50)\n beep(.3, 1046.50)\n beep(.6, 987.77)\n beep(.5, 783.99)\n beep(.5, 880)\n beep(.2, 1046.50)\n beep(.2, 1046.50)\n beep(.5, 783.99)\n\ndef greetMenu():\n def menu():\n print (\"1) Potato\")\n print (\"2) Fish Treats...\")\n print (\"3) Scooby Snacks?\")\n print (\"4) Cat Treats!\")\n print (\"5) Dragon Treats!!!\")\n print ()\n print (\"0) Exit\")\n run = True\n while run == True:\n menu()\n choice = int(input(\"Give Trapper some treats\"))\n if choice == 1:\n potato()\n print()\n elif choice == 2:\n fish()\n print()\n elif choice ==3:\n scooby()\n print()\n elif choice == 4:\n cat()\n print()\n elif choice == 5:\n dragon()\n print()\n elif choice ==0:\n print()\n print (\"Bye! Thank you!\")\n run = False\n else:\n askQuestion(\"Don't be mean. Please choose some treats.\",[\"Sorry\"])\n print()","sub_path":"trickmenu.py","file_name":"trickmenu.py","file_ext":"py","file_size_in_byte":3595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"433944841","text":"import logging\r\nimport inspect\r\nfrom datetime import datetime\r\n\r\nfrom unuk.core import exceptions\r\nfrom unuk.utils import pathbits\r\n\r\n__all__ = ['Handler']\r\n\r\n\r\nclass MetaRpcHandler(type):\r\n \r\n def __new__(cls, name, bases, attrs):\r\n funcprefix = attrs.get('serve_as',None)\r\n if not funcprefix:\r\n for base in bases[::-1]:\r\n if isinstance(base, MetaRpcHandler):\r\n funcprefix = base.serve_as\r\n if funcprefix:\r\n break\r\n rpc = {}\r\n if funcprefix:\r\n fprefix = '%s_' % funcprefix\r\n for key, method in attrs.items():\r\n if callable(method) and key.startswith(fprefix):\r\n namefunc = key[len(fprefix):]\r\n func = attrs.pop(key)\r\n func.__name__ = namefunc\r\n rpc[namefunc] = func\r\n for base in bases[::-1]:\r\n if hasattr(base, 'rpcfunctions'):\r\n rpcbase = base.rpcfunctions\r\n for key,method in rpcbase.items():\r\n if not rpc.has_key(key):\r\n rpc[key] = method\r\n \r\n attrs['rpcfunctions'] = rpc\r\n return super(MetaRpcHandler, cls).__new__(cls, name, bases, attrs)\r\n\r\n\r\nclass funcobj(object):\r\n \r\n def __init__(self, func, deco):\r\n self.func = func\r\n self.deco = deco\r\n \r\n def __call__(self, *args, **kwargs):\r\n return self.deco(self.func, *args, **kwargs)\r\n\r\n\r\nclass Handler(object):\r\n '''Server Handler\r\n \r\n Sub-handlers for prefixed methods (e.g., system.listMethods)\r\n can be added with putSubHandler. By default, prefixes are\r\n separated with a '.'. Override self.separator to change this.\r\n '''\r\n __metaclass__ = MetaRpcHandler\r\n \r\n serve_as = None\r\n '''Type of server and prefix to functions providing services'''\r\n separator = '.'\r\n '''Separator between subhandlers.'''\r\n\r\n def __init__(self,\r\n subhandlers = None,\r\n http = None,\r\n attrs = None,\r\n **kwargs):\r\n self.subHandlers = {}\r\n self.http = http\r\n self.started = datetime.now()\r\n logger = kwargs.pop('logger',None)\r\n if logger:\r\n self.logger = logger\r\n else:\r\n self.logger = logging.getLogger(self.__class__.__name__)\r\n if subhandlers:\r\n for route,handler in subhandlers.items():\r\n if inspect.isclass(handler):\r\n handler = handler(http = self.http)\r\n self.putSubHandler(route, handler)\r\n \r\n def stop(self):\r\n '''Stop the handler'''\r\n pass\r\n \r\n def get_handler(self, path):\r\n urlbits = pathbits(path)\r\n handler = self\r\n for path in urlbits:\r\n subhandler = handler.getSubHandler(path)\r\n if subhandler:\r\n handler = subhandler\r\n else:\r\n break\r\n # a dummy handler, check for child with no prefix\r\n if not handler.serve_as:\r\n handler = handler.getSubHandler('')\r\n return handler\r\n \r\n def putSubHandler(self, prefix, handler):\r\n '''Add a subhandler with prefix prefix\r\n \r\n:keyword prefix: a string defining the url of the subhandler\r\n:keyword handler: the sub-handler, an instance of :class:`Handler` \r\n '''\r\n self.subHandlers[prefix] = handler\r\n\r\n def getSubHandler(self, prefix):\r\n '''Get a subhandler at ``prefix``\r\n '''\r\n return self.subHandlers.get(prefix, None)\r\n \r\n def wrap_function_decorator(self, func, *args, **kwargs):\r\n return func(*args,**kwargs)\r\n \r\n def _getFunction(self, method):\r\n prefix_method = method.split(self.separator, 1)\r\n if len(prefix_method) == 2:\r\n # Found a prefix, get the subhandler\r\n prefix, method = prefix_method\r\n handler = self.getSubHandler(prefix)\r\n if handler is None:\r\n raise exceptions.NoSuchFunction(\"no such subHandler %s\" % prefix)\r\n return handler._getFunction(method)\r\n else:\r\n try:\r\n return funcobj(self.rpcfunctions[method],\r\n self.wrap_function_decorator)\r\n except:\r\n raise exceptions.NoSuchFunction(\"function %s not found\" % method)\r\n\r\n def invokeServiceEndpoint(self, meth, args):\r\n return meth(*args)\r\n\r\n def listFunctions(self):\r\n return self.rpcfunctions.keys()\r\n \r\n def wsgi(self, environ, start_response):\r\n '''The WSGI Handler'''\r\n path = environ['PATH_INFO']\r\n handler = self.get_handler(path)\r\n if handler:\r\n request = self.http.Request(environ)\r\n response = handler.serve(request)\r\n else:\r\n response = self.http.HttpResponse(status = 500)\r\n try:\r\n status_text = self.http.STATUS_CODE_TEXT[response.status_code]\r\n except KeyError:\r\n status_text = 'UNKNOWN STATUS CODE'\r\n status = '%s %s' % (response.status_code, status_text)\r\n response_headers = [(str(k), str(v)) for k, v in response.items()]\r\n for c in response.cookies.values():\r\n response_headers.append(('Set-Cookie', str(c.output(header=''))))\r\n start_response(status, response_headers)\r\n return response\r\n \r\n def serve(self, request):\r\n return ['

    Not Found

    '] \r\n \r\n\r\n","sub_path":"src/unuk/core/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":5595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"410480317","text":"import pandas as pd\n\ndef get_acreage():\n f= \"FruitYearbookGeneral_ATables.xlsx\"\n tabs = [\"taba-4\", 'taba-5', 'taba-8']\n\n acreage = pd.read_excel(f, sheet_name=tabs[0], header = 1 )\n acreage = acreage.drop([0,1], axis = 0)\n acreage = acreage.drop(acreage.index[35:77], axis = 0)\n\n ###map index as year\n index = acreage[\"Year\"].astype('int64')\n acreage = (acreage.drop(\"Year\", axis = 1)) * 1000\n acreage.index = index\n\n ###clean up column names\n col_names = acreage.columns\n new_names = []\n for name in col_names:\n name = name.replace(\" 1\",\"\")\n name = name.replace(\" \", \"\")\n new_names.append(name)\n acreage.columns = new_names\n\n ###removing crops with incomplete data > 1 year\n #remove = ['Limes', 'Temples', 'Pineapples', 'Pomegranates', 'Mangoes']\n #acreage.drop(remove, axis = 1, inplace = True)\n \n return(acreage_data)\n\nif __name__ == \"__main__\":\n get_acreage()\n ","sub_path":".ipynb_checkpoints/get_data-checkpoint (1).py","file_name":"get_data-checkpoint (1).py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"39170551","text":"import cv2\nimport skeletonization as skel\n\n\ndef main():\n\n img_skeleton = skel.execute('fingerprints/101_1.tif')\n\n # find harris corners\n dst = cv2.cornerHarris(img_skeleton, 2, 3, 0.04)\n ret, dst = cv2.threshold(dst, 0.01 * dst.max(), 255, 0)\n\n cv2.imshow(\"skel\", img_skeleton)\n cv2.imshow(\"dst\", dst)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"192214520","text":"'''@author Samuel Tenka\nVerticalDominance.py segments newspages by\n 0. Reading textlines from XML\n 1. Classifying textlines as Title or Text, based on fontsize\n 2. Assigning Textlines to Titlelines\n 3. Merging, for each Titleline, the set of all associated Textlines.\n'''\n\nimport json\nimport processXML\nimport matplotlib.pyplot as plt\nfrom memory_profiler import profile \nimport sys, ReadTextLines0\nimport timeit\nimport VD2\nassert(len(sys.argv)==5)\nfp = open('VerticalDominance2New.log', 'w+')\n@profile(stream=fp)\ndef main():\n outfolder, imagename, xmlname,outname = sys.argv[1:5]\n outname = outfolder + '/' + outname.split('/')[-1]\n scrapedname = xmlname+'.scraped.txt'\n titlesname = xmlname+'.titles.txt'\n textsname = xmlname+'.texts.txt'\n '''\n *** Step 0: Fetch Strips from XML ***'''\n start = timeit.default_timer()\n ReadTextLines0.readxml(xmlname,imagename, scrapedname)\n vdclass = VD2.VerticalDominance()\n vdclass.parse(scrapedname) #contents,coordinates,heights = \n vdclass.getstrips() #titlestrips,textstrips = \n # titlestrips,textstrips = getstrips(contents,coordinates,heights)\n DONT_MERGE_JUST_SHOW=False\n if DONT_MERGE_JUST_SHOW:\n titleblocks, articleblocks = vdclass.titlecoors, [[ts] for ts in vdclass.newtextcoors];\n title_assignments = list(range(len(titleblocks)))\n # print(title_assignments)\n else:\n '''\n *** Step 1: Classify some blocks as Titles *** '''\n vdclass.gettitleblocks()\n '''\n *** Step 2: Compute assignments of Textblocks to Titles *** '''\n vdclass.assign_textblocks()\n '''\n *** Step 3: Merge articleblocks based on title *** '''\n vdclass.group_titleblocks()\n # print(title_assignments)\n vdclass.group_textblocks()\n '''\n *** Step 4: Write to JSON: *** '''\n anns = []\n for j,(y,x,h,w) in enumerate(vdclass.titlecoors):\n anns.append({\"class\": \"title\",\n \"height\": h-y,\n \"id\": str(int(vdclass.title_assignments[j])),\n \"type\": \"rect\",\n \"width\": w-x,\n \"x\": x,\n \"y\": y})\n for j,ab in enumerate(vdclass.articleblocks):\n for (y,x,h,w) in ab:\n anns.append({\"class\": \"article\",\n \"height\": h-y,\n \"id\": str(j),\n \"type\": \"rect\",\n \"width\": w-x,\n \"x\": x,\n \"y\": y})\n\n seg = [{\n \"annotations\": anns,\n }]\n\n with open(outname,'w') as f:\n json.dump(seg, f, indent=4)\n f.close()\n with open('../../output/segment'+'/'+'VD2newtime', 'a+') as f:\n f.write(\"%f\"%(timeit.default_timer() - start,)) \n f.write(' ')\n f.close()\nif __name__=='__main__':\n main()","sub_path":"code/end_to_end/VerticalDominance2New.py","file_name":"VerticalDominance2New.py","file_ext":"py","file_size_in_byte":2729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"534834137","text":"import os\nimport click\nimport time\n\nfrom urllib2 import HTTPError\n\nfrom shellfoundry.exceptions import FatalError\nfrom shellfoundry.utilities.config_reader import Configuration, CloudShellConfigReader\nfrom shellfoundry.utilities.shell_package import ShellPackage\nfrom cloudshell.rest.api import PackagingRestApiClient\nfrom cloudshell.rest.exceptions import ShellNotFoundException\n\nCloudShell_Max_Retries = 5\nCloudShell_Retry_Interval_Sec = 0.5\nDefault_Time_Wait = 1.0\n\n\nclass ShellPackageInstaller(object):\n def __init__(self):\n self.cloudshell_config_reader = Configuration(CloudShellConfigReader())\n\n def install(self, path):\n shell_package = ShellPackage(path)\n shell_filename = shell_package.get_shell_name() + '.zip'\n package_full_path = os.path.join(path, 'dist', shell_filename)\n\n cloudshell_config = self.cloudshell_config_reader.read()\n\n cs_connection_label = 'Connecting to CloudShell at {}:{}'.format(cloudshell_config.host, cloudshell_config.port)\n with click.progressbar(length=CloudShell_Max_Retries,\n show_eta=False,\n label=cs_connection_label\n ) as pbar:\n try:\n client = self._open_connection_to_quali_server(cloudshell_config, pbar, retry=CloudShell_Max_Retries)\n finally:\n self._render_pbar_finish(pbar)\n\n pbar_install_shell_len = 2 # amount of possible actions (update and add)\n installation_label = 'Installing shell into CloudShell'.ljust(len(cs_connection_label))\n with click.progressbar(length=pbar_install_shell_len,\n show_eta=False,\n label=installation_label) as pbar:\n try:\n client.update_shell(package_full_path)\n except ShellNotFoundException:\n self._increase_pbar(pbar, Default_Time_Wait)\n self._add_new_shell(client, package_full_path)\n except Exception as e:\n self._increase_pbar(pbar, Default_Time_Wait)\n raise FatalError(self._parse_installation_error('Failed to update shell', e))\n finally:\n self._render_pbar_finish(pbar)\n\n def _open_connection_to_quali_server(self, cloudshell_config, pbar, retry):\n if retry == 0:\n raise FatalError('Connection to CloudShell Server failed. Please make sure it is up and running properly.')\n\n try:\n client = PackagingRestApiClient(ip=cloudshell_config.host,\n username=cloudshell_config.username,\n port=cloudshell_config.port,\n domain=cloudshell_config.domain,\n password=cloudshell_config.password)\n return client\n except HTTPError as e:\n if e.code == 401:\n raise FatalError(u'Login to CloudShell failed. Please verify the credentials in the config')\n raise FatalError('Connection to CloudShell Server failed. Please make sure it is up and running properly.')\n except:\n self._increase_pbar(pbar, time_wait=CloudShell_Retry_Interval_Sec)\n return self._open_connection_to_quali_server(cloudshell_config, pbar, retry - 1)\n\n def _add_new_shell(self, client, package_full_path):\n try:\n client.add_shell(package_full_path)\n except Exception as e:\n raise FatalError(self._parse_installation_error('Failed to add new shell', e))\n\n def _parse_installation_error(self, base_message, error):\n import json\n cs_message = json.loads(error.message)['Message']\n return \"{}. CloudShell responded with: '{}'\".format(base_message, cs_message)\n\n def _increase_pbar(self, pbar, time_wait):\n time.sleep(time_wait)\n pbar.next()\n\n def _render_pbar_finish(self, pbar):\n pbar.finish()\n pbar.render_progress()\n","sub_path":"shellfoundry/utilities/shell_package_installer.py","file_name":"shell_package_installer.py","file_ext":"py","file_size_in_byte":4056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"254394064","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@Author : yanyongyu\n@Date : 2020-09-10 17:12:05\n@LastEditors : yanyongyu\n@LastEditTime : 2021-01-01 17:57:10\n@Description : Entry File of the Bot\n@GitHub : https://github.com/yanyongyu\n\"\"\"\n__author__ = \"yanyongyu\"\n\nimport nonebot\nfrom nonebot.adapters.cqhttp import Bot as CQHTTPBot\nfrom nonebot.adapters.ding import Bot as DINGBot\n\nnonebot.init()\napp = nonebot.get_asgi()\n\ndriver = nonebot.get_driver()\ndriver.register_adapter(\"cqhttp\", CQHTTPBot)\ndriver.register_adapter(\"ding\", DINGBot)\n\nnonebot.load_plugins(\"src/plugins\")\n\nif __name__ == \"__main__\":\n nonebot.run(app=\"bot:app\")\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"199820655","text":"from django.urls import path\n\nfrom manuels.views import AddBookView, ListBooksView, clear_teacher_view, AddSuppliesView, EditBookView, \\\n EditSuppliesView, DeleteBookView, DeleteSuppliesView, ConfirmTeacherView, isbn_api\n\nurlpatterns = [\n path('teacher//add_book', AddBookView.as_view(), name='add_book'),\n path('teacher//add_supplies', AddSuppliesView.as_view(), name='add_supplies'),\n path('teacher/', ListBooksView.as_view(), name='list_books'),\n path('teacher//book/', EditBookView.as_view(), name='edit_book'),\n path('teacher//book//delete', DeleteBookView.as_view(), name='delete_book'),\n path('teacher//supplies/', EditSuppliesView.as_view(), name='edit_supplies'),\n path('teacher//supplies//delete', DeleteSuppliesView.as_view(), name='delete_supplies'),\n path('teacher//confirm', ConfirmTeacherView.as_view(), name='confirm_teacher'),\n path('clear', clear_teacher_view, name='clear_teacher'),\n path('isbn_api/', isbn_api, name='isbn_api'),\n]\n","sub_path":"manuels/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"235820025","text":"from django.contrib import admin\r\nfrom .models import List\r\n\r\n\r\n@admin.register(List)\r\nclass ListAdmin(admin.ModelAdmin):\r\n\r\n \"\"\" List Admin 정의 \"\"\"\r\n\r\n list_display = (\r\n \"creator\",\r\n \"name\",\r\n \"count_posts\",\r\n )\r\n\r\n search_fields = (\r\n \"^creator__username\",\r\n \"^name\",\r\n )\r\n\r\n","sub_path":"lists/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"609467193","text":"from configparser import ConfigParser\nimport networkx as nx\nimport numpy as np\nimport itertools\nimport random\nimport csv\nimport os\nimport sys\nimport pickle\n\nalert_types = {\"fan_out\":1, \"fan_in\":2, \"cycle\":3, \"bipartite\":4, \"stack\":5, \"dense\":6} # Pattern name and model ID\n\n# function to create and populate the alertPatterns.csv file\ndef generate_alertPatterns_file():\n \n#Calculating each number of alert patterns to be generated\n count =0\n count = int (len(open('outputs/accounts.csv').readlines())/100)\n \n schedule_id=2\n number_min_accounts = 7\n number_max_accounts = 10\n min_aggregate_amount = 100\n max_aggregate_amount = 1000\n min_individual_amount = 10\n max_individual_amount = 100\n min_amount_difference = 20\n max_amount_difference = 100\n min_period = 10\n max_period = 20\n amount_rounded =0.5\n orig_country = bene_country = orig_business = bene_business = 'TRUE'\n is_fraud = 'TRUE'\n\n with open('paramFiles/alertPatterns.csv','w') as csvfile:\n\n \tfilewriter = csv.writer(csvfile)\n \tfilewriter.writerow(['count','type',\n\t \t\t'schedule_id','accounts',\n\t \t\t'individual_amount','aggregated_amount',\n\t \t\t'transaction_count','amount_difference',\n\t \t\t'period','amount_rounded',\n\t \t\t'orig_country','bene_country',\n\t \t\t'orig_business','bene_business','is_fraud'])\n\n \tfor i in alert_types.keys():\n \t\tnumber_accounts = random.randint(number_min_accounts,number_max_accounts+1)\n \t\tagg_amount = random.randint(min_aggregate_amount,max_aggregate_amount)\n \t\tindividual_amount = random.randint(min(min_aggregate_amount,min_individual_amount),min(max_individual_amount,agg_amount))\n \t\ttransaction_count = number_accounts * random.randint(2,5)\n \t\tamount_difference = random.randint(min_amount_difference,max_amount_difference)\n \t\tperiod = random.randint(min_period,max_period)\n\n \t\tfilewriter.writerow([count,i,schedule_id,number_accounts,\n\t \t\t\tindividual_amount,agg_amount,\n\t \t\t\ttransaction_count, amount_difference, \n\t \t\t\tperiod, amount_rounded,\n\t \t\t\torig_country,bene_country,\n\t \t\t\tbene_country,bene_business,is_fraud])\n\n\n\n\n\ndef main():\n\tgenerate_alertPatterns_file()\n\nif __name__ == \"__main__\":\n\tmain()\n\n\n\n","sub_path":"scripts/generate_alert_patterns.py","file_name":"generate_alert_patterns.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"522122182","text":"from django.shortcuts import render\nimport numpy as np\nimport pymongo\nimport json\n\ndef get_world():\n client = pymongo.MongoClient(\"mongodb://Song:a931021@cluster0-shard-00-00-ywxjv.azure.mongodb.net:27017,cluster0-shard-00-01-ywxjv.azure.mongodb.net:27017,cluster0-shard-00-02-ywxjv.azure.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority\")\n db = client.nCoV_data\n world_data = db.nCoV_world_data\n\n infect_data = []\n for data in world_data.find():\n day_infection = {}\n time = data['date'][:4].replace('/', '.')\n day_infection['time'] = time\n \n # sort the country infect data\n country_data = data['country_data']\n sorted_country_data = sorted(country_data.items(), key=lambda item:item[1][0]['Confrimed'], reverse=True)\n temp_d = {}\n for a, b in sorted_country_data: \n temp_d.setdefault(a, b)\n \n country_data_list = []\n countries = list(temp_d.keys())\n value_list = list(temp_d.values())\n for i in range(0, len(countries)):\n country_data_list.append({\n 'name': countries[i], \n 'value': [value_list[i][0]['Confrimed']] + [value_list[i][1]['Recovered']] + [value_list[i][2]['Deaths']]\n })\n day_infection['data'] = country_data_list\n infect_data.append(day_infection)\n \n return infect_data\n\n# Create your views here.\ndef index(request):\n client = pymongo.MongoClient(\"mongodb://Song:a931021@cluster0-shard-00-00-ywxjv.azure.mongodb.net:27017,cluster0-shard-00-01-ywxjv.azure.mongodb.net:27017,cluster0-shard-00-02-ywxjv.azure.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority\")\n db = client.nCoV_data\n\n CN_data = db.nCoV_CN_data\n results = db.results\n\n # get the viurs data in China\n province_list = []\n province_infection = CN_data.find({'date': '2020-02-16'})[0]['province_infection']\n for each in province_infection:\n province_list.append(each['province'])\n\n days_list = []\n infect_data = []\n overall_confirmed = []\n overall_death = []\n overall_recovered = []\n for data in CN_data.find():\n days_list.append(data['date'][6:11])\n \n # construct the infected data list for each province in each day\n day_infection = []\n current_provinces = {}\n for each in data['province_infection']:\n current_provinces[each['province']] = each['confirmed']\n for province in province_list:\n if province in list(current_provinces.keys()):\n day_infection.append(current_provinces[province])\n else:\n day_infection.append(0)\n infect_data.append(day_infection)\n overall_confirmed.append(data['overall'][0]['confirmed_overall'])\n overall_death.append(data['overall'][0]['dead_overall'])\n overall_recovered.append(data['overall'][0]['cured_overall'])\n for i in range(0,31):\n days_list[i] = '1' + days_list[i]\n province_list = ['上海', '云南', '内蒙古', '北京', '台湾', '吉林', '四川', '天津', '宁夏', '安徽', '山东', '山西', '广东', '广西', '新疆', '江苏', '江西', '河北', '河南', '浙江', '海南', '湖北', '湖南', '澳门', '甘肃', '福建', '西藏', '贵州', '辽宁', '重庆', '陕西', '青海', '香港', '黑龙江']\n\n # get the data for sentiment analysis page\n SA_data = results.find({'tag': 'sentiment_analysis'})[0]['data']\n weibo_cnt = results.find({'tag': 'weibo_count'})[0]['data']\n predictions = []\n for each in SA_data:\n predictions.append(each['day_sentiment'])\n post_days = list(weibo_cnt.keys())\n post_days = [day[5:] for day in post_days]\n post_cnt = list(weibo_cnt.values())\n # get the sentiment counts for each day\n pred_cnt = results.find({'tag': 'prediction_count'})[0]['data']\n pos_cnt, neu_cnt, neg_cnt = [], [], []\n for each in list(pred_cnt.values()):\n pos_cnt.append(each['1'])\n neu_cnt.append(each['0'])\n neg_cnt.append(each['-1'])\n # normalize the confirmed data\n av_confirmed = np.mean(overall_confirmed)\n min_confirmed = min(overall_confirmed)\n norm_confirmed = [ (x - av_confirmed) / (2*(av_confirmed - min_confirmed)) for x in overall_confirmed]\n # compute the daliy active cases \n overall_active = [overall_confirmed[i] - overall_recovered[i] - overall_death[i] for i in range(len(overall_confirmed))]\n # get world comfirmed data \n world_data = get_world()\n world_confirmed = []\n for day_data in world_data:\n sum_confirmed = 0\n for each in day_data['data']:\n sum_confirmed += each['value'][0]\n world_confirmed.append(sum_confirmed)\n world_confirmed = overall_confirmed[19:52] + world_confirmed\n\n # get the data for word cloud page\n WC_data = results.find({'tag': 'word_cloud'})[0]['data']\n word_cloud_kws = list(WC_data.keys())\n word_cloud_weights = list(WC_data.values())\n\n context = {\n 'days_list': json.dumps(days_list),\n 'province_list': json.dumps(province_list),\n 'infect_data': json.dumps(infect_data),\n 'overall_confirmed': json.dumps(overall_confirmed),\n 'overall_death': json.dumps(overall_death),\n 'overall_active': json.dumps(overall_active),\n 'post_cnt': json.dumps(post_cnt),\n 'predictions': json.dumps(predictions),\n 'post_days': json.dumps(post_days),\n 'norm_confirmed': json.dumps(norm_confirmed),\n 'word_cloud_kws': json.dumps(word_cloud_kws),\n 'word_cloud_weights': json.dumps(word_cloud_weights),\n 'pos_cnt': json.dumps(pos_cnt),\n 'neu_cnt': json.dumps(neu_cnt),\n 'neg_cnt': json.dumps(neg_cnt),\n 'world_confirmed': json.dumps(world_confirmed),\n }\n\n return render(request, 'index.html', context)\n\n\ndef world(request):\n infect_data = get_world()\n\n context = {\n 'infect_data': json.dumps(infect_data),\n }\n\n return render(request, 'world.html', context)\n\n\ndef document(request):\n \n context = {\n\n }\n\n return render(request, 'document.html', context)\n\ndef key_tech(request):\n\n context = {\n\n }\n return render(request, 'key_tech.html', context)\n\ndef contact(request):\n\n context = {\n\n }\n return render(request, 'contact.html', context)\n","sub_path":"localweb/localweb/catalog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"606268624","text":"#! /usr/bin/env python2.7\n#coding=utf-8\n\nfrom sqlalchemy import Column, String, ForeignKey,\\\n DateTime, Integer, BigInteger, Boolean, Text\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import and_, func, create_engine\nfrom datetime import datetime, timedelta\n\nBase = declarative_base()\n\nengine = create_engine('sqlite:///shit-email.sqlite', echo=True)\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nclass DBError(RuntimeError):\n def __init__(self, arg):\n self.args = arg\n\ndef first_date_of_week():\n now = datetime.now()\n weekday_of_today = now.weekday()\n first_day = now - timedelta(days=weekday_of_today)\n return datetime(first_day.year, first_day.month, first_day.day, \\\n hour=0, minute=0, second=0, microsecond=0, tzinfo=None)\n\nclass User(Base):\n\n __tablename__ = 'user'\n\n name = Column(String(50), primary_key=True)\n email = Column(String(40), unique=True)\n realname = Column(String(10))\n # 邮件发送者的邮箱密码\n password = Column(String(40))\n sender = Column(Boolean, default=False)\n airplane_mode = Column(Boolean, default=False)\n phone_number = Column(String(11), default=None)\n # 禅道\n chandao_object_id = Column(String(40), default=None)\n chandao_name = Column(String(40), default=None)\n chandao_password = Column(String(40), default=None)\n # 分组\n group = Column(String(60), default=None)\n\n # useless\n chandao_session_id = Column(String(40), default=None)\n chandao_za = Column(String(40), default=None)\n\n @staticmethod\n def all_users(allow_group, sess=session):\n return sess.query(User)\\\n .filter(User.group == allow_group).all()\n\n @staticmethod\n def query_user(name):\n return session.query(User).filter(User.name == name).first()\n\n @staticmethod\n def query_user_group(name):\n group_id = User.query_user_group_id(name)\n msg = None\n if group_id :\n group = Group.query_group_name(group_id)\n if group:\n msg = u'用户:%s,分组(id = %s)为%s。' \\\n % (name, group_id, group)\n else:\n msg = u'用户:%s,目前没有分组' % name\n else:\n msg = u'用户:%s 不存在。' % name\n return msg\n\n @staticmethod\n def query_user_group_id(name):\n \"\"\"查询当前用户的 group id\n \n Arguments:\n name {string} -- 用户名\n \n Returns:\n string -- 当前的用户 group id 没有返回 none\n \"\"\"\n user = User.query_user(name)\n if user:\n return user.group\n \n return None\n\n @staticmethod\n def set_user_airplane_mode(name, mode):\n user = User.query_user(name)\n if user:\n user.airplane_mode = mode\n session.commit()\n return u'%s:设置飞行模式成功,当前 %s' % \\\n (name, u'开启' if mode else u'关闭')\n \n return u'%s:设置勿扰模式失败'\n\n @staticmethod\n def set_slience_mode(mode, group):\n for user in User.all_users(group):\n user.airplane_mode = mode\n session.commit()\n msg = None\n if mode:\n msg = u'关闭所有人提醒'\n else:\n msg = u'打开所有提醒'\n return msg\n\n @staticmethod\n def update_user_group_id(name, group_id):\n \"\"\"更新用户的 group \n \n Arguments:\n name {string} -- 用户名\n group_id {string} -- 用户的 group id\n \n Returns:\n string -- 返回的消息\n \"\"\"\n user = User.query_user(name)\n group = Group.query_group_name(group_id)\n if user and group:\n user.group = group_id\n session.commit()\n return u'用户:%s 分组更新为 id = %s' \\\n % (name, group_id)\n\n return u'用户:%s 不存在或者分组 id = %s 不存在。' \\\n % (name, group_id)\n\n @staticmethod\n def user_chandao_info(name):\n \"\"\"用户的禅道信息\n \"\"\"\n user = User.query_user(name)\n msg = None\n if user:\n msg = u'用户 %s\\nchandao name: %s\\nobject id:%s' \\\n % (name, user.chandao_name, user.chandao_object_id)\n else:\n msg = u'都没注册信息,查询 nmb'\n return msg\n\n @staticmethod\n def update_chandao(name, chandao_name=None, password=None, object_id=None):\n \"\"\"更新禅道的相关信息\n \n Arguments:\n name {string} -- 用户名\n \n Keyword Arguments:\n chandao_name {string} -- 禅道的用户名 (default: {None})\n password {string} -- 禅道的密码 (default: {None})\n object_id {string} -- 禅道的 object id,通过web页面去获取 (default: {None})\n \n Returns:\n string -- 返回更新的结果\n \"\"\"\n user = User.query_user(name)\n msg = None\n if user:\n if chandao_name:\n user.chandao_name = chandao_name\n if password:\n user.chandao_password = password\n if object_id:\n user.chandao_object_id = object_id\n session.commit()\n msg = u'禅道信息更新成功'\n else:\n msg = u'都没注册信息,查询 nmb'\n return msg\n\n @staticmethod\n def create_user(name, email=None, password=None, \\\n realname=None, group=None, tel=None):\n \"\"\"创建一个 user 如果必要的话,如果当前 user 已经存在,那么会更新不为空的信息。\n\n Arguments:\n name {string} -- 需要更新或者创建的用户\n\n Keyword Arguments:\n email {string} -- 263邮箱 (default: {None})\n password {string} -- 263邮箱密码 (default: {None})\n realname {string} -- 真实的名字,如果这里为 None 会拆分邮箱前缀 (default: {None})\n \"\"\"\n user = User.query_user(name)\n msg = u'创建或者更新异常'\n if user:\n if email:\n user.email = email\n if password:\n user.password = password\n if realname:\n user.realname = realname\n if group and Group.query_group_name(group):\n user.group = group\n if tel:\n user.phone_number = tel\n session.commit()\n msg = u'更新成功'\n else:\n if email == None or password == None:\n msg = u'邮箱和密码不能为空'\n else:\n emailnames = email.split('@')\n emailname = emailnames[0] if len(emailnames) >= 1 else email\n realname = realname if realname is not None else emailname\n user = User(name=name, email=email, \\\n password=password, realname=realname)\n user.group = group\n user.phone_number = tel\n user.airplane_mode = False\n session.add(user)\n session.commit()\n if user in session:\n msg = u'用户 %s 创建成功' % name\n else:\n msg = u'用户 %s 创建失败' % name\n return msg\n\n @staticmethod\n def check_user_group_id(name, group_id):\n \"\"\"检查用户的 group id 是否正确\n\n Arguments:\n group_id {int} -- 检查的 group id\n\n Return:\n 返回是否是正确的分组\n \"\"\"\n user = User.query_user(name)\n if user:\n return user.group == group_id\n\n return False\n\n @staticmethod\n def is_sender(name):\n \"\"\" 指定的用户是不是邮件发送者\n\n Arguments:\n sender {string} -- 当前消息发送者的名字\n \"\"\"\n user = User.query_user(name)\n if user:\n return user.sender\n else:\n return False\n\n @staticmethod\n def sender_set_to(name):\n \"\"\"设置当前的 sender 为 name 的 user\n\n Arguments:\n name {string} -- 当前的发送者的名字,也是即将被设置为邮件发送者\n\n Returns:\n {string} -- 设置的相关信息返回\n \"\"\"\n maybe_sender = User.query_user(name)\n if maybe_sender:\n current_sender = session.query(User).filter(User.sender == True).first()\n msg = u''\n if current_sender:\n if current_sender.name == maybe_sender.name:\n return u'你他mb的设置个毛啊,本来就是你'\n else:\n current_sender.sender = False\n msg += u'发送者 %s 已经被取消\\n' % current_sender.name\n maybe_sender.sender = True\n msg += u'发送者 %s 已经被设置' % maybe_sender.name\n session.commit()\n return msg\n else:\n return u'都没注册信息,发送 nmb'\n\n @staticmethod\n def query_mail_sender():\n \"\"\"返回当前的 mail 发送者\n \"\"\"\n return session.query(User).filter(User.sender == True).first()\n\n @staticmethod\n def show_sender():\n \"\"\" 查询当前的邮件发送者是谁\n \n Returns:\n {string} -- 返回发送者的名字信息\n \"\"\"\n user = User.query_mail_sender()\n if user:\n return u'当前发送者为 %s' % user.name\n else:\n return u'当前未设置发送者'\n\n @staticmethod\n def delete_user(name):\n user = User.query_user(name)\n if user:\n session.delete(user)\n session.commit()\n return u'删除 %s 的用户成功' % name\n else:\n return u'瞎删你mb'\n\n @staticmethod\n def user_exist(name):\n \"\"\"查询指定用户是否存在\n\n Arguments:\n name {string} -- 查询的用户名,用户名在数据库中是唯一的,并且为微信名\n \"\"\"\n user = User.query_user(name)\n sender = u'是发送者' if user.sender else u'不是发送者'\n group_info = None\n if user.group:\n group = Group.query_group_name(user.group)\n if group:\n group_info = u'分组为(id=%s-%s),' % \\\n (user.group, group.group_name)\n else:\n group_info = u''\n else:\n group_info = u''\n\n return u'叫 %s(%s) 的用户存在,%s邮箱为 %s,%s' % \\\n (name, user.realname, group_info, user.email, sender) \\\n if user else u'叫 %s 的用户不存在' % name\n\n @staticmethod\n def all_user_note(allow_group):\n \"\"\"返回今天所有人的记录\n \"\"\"\n users = session.query(User)\\\n .filter(User.group == allow_group)\\\n .all()\n all_notes = {}\n for u in users:\n print('user = %s, realname = %s' % (u.name, u.realname))\n messages = Message.query_today_message(u.name).all()\n print('has %d message' % len(messages))\n all_notes[u.realname] = messages\n return all_notes\n\n def __str__(self):\n return '%s(%s)' % (self.name, self.email)\n \n\nclass Message(Base):\n\n __tablename__ = 'message'\n\n id = Column(BigInteger().with_variant(Integer, \"sqlite\"), primary_key=True)\n sender = Column(String(50), ForeignKey('user.name'))\n message = Column(String(200))\n date_create = Column(DateTime, default=datetime.now)\n\n @staticmethod\n def add_message(sender, message):\n m = Message(sender=sender, message=message)\n session.add(m)\n session.commit()\n if m in session:\n return u'添加成功'\n else:\n return u'添加记录失败'\n\n @staticmethod\n def update_message(id, sender, message):\n \"\"\"创建或者更新一条记录\n \n Arguments:\n id {string} -- 如果需要更新的话会指定一个记录的 id,创建则不传递这个字段\n sender {string} -- 发送者的名字\n message {string} -- 一条记录的内容\n \n Returns:\n [string] -- 创建或者更新的结果文字\n \"\"\"\n m = session.query(Message) \\\n .filter(and_(Message.sender == sender, Message.id == id)) \\\n .first()\n if m is None:\n return u'id = %s 的记录不存在' % id\n else:\n m.message = message\n session.commit()\n return u'记录更新成功,id 为 %s' % m.id\n\n @staticmethod\n def delete_message(msg_id, sender):\n \"\"\"\n 删除一条指定 id 的消息\n\n Arguments:\n id {string} -- 删除消息的 id\n sender {[type]} -- 确保删除的消息是自己的\n \"\"\"\n msg = session.query(Message) \\\n .filter(and_(Message.sender == sender, Message.id == msg_id)) \\\n .first()\n if msg is None:\n return u'id = %s 的记录不存在' % msg_id\n else:\n session.delete(msg)\n session.commit()\n return u'id = %s 的消息删除成功' % msg_id\n \n\n @staticmethod\n def query_today_message(sender):\n \"\"\"\n 指定用户今日的全部日志\n\n Arguments:\n sender {string} -- 查询日志的用户名\n \"\"\"\n now = datetime.now()\n today = datetime(now.year, now.month, now.day, \\\n hour=0, minute=0, second=0, microsecond=0, tzinfo=None)\n return session.query(Message) \\\n .filter(and_(Message.sender == sender, Message.date_create > today))\n\n @staticmethod\n def check_today_message(allow_group):\n \"\"\"\n 检查当前所有用户的日志情况\n \"\"\" \n msg = u''\n for user in User.all_users(allow_group):\n msg += u'%s' % user.name\n message_count = len(Message.query_today_message(user.name).all())\n msg += u' 今日%d条日志已添加\\n' % message_count \\\n if message_count > 0 else u' 今日日志未添加\\n'\n if msg:\n return msg\n\n @staticmethod\n def check_empty_message(allow_group):\n \"\"\"\n 检查今日组内每个人的消息是否都添加\n\n Returns:\n [Boolean] -- 返回 bool 代表当前是否都添加完\n \"\"\"\n checked = True\n for user in User.all_users(allow_group):\n message_count = len(Message.query_today_message(user.name).all())\n if message_count <= 0:\n checked = False\n break\n return checked\n\n @staticmethod\n def query_weekly_message(sender):\n \"\"\"\n 查询每周用户为 sender 名下所有消息记录。\n \"\"\"\n first_day_of_week = first_date_of_week()\n return session.query(Message) \\\n .filter(and_(Message.sender == sender, Message.date_create > first_day_of_week))\n\n @staticmethod\n def week_messages(sender):\n \"\"\"\n 本周的指定用户的全部日志\n\n Arguments:\n sender {string} -- 查询本周日志的用户名\n\n Returns:\n [Message] -- 本周指定用户的所有日志\n \"\"\"\n s = ''\n for m in Message.query_weekly_message(sender):\n s += 'id=%s, content=%s-%s\\n' \\\n % (m.id, m.message, m.date_create.strftime(\"%Y-%m-%d\"))\n return s\n\n @staticmethod\n def today_message(sender):\n s = ''\n for m in Message.query_today_message(sender):\n s += 'id=%s, content=%s\\n' % (m.id, m.message)\n\n return u'今日无%s的记录' % sender if len(s) <= 0 else s\n\nclass Report(Base):\n \"\"\"\n 每周日报的 orm 模型类\n \"\"\"\n __tablename__ = 'weekly_report'\n\n report_id = Column(BigInteger().with_variant(Integer, \"sqlite\"), primary_key=True)\n reporter = Column(String(50), ForeignKey('user.name'))\n\n origin_report = Column(Text, default=None)\n checked = Column(Boolean, default=False)\n # 用户可以更新周报,但是永远不会改变原始记录\n fix_report = Column(Text, default=None)\n\n # 周报的时间间隔记录\n start_date = Column(DateTime, default=first_date_of_week)\n end_date = Column(DateTime, default=datetime.now)\n\n next_week_todo = Column(Text, default=None)\n project_title = Column(String(40), default=None)\n description = Column(String(40), default=None)\n\n @staticmethod\n def create_report(reporter, origin_report, todo, \\\n project_title=None, description=None):\n \"\"\"\n 创建一个指定用户的原始周报。\n\n Arguments:\n reporter {string} -- 周报是为谁创建的\n origin_report {string} -- 周报的内容,其中 ‘-’开头的行为一组记录的关键词\n todo {string} -- 下周代办的内容,多条代办以中文逗号分隔\n project_title {string} -- 项目名,在邮件中展示用 默认值见代码\n description {string} -- 项目的描述,在邮件中展示用 默认值见代码\n Raises:\n Exception -- 插入失败的话返回异常\n\n Returns:\n [None] -- 成功无返回\n \"\"\"\n title = project_title if project_title else u'尚德机构企业版App'\n desc = description if description else u'尚德机构 iOS-App'\n\n if Report.query_weekly_report(reporter):\n raise DBError('report')\n report = Report(reporter=reporter, origin_report=origin_report, \\\n next_week_todo=todo, project_title=title, description=desc)\n session.add(report)\n session.commit()\n if report in session:\n return report.report_id\n else:\n raise DBError('report')\n\n @staticmethod\n def query_weekly_report(reporter):\n \"\"\"\n 查询本周周报\n\n Arguments:\n reporter {string} -- 周报的查询者\n\n Returns:\n [Reporter | None] -- 返回本周周报或者 none\n \"\"\"\n first_day_of_week = first_date_of_week()\n return session.query(Report) \\\n .filter(and_(Report.reporter == reporter, \\\n Report.start_date >= first_day_of_week)) \\\n .first()\n\n @staticmethod\n def week_date_duration():\n \"\"\"\n 辅助函数返回当前本周一到周五区间的文字\n \"\"\"\n style = '%Y.%m.%d'\n first_day = first_date_of_week().strftime(style)\n now = datetime.now().strftime(style)\n return u'%s-%s' % (first_day, now)\n\n def report_checked(self):\n \"\"\"\n 设置用户本周的周报为通过 review\n \"\"\"\n self.checked = True\n if not self.fix_report:\n self.fix_report = self.origin_report\n session.commit()\n\n def update_report(self, done=None, \\\n todo=None, title=None, desc=None):\n \"\"\"\n 更新本周的周报\n\n Keyword Arguments:\n done {string} -- 周报的主体内容 (default: {None})\n todo {string} -- 周报的主体内容 (default: {None})\n title {string} -- 标题 (default: {None})\n desc {string} -- 描述 (default: {None})\n \"\"\"\n if done or todo or title or desc:\n if done:\n self.fix_report = done\n if todo:\n self.next_week_todo = todo\n if title:\n self.project_title = title\n if desc:\n self.description = desc\n session.commit()\n return u'%s:更新周报成功' % self.reporter\n else:\n return u'%s:瞎更 nmb' % self.reporter\n\n\nclass Group(Base):\n \"\"\"\n 用户分组的 orm 模型类\n \"\"\"\n __tablename__ = 'group'\n\n group_id = Column(BigInteger().with_variant(Integer, \"sqlite\"), primary_key=True)\n group_name = Column(String(50))\n\n @staticmethod\n def query_group_name(gid):\n \"\"\"查询指定 id 的分组\n\n Arguments:\n gid {int} -- 分组的 id\n\n Returns:\n [Group] -- 查询到的分组模型或者 None\n \"\"\"\n return session.query(Group) \\\n .filter(Group.group_id == gid)\\\n .first()\n\n\nBase.metadata.create_all(engine)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":20578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"371867503","text":"#For Loop, \n\nsum=0\n\nfor i in range( 1, 100):\n sum+=i\n\nprint(' Sume is = ' , sum )\n\n# powers of 10 ---------------------------------\n\nfor n in range(16):\n print(\"{0:3} {1:17} \".format(n, 10**n))\n \n# Letters in the word ---------------------\n\nword = input(' Enter the word = ')\n\nfor char in word:\n print(char)\n\n# Formatted characters --------------------------\n\nfor c in 'ABCDEFGHI':\n print ( '[',c,']', end='', sep='')\n\n# Count vowels in the given word/text---------------------------------\n\nword = input (' Enter the text or word = ' )\nvCount = 0\n\nfor c in word:\n if c=='A' or c=='a' or c=='E' or c=='e' or c=='I' or c=='i' or \\\n c=='O' or c=='o' or c=='U' or c=='u':\n vCount += 1\n print ( '[' , c , ']' , end='', sep='')\nprint ('\\n Number of vowels in given text\\word = ', vCount )\n\n#-------------------\n\n#printing *'s----------------------------------\n\nheight = int ( input ( ' Enter the height f the pyramid = ' ) )\nrow=0\n\nfor row in range(height):\n#print white spaces \n for count in range(height - row ):\n print(end=' ')\n \n #printing *'s \n for count in range(2*row+1):\n print (end='*')\n \n print()\n\n#______________________________\n\n# Printing the tables\n\nsize = int ( input ( 'Enter the table size = ' ) )\n\nfor row in range(1, size+1):\n \n for column in range(1, size+1):\n print ( '{0:3} '.format(row*column), end=' ')\n \n print ()\n \n","sub_path":"ForLoop.py","file_name":"ForLoop.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"184531245","text":"import project2_util\n\ndef weekdays(wday):\n weekdays = ['一', '二', '三', '四', '五', '六', '日']\n return weekdays[wday - 1]\n\n\ndef test_datetime():\n a = project2_util.get_time()\n print('今天是星期%s,当前时间%02d:%02d'%(weekdays(a[0]), a[1], a[2])) \n \n interval = int(input('请输入一个时间间隔(分钟)'))\n t = a[1] * 60 + a[2] + interval\n d = t // 1440\n wday_d = (d + a[0]) % 7\n print('在%d分钟之后是今天之后的第%d天,那一天是星期%s' % (interval, d, weekdays(wday_d)))\n\n\nif __name__ == '__main__':\n test_datetime()\n\n \n\n\n\n\n \n \n\n\n","sub_path":"project2/project/18301050110.py","file_name":"18301050110.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"186777114","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\nwhite_wine = pd.read_csv('https://raw.githubusercontent.com/dipanjanS/practical-machine-learning-with-python/master/bonus%20content/effective%20data%20visualization/winequality-white.csv', sep=';')\nred_wine = pd.read_csv('https://raw.githubusercontent.com/dipanjanS/practical-machine-learning-with-python/master/bonus%20content/effective%20data%20visualization/winequality-red.csv', sep=';')\n\n\nred_wine['wine_type'] = 'red'\nwhite_wine['wine_type'] = 'white'\n\n\n\n# bucket wine quality scores into qualitative quality labels\nred_wine['quality_label'] = red_wine['quality'].apply(lambda value: 'low'\n if value <= 5 else 'medium'\n if value <= 7 else 'high')\nred_wine['quality_label'] = pd.Categorical(red_wine['quality_label'],\n categories=['low', 'medium', 'high'])\n\n\n\n\nwhite_wine['quality_label'] = white_wine['quality'].apply(lambda value: 'low'\n if value <= 5 else 'medium'\n if value <= 7 else 'high')\nwhite_wine['quality_label'] = pd.Categorical(white_wine['quality_label'],\n categories=['low', 'medium', 'high'])\n\n\n# merge red and white wine datasets\nwines = pd.concat([red_wine, white_wine])\n\n# re-shuffle records just to randomize data points\nwines = wines.sample(frac=1, random_state=42).reset_index(drop=True)\n\n\n# getting overall stats for specific features\nsubset_attributes = ['residual sugar', 'total sulfur dioxide', 'sulphates',\n 'alcohol', 'volatile acidity', 'quality']\nrs = round(red_wine[subset_attributes].describe(),2)\nws = round(white_wine[subset_attributes].describe(),2)\n#overall stats\nwines_desc=round(wines[subset_attributes].describe(),2)\n# concatinate the descriptions but can easier open the two windows\nstats=pd.concat([rs, ws], axis=1, keys=['Red Wine Statistics', 'White Wine Statistics'])\n\n\n# A histogram is a representation of the distribution of data. number of bins to distibute to\nwines.hist(bins=15, color='steelblue', edgecolor='black', linewidth=0.8,\n xlabelsize=4, ylabelsize=4, grid=True)\nplt.tight_layout()\n#plt.savefig('wines-hist.pdf', format='pdf', dpi=1200)\n\n\n# Histogram for a specific feature\nfeature_name='sulphates'\nfeature=wines[feature_name]\nmean=feature.mean()\nstd=feature.std()\nstd_lower=(mean - std)\nstd_higher=(mean + std)\n\nfig = plt.figure(figsize = (6,4))\ntitle = fig.suptitle(feature_name + \" Content in Wine\", fontsize=14)\nfig.subplots_adjust(top=0.85, wspace=0.3)\n\nax = fig.add_subplot(1, 1, 1)\nax.set_xlabel(feature_name)\nax.set_ylabel(\"Frequency\")\nax.axvline(x=mean, label= r'$\\mu$ mean='+str(round(mean,2)))\nax.axvline(x=std_lower, color='r', label='srd lower='+str(round(std_lower,2)))\nax.axvline(x=std_higher, color='g', label='srd higher='+str(round(std_higher,2)))\nax.legend()\n\nfreq, bins, patches = ax.hist(feature, color='steelblue', bins=25,\n edgecolor='black', linewidth=1)\n#plt.savefig(feature_name + '-freq.pdf', format='pdf', dpi=1200)\n\n\n# Density Plot\n# It is a smoothed version of the histogram above and is used in the same concept\nfig = plt.figure(figsize = (6, 4))\ntitle = fig.suptitle(\"Sulphates Content in Wine\", fontsize=14)\nfig.subplots_adjust(top=0.85, wspace=0.3)\n\nax1 = fig.add_subplot(1,1, 1)\nax1.set_xlabel(feature_name)\nax1.set_ylabel(\"Density\") \nsns.kdeplot(feature, ax=ax1, shade=True, color='steelblue')\n#plt.savefig(feature_name + '-density.pdf', format='pdf', dpi=1200)\n\n\n\n# Bar Plot\nfig = plt.figure(figsize = (6, 4))\ntitle = fig.suptitle(\"Wine Quality Frequency\", fontsize=14)\nfig.subplots_adjust(top=0.85, wspace=0.3)\n\nax = fig.add_subplot(1,1, 1)\nax.set_xlabel(\"Quality\")\nax.set_ylabel(\"Frequency\") \n# count the frequency of each quality\nw_q = wines['quality'].value_counts()\n#create x and y axis data\nw_q = (list(w_q.index), list(w_q.values))\nax.tick_params(axis='both', which='major', labelsize=8.5)\nbar = ax.bar(w_q[0], w_q[1], color='steelblue', \n edgecolor='black', linewidth=1)\n#plt.savefig('quality-freq-bar.pdf', format='pdf', dpi=1200)\n\n\n","sub_path":"1d-visualisation.py","file_name":"1d-visualisation.py","file_ext":"py","file_size_in_byte":4344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"226345862","text":"from audioprocess import *\nimport librosa\nfrom librosa.util import peak_pick\nfrom tensorflow import keras\nfrom scipy import signal\nimport numpy as np\nimport sys\nimport os\n\nclass MapGenerator:\n def __init__(self):\n self.music_path=\"\"\n self.save_path=\"\"\n self.placement_model_path=\"StepPlacementAttention100.h5\"\n self.selection_model_path=\"StepSelection1000.h5\"\n self.placement_model = keras.models.load_model(self.placement_model_path)\n self.selection_model = keras.models.load_model(self.selection_model_path)\n\n def generate(self,music_path,save_path,level=4):\n self.music_path=music_path\n self.save_path=save_path\n feature = self.__getFeature()\n peaks = self.__getPeaks(feature,level)\n y = self.__getGenMap(peaks)\n self.__saveMap(y,level)\n\n def generateAllDiff(self,music_path,save_path):\n self.music_path=music_path\n self.save_path=save_path\n feature = self.__getFeature()\n for i in range(5):\n level = i\n peaks = self.__getPeaks(feature,level)\n y = self.__getGenMap(peaks)\n self.__saveMap(y,level)\n \n def __saveMap(self,m,level):\n f = open(self.save_path+\"/\"+str(level),'w')\n for obj in m:\n f.writelines(str(obj[0])+\"0 \"+str(obj[1])+\"\\n\")\n f.close\n\n def __getFeature(self):\n music_name = self.music_path.split(\"/\")[-1][:-4]\n self.save_path = self.save_path+music_name\n if not os.path.isdir(self.save_path):\n os.mkdir(self.save_path)\n audio2wav(self.music_path,self.save_path)\n filter_bank = getMelFB(self.save_path+\"/\"+\"audio.wav\")\n cnn_data = getCNNformat(filter_bank)\n x = getNormalization(cnn_data)\n return x\n\n def __getPeaks(self,x,level):\n y = np.zeros(shape=(x.shape[0],5))\n y[:,level]=1\n\n result = self.placement_model.predict([x,y])\n\n data = []\n for r in result:\n data.append(r[0])\n data=np.array(data)\n data = data*1000\n data = data.astype(int)\n win = signal.windows.hamming(50)\n x = signal.convolve(data,win,mode='same')/sum(win)\n peaks, _ = signal.find_peaks(x, prominence=6-level)\n return peaks\n\n def __getGenMap(self,peaks):\n x = np.zeros((1, 1, 6))\n x[0][0]=np.array([1,0,0,0,0,0])\n state=np.zeros(shape=(1,128))\n lstm1_state=[state,state]\n lstm2_state=[state,state]\n result=[]\n for i, peak in enumerate(peaks):\n if i==0:\n x[0][0][-1]=peak+8\n else:\n x[0][0][-1]=peak-peaks[i-1]\n y,lstm1_state[0], lstm1_state[1], lstm2_state[0], lstm2_state[1]=\\\n self.selection_model.predict([x]+[lstm1_state]+[lstm2_state])\n x[0][0]=np.array([0,0,0,0,0,0])\n x[0][0][np.argmax(y)]=1\n result.append(np.array([peak+8,(np.argmax(y)-1)*4]))\n return result\n\nif __name__==\"__main__\":\n # x = getFeature(\"Agehachou.mp3\",\"generate_map/\")\n # x = getPeaks(x,0)\n # m = getGenMap(x)\n \n # path = sys.argv[1]\n # print(path)\n mg = MapGenerator()\n mg.generate(\"D:/myMusic/youtube轉出音樂/ReCREATORS Opening 1 Full『SawanoHiroyuki[nZk] Feat. Tielle Gemie - gravityWall』.mp3\",\"../song/\")\n #D:/myMusic/youtube轉出音樂/歌ってみたグッバイ宣言 Kotone(天神子兎音).mp3","sub_path":"PythonGenMap/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"182271109","text":"# this page will contain forms using the form-wtf plugin for Flask\n# Classes represent individual quizes and then fields are the vars\n# inside each class.\n\nimport flask_wtf as wtf\nimport models as ml\nfrom wtforms import StringField, IntegerField, SelectField, DateField, FloatField, HiddenField, BooleanField\nfrom wtforms.validators import DataRequired, EqualTo, Required, NumberRange\n\nclass Settings_Search(wtf.FlaskForm):\n search_name = StringField('name', validators=[DataRequired()])\n\nclass Create_Dataset(wtf.FlaskForm):\n name = StringField('name', validators=[DataRequired()])\n # get the search types available\n res = ml.Search_Names.query.all()\n search_type = SelectField(u'Search Type', coerce=str, validators=[Required(\"Please enter your name.\")], choices=[(str(r.id), r.name) for r in res])\n year_start = DateField('year_start', validators=[Required(\"Please enter the correct date.\")], format='%Y')\n year_end = DateField('year_end', validators=[Required(\"Please enter the correct date.\")], format='%Y')\n access = IntegerField('access_id')\n freq_opt = ml.Frequencies.query.all()\n freq = SelectField(u'freq', coerce=int, validators=[DataRequired(\"Please decide the frequency\")], choices=[(f.id, f.name) for f in freq_opt])\n\nclass Edit_Dataset(wtf.FlaskForm):\n name = StringField('name')\n # get the search types available\n res = ml.Search_Names.query.all()\n search_type = SelectField(u'Search Type', coerce=str, choices=[(str(r.id), r.name) for r in res])\n year_start = DateField('year_start')\n year_end = DateField('year_end')\n access = IntegerField('access_id')\n\nclass Create_Transaction(wtf.FlaskForm):\n name = StringField('name', [DataRequired()])\n amount = FloatField('amount', [DataRequired()])\n\n #prefill this with the filled value of the current user\n who_assigned = IntegerField('who_assigned', [DataRequired()])\n who_previous_stages = StringField('who_previous_stages')\n\n # hiddens\n dataset_id = HiddenField('ds_id')\n task_id = HiddenField('t_id')\n\nclass Edit_Task(wtf.FlaskForm):\n nickname = StringField('nickname', validators=[DataRequired(\"Please ensure you've entered a name\")])\n date_start = DateField('date_start', format='%Y', validators=[DataRequired(\"This date cannot be empty\")])\n date_end = DateField('date_end', format='%Y', validators=[DataRequired(\"This date cannot be empty\")])\n who_assigned = IntegerField('who_assigned')\n search_term = StringField('search_term', validators=[DataRequired()])\n dataset_owner = StringField('dataset_owner', validators=[DataRequired(\"The dataset must have an owner\")])\n\n # creating Transactions\n entity_name = StringField('entity_name', validators=[DataRequired()])\n rumour_date = DateField('rumour', validators=[DataRequired()])\n anouncement_date = DateField('annoucement', validators=[DataRequired()])\n mandarin_next = BooleanField('mandarin')\n \n\n\n# chin_inv_file_no = FloatField('chin_inv_file_no', \\\n# validators=[NumberRange(0, 99999999, \"Invalid file number\")])\n# counterpart_file_no = FloatField('counterpart_file_no', \\\n# validators=[NumberRange(0, 99999999, \"Invalid file number\")])\n","sub_path":"code/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"339135128","text":"\"\"\" Module for Map related functions \"\"\"\nimport math\n\n\ndef calculate_distance(coord1, coord2):\n \"\"\" Return the distance between two geographical points. \"\"\"\n\n deg2rad = math.pi / 180\n phi1 = (90.0 - coord1[0]) * deg2rad\n phi2 = (90.0 - coord2[0]) * deg2rad\n\n th1 = coord1[1] * deg2rad\n th2 = coord2[1] * deg2rad\n\n cos = (math.sin(phi1) * math.sin(phi2) * math.cos(th1 - th2) + \\\n math.cos(phi1) * math.cos(phi2))\n # cos = (math.sin(phi1) * math.sin(phi2) + math.cos(th1 - th2) * \\\n # math.cos(phi1) * math.cos(phi2))\n\n if cos > 1:\n cos = 1\n\n distance = math.acos(cos) * 6373\n\n return distance \n\n''' Function which convert map to graph. It returns\n a list of all edges with weights.\n'''\ndef map_to_graph(node_dict, way_dict):\n edge_dict = {}\n for way in way_dict:\n way_nodes = way_dict[way][0]\n way_distance = 0.0\n for i in range(1, len(way_nodes)):\n way_distance += calculate_distance(node_dict[way_nodes[i-1]][1], \\\n node_dict[way_nodes[i]][1])\n\n edge_dict[(way_nodes[0], way_nodes[i])] = (way_distance, way_dict[way][1])\n\n return edge_dict\n \n\n''' Function to reduce complexity of graph by giving small values for\n way IDs and node IDs. Also the function will split the ways, \n which has an intersection with another way, into two or more paths \n so that the movemets can be make simple.\n'''\ndef normalize_map(node_dict, way_dict):\n \"\"\" Reduce the map by splitting ways which form juctions with other\n ways at the middle of the road. Fuction also appends the length of\n each ways to the way_dict. \"\"\"\n \n dup_way_dict = {} \n i = 0\n for way in way_dict:\n way_type = way_dict[way][1]\n way_nodes = way_dict[way][0]\n if not way_nodes:\n continue\n temp = [way_nodes[0]]\n way_distance = 0.0\n for j in xrange(1, len(way_nodes)):\n way_distance += calculate_distance(node_dict[way_nodes[j - 1]][0], \\\n node_dict[way_nodes[j]][0])\n if len(node_dict[way_nodes[j]][2]) > 1 or j == len(way_nodes) - 1:\n temp.append(way_nodes[j])\n dup_way_dict[i] = [temp, way_type, way_distance]\n i += 1\n temp = [way_nodes[j]]\n way_distance = 0.0\n else:\n temp.append(way_nodes[j])\n \n dup_node_dict = {}\n for item in node_dict:\n dup_node_dict[item] = [node_dict[item][0], node_dict[item][1], []]\n\n for way in dup_way_dict:\n for item in dup_way_dict[way][0]:\n dup_node_dict[item][2].append(way)\n \n return dup_node_dict, dup_way_dict\n\n\n\ndef normalize_map2(node_dict, way_dict):\n for way in way_dict:\n way_nodes = way_dict[way][0]\n way_dist = 0.0\n \n v1 = way_nodes[0]\n for v2 in way_nodes[1:]:\n v1_pt = node_dict[v1][0]\n v2_pt = node_dict[v2][0]\n \n dist = calculate_distance(v1_pt, v2_pt)\n way_dist += dist\n \n v1 = v2\n way_dict[way].append(way_dist)\n\n return node_dict, way_dict\n \n \n","sub_path":"maps.py","file_name":"maps.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"281156432","text":"#!/usr/bin/env fbpython\n# Copyright (c) Meta Platforms, Inc. and affiliates.\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 unittest\nfrom sys import getrefcount\n\nimport thrift.python_capi.fixture as fixture\nfrom thrift.test.python_capi.module.thrift_types import ( # @manual=:test_module-python-types\n AnnoyingEnum,\n ComposeStruct,\n DoubledPair,\n EmptyStruct,\n ListStruct,\n MapStruct,\n MyDataItem,\n MyEnum,\n MyStruct,\n MyStructPatch, # this import breaks autodeps w/o manual\n MyUnion,\n PrimitiveStruct,\n SetStruct,\n StringPair,\n)\n\n\nclass PythonCapiFixture(unittest.TestCase):\n def my_struct(self) -> MyStruct:\n return MyStruct(\n inty=1,\n stringy=\"hello\",\n myItemy=MyDataItem(),\n myEnumy=MyEnum.MyValue1,\n booly=True,\n floatListy=[-1.0, 1.0, 2.0, 3.0],\n strMappy={b\"hello\": \"world\", b\"-1\": \"-1\"},\n intSetty={-1, 1, 2, 3, 5, 8},\n )\n\n def my_union(self) -> MyUnion:\n return MyUnion(myStruct=self.my_struct())\n\n def primitive(self) -> PrimitiveStruct:\n return PrimitiveStruct(\n booly=True,\n charry=-9,\n shorty=-1,\n inty=2**31 - 1,\n longy=-(2**63),\n floaty=-1.0,\n dubby=-1.0,\n stringy=\"€ to £ to ₹\",\n bytey=b\"bippity boppity boo\",\n )\n\n def primitive_unset(self) -> PrimitiveStruct:\n return PrimitiveStruct(\n booly=True,\n # charry leave deliberately unset, should be 0\n shorty=-1,\n inty=2**31 - 1,\n longy=-(2**63),\n # leave optional `floaty` `dubby`, `stringy`, `bytey` unset\n )\n\n def struct_patch(self) -> MyStructPatch:\n return MyStructPatch(\n assign=self.my_struct(),\n )\n\n def list_struct(self) -> ListStruct:\n return ListStruct(\n boolz=[True, True, False, False, False, False, True, True, False, True],\n intz=[-1, -2, -1, 0, 1, 2, 2, 2, 2, 10],\n stringz=[\"wat\", \"\", \"-1\", \"-1\", \"lol\", \"loool\"],\n encoded=[b\"beep\", b\"boop\", b\"bop\"],\n uidz=[-(2**63), -1, 0, 1, 2**63 - 1],\n matrix=[[4.0, 9.0, 2.0], [3.0, 5.0, 7.0], [8.0, 1.0, 6.0]],\n ucharz=[[2, 7, 6], [9, 5, 1], [4, 3, 8]],\n voxels=[\n [[2, 7, 6], [9, 5, 1], [4, 3, 8]],\n [[2, 7, 6], [9, 5, 1], [4, 3, 8]],\n [[2, 7, 6], [9, 5, 1], [4, 3, 8]],\n ],\n )\n\n def empty_lists(self) -> ListStruct:\n # optional fields left unset\n return ListStruct(\n boolz=[],\n encoded=[],\n uidz=[],\n matrix=[],\n ucharz=[[], [9, 5, 1], []],\n voxels=[[], [[]], [[], [3], []]],\n )\n\n def set_struct(self) -> SetStruct:\n return SetStruct(\n enumz={MyEnum.MyValue1, MyEnum.MyValue2},\n intz={1, 1, 2, 3, 5, 8, 13, 23, 42},\n binnaz={b\"abcd\", b\"efgh\", b\"ijkl\", b\"mnop\"},\n encoded={b\"abcd\", b\"bcda\", b\"cdab\", b\"dabc\"},\n uidz={0, 10, 100, 1000, 10000},\n charz={0, 1, 2, 4, 8, 16},\n setz=[{1, 2, 3}, {}, {2, 3}, {1, 2, 3}],\n )\n\n def empty_sets(self) -> SetStruct:\n return SetStruct(\n enumz={},\n intz={},\n binnaz={},\n encoded={},\n uidz={},\n charz={},\n setz=[{}],\n )\n\n def map_struct(self) -> MapStruct:\n return MapStruct(\n enumz={MyEnum.MyValue1: \"V1\", MyEnum.MyValue2: \"V2\"},\n intz={i: str(i) for i in range(-3, 3)},\n binnaz={b\"a\": self.primitive(), b\"b\": self.primitive()},\n encoded={\"wdf\": 3.1, \"wef\": 2.9},\n flotz={i: float(i) for i in range(5)},\n map_list=[{i: i**2 for i in range(j)} for j in range(2)],\n list_map={1: [1, 2, 3, 5], 2: [4, 8, 16]},\n fast_list_map={1: [-1.0, 1.0], -1: [1.0, -1.0]},\n )\n\n def empty_maps(self) -> MapStruct:\n return MapStruct(\n enumz={},\n encoded={},\n flotz={},\n map_list=[{}],\n list_map={},\n fast_list_map={},\n )\n\n def composed(self) -> ComposeStruct:\n return ComposeStruct(\n enum_=MyEnum.MyValue2,\n renamed_=AnnoyingEnum.FOO,\n primitive=self.primitive(),\n aliased=self.list_struct(),\n )\n\n\nclass PythonCapiRoundtrip(PythonCapiFixture):\n def test_roundtrip_struct(self) -> None:\n i = MyDataItem()\n empty = MyStruct()\n s = self.my_struct()\n self.assertEqual(i, fixture.roundtrip_MyDataItem(i))\n self.assertEqual(empty, fixture.roundtrip_MyStruct(empty))\n self.assertEqual(s, fixture.roundtrip_MyStruct(s))\n\n def test_roundtrip_union(self) -> None:\n self.assertEqual(self.my_union(), fixture.roundtrip_MyUnion(self.my_union()))\n\n def test_roundtrip_enum(self) -> None:\n self.assertEqual(MyEnum.MyValue1, fixture.roundtrip_MyEnum(MyEnum.MyValue1))\n self.assertEqual(MyEnum.MyValue2, fixture.roundtrip_MyEnum(MyEnum.MyValue2))\n\n def test_roundtrip_struct_patch(self) -> None:\n self.assertEqual(\n self.struct_patch(), fixture.roundtrip_MyStructPatch(self.struct_patch())\n )\n empty_patch = MyStructPatch(assign=MyStruct())\n self.assertEqual(empty_patch, fixture.roundtrip_MyStructPatch(empty_patch))\n\n def test_roundtrip_field_adapted(self) -> None:\n a, b = (\"TacosSalad\", \"DaLassoCat\")\n s = StringPair(normal=a, doubled=b)\n self.assertEqual(s, fixture.roundtrip_StringPair(s)),\n\n def test_roundtrip_type_adapted(self) -> None:\n s = DoubledPair(s=\"TacosSalad\", x=42)\n self.assertEqual(s, fixture.roundtrip_DoubledPair(s))\n\n def test_roundtrip_marshal_EmptyStruct(self) -> None:\n self.assertEqual(EmptyStruct(), fixture.roundtrip_EmptyStruct(EmptyStruct()))\n with self.assertRaises(TypeError):\n fixture.roundtrip_EmptyStruct(MyStruct())\n\n def test_roundtrip_TypeError(self) -> None:\n with self.assertRaises(TypeError):\n fixture.roundtrip_MyDataItem(MyEnum.MyValue1)\n with self.assertRaises(TypeError):\n fixture.roundtrip_MyUnion(MyEnum.MyValue1)\n with self.assertRaises(AttributeError):\n fixture.roundtrip_MyEnum(self.my_struct())\n\n def test_roundtrip_marshal_PrimitiveStruct(self) -> None:\n self.assertEqual(\n PrimitiveStruct(), fixture.roundtrip_PrimitiveStruct(PrimitiveStruct())\n )\n self.assertEqual(\n self.primitive(), fixture.roundtrip_PrimitiveStruct(self.primitive())\n )\n self.assertEqual(\n self.primitive_unset(),\n fixture.roundtrip_PrimitiveStruct(self.primitive_unset()),\n )\n unset_primitive = fixture.roundtrip_PrimitiveStruct(self.primitive_unset())\n self.assertIsNone(unset_primitive.floaty)\n self.assertIsNone(unset_primitive.dubby)\n self.assertIsNone(unset_primitive.stringy)\n self.assertIsNone(unset_primitive.bytey)\n with self.assertRaises(TypeError):\n fixture.roundtrip_PrimitiveStruct(self.my_struct())\n\n def test_memleak_primitive(self) -> None:\n # Use non-singleton objects to avoid noise from runtime\n short = 9001\n f = 9001.0\n bytes_ = b\"bippity boppity boo\"\n\n def make_primitive():\n return PrimitiveStruct(\n shorty=short,\n inty=short,\n longy=short,\n floaty=f,\n dubby=f,\n bytey=bytes_,\n )\n\n primitive = make_primitive()\n # This test works to detect leaks of primitives only because they are\n # placed directly into struct internal data without conversion.\n # Non-primitives can be leaked, but not detectable by this test.\n self.assertIs(primitive.shorty, short)\n self.assertIs(primitive.inty, short)\n self.assertIs(primitive.longy, short)\n self.assertIs(primitive.floaty, f)\n self.assertIs(primitive.dubby, f)\n self.assertIs(primitive.bytey, bytes_)\n\n short_refcount = getrefcount(short)\n f_refcount = getrefcount(f)\n bytes_refcount = getrefcount(bytes_)\n\n for _ in range(10):\n fixture.roundtrip_PrimitiveStruct(make_primitive())\n\n # These all fail if there is a leak in Extractor\n self.assertEqual(bytes_refcount, getrefcount(bytes_))\n self.assertEqual(f_refcount, getrefcount(f))\n self.assertEqual(short_refcount, getrefcount(short))\n\n def test_roundtrip_marshal_ListStruct(self) -> None:\n self.assertEqual(ListStruct(), fixture.roundtrip_ListStruct(ListStruct()))\n self.assertEqual(\n self.list_struct(), fixture.roundtrip_ListStruct(self.list_struct())\n )\n self.assertEqual(\n self.empty_lists(), fixture.roundtrip_ListStruct(self.empty_lists())\n )\n self.assertIsNone(fixture.roundtrip_ListStruct(self.empty_lists()).intz)\n self.assertIsNone(fixture.roundtrip_ListStruct(self.empty_lists()).stringz)\n\n def test_roundtrip_marshal_SetStruct(self) -> None:\n self.assertEqual(SetStruct(), fixture.roundtrip_SetStruct(SetStruct()))\n self.assertEqual(\n self.empty_sets(), fixture.roundtrip_SetStruct(self.empty_sets())\n )\n expected = self.set_struct()\n actual = fixture.roundtrip_SetStruct(self.set_struct())\n # sets are serialized in a non-sorted order, so compare field by field\n for f in [\"enumz\", \"intz\", \"binnaz\", \"encoded\", \"uidz\", \"charz\", \"setz\"]:\n self.assertEqual(getattr(expected, f), getattr(actual, f), f)\n\n def test_roundtrip_marshal_MapStruct(self) -> None:\n self.assertEqual(MapStruct(), fixture.roundtrip_MapStruct(MapStruct()))\n self.assertEqual(\n self.empty_maps(), fixture.roundtrip_MapStruct(self.empty_maps())\n )\n expected = self.map_struct()\n actual = fixture.roundtrip_MapStruct(self.map_struct())\n for f in [\n \"enumz\",\n \"intz\",\n \"binnaz\",\n \"encoded\",\n \"flotz\",\n \"map_list\",\n \"list_map\",\n \"fast_list_map\",\n ]:\n self.assertEqual(getattr(expected, f), getattr(actual, f), f)\n\n def test_roundtrip_marshal_ComposeStruct(self) -> None:\n self.assertEqual(\n ComposeStruct(), fixture.roundtrip_ComposeStruct(ComposeStruct())\n )\n self.assertEqual(\n self.composed(), fixture.roundtrip_ComposeStruct(self.composed())\n )\n\n\nclass PythonCapiTypeCheck(PythonCapiFixture):\n def test_typeCheck_struct(self) -> None:\n i = MyDataItem()\n s = self.my_struct()\n self.assertTrue(fixture.check_MyDataItem(i))\n self.assertFalse(fixture.check_MyDataItem(s))\n self.assertTrue(fixture.check_MyStruct(s))\n self.assertFalse(fixture.check_MyStruct(i))\n\n def test_typeCheck_union(self) -> None:\n self.assertTrue(fixture.check_MyUnion(self.my_union()))\n self.assertFalse(fixture.check_MyUnion(self.my_struct()))\n self.assertFalse(fixture.check_MyUnion(MyEnum.MyValue1))\n\n def test_typeCheck_struct_patch(self) -> None:\n self.assertTrue(fixture.check_MyStructPatch(self.struct_patch()))\n self.assertFalse(fixture.check_MyStructPatch(self.my_struct()))\n self.assertFalse(fixture.check_MyStructPatch(MyEnum.MyValue1))\n\n def test_typeCheck_enum(self) -> None:\n self.assertTrue(fixture.check_MyEnum(MyEnum.MyValue1))\n self.assertTrue(fixture.check_MyEnum(MyEnum.MyValue2))\n self.assertFalse(fixture.check_MyEnum(self.my_struct()))\n\n def test_roundtrip_field_adapted(self) -> None:\n a, b = (\"TacosSalad\", \"DaLassoCat\")\n self.assertTrue(fixture.check_StringPair(StringPair(normal=a, doubled=b)))\n self.assertFalse(fixture.check_StringPair(MyEnum.MyValue1))\n\n def test_roundtrip_type_adapted(self) -> None:\n self.assertTrue(\n fixture.check_DoubledPair(DoubledPair(s=\"TacosSalad\" * 2, x=42))\n )\n self.assertFalse(fixture.check_DoubledPair(MyEnum.MyValue1))\n\n def test_typeCheck_PrimitiveStruct(self) -> None:\n self.assertTrue(fixture.check_PrimitiveStruct(self.primitive()))\n self.assertTrue(fixture.check_PrimitiveStruct(PrimitiveStruct()))\n self.assertFalse(fixture.check_PrimitiveStruct(MyEnum.MyValue1))\n self.assertFalse(fixture.check_PrimitiveStruct(self.my_struct()))\n\n def test_typeCheck_ListStruct(self) -> None:\n self.assertTrue(fixture.check_ListStruct(self.list_struct()))\n self.assertTrue(fixture.check_ListStruct(self.empty_lists()))\n self.assertTrue(fixture.check_ListStruct(ListStruct()))\n self.assertFalse(fixture.check_ListStruct(MyEnum.MyValue1))\n self.assertFalse(fixture.check_ListStruct(self.my_struct()))\n\n def test_typeCheck_SetStruct(self) -> None:\n self.assertTrue(fixture.check_SetStruct(self.set_struct()))\n self.assertTrue(fixture.check_SetStruct(self.empty_sets()))\n self.assertTrue(fixture.check_SetStruct(SetStruct()))\n self.assertFalse(fixture.check_SetStruct(MyEnum.MyValue1))\n self.assertFalse(fixture.check_SetStruct(self.my_struct()))\n\n def test_typeCheck_MapStruct(self) -> None:\n self.assertTrue(fixture.check_MapStruct(self.map_struct()))\n self.assertTrue(fixture.check_MapStruct(self.empty_maps()))\n self.assertTrue(fixture.check_MapStruct(MapStruct()))\n self.assertFalse(fixture.check_MapStruct(MyEnum.MyValue1))\n self.assertFalse(fixture.check_MapStruct(self.my_struct()))\n\n def test_typeCheck_ComposeStruct(self) -> None:\n self.assertTrue(fixture.check_ComposeStruct(self.composed()))\n self.assertTrue(fixture.check_ComposeStruct(ComposeStruct()))\n self.assertFalse(fixture.check_ComposeStruct(MyEnum.MyValue1))\n self.assertFalse(fixture.check_ComposeStruct(self.my_struct()))\n","sub_path":"third-party/thrift/src/thrift/test/python_capi/capi_test.py","file_name":"capi_test.py","file_ext":"py","file_size_in_byte":14747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"145275856","text":"str = \"abcdf\"\n\nletters = set() # or list not differs\n\n\ndef uni_char(s):\n for let in s:\n if let in letters:\n return False\n else:\n letters.add(let)\n\n return True\n\n\nprint(\"solution 1 manually way :\", uni_char(str))\n\n'''\nfrom collections import defaultdict\n\nstr = \"abcdfgf\"\n\n\ndef uniq_char(s):\n dict = defaultdict(int)\n redundant_chars = []\n uniq_chars = []\n for char in s:\n dict[char] += 1\n for char in dict:\n if dict[char] != 1:\n redundant_chars.append(char)\n return False\n return True\n\n\nprint(\"solution 2 manually way :\", uniq_char(str))\n\n'''\n# ***************** using set() advantage *********************\n# just learn the interviewer about that solution only not not do it but use the manually solution instade\n# set() give u the unique number of element even if the number is duplicated , for example\n# print(set(str))\n'''\ndef uni_char(s):\n return bool(len(set(str)) == len(str))\n\n\nprint(\"Solution 2 using set trick \", uni_char(str))\n'''\n","sub_path":"Array/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"19168510","text":"from django.contrib import admin\n\nfrom .models import Canal, Industria\n\n\n# Register your models here.\n\n\nclass IndustriAdmin(admin.ModelAdmin):\n list_display = ['nombre','descripcion']\n\n def get_queryset(self, request):\n qs = super().get_queryset(request)\n return qs.order_by(\"nombre\")\n\n\nadmin.site.register(Canal)\nadmin.site.register(Industria, IndustriAdmin)\n","sub_path":"empresas/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"290645358","text":"'''\nGiven a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.\n\nExamples:\nInput: S = \"a1b2\"\nOutput: [\"a1b2\", \"a1B2\", \"A1b2\", \"A1B2\"]\n\nInput: S = \"3z4\"\nOutput: [\"3z4\", \"3Z4\"]\n\nInput: S = \"12345\"\nOutput: [\"12345\"]\n'''\ndef letterCasePermutation(S):\n ans = [\"\"]\n for c in S:\n if c.isnumeric():\n ans = [s+c for s in ans]\n else:\n s1 = [s+c.lower() for s in ans]\n s2 = [s+c.upper() for s in ans]\n ans = s1 + s2\n return ans\n\nprint(letterCasePermutation(\"a1b2\"))\n\n","sub_path":"LeetCode/LetterCasePermutation.py","file_name":"LetterCasePermutation.py","file_ext":"py","file_size_in_byte":637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"618254916","text":"\"\"\"\nstep 1 : 实现一个登录的页面\n关键点: 使用wtf from 实现登录的表单\n\nstep 2 :使用sqlalchemy 实现了基本的查询todolist里面的内容\n关键点:\n1. 如果不熟悉orm,可能要先看一下sqlalchemy\n2. 然后看一下flask-sqlalchemy 这个东西 ,熟悉一下基本的语法\n\n\nstep 3:\n1. 修改的一部分的index页面,是index的页面更加完整一点\n2. 修改了一部分的登录界面的登录逻辑\n3. 实现了登录页面的消息闪现 flash : http://docs.jinkan.org/docs/flask/patterns/flashing.html\n\nstep 4 :\n1. flask_login 模块的使用,只有登录之后才能访问某些页面(如果不使用flask_login,可以使用session来解决这个问题)\n\nstep 5:\n使用bootstrap \n在step5里面使用了一个小例子表示了一下,(localhost:port/test),添加了一个index_test.html的页面就是用bootstrap写的\n\nstep 6:\n1. 在login页面里面加上了bootstrap的前端\n2. 后台的逻辑基本上写好了\n3. 下一步就是完整的加上前端\n\"\"\"\n\nfrom flask import (Flask, render_template, redirect, url_for, request, flash)\nimport forms\nimport config\nfrom ext import db,login_manager\nfrom models import TodoList, User\n#登录权限管理的扩展\nfrom flask_login import login_required, login_user, logout_user, current_user\nfrom flask_bootstrap import Bootstrap\n\napp = Flask(__name__)\napp.secret_key=config.SECRET_KEY\napp.config['SQLALCHEMY_DATABASE_URI'] = \"mysql://root:root@127.0.0.1/test\"\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\ndb.init_app(app)\n\n#flask_login,注意login_manager在ext文件里面定义\nlogin_manager.init_app(app)\nlogin_manager.login_view = \"login\"\nbootstrap = Bootstrap(app)\n\n#flask_login\n@login_manager.user_loader\ndef load_user(user_id):\n return User.query.filter_by(id=int(user_id)).first()\n\n\n\n@app.route('/test', methods=['GET', 'POST'])\ndef test():\n return render_template(\"index_test.html\")\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n form = forms.LoginFrom()\n if request.method == 'GET':\n return render_template(\"login.html\",form=form)\n else:\n username=request.form['username']\n password=request.form['password']\n user = User.query.filter_by(username=request.form['username'], password=request.form['password']).first()\n if user:\n #flask_login\n login_user(user)\n flash('you have logged in!')\n return redirect(url_for('showtodolist' ))\n else:\n flash(\"error password !\")\n return render_template(\"login.html\",form=form)\n #return \"

    home post method

    post data is {} and {}\".format(username,password)\n\n\n@app.route('/show', methods=['GET', 'POST'])\n@login_required\ndef showtodolist():\n form = forms.TodolistFrom()\n if request.method==\"GET\":\n todolists =TodoList.query.all()\n return render_template(\"index.html\",todolists=todolists,form=form)\n else:\n title=request.form['title']\n status=request.form['status']\n todolist = TodoList(current_user.id, title, status)\n db.session.add(todolist)\n db.session.commit()\n flash('You have add a new todo list')\n return redirect(url_for('showtodolist'))\n\n@app.route('/delete/')\n@login_required\ndef delete_todo_list(id):\n todolist = TodoList.query.filter_by(id=id).first_or_404()\n db.session.delete(todolist)\n db.session.commit()\n flash('You have delete a todo list')\n return redirect(url_for('show_todo_list'))\n\n@app.route('/change/', methods=['GET', 'POST'])\n@login_required\ndef change_todo_list(id):\n return \"

    change to do list

    \"\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('you have logout!')\n return redirect(url_for('login'))\n\n\nif __name__==\"__main__\":\n app.run(debug=True,port=5002)","sub_path":"step6/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"634556106","text":"# -*- coding utf-8 -*-\n# @Time : 2021/5/29 17:15\n# @Author : DH\n# @Software : PyCharm\n# @Desc : 一辆车追踪另一辆车的异步版本\nimport asyncio\nimport json\nimport socket\nimport traceback\n\nimport aiofiles\nimport aiohttp\nfrom aiofiles.threadpool import AsyncTextIOWrapper\n\nfrom car_control import *\nfrom models import Car, UWB\nfrom utils import get_root_path\n\nROOT_PATH = get_root_path()\ntotal_car_number = 5\nip2CarNumber = {\n '127.0.0.1': 1,\n '192.168.43.64': 2,\n '192.168.43.40': 3,\n '192.168.43.242': 5,\n}\nip2UWBNumber = {\n '192.168.43.253': 1,\n '192.168.43.141': 2,\n '192.168.43.142': 3,\n}\ncar_map = {}\nfor i in range(1, total_car_number + 1):\n car_map[i] = Car(i)\nuwb_map = {}\n# 每次测试需要手动填入三个 uwb 的 gps 信息\nuwb_gps = [[103.92792, 30.75436], [103.92768, 30.75445], [0, 0]]\nfor i in range(1, 4):\n uwb_map[i] = UWB(i, uwb_gps[i - 1])\n\n\ndef accept_socket(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):\n ip = writer.get_extra_info(\"peername\")[0]\n global car_map, uwb_map\n if ip2UWBNumber.get(ip, None):\n # 如果是UWBip地址,则需要建立单独的线程来控制uwb;\n uwb_number = ip2UWBNumber[ip]\n uwb = uwb_map[uwb_number]\n # 如果对应uwb没有活跃的连接线程,则创建线程;否则,忽视。\n if not uwb.connected:\n uwb.connect_uwb(reader)\n asyncio.create_task(uwb.receive())\n print(\"UWB {0} 已连接!\".format(uwb.uwb_number))\n elif ip2CarNumber.get(ip, None):\n # 如果为小车地址;\n car_number = ip2CarNumber[ip]\n car = car_map[car_number]\n # 如果对应小车没有建立连接,则连接并创建receive协程\n if not car.connected:\n car.connect_car(reader, writer)\n asyncio.create_task(car.receive())\n print(\"小车 {0} 已连接!\".format(car.car_number))\n\n\nasync def listen_socket():\n \"\"\" 监听小车和uwb的连接请求 127.0.0.1\"\"\"\n server = await asyncio.start_server(accept_socket, host=\"192.168.43.230\", port=8888, family=socket.AF_INET)\n print(\"等待连接中...\")\n try:\n await server.serve_forever()\n finally:\n server.close()\n await server.wait_closed()\n\n\nasync def post_data(session: aiohttp.ClientSession):\n \"\"\" 上传各个小车的数据给后台服务器 \"\"\"\n url = \"http://192.168.43.35:8080/car/insert\"\n headers = {'content-type': 'application/json'}\n data_list = []\n for car in car_map.values():\n if car.connected:\n base_map = dict()\n base_map[\"number\"] = car.car_number\n base_map[\"gps\"] = car.gps\n base_map[\"angle\"] = car.angle\n base_map[\"battery\"] = car.battery\n data_list.append(base_map)\n json_data = json.dumps(data_list)\n while True:\n if session.closed:\n break\n await session.post(url=url, data=json_data, headers=headers)\n print(json_data)\n await asyncio.sleep(2.0)\n\n\nasync def main():\n asyncio.create_task(listen_socket())\n cmd_log = await aiofiles.open('{0}/logs/car_logs/car_cmd_{1}.txt'.format(\n ROOT_PATH, datetime.now().strftime('%m_%d')), mode='a') # type: AsyncTextIOWrapper\n await cmd_log.write(\"************* 开始测试,时间:\" + datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\n + \" *************\" + '\\n')\n target_car = car_map[5]\n car = car_map[3]\n while not target_car.connected or not car.connected:\n await asyncio.sleep(0.1)\n\n session = aiohttp.ClientSession()\n asyncio.create_task(post_data(session))\n try:\n while True:\n # await asyncio.sleep(0.5)\n if car.gps is not None:\n info = await move_forward_target(car, target_car.position, variable_speed=True)\n await cmd_log.write(info + '\\n')\n except Exception:\n traceback.print_exc()\n finally:\n print(\"服务器关闭!\")\n await cmd_log.write(\"************* 结束测试,时间:\" + datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\n + \" *************\" + '\\n\\n')\n await cmd_log.close()\n await session.close()\n await asyncio.sleep(1.0)\n\n\nif __name__ == '__main__':\n try:\n asyncio.run(main())\n except KeyboardInterrupt:\n print(\"键盘中断!\")\n","sub_path":"src/aio_server.py","file_name":"aio_server.py","file_ext":"py","file_size_in_byte":4406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"582569700","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n hashValue = {}\n \n for i in strs:\n current = ''.join(sorted(i))\n if current in hashValue:\n hashValue[current].append(i)\n else:\n hashValue[current] = [i]\n return list(hashValue.values())\n","sub_path":"baekjoon/groupAnagrams.py","file_name":"groupAnagrams.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"146500812","text":"from django.urls import path\nfrom . import views\n# when it comes from url of crm here then it triggers these 3 function which takes us to views file\nurlpatterns = [\n # base url\n path('', views.home, name=\"home\"),\n # other pages\n path('products/', views.products,name='products'),\n # / added this for dynamic url routing i.e we can find customer by id i.e /customer/4/\n path('customer//', views.customer,name=\"i\"),\n path('create_order//', views.createOrder, name=\"create_order\"),\n path('update_order//', views.updateOrder, name=\"update_order\"),\n path('delete_order//', views.deleteOrder, name=\"delete_order\"),\n]\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"498445851","text":"from tkinter import *\nfrom PIL import Image, ImageTk\nimport threading, time, calendar\nfrom agente import Agente\nfrom SNMP import *\nfrom notificador import Notificador\nfrom logger import Logger\nimport rrdtool\nfrom http_cliente import HTTPMonitor\nfrom PDFM import PDF\nfrom smtp_cliente import SENSOR\nfrom Sensor_SSH import SSH\nfrom ftp_cliente import FTPMonitor\nfrom sensDNS import sensDNS\n\nclass Monitor(threading.Thread):\n\t\"\"\"docstring for Agente\"\"\"\n\tdef __init__(self,id_agente):\n\t\tthreading.Thread.__init__(self)\n\t\tself.agente=Agente(id_agente)\n\t\tself.data={}\n\t\tself.top=Toplevel()\n\t\tself.top.geometry(\"2100x800\")\n\t\tself.top.resizable(0,0)\n\t\tself.b = Button(self.top, text=\"Salir\", command=self.salir)\n\t\tself.b.grid(row=1, column=2, sticky=W+E+N+S)\n\t\tself.boton_pdf = Button(self.top, text=\"Generar reporte\", command=self.generar_pdf)\n\t\tself.boton_pdf.grid(row=1, column=3, sticky=W+E+N+S)\n\t\tself.frame=Frame(self.top, width = 550, height = 150, relief = 'raised', borderwidth=3)\n\t\tself.frame.grid(row = 1, column = 0, columnspan=1, sticky=W+E+N+S)\n\t\tself.continuar=True\n\t\tself.image=[\"\"]*8\n\t\tself.photo=[\"\"]*8\n\t\tself.label=[\"\"]*8\n\t\tself.umbralCPU, self.umbralRAM, self.umbralHDD=self.obtenerUmbrales()\n\t\tself.notificacionCPU=self.notificacionRAM=self.notificacionHDD=False\n\t\tself.noti=Notificador(self.agente.hostname)\n\t\tself.log=Logger(self.agente.hostname)\n\t\tself.mostrarInfo()\n\t\tself.crearRRDs()\n\t\t#sensores\n\t\tself.monitorHTPP=HTTPMonitor(self.agente.ip,5000)\n\t\tself.monitorSMTP=SENSOR()\n\t\t#self.monitorSSH=SSH(self.agente.ip,\"gabs\",\"0001\")\n\t\tself.monitorFTP=FTPMonitor(self.agente.ip,\"gabs\",\"0001\")\n\t\tself.monitorDNS=sensDNS()\n\tdef run(self):\n\t\twhile self.continuar:\n\n\t\t\t#Monitorear HTTP\n\t\t\tself.monitorHTPP.actualizar()\n\t\t\t#self.monitorHTPP.imprimir()\n\t\t\t#Monitorear SMTP\n\t\t\tself.monitorSMTP.scan_smtp()\n\n\t\t\t#self.monitorSSH.SSHConnection()\n\t\t\tself.monitorFTP.actualizar_SensorFTP()\n\t\t\tself.monitorFTP.actualizar_SensorFTP_SFC()\n\t\t\tself.monitorDNS.dnsServer('lostani.ex.net')\n\n\n\t\t\t#Interfaces\n\t\t\tself.graficarRRD('IF-MIB','ifInOctets','ifOutOctets',\"interfaz\",\"Tráfico de red en interfaces ('ifInOctets,ifOutOctets')\",2)\n\t\t\t#ICMP ->Deprecated\n\t\t\tself.graficarRRD('IP-MIB','icmpInMsgs','icmpOutMsgs',\"icmp\",\"Tráfico ICMP ('icmpInMsgs','icmpOutMsgs')\",0)\n\t\t\t#TCP\n\t\t\tself.graficarRRD('TCP-MIB','tcpInSegs','tcpOutSegs',\"tcp\",\"Tráfico segmentos TCP ('tcpInSegs','tcpOutSegs')\",0)\n\t\t\t#SNMP\n\t\t\tself.graficarRRD('SNMPv2-MIB','snmpInPkts','snmpOutPkts',\"snmp\", \"Tráfico SNMP ('snmpInPkts','snmpOutPkts')\",0)\n\t\t\t########################\n\t\t\t#LOS ULTIMOS VALORES PARA CPU, RAM Y HDD, VARIAN PARA WINDOWS Y LINUX\n\t\t\t#PARA WINDOWS LOS VALORES SON: 6,3,1\n\t\t\t#PARA LINUX SON: 196608,1,36\n\t\t\t##########################\n\t\t\tif self.agente.nombre_so==\"Ubuntu\":\n\t\t\t\t#UDP\n\t\t\t\tself.graficarRRD('UDP-MIB','udpInDatagrams','udpOutDatagrams',\"udp\",\"Tráfico UDP Datagramas ('udpInDatagrams','udpOutDatagrams')\",0)\n\t\t\t\t#CPU\n\t\t\t\tself.graficarCPU(\"HOST-RESOURCES-MIB\",\"hrProcessorLoad\",\"cpu\",\"Uso del Procesador\",196608)\n\t\t\t\t#RAM\n\t\t\t\tself.graficarRAM(\"HOST-RESOURCES-MIB\",\"hrStorageSize\",\"hrStorageUsed\",\"hrStorageAllocationUnits\",\"ram\", \"Uso de RAM\",1)\n\t\t\t\t#HDD\n\t\t\t\tself.graficarHDD(\"HOST-RESOURCES-MIB\",\"hrStorageSize\",\"hrStorageUsed\",\"hrStorageAllocationUnits\",\"hdd\", \"Uso de HHD\",36)\n\t\t\telif self.agente.nombre_so==\"Windows\":\n\t\t\t\t#UDP\n\t\t\t\tself.graficarRRD('UDP-MIB','udpInDatagrams','udpOutDatagrams',\"udp\",\"Tráfico UDP Datagramas ('udpInDatagrams','udpOutDatagrams')\",0)\n\t\t\t\t#CPU\n\t\t\t\tself.graficarCPU(\"HOST-RESOURCES-MIB\",\"hrProcessorLoad\",\"cpu\",\"Uso del Procesador\",6)\n\t\t\t\t#RAM\n\t\t\t\tself.graficarRAM(\"HOST-RESOURCES-MIB\",\"hrStorageSize\",\"hrStorageUsed\",\"hrStorageAllocationUnits\",\"ram\", \"Uso de RAM\",3)\n\t\t\t\t#HDD\n\t\t\t\tself.graficarHDD(\"HOST-RESOURCES-MIB\",\"hrStorageSize\",\"hrStorageUsed\",\"hrStorageAllocationUnits\",\"hdd\", \"Uso de HHD\",1)\n\t\t\telif self.agente.nombre_so==\"MacOs\":\n\t\t\t\t#UDP\n\t\t\t\tself.graficarRRD('UDP-MIB','udpInErrors','udpOutDatagrams',\"udp\",\"Tráfico UDP Datagramas ('udpInDatagrams','udpOutDatagrams')\",0)\n\t\t\t\t#CPU\n\t\t\t\tself.graficarCPU(\"HOST-RESOURCES-MIB\",\"hrProcessorLoad\",\"cpu\",\"Uso del Procesador\",196608)\n\t\t\t\t#RAM\n\t\t\t\tself.graficarRAM(\"HOST-RESOURCES-MIB\",\"hrStorageSize\",\"hrStorageUsed\",\"hrStorageAllocationUnits\",\"ram\", \"Uso de RAM\",1)\n\t\t\t\t#HDD->el 31 es tentativo\n\t\t\t\tself.graficarHDD(\"HOST-RESOURCES-MIB\",\"hrStorageSize\",\"hrStorageUsed\",\"hrStorageAllocationUnits\",\"hdd\", \"Uso de HDD\",31)\n\t\t\telif self.agente.nombre_so==\"Linux\":\n\t\t\t\t#UDP\n\t\t\t\tself.graficarRRD('UDP-MIB','udpInDatagrams','udpOutDatagrams',\"udp\",\"Tráfico UDP Datagramas ('udpInDatagrams','udpOutDatagrams')\",0)\n\t\t\t\t#CPU\n\t\t\t\tself.graficarCPU(\"HOST-RESOURCES-MIB\",\"hrProcessorLoad\",\"cpu\",\"Uso del Procesador\",1281)\n\t\t\t\t#RAM\n\t\t\t\tself.graficarRAM(\"HOST-RESOURCES-MIB\",\"hrStorageSize\",\"hrStorageUsed\",\"hrStorageAllocationUnits\",\"ram\", \"Uso de RAM\",1)\n\t\t\t\t#HDD\n\t\t\t\tself.graficarHDD(\"HOST-RESOURCES-MIB\",\"hrStorageSize\",\"hrStorageUsed\",\"hrStorageAllocationUnits\",\"hdd\", \"Uso de HHD\",31)\n\n\t\t\t#Ahora actualizamos las imágenes\n\t\t\tself.actualizarImagen(0,self.agente.hostname+\"_\"+self.agente.id_agente+\"_interfaz.png\",2,0)\n\n\t\t\tself.actualizarImagen(1,self.agente.hostname+\"_\"+self.agente.id_agente+\"_icmp.png\",3,0)\n\n\t\t\tself.actualizarImagen(2,self.agente.hostname+\"_\"+self.agente.id_agente+\"_tcp.png\",2,1)\n\n\t\t\tself.actualizarImagen(3,self.agente.hostname+\"_\"+self.agente.id_agente+\"_udp.png\",3,1)\n\n\t\t\tself.actualizarImagen(4,self.agente.hostname+\"_\"+self.agente.id_agente+\"_snmp.png\",2,2)\n\n\t\t\tself.actualizarImagen(5,self.agente.hostname+\"_\"+self.agente.id_agente+\"_cpu.png\",2,3)\n\n\t\t\tself.actualizarImagen(6,self.agente.hostname+\"_\"+self.agente.id_agente+\"_ram.png\",3,3)\n\n\t\t\tself.actualizarImagen(7,self.agente.hostname+\"_\"+self.agente.id_agente+\"_hdd.png\",2,4)\n\n\t\t\ttime.sleep(5)\n\t\tself.top.destroy()\n\tdef salir(self):\n\t\tself.continuar=False\n\tdef generar_pdf(self):\n\t\tPDF(self.agente.id_agente,self.monitorHTPP,self.monitorSMTP,self.monitorFTP,self.monitorDNS,self.agente.hostname+\"_\"+self.agente.id_agente+\"_cpu.png\",self.agente.hostname+\"_\"+self.agente.id_agente+\"_ram.png\",self.agente.hostname+\"_\"+self.agente.id_agente+\"_hdd.png\")\n\tdef obtenerUmbrales(self):\n\t\tumbrales=[]\n\t\twith open(\"umbrales.txt\") as f:\n\t\t\tfor i, linea in enumerate(f):\n\t\t\t\tumbrales.append(linea.split(\":\")[1])\n\t\treturn umbrales\n\tdef mostrarInfo(self):\n\t\timage1=Image.open(self.agente.logo_so).resize((50,50),Image.ANTIALIAS)\n\t\tphoto1=ImageTk.PhotoImage(image1)\n\t\tlabel1=Label(self.frame,image=photo1)\n\t\tlabel1.image=photo1\n\t\tlabel1.grid(row=1, column=1, sticky=W+E+N+S)\n\t\tLabel(self.frame, text=\"ID agente: \"+self.agente.id_agente).grid(row=2, column=1, sticky=W)\n\t\tLabel(self.frame, text=\"Hostname: \"+self.agente.hostname).grid(row=3, column=1, sticky=W)\n\t\tLabel(self.frame, text=\"IP: \"+self.agente.ip).grid(row=4, column=1, sticky=W)\n\t\tLabel(self.frame, text=\"Comunidad: \"+self.agente.comunidad).grid(row=5, column=1, sticky=W)\n\t\tLabel(self.frame, text=\"Versión SNMP: \"+str((int(self.agente.version))+1)).grid(row=6, column=1, sticky=W)\n\t\tLabel(self.frame, text=\"Puerto: \"+self.agente.puerto).grid(row=7, column=1, sticky=W)\n\t\tLabel(self.frame, text=\"Nombre SO: \"+self.agente.nombre_so).grid(row=2, column=2, sticky=W)\n\t\tLabel(self.frame, text=\"Versión SO: \"+self.agente.version_so).grid(row=3, column=2, sticky=W)\n\t\tLabel(self.frame, text=\"Número de interfaces: \"+self.agente.num_interfaces).grid(row=4, column=2, sticky=W)\n\t\tLabel(self.frame, text=\"Ubicación física: \"+self.agente.ubicacion).grid(row=5, column=2, sticky=W)\n\t\tLabel(self.frame, text=\"Contacto: \"+self.agente.contacto).grid(row=6, column=2, sticky=W)\n\tdef crearRRDs(self):\n\t\t#Para tr{afico de red:\n\t\tcrearRRDDos(self.agente.hostname+\"_\"+self.agente.id_agente+\"_interfaz.rrd\",\"N\",\"1\",\"60\",\"1\",\"1\",\"100\",\"100\",\"COUNTER\")\n\t\t#Para tr{afico de IP\n\t\tcrearRRDDos(self.agente.hostname+\"_\"+self.agente.id_agente+\"_icmp.rrd\",\"N\",\"1\",\"60\",\"1\",\"1\",\"100\",\"100\",\"GAUGE\")\n\t\t#Para tr{afico de TCP segmentos\n\t\tcrearRRDDos(self.agente.hostname+\"_\"+self.agente.id_agente+\"_tcp.rrd\",\"N\",\"1\",\"60\",\"1\",\"1\",\"100\",\"100\",\"GAUGE\")\n\t\t#Para tr{afico de Datagramas UDP\n\t\tcrearRRDDos(self.agente.hostname+\"_\"+self.agente.id_agente+\"_udp.rrd\",\"N\",\"1\",\"60\",\"1\",\"1\",\"100\",\"100\",\"COUNTER\")\n\t\t#Para tr{afico de SNMP\n\t\tcrearRRDDos(self.agente.hostname+\"_\"+self.agente.id_agente+\"_snmp.rrd\",\"N\",\"1\",\"60\",\"1\",\"1\",\"100\",\"100\",\"COUNTER\")\n\t\t#Para CPU\n\t\tcrearRRDUno(self.agente.hostname+\"_\"+self.agente.id_agente+\"_cpu.rrd\",\"N\",\"1\",\"60\",\"1\",\"1\",\"100\",\"100\",\"GAUGE\")\n\t\t#Para Ram\n\t\tcrearRRDTres(self.agente.hostname+\"_\"+self.agente.id_agente+\"_ram.rrd\",\"N\",\"1\",\"60\",\"1\",\"1\",\"1\",\"100\",\"100\",\"100\",\"GAUGE\")\n\t\t#Para HDD\n\t\tcrearRRDTres(self.agente.hostname+\"_\"+self.agente.id_agente+\"_hdd.rrd\",\"N\",\"1\",\"60\",\"1\",\"1\",\"1\",\"100\",\"100\",\"100\",\"GAUGE\")\n\n\tdef graficarRRD(self, grupo, oid1, oid2, archivo, header, numero):\n\t\tultimo=rrdtool.last(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\")\n\t\tconsulta=consultaSNMP(self.agente.comunidad,self.agente.ip,int(self.agente.version),numero,grupo,oid1,oid2,int(self.agente.puerto))\n\t\tif consulta[0]!=\"\" or consulta[1]!=\"\":\n\t\t\tvalor = \"N:\" + str(consulta[0]) + ':' + str(consulta[1])\n\t\t\t#print (valor)\n\t\t\trrdtool.update(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\", valor)\n\t\t\trrdtool.dump(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\",self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".xml\")\n\t\t\tret = rrdtool.graph(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".png\",\n\t\t \"--start\",str(ultimo-100),\n\t\t \"--end\",\"+100\",\n\t\t \"--vertical-label=Bytes/s\",\n\t\t \"--title=\"+header,\n\t\t \"DEF:in=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:in:AVERAGE\",\n\t\t \"DEF:out=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:out:AVERAGE\",\n\t\t \"LINE1:in#00FF00:In traffic\",\n\t\t \"LINE1:out#0000FF:Out traffic\")\n\tdef graficarCPU(self, grupo, oid1, archivo, header, numero):\n\t\tumbral=int(self.umbralCPU)\n\t\tultimo=rrdtool.last(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\")\n\t\tprimero=rrdtool.first(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\")\n\t\tconsulta=consultav2SNMP(self.agente.comunidad,self.agente.ip,int(self.agente.version),numero,grupo,oid1,int(self.agente.puerto))\n\t\tif consulta!=\"\":\n\t\t\tvalor = \"N:\" + str(consulta)\n\t\t\trrdtool.update(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\", valor)\n\t\t\trrdtool.dump(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\",self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".xml\")\n\t\t\tret = rrdtool.graphv(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".png\",\n\t\t \"--start\",str(ultimo-100),\n\t\t \"--end\",str(ultimo+100),\n\t\t #\"--end\",str(ultimo+200),\n\t\t \"--vertical-label=Porcentaje/s\",\n\t\t \"--title=\"+header,\n\t\t\t\t\t\t \"--lower-limit\",\"0\",\n\t\t\t\t\t\t \"--upper-limit\",\"100\",\n\t\t \"DEF:usage=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:valor1:AVERAGE\",\n\t\t \"CDEF:umbral\"+str(umbral-20)+\"_1=usage,\"+str(umbral-20)+\",GT,usage,\"+str(umbral-10)+\",LT,EQ,usage,0,IF\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-10)+\"_1=usage,\"+str(umbral-10)+\",GT,usage,\"+str(umbral)+\",LT,EQ,usage,0,IF\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral)+\"_1=usage,\"+str(umbral)+\",GT,usage,\"+str(umbral+(100-umbral))+\",LT,EQ,usage,0,IF\",\n\t\t\t\t\t\t \"AREA:usage#FFBB0077:Uso de CPU\",\n\t\t \"VDEF:m=usage,LSLSLOPE\",\n\t\t \"VDEF:b=usage,LSLINT\",\n\t\t \"CDEF:avg=usage,POP,m,COUNT,*,b,+\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-20)+\"=avg,\"+str(umbral-20)+\",\"+str(umbral-10)+\",LIMIT\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-10)+\"=avg,\"+str(umbral-10)+\",\"+str(umbral)+\",LIMIT\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral)+\"=avg,\"+str(umbral)+\",\"+str(umbral+(100-umbral))+\",LIMIT\",\n\t\t\t\t\t\t \"VDEF:minUmbral\"+str(umbral)+\"=umbral\"+str(umbral)+\",FIRST\",\n\t\t\t\t\t\t \"VDEF:last=usage,LAST\",\n\t\t\t\t\t\t \"PRINT:last:%6.2lf %S\",\n\t\t\t\t\t\t \"GPRINT:minUmbral\"+str(umbral)+\": Se alcanzará el \"+str(umbral)+\"% @ %c :strftime\",\n\t\t \"LINE1:avg#FF9F00\",\n \t\t\t\t \t \"LINE2:\"+str(umbral-20),\n\t\t\t\t\t\t \"AREA:10#FF000022::STACK\",\n\t\t\t\t\t\t \"AREA:10#FF000044::STACK\",\n\t\t\t\t\t\t \"AREA:\"+str(100-umbral)+\"#FF000066::STACK\",\n\t\t\t\t\t \"AREA:umbral\"+str(umbral-20)+\"#0077FF77:Tráfico de carga mayor que el \"+str(umbral-20)+\" y menor que el \"+str(umbral-10)+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-10)+\"#00880077:Tráfico de carga mayor que el \"+str(umbral-10)+\" y menor que el \"+str(umbral)+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral)+\"#FF000088:Tráfico de carga mayor que el \"+str(umbral)+\" y menor que el \"+str(umbral+(100-umbral))+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-20)+\"_1#0077FF77\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-10)+\"_1#00880077\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral)+\"_1#FF000088\")\n\t\t\tvalor=float(ret[\"print[0]\"])\n\t\t\tif valor>float(umbral):\n\t\t\t\tif not self.notificacionCPU:\n\t\t\t\t\tself.notificacionCPU=True\n\t\t\t\t\t#self.noti.enviarCorreo(0,self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".png\")\n\t\t\t\t\tself.log.escribirLog(0)\n\t\t\telse:\n\t\t\t\tself.notificacionCPU=False\n\n\tdef graficarHDD(self, grupo, oid1, oid2,oid3, archivo, header, numero):\n\t\tumbral=int(self.umbralHDD)\n\t\tultimo=rrdtool.last(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\")\n\t\tprimero=rrdtool.first(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\")\n\t\tconsulta=consultav5SNMP(self.agente.comunidad,self.agente.ip,int(self.agente.version),numero,grupo,oid1,oid2,oid3,int(self.agente.puerto))\n\t\tif consulta[0]!=\"\" or consulta[1]!=\"\" or consulta[2]!=\"\":\n\t\t\tvalor = \"N:\" + str(consulta[0]) + ':' + str(consulta[1]) + ':' + str(consulta[2])\n\t\t\trrdtool.update(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\", valor)\n\t\t\trrdtool.dump(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\",self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".xml\")\n\t\t\tret = rrdtool.graphv(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".png\",\n\t\t \"--start\",str(ultimo-100),\n\t\t \"--end\",str(ultimo+100),\n\t\t \"--vertical-label=Porcentaje/s\",\n\t\t \"--title=\"+header,\n\t\t \"--lower-limit\",\"0\",\n\t\t\t\t \t\t \"--upper-limit\",\"100\",\n\t\t \"DEF:val1=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:size:AVERAGE\",\n\t\t \"DEF:val2=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:used:AVERAGE\",\n\t\t \"DEF:val3=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:all:AVERAGE\",\n\t\t \"CDEF:totalHDD=val1,val3,*\",\n\t\t \"CDEF:usoHDDporcentaje=val2,val3,*,100,*,totalHDD,/\",\n\t\t\t\t\t\t \"CDEF:usoHDD=val2,val3,*\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-20)+\"_1=usoHDDporcentaje,\"+str(umbral-20)+\",GT,usoHDDporcentaje,\"+str(umbral-10)+\",LT,EQ,usoHDDporcentaje,0,IF\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-10)+\"_1=usoHDDporcentaje,\"+str(umbral-10)+\",GT,usoHDDporcentaje,\"+str(umbral)+\",LT,EQ,usoHDDporcentaje,0,IF\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral)+\"_1=usoHDDporcentaje,\"+str(umbral)+\",GT,usoHDDporcentaje,\"+str(umbral+(100-umbral))+\",LT,EQ,usoHDDporcentaje,0,IF\",\n\t\t\t\t \"AREA:usoHDDporcentaje#FFBB0077:HDD en uso\",\n\t\t\t\t\t\t \"VDEF:m=usoHDDporcentaje,LSLSLOPE\",\n\t\t \"VDEF:b=usoHDDporcentaje,LSLINT\",\n\t\t \"CDEF:avg=usoHDDporcentaje,POP,m,COUNT,*,b,+\",\n\t\t \"CDEF:umbral\"+str(umbral-20)+\"=avg,\"+str(umbral-20)+\",\"+str(umbral-10)+\",LIMIT\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-10)+\"=avg,\"+str(umbral-10)+\",\"+str(umbral)+\",LIMIT\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral)+\"=avg,\"+str(umbral)+\",\"+str(umbral+(100-umbral))+\",LIMIT\",\n\t\t\t\t\t\t \"VDEF:minUmbral\"+str(umbral)+\"=umbral\"+str(umbral)+\",FIRST\",\n\t\t\t\t\t\t \"VDEF:last=usoHDDporcentaje,LAST\",\n\t\t\t\t\t\t \"PRINT:last:%6.2lf %S\",\n\t\t\t\t\t\t \"GPRINT:minUmbral\"+str(umbral)+\": Se alcanzará el \"+str(umbral)+\"% @ %c :strftime\",\n\t\t\t\t\t\t \"LINE1:avg#FF9F00\",\n\t\t\t\t\t \"LINE3:\"+str(umbral-20),\n\t\t\t\t\t\t \"AREA:10#FF000022::STACK\",\n\t\t\t\t\t\t \"AREA:10#FF000044::STACK\",\n\t\t\t\t\t\t \"AREA:\"+str(100-umbral)+\"#FF000066::STACK\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-20)+\"#0077FF77:Uso mayor que el \"+str(umbral-20)+\" y menor que el \"+str(umbral-10)+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-10)+\"#00880077:Uso mayor que el \"+str(umbral-10)+\" y menor que el \"+str(umbral)+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral)+\"#FF000088:Uso mayor que el \"+str(umbral)+\" y menor que el \"+str(umbral+(100-umbral))+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-20)+\"_1#0077FF77\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-10)+\"_1#00880077\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral)+\"_1#FF000088\")\n\t\t\tvalor=float(ret[\"print[0]\"])\n\t\t\tif valor>float(umbral):\n\t\t\t\tif not self.notificacionHDD:\n\t\t\t\t\tself.notificacionHDD=True\n\t\t\t\t\t#self.noti.enviarCorreo(2,self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".png\")\n\t\t\t\t\tself.log.escribirLog(2)\n\t\t\telse:\n\t\t\t\tself.notificacionHDD=False\n\n\tdef graficarRAM(self, grupo, oid1, oid2,oid3, archivo, header, numero):\n\t\tumbral=int(self.umbralRAM)\n\t\tultimo=rrdtool.last(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\")\n\t\tprimero=rrdtool.first(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\")\n\t\tconsulta=consultav5SNMP(self.agente.comunidad,self.agente.ip,int(self.agente.version),numero,grupo,oid1,oid2,oid3,int(self.agente.puerto))\n\t\tif consulta[0]!=\"\" or consulta[1]!=\"\" or consulta[2]!=\"\":\n\t\t\tvalor = \"N:\" + str(consulta[0]) + ':' + str(consulta[1]) + ':' + str(consulta[2])\n\t\t\trrdtool.update(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\", valor)\n\t\t\trrdtool.dump(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd\",self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".xml\")\n\t\t\tret = rrdtool.graphv(self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".png\",\n\t\t \"--start\",str(ultimo-100),\n\t\t \"--end\",str(ultimo+100),\n\t\t \"--vertical-label=Porcentaje/s\",\n\t\t \"--title=\"+header,\n\t\t \"--lower-limit\",\"0\",\n\t\t\t\t \t\t \"--upper-limit\",\"100\",\n\t\t \"DEF:val1=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:size:AVERAGE\",\n\t\t \"DEF:val2=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:used:AVERAGE\",\n\t\t \"DEF:val3=\"+self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".rrd:all:AVERAGE\",\n\t\t \"CDEF:totalRAM=val1,val3,*\",\n\t\t \"CDEF:usoRAMporcentaje=val2,val3,*,100,*,totalRAM,/\",\n\t\t\t\t\t\t \"CDEF:usoRAM=val2,val3,*\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-20)+\"_1=usoRAMporcentaje,\"+str(umbral-20)+\",GT,usoRAMporcentaje,\"+str(umbral-10)+\",LT,EQ,usoRAMporcentaje,0,IF\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-10)+\"_1=usoRAMporcentaje,\"+str(umbral-10)+\",GT,usoRAMporcentaje,\"+str(umbral)+\",LT,EQ,usoRAMporcentaje,0,IF\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral)+\"_1=usoRAMporcentaje,\"+str(umbral)+\",GT,usoRAMporcentaje,\"+str(umbral+(100-umbral))+\",LT,EQ,usoRAMporcentaje,0,IF\",\n\t\t\t\t \"AREA:usoRAMporcentaje#FFBB0077:En uso\",\n\t\t\t\t\t\t \"VDEF:m=usoRAMporcentaje,LSLSLOPE\",\n\t\t \"VDEF:b=usoRAMporcentaje,LSLINT\",\n\t\t \"CDEF:avg=usoRAMporcentaje,POP,m,COUNT,*,b,+\",\n\t\t\t\t\t \"CDEF:umbral\"+str(umbral-20)+\"=avg,\"+str(umbral-20)+\",\"+str(umbral-10)+\",LIMIT\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral-10)+\"=avg,\"+str(umbral-10)+\",\"+str(umbral)+\",LIMIT\",\n\t\t\t\t\t\t \"CDEF:umbral\"+str(umbral)+\"=avg,\"+str(umbral)+\",\"+str(umbral+(100-umbral))+\",LIMIT\",\n\t\t\t\t\t\t \"VDEF:minUmbral\"+str(umbral)+\"=umbral\"+str(umbral)+\",FIRST\",\n\t\t\t\t\t\t \"VDEF:last=usoRAMporcentaje,LAST\",\n\t\t\t\t\t\t \"PRINT:last:%6.2lf %S\",\n\t\t\t\t\t\t \"GPRINT:minUmbral\"+str(umbral)+\": Se alcanzará el \"+str(umbral)+\"% @ %c :strftime\",\n\t\t \"LINE1:avg#FF9F00\",\n\t\t\t\t\t \"LINE3:\"+str(umbral-20),\n\t\t\t\t\t\t \"AREA:10#FF000022::STACK\",\n\t\t\t\t\t\t \"AREA:10#FF000044::STACK\",\n\t\t\t\t\t\t \"AREA:\"+str(100-umbral)+\"#FF000066::STACK\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-20)+\"#0077FF77:Uso mayor que el \"+str(umbral-20)+\" y menor que el \"+str(umbral-10)+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-10)+\"#00880077:Uso mayor que el \"+str(umbral-10)+\" y menor que el \"+str(umbral)+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral)+\"#FF000088:Uso mayor que el \"+str(umbral)+\" y menor que el \"+str(umbral+(100-umbral))+\" por ciento\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-20)+\"_1#0077FF77\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral-10)+\"_1#00880077\",\n\t\t\t\t\t\t \"AREA:umbral\"+str(umbral)+\"_1#FF000088\")\n\t\t\tvalor=float(ret[\"print[0]\"])\n\t\t\tif valor>float(umbral):\n\t\t\t\tif not self.notificacionRAM:\n\t\t\t\t\tself.notificacionRAM=True\n\t\t\t\t\t#self.noti.enviarCorreo(1,self.agente.hostname+\"_\"+self.agente.id_agente+\"_\"+archivo+\".png\")\n\t\t\t\t\tself.log.escribirLog(1)\n\t\t\telse:\n\t\t\t\tself.notificacionRAM=False\n\n\tdef actualizarImagen(self,index,archivo,fila,columna):\n\t\tself.image[index]=Image.open(archivo).resize((400,200),Image.ANTIALIAS)\n\t\tself.photo[index]=ImageTk.PhotoImage(self.image[index])\n\t\tself.label[index]=Label(self.top,image=self.photo[index])\n\t\tself.label[index].image=self.photo[index]\n\t\tself.label[index].grid(row=fila, column=columna, sticky=W)\n","sub_path":"redes3/Practicas/3erParcial/EvaluacionServidores/Reporte/src/segundo/monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":21656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"65589568","text":"def dfs(graph, root):\n stack = [root]\n visited = set()\n scanned = []\n while len(stack) > 0:\n node = stack.pop()\n if node in visited:\n continue\n visited.add(node)\n for child in graph.get_children(node):\n stack.append(child)\n scanned.append(node)\n return scanned\n","sub_path":"algorithms/graph/depth.py","file_name":"depth.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"107795347","text":"import pandas as pd\nimport seaborn as sns\nimport os\n\n# Read data\n\nreader = pd.read_csv('datasets/train.tsv', sep='\\t', header=0)\nreader = reader.drop('Id', 1)\n\n# Create output directory\n\nif not os.path.exists(\"output\"):\n os.makedirs(\"output\")\n\n# Create histograms and box plots for every feature\n\nfor i, attribute in enumerate(reader.drop('Label', 1)):\n if reader[attribute].dtype == \"object\":\n sns.plt.figure(i)\n g = sns.countplot(y=attribute, hue=\"Label\", data=reader, palette=\"Reds_d\")\n g.axes.set_title(attribute + \" histogram\", fontsize=18)\n sns.plt.savefig('output/' + attribute + '.svg')\n else:\n sns.plt.figure(i)\n g = sns.boxplot(y=attribute, x=\"Label\", data=reader)\n g.axes.set_title(attribute + \" box plot\", fontsize=18)\n sns.plt.savefig('output/' + attribute + '.svg')\n","sub_path":"ys11_hw2/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"120526596","text":"# Definition for singly-linked list.\nfrom queue import PriorityQueue\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\"\"\"\nInput:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nOutput: 1->1->2->3->4->4->5->6\nq = []\nprev =Node(4)\nhead = Node(1)\ncurrent = Node(6)\n\"\"\"\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n q = PriorityQueue()\n prev = head = None\n for ll in lists:\n if ll:\n q.put((ll.val, id(ll), ll))\n while not q.empty():\n _, _, current = q.get()\n if not head:\n head = current\n if current.next:\n q.put((current.next.val, id(current.next), current.next ))\n if prev:\n prev.next = current\n prev = current\n return head\n \n ","sub_path":"Google/arrays_and_strings/merge_k_sorted_lists.py","file_name":"merge_k_sorted_lists.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"132970527","text":"from unittest import skip, skipIf\n\nfrom django.test import TestCase, skipIfDBFeature\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\n\nimport tempfile\nimport shutil\nimport os.path\nimport time\n\nfrom librarian.models import Dataset\nimport kive.testing_utils as tools\nfrom pipeline.models import Pipeline, PipelineFamily\nfrom kive.tests import install_fixture_files, remove_fixture_files, BaseTestCases\nfrom method.models import Method\nfrom fleet.workers import Manager\nfrom archive.models import Run\nfrom fleet.slurmlib import DummySlurmScheduler\nfrom fleet.dockerlib import DummyDockerHandler, DockerHandler\nimport file_access_utils\n\n\n@skipIfDBFeature('is_mocked')\nclass SandboxRMTestCase(BaseTestCases.SlurmExecutionTestCase):\n def setUp(self):\n tools.create_sandbox_testing_tools_environment(self)\n\n def tearDown(self):\n tools.destroy_sandbox_testing_tools_environment(self)\n\n\n@skipIfDBFeature('is_mocked')\nclass ExecuteResultTestsRM(TestCase):\n \"\"\"\n Tests on the results of executing Pipelines.\n \"\"\"\n fixtures = [\"execute_result_tests_rm\"]\n\n def setUp(self):\n install_fixture_files(\"execute_result_tests_rm\")\n self.method_complement = Method.objects.get(\n family__name=\"DNA complement\",\n revision_name=\"v1\"\n )\n\n self.pipeline_complement = Pipeline.objects.get(\n family__name=\"DNA complement\",\n revision_name=\"v1\"\n )\n self.pipeline_reverse = Pipeline.objects.get(\n family__name=\"DNA reverse\",\n revision_name=\"v1\"\n )\n self.pipeline_revcomp = Pipeline.objects.get(\n family__name=\"DNA revcomp\",\n revision_name=\"v1\"\n )\n\n self.user_alice = User.objects.get(username=\"alice\")\n\n self.comp_run = self.pipeline_complement.pipeline_instances.order_by(\"start_time\").first()\n self.comp_run_2 = self.pipeline_complement.pipeline_instances.order_by(\"start_time\").last()\n self.reverse_run = self.pipeline_reverse.pipeline_instances.first()\n self.revcomp_run = self.pipeline_revcomp.pipeline_instances.first()\n\n self.dataset_labdata = Dataset.objects.get(\n name=\"lab data\",\n user=self.user_alice\n )\n\n # Tracking down CDTs is a pain....\n self.cdt_record = self.method_complement.inputs.first().structure.compounddatatype\n\n def tearDown(self):\n tools.clean_up_all_files()\n remove_fixture_files()\n\n def test_execute_pipeline_run(self):\n \"\"\"\n Check the coherence of Runs created when a pipeline is executed the first time.\n \"\"\"\n run = self.comp_run\n self.assertEqual(run.user, self.user_alice)\n self.assertEqual(run.start_time < timezone.now(), True)\n self.assertEqual(run.is_complete(), True)\n self.assertEqual(run.parent_runstep, None)\n self.assertEqual(run.complete_clean(), None)\n\n def test_execute_pipeline_runstep(self):\n \"\"\"\n Check the coherence of a RunStep created when a Pipeline is executed the first time.\n \"\"\"\n run = self.comp_run\n # sandbox_complement has only one step, so this is OK.\n runstep = run.runsteps.first()\n\n self.assertEqual(runstep.run, run)\n self.assertTrue(runstep.start_time < timezone.now())\n self.assertFalse(runstep.reused)\n self.assertTrue(runstep.is_complete())\n self.assertEqual(runstep.complete_clean(), None)\n self.assertFalse(hasattr(runstep, \"child_run\"))\n self.assertTrue(runstep.is_successful())\n self.assertEqual(runstep.outputs.count(), 1)\n\n def test_execute_pipeline_dataset_contents(self):\n \"\"\"\n Test that the content checks, which take place as part of Pipeline\n execution, pass in the ordinary Pipeline execution case.\n \"\"\"\n run = self.comp_run\n runstep = run.runsteps.first()\n execrecord = runstep.execrecord\n dataset = execrecord.execrecordouts.first().dataset\n check = dataset.content_checks.first()\n\n self.assertEqual(dataset.content_checks.count(), 1) # should have been checked once\n self.assertEqual(check.dataset, dataset)\n self.assertEqual(check.end_time is None, False)\n self.assertEqual(check.start_time <= check.end_time, True)\n self.assertEqual(check.start_time.date(), check.end_time.date())\n self.assertEqual(check.is_fail(), False)\n\n @skip(reason=\"Fails because Method.submit_code has been removed for docker\"\n \" support. Needs to be fixed or removed.\")\n def test_execute_pipeline_dataset(self):\n \"\"\"\n Test the integrity of a Dataset output by a PipelineStep in\n the middle of a Pipeline.\n NOTE: 2017-10-03: this tests fails because Method.submit_code has been removed\n for docker support.\n \"\"\"\n # Figure out the MD5 of the output file created when the complement method\n # is run on Alice's data to check against the result of the run.\n tmpdir = tempfile.mkdtemp(dir=file_access_utils.sandbox_base_path())\n file_access_utils.configure_sandbox_permissions(tmpdir)\n outfile = os.path.join(tmpdir, \"output\")\n stdout_path = os.path.join(tmpdir, \"stdout.txt\")\n stderr_path = os.path.join(tmpdir, \"stderr.txt\")\n\n self.method_complement.install(tmpdir)\n\n # Set up the dummy scheduler.\n slurm_sched_class = DummySlurmScheduler\n slurm_sched_class.slurm_is_alive()\n\n complement_job_handle = self.method_complement.submit_code(\n tmpdir,\n [self.dataset_labdata.dataset_file.file.name],\n [outfile],\n stdout_path,\n stderr_path,\n slurm_sched_class=slurm_sched_class\n )\n\n is_done = False\n while not is_done:\n time.sleep(settings.DEFAULT_SLURM_CHECK_INTERVAL)\n accounting_info = DummySlurmScheduler.get_accounting_info([complement_job_handle])\n if len(accounting_info) > 0:\n curr_state = accounting_info[complement_job_handle.job_id][\"state\"]\n is_done = curr_state == DummySlurmScheduler.COMPLETED\n\n slurm_sched_class.shutdown()\n\n labdata_compd_md5 = file_access_utils.compute_md5(open(outfile))\n shutil.rmtree(tmpdir)\n\n run = self.comp_run\n runstep = run.runsteps.first()\n execrecord = runstep.execrecord\n dataset = execrecord.execrecordouts.first().dataset\n ds = runstep.outputs.first()\n\n self.assertEqual(dataset.MD5_checksum, labdata_compd_md5)\n self.assertEqual(dataset, ds)\n self.assertEqual(hasattr(dataset, \"usurps\"), False)\n self.assertEqual(dataset.has_data(), True)\n self.assertEqual(dataset.num_rows(), 10)\n self.assertEqual(dataset.is_raw(), False)\n self.assertEqual(dataset.get_cdt(), self.cdt_record)\n self.assertEqual(dataset.structure.compounddatatype, self.cdt_record)\n self.assertEqual(dataset.structure.num_rows, 10)\n self.assertEqual(dataset.is_OK(), True)\n\n def test_execute_pipeline_runstep_execrecordout(self):\n \"\"\"\n Check the coherence of a RunStep's ExecRecord's ExecRecordOut, created\n when a Pipeline is executed the first time.\n \"\"\"\n run = self.comp_run\n\n pipelinestep = self.pipeline_complement.steps.first() # 1 step\n runstep = run.runsteps.first()\n dataset_out = runstep.outputs.first()\n execlog = runstep.log\n execrecord = runstep.execrecord\n execrecordout = execrecord.execrecordouts.first()\n\n self.assertEqual(execrecordout is None, False)\n self.assertEqual(execrecordout.execrecord, execrecord)\n self.assertEqual(execrecordout.dataset, dataset_out)\n self.assertEqual(execrecordout.generic_output.definite, pipelinestep.transformation.outputs.first())\n self.assertEqual(execrecordout.has_data(), True)\n self.assertEqual(execrecordout.is_OK(), True)\n self.assertNotEqual(None, execlog)\n\n def test_execute_pipeline_runstep_execrecord(self):\n \"\"\"\n Check the coherence of a RunStep's ExecRecord, created when a Pipeline\n is executed the first time.\n \"\"\"\n run = self.comp_run\n runstep = run.runsteps.first()\n execlog = runstep.log\n execrecord = runstep.execrecord\n outputs = self.method_complement.outputs.all()\n\n self.assertEqual(execrecord.generator, execlog)\n self.assertEqual(execrecord.complete_clean(), None)\n self.assertEqual(execrecord.general_transf(), runstep.pipelinestep.transformation.method)\n self.assertEqual(execrecord.provides_outputs(outputs), True)\n self.assertEqual(execrecord.outputs_OK(), True)\n\n def test_execute_pipeline_reuse(self):\n \"\"\"\n An identical pipeline, run in a different sandbox, should reuse an ExecRecord\n and not create an ExecLog.\n \"\"\"\n step1 = self.comp_run.runsteps.first()\n step2 = self.comp_run_2.runsteps.first()\n\n self.assertEqual(step1.reused, False)\n self.assertEqual(step2.reused, True)\n self.assertFalse(step2.has_log())\n self.assertEqual(step1.execrecord, step2.execrecord)\n\n def test_execute_pipeline_fill_in_ER(self):\n \"\"\"\n Running an identical Pipeline where we did not keep the data around the first time\n should fill in an existing ExecRecord, but also create a new ExecLog.\n \"\"\"\n step1 = self.comp_run.runsteps.first()\n step2 = self.comp_run_2.runsteps.first()\n\n self.assertEqual(step1.reused, False)\n self.assertEqual(step2.reused, True)\n self.assertTrue(step1.has_log())\n self.assertFalse(step2.has_log())\n self.assertEqual(step1.execrecord, step2.execrecord)\n\n def test_execute_pipeline_reuse_within_different_pipeline(self):\n \"\"\"\n Running the same dataset through the same Method, in two different\n pipelines, should reuse an ExecRecord.\n \"\"\"\n step1 = self.reverse_run.runsteps.first() # 1 step\n step2 = self.revcomp_run.runsteps.get(pipelinestep__step_num=1)\n\n self.assertEqual(step1.reused, False)\n self.assertEqual(step2.reused, True)\n self.assertFalse(step2.has_log())\n self.assertEqual(step1.execrecord, step2.execrecord)\n\n def test_execute_pipeline_output_dataset(self):\n \"\"\"\n A Pipeline with no deleted outputs should have a Dataset as an output.\n \"\"\"\n output = self.comp_run.runoutputcables.first()\n output_dataset = output.execrecord.execrecordouts.first().dataset\n self.assertEqual(output_dataset is not None, True)\n\n def test_trivial_cable_num_rows(self):\n \"\"\"\n A trivial cable should have the same dataset all the way through.\n \"\"\"\n step = self.comp_run.runsteps.first()\n step_output_dataset = step.execrecord.execrecordouts.first().dataset\n\n outcable = self.comp_run.runoutputcables.first()\n outcable_input_dataset = outcable.execrecord.execrecordins.first().dataset\n outcable_output_dataset = outcable.execrecord.execrecordouts.first().dataset\n\n self.assertEqual(step_output_dataset, outcable_input_dataset)\n self.assertEqual(outcable_input_dataset, outcable_output_dataset)\n self.assertEqual(step_output_dataset.num_rows(), outcable_input_dataset.num_rows())\n self.assertEqual(outcable_input_dataset.num_rows(), outcable_output_dataset.num_rows())\n\n def test_execute_pipeline_num_rows(self):\n \"\"\"\n A pipeline which does not change the number of rows in a dataset,\n should have the same number of rows in all datasets along the way.\n \"\"\"\n incable = self.comp_run.runsteps.first().RSICs.first()\n incable_input_dataset = incable.execrecord.execrecordins.first().dataset\n incable_output_dataset = incable.execrecord.execrecordins.first().dataset\n\n step = self.comp_run.runsteps.first()\n step_input_dataset = step.execrecord.execrecordins.first().dataset\n step_output_dataset = step.execrecord.execrecordouts.first().dataset\n\n outcable = self.comp_run.runoutputcables.first()\n outcable_input_dataset = outcable.execrecord.execrecordins.first().dataset\n outcable_output_dataset = outcable.execrecord.execrecordouts.first().dataset\n\n self.assertEqual(incable_input_dataset.num_rows(), self.dataset_labdata.num_rows())\n self.assertEqual(incable_input_dataset.num_rows(), incable_output_dataset.num_rows())\n self.assertEqual(incable_output_dataset.num_rows(), step_input_dataset.num_rows())\n self.assertEqual(step_input_dataset.num_rows(), step_output_dataset.num_rows())\n self.assertEqual(step_output_dataset.num_rows(), outcable_input_dataset.num_rows())\n self.assertEqual(outcable_input_dataset.num_rows(), outcable_output_dataset.num_rows())\n\n\n@skipIfDBFeature('is_mocked')\nclass ExecuteDiscardedIntermediateTests(BaseTestCases.SlurmExecutionTestCase):\n fixtures = [\"execute_discarded_intermediate_tests_rm\"]\n\n def setUp(self):\n install_fixture_files(\"execute_discarded_intermediate_tests_rm\")\n self.revcomp_pf = PipelineFamily.objects.get(name=\"DNA revcomp\")\n self.pipeline_revcomp_v2 = self.revcomp_pf.members.get(revision_name=\"2\")\n self.pipeline_revcomp_v3 = self.revcomp_pf.members.get(revision_name=\"3\")\n\n self.user_alice = User.objects.get(username=\"alice\")\n\n self.revcomp_v2_run = self.pipeline_revcomp_v2.pipeline_instances.first() # only one exists\n\n self.dataset_labdata = Dataset.objects.get(\n name=\"lab data\",\n user=self.user_alice\n )\n\n def tearDown(self):\n tools.clean_up_all_files()\n remove_fixture_files()\n\n def test_discard_intermediate_file(self):\n \"\"\"\n A Pipeline which indicates one of its intermediate outputs should not be kept,\n should not create any datasets for that output.\n \"\"\"\n runstep = self.revcomp_v2_run.runsteps.get(pipelinestep__step_num=1)\n output = runstep.execrecord.execrecordouts.first().dataset\n step = self.pipeline_revcomp_v2.steps.get(step_num=1)\n self.assertEqual(runstep.pipelinestep.outputs_to_retain(), [])\n self.assertEqual(output.has_data(), False)\n self.assertNotEqual(None, step)\n\n def test_recover_intermediate_dataset(self):\n \"\"\"\n Test recovery of an intermediate dataset.\n \"\"\"\n # In the fixture, we already ran self.pipeline_revcomp_v2, which discards the intermediate\n # output. We now run v3, which will recover it.\n run = Manager.execute_pipeline(\n self.user_alice,\n self.pipeline_revcomp_v3,\n [self.dataset_labdata],\n docker_handler_class=DummyDockerHandler\n ).get_last_run()\n\n self.assertTrue(run.is_successful())\n\n\nclass BadRunTestsBase(object):\n \"\"\"\n Foundations of tests for when things go wrong during Pipeline execution.\n\n We split this code out into an object (not a TestCase) so it can be\n reused in another test class.\n \"\"\"\n def setUp(self):\n tools.create_grandpa_sandbox_environment(self)\n\n def tearDown(self):\n tools.destroy_grandpa_sandbox_environment(self)\n\n def cable_tester(self, runstep):\n for rsic in runstep.RSICs.all():\n self.assertTrue(rsic.is_successful())\n\n def test_method_fails(self,\n slurm_sched_class=DummySlurmScheduler,\n docker_handler_class=DummyDockerHandler):\n \"\"\"Properly handle a failed method in a pipeline.\"\"\"\n run = Manager.execute_pipeline(\n self.user_grandpa,\n self.pipeline_fubar,\n [self.dataset_grandpa],\n slurm_sched_class=slurm_sched_class,\n docker_handler_class=docker_handler_class\n ).get_last_run()\n\n self.assertTrue(run.is_failed())\n self.assertIsNone(run.complete_clean())\n\n runstep1 = run.runsteps.get(pipelinestep__step_num=1)\n self.cable_tester(runstep1)\n self.assertIsNone(runstep1.complete_clean())\n self.assertTrue(runstep1.is_successful())\n\n runstep2 = run.runsteps.get(pipelinestep__step_num=2)\n self.cable_tester(runstep2)\n self.assertIsNone(runstep2.complete_clean())\n self.assertTrue(runstep2.is_failed())\n\n log = runstep2.log\n\n self.assertFalse(log.is_successful())\n self.assertEqual(log.methodoutput.return_code, 1)\n self.assertEqual(log.missing_outputs(), [runstep2.execrecord.execrecordouts.first().dataset])\n\n\n@skipIfDBFeature('is_mocked')\nclass BadRunTests(BaseTestCases.SlurmExecutionTestCase, BadRunTestsBase):\n \"\"\"\n Tests for when things go wrong during Pipeline execution.\n \"\"\"\n def setUp(self):\n BaseTestCases.SlurmExecutionTestCase.setUp(self)\n BadRunTestsBase.setUp(self)\n\n def tearDown(self):\n BaseTestCases.SlurmExecutionTestCase.tearDown(self)\n BadRunTestsBase.tearDown(self)\n\n pass\n\n\n@skipIfDBFeature('is_mocked')\nclass FindDatasetTests(BaseTestCases.SlurmExecutionTestCase):\n \"\"\"\n Tests for first_generator_of_dataset.\n \"\"\"\n fixtures = ['find_datasets']\n\n def setUp(self):\n install_fixture_files('find_datasets')\n\n def tearDown(self):\n remove_fixture_files()\n\n def test_find_dataset_pipeline_input_and_step_output(self):\n \"\"\"\n Finding a Dataset which was input to a Pipeline should return None\n as the generator, and the top-level run as the run.\n\n Finding a Dataset which was output from a step, and also input\n to a cable, should return the step (and in particular, not the cable).\n \"\"\"\n self.pipeline_noop = Pipeline.objects.get(family__name=\"simple pipeline\")\n self.dataset_words = Dataset.objects.get(name='blahblah')\n self.user_bob = User.objects.get(username='bob')\n\n mgr = Manager.execute_pipeline(self.user_bob,\n self.pipeline_noop,\n [self.dataset_words],\n docker_handler_class=DummyDockerHandler)\n x = mgr.history_queue.pop()\n self.assertIsNone(x.run.complete_clean())\n self.assertTrue(x.run.is_successful())\n\n run, gen = x.first_generator_of_dataset(self.dataset_words)\n self.assertEqual(run, x.run)\n self.assertEqual(gen, None)\n\n dataset_out_intermediate = x.run.runsteps.first().execrecord.execrecordouts.first().dataset\n run_2, gen_2 = x.first_generator_of_dataset(dataset_out_intermediate)\n self.assertEqual(run_2, x.run)\n self.assertEqual(gen_2, self.pipeline_noop.steps.first())\n\n def test_find_dataset_pipeline_input_and_intermediate_custom_wire(self):\n \"\"\"\n Finding a Dataset which was passed through a custom wire to a\n Pipeline should return the cable as the generator, and the top-level\n run as the run.\n\n Finding a Dataset which was produced by a custom wire as an\n intermediate step should return the cable as the generator, and the\n top-level run as the run.\n \"\"\"\n self.pipeline_twostep = Pipeline.objects.get(family__name=\"two-step pipeline\")\n self.dataset_backwords = Dataset.objects.get(name='backwords')\n self.user_bob = User.objects.get(username='bob')\n\n mgr = Manager.execute_pipeline(self.user_bob,\n self.pipeline_twostep,\n [self.dataset_backwords],\n docker_handler_class=DummyDockerHandler)\n sandbox = mgr.history_queue.pop()\n self.assertIsNone(sandbox.run.complete_clean())\n self.assertTrue(sandbox.run.is_successful())\n\n runcable = sandbox.run.runsteps.get(pipelinestep__step_num=1).RSICs.first()\n dataset_to_find = runcable.execrecord.execrecordouts.first().dataset\n\n run, gen = sandbox.first_generator_of_dataset(dataset_to_find)\n self.assertEqual(run, sandbox.run)\n self.assertEqual(gen, runcable.PSIC)\n\n # Testing on an intermediate Dataset.\n runcable_2 = sandbox.run.runsteps.get(pipelinestep__step_num=2).RSICs.first()\n dataset_to_find_2 = runcable_2.execrecord.execrecordouts.first().dataset\n\n run_2, gen_2 = sandbox.first_generator_of_dataset(dataset_to_find_2)\n self.assertEqual(run_2, sandbox.run)\n self.assertEqual(gen_2, runcable_2.PSIC)\n\n def test_find_dataset_subpipeline_input_and_intermediate(self):\n \"\"\"\n Find a dataset in a sub-pipeline, which is output from a step.\n\n Find a dataset in a sub-pipeline, which is input to the sub-pipeline\n on a custom cable.\n \"\"\"\n self.pipeline_nested = Pipeline.objects.get(family__name=\"nested pipeline\")\n self.dataset_backwords = Dataset.objects.get(name='backwords')\n self.user_bob = User.objects.get(username='bob')\n\n mgr = Manager.execute_pipeline(self.user_bob,\n self.pipeline_nested,\n [self.dataset_backwords],\n docker_handler_class=DummyDockerHandler)\n sandbox = mgr.history_queue.pop()\n self.assertIsNone(sandbox.run.complete_clean())\n self.assertTrue(sandbox.run.is_successful())\n\n subpipeline_step = sandbox.run.runsteps.get(pipelinestep__step_num=2)\n subrun = subpipeline_step.child_run\n runstep = subrun.runsteps.first()\n outrecord = runstep.execrecord.execrecordouts.first()\n dataset_to_find = outrecord.dataset\n\n run, gen = sandbox.first_generator_of_dataset(dataset_to_find)\n self.assertEqual(run, subrun)\n self.assertEqual(gen, runstep.pipelinestep)\n\n cable = runstep.RSICs.first()\n dataset_to_find_2 = runstep.execrecord.execrecordins.first().dataset\n\n run_2, gen_2 = sandbox.first_generator_of_dataset(dataset_to_find_2)\n self.assertEqual(run_2, subrun)\n self.assertEqual(gen_2, cable.PSIC)\n\n\nclass RawTests(SandboxRMTestCase):\n\n def setUp(self):\n super(RawTests, self).setUp()\n\n self.addTypeEqualityFunc(str, self.assertMultiLineEqual)\n self.pipeline_raw = tools.make_first_pipeline(\n \"raw noop\", \"a pipeline to do nothing to raw data\",\n self.user_bob)\n tools.create_linear_pipeline(self.pipeline_raw, [self.method_noop_raw], \"raw_in\", \"raw_out\")\n self.pipeline_raw.create_outputs()\n\n self.dataset_raw = Dataset.create_dataset(\n \"/usr/share/dict/words\",\n user=self.user_bob,\n cdt=None,\n keep_file=True,\n name=\"raw\",\n description=\"some raw data\"\n )\n\n def test_execute_pipeline_raw(self):\n \"\"\"Execute a raw Pipeline.\"\"\"\n run = Manager.execute_pipeline(self.user_bob,\n self.pipeline_raw,\n [self.dataset_raw],\n docker_handler_class=DummyDockerHandler).get_last_run()\n run.refresh_from_db()\n self.assertTrue(run.is_successful())\n\n def test_execute_pipeline_raw_twice(self):\n \"\"\"Execute a raw Pipeline and reuse an ExecRecord.\"\"\"\n run = Manager.execute_pipeline(self.user_bob,\n self.pipeline_raw,\n [self.dataset_raw],\n docker_handler_class=DummyDockerHandler).get_last_run()\n run = Run.objects.get(pk=run.pk)\n self.assertTrue(run.is_successful())\n\n run2 = Manager.execute_pipeline(self.user_bob,\n self.pipeline_raw,\n [self.dataset_raw],\n docker_handler_class=DummyDockerHandler).get_last_run()\n run2 = Run.objects.get(pk=run2.pk)\n self.assertTrue(run2.is_successful())\n\n @skipIf(not settings.RUN_DOCKER_TESTS, \"Docker tests disabled.\")\n def test_execute_pipeline_raw_with_docker(self):\n \"\"\"Execute a raw Pipeline.\"\"\"\n self.maxDiff = None\n run = Manager.execute_pipeline(self.user_bob,\n self.pipeline_raw,\n [self.dataset_raw],\n docker_handler_class=DockerHandler).get_last_run()\n run.refresh_from_db()\n stderr_path = os.path.join(run.sandbox_path,\n \"step1\",\n \"logs\",\n \"step1_stderr_slurmID0_node0.txt\")\n with open(stderr_path, 'rU') as f:\n stderr_text = f.read()\n self.assertEqual(\"\", stderr_text)\n self.assertTrue(run.is_successful())\n\n def tearDown(self):\n super(RawTests, self).tearDown()\n","sub_path":"kive/sandbox/tests_rm.py","file_name":"tests_rm.py","file_ext":"py","file_size_in_byte":25186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"19064073","text":"# Copyright (c) 2012 Michel Crucifix \n\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject\n\n# the following conditions:\n\n# The above copyright notice and this permission notice shall be\n# incluuded in all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND INFRINGEMENT\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\n\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n# ------------------------------------------------------------------\n# Code developed for Python 2.7 \n# ------------------------------------------------------------------ \n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import mpl\nfrom matplotlib import colors\nimport itertools\n\nfrom rpy2 import robjects\nfile='pullback_34'\n\n\nfig,ax = plt.subplots(nrows=3,ncols=1)\nfig.subplots_adjust( hspace=0.6) \nfig.set_size_inches(7,7)\n\nprint(robjects.r.load ('../RData/'+file+'.RData'))\np36 = robjects.r('p36')\ns36 = robjects.r('s36')\np38 = robjects.r('p38')\ntimes = np.array(robjects.r('times'))*10.\n\n\nclr = itertools.cycle(('red','green'))\n\nfor Y in p36:\n Y = np.array(Y)[:,0]\n c = clr.next();\n ax[0].plot(times,Y, linewidth=1.2, color=c)\n ax[1].plot(times,Y,'-', linewidth=0.5, color=c)\n ax[2].plot(times,Y,'-', linewidth=0.5, color=c)\n\nfor i in range(30):\n ax[2].plot(times,np.array(s36[i])[:,0], linewidth=1.2, color='grey')\nax[1].plot(times,np.array(p38)[:,0], linewidth=1.2, color='black')\n\nax[0].set_title('pullback attractors $\\\\tau=36\\,\\\\mathrm{ka}$')\nax[2].set_title('stochastic realisations $\\\\tau=36\\,\\\\mathrm{ka}$')\nax[1].set_title('one pullback attractor $\\\\tau=38\\,\\\\mathrm{ka}$')\n\nfor j in range(3):\n ax[j].xaxis.set_major_locator(plt.MaxNLocator(4))\n ax[j].xaxis.set_major_locator(plt.MaxNLocator(4))\n ax[j].set_xticks(np.arange(-500,100,100))\n ax[j].set_ylabel('y')\n\nax[2].set_xlabel('time [kyr]')\n\nfig.savefig('../Pdf/pullback_vdp_34.pdf')\n\n\n\n","sub_path":"Py/pullback_vdp_34.py","file_name":"pullback_vdp_34.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"100426080","text":"#\n# axial_coordinate.py\n#\n# Copyright © 2016 Monotype Imaging Inc. All Rights Reserved.\n#\n\n\"\"\"\nSupport for single floating-point values used as entries in AxisInfo and\nInstanceInfo objects. These are essentially values along one axis.\n\"\"\"\n\n# Other imports\nfrom fontio3.fontdata import valuemeta\nfrom fontio3.fontmath import mathutilities\n\n# -----------------------------------------------------------------------------\n\n#\n# Classes\n#\n\nclass AxialCoordinate(float, metaclass=valuemeta.FontDataMetaclass):\n \"\"\"\n Single floating-point values, used in AxisInfo and InstanceInfo objects.\n Note that they have a custom __str__() method to display to three places\n only, although the actual data value is always preserved.\n \"\"\"\n\n #\n # Methods\n #\n\n def __str__(self):\n \"\"\"\n Returns a string representing the value. This string will be rounded to\n three places, but its internal value remains unchanged.\n\n >>> print((AxialCoordinate(1/3)))\n 0.333\n \"\"\"\n\n return str(round(self, 3))\n\n # noinspection PyUnusedLocal\n def buildBinary(self, w, **kwArgs):\n \"\"\"\n Adds the binary data for self to the specified writer.\n\n >>> h = utilities.hexdump\n >>> v = [-2.0, -1.5, -1.0, -0.5, 0, 0.5, 1.0, 1.5]\n >>> for n in v:\n ... h(AxialCoordinate(n).binaryString())\n 0 | FFFE 0000 |.... |\n 0 | FFFE 8000 |.... |\n 0 | FFFF 0000 |.... |\n 0 | FFFF 8000 |.... |\n 0 | 0000 0000 |.... |\n 0 | 0000 8000 |.... |\n 0 | 0001 0000 |.... |\n 0 | 0001 8000 |.... |\n \"\"\"\n\n w.add('L', mathutilities.floatToFixed(self, forceUnsigned=True))\n\n @classmethod\n def fromvalidatedwalker(cls, w, **kwArgs):\n \"\"\"\n Creates and returns a new AxialCoordinate object from the data in the\n specified walker, doing source validation.\n\n >>> bs = utilities.fromhex(\"00 01 00 00\")\n >>> obj = AxialCoordinate.fromvalidatedbytes(bs)\n AxialCoordinate - DEBUG - Walker has 4 remaining bytes.\n >>> print(obj)\n 1.0\n >>> utilities.hexdump(obj.binaryString())\n 0 | 0001 0000 |.... |\n\n >>> bs = utilities.fromhex(\"FF FF 80 00\")\n >>> obj = AxialCoordinate.fromvalidatedbytes(bs)\n AxialCoordinate - DEBUG - Walker has 4 remaining bytes.\n >>> print(obj)\n -0.5\n >>> utilities.hexdump(obj.binaryString())\n 0 | FFFF 8000 |.... |\n \n >>> bs = utilities.fromhex(\"00 00 01\")\n >>> AxialCoordinate.fromvalidatedbytes(bs)\n AxialCoordinate - DEBUG - Walker has 3 remaining bytes.\n AxialCoordinate - ERROR - Insufficient bytes (3) for AxialCoordinate (minimum 4)\n \"\"\"\n\n if 'logger' in kwArgs:\n logger = kwArgs.pop('logger').getChild('AxialCoordinate')\n else:\n logger = utilities.makeDoctestLogger('AxialCoordinate')\n\n remaining_length = w.length()\n \n logger.debug((\n 'V0001',\n (remaining_length,),\n \"Walker has %d remaining bytes.\"))\n\n bytes_needed = 4\n \n if remaining_length < bytes_needed:\n logger.error((\n 'V0004',\n (remaining_length, bytes_needed),\n \"Insufficient bytes (%d) for AxialCoordinate (minimum %d)\"))\n \n return None\n\n return cls(mathutilities.fixedToFloat(w.unpack(\"L\")))\n\n # noinspection PyUnusedLocal\n @classmethod\n def fromwalker(cls, w, **kwArgs):\n \"\"\"\n Creates and returns a new AxialCoordinate object from the data in the\n specified walker.\n\n >>> bs = utilities.fromhex(\"00 01 00 00\")\n >>> obj = AxialCoordinate.frombytes(bs)\n >>> print(obj)\n 1.0\n >>> utilities.hexdump(obj.binaryString())\n 0 | 0001 0000 |.... |\n\n >>> bs = utilities.fromhex(\"FF FF 80 00\")\n >>> obj = AxialCoordinate.frombytes(bs)\n >>> print(obj)\n -0.5\n >>> utilities.hexdump(obj.binaryString())\n 0 | FFFF 8000 |.... |\n \"\"\"\n\n return cls(mathutilities.fixedToFloat(w.unpack(\"L\")))\n\n# -----------------------------------------------------------------------------\n\n#\n# Test code\n#\n\nif 0:\n def __________________(): pass\n\nif __debug__:\n from fontio3 import utilities\n\ndef _test():\n import doctest\n doctest.testmod()\n\nif __name__ == \"__main__\":\n if __debug__:\n _test()\n\n","sub_path":"fontio3/build/lib.linux-x86_64-3.6/fontio3/fvar/axial_coordinate.py","file_name":"axial_coordinate.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"303870597","text":"class Solution(object):\n\tdef multiply(self, num1, num2):\n\t\tnum1= num1[::-1]\n\t\tnum2= num2[::-1]\n\n\t\tresultarray = [0 for i in range(len(num1)+len(num2)+ 1)]\n\t\tresultarraystr = [\"\" for i in range(len(num1)+len(num2)+ 1)]\n\n\t\tfor i in range(0,len(num1)):\n\t\t\t#print(resultarray)\n\t\t\tfor j in range(0,len(num2)):\n\t\t\t\tresultarray[i+j]+=int(num1[i])*int(num2[j])\n\t\t\t\tresultarray[i+j+1] += int(resultarray[i+j] / 10)\n\t\t\t\tresultarray[i+j] = resultarray[i+j] % 10\n\n\t\tresult = \"\"\n\n\t\tfor i in range(0,len(resultarray)):\n\t\t\tresultarraystr[i] = str(resultarray[i])\n\n\t\tresult =''.join(resultarraystr)[::-1]\n\n\t\tfor i in range(0,len(resultarray)):\n\t\t\tif result[i]!= \"0\":\n\t\t\t\treturn result[i:]\n\n\t\treturn \"0\"\n\n\ntestClass = Solution()\n\n\nprint(testClass.multiply(\"123123123\",\"456456456\"))\n\n","sub_path":"43-mutiply-string/43.py","file_name":"43.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"294157004","text":"# Solution to Project Euler Question #9\n\n'''There exists exactly one Pythagorean triplet for which a + b + c = 1000.\nFind the product abc.'''\n\n\n# main, finds the product of Pythagorean triplet where a + b + c = 1000\n\ndef pyth_trip():\n for a in range(1, 1000, 1):\n for b in range(a + 1, 1000, 1):\n c = 1000 - a - b\n if (c > 0) & (a ** 2 + b ** 2 == c ** 2):\n return a * b * c\n return 0\n\n# print(pyth_trip()) => 31875000\n","sub_path":"euler9.py","file_name":"euler9.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"188072669","text":"import os\nimport papermill as pm\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-k\", \"--kernel-name\", type=str, \n default='python3',\n help=\"kernel name used to execute the notebook\")\nparser.add_argument(\"-i\", \"--input\", type=str, \n default=\"hello_world.ipynb\",\n help=\"input notebook to execute\")\nparser.add_argument(\"-o\", \"--output\", type=str, \n default=\"outputs/hello_world_output.ipynb\",\n help=\"output notebook to write to\")\n## parameters for hello_world\nparser.add_argument(\"-x\", type=int, \n default=1,\n help=\"value of x parameter in notebook\")\nparser.add_argument(\"-y\", type=int, \n default=1,\n help=\"value of y parameter in notebook\")\n\nargs = parser.parse_args()\n\nKERNEL_NAME = args.kernel_name\n\nOUTPUT_NOTEBOOK = args.output\n\n## make sure output directory exists\noutdir = os.path.dirname(OUTPUT_NOTEBOOK)\n\nif outdir is \"\":\n outdir = os.getcwd()\n\nif not os.path.isdir(outdir):\n print(\"output directory\", outdir, \"does not exist. Creating.\")\n os.makedirs(outdir)\n\nnotebooks = {\n \"hello_world\": args.input\n}\n\nnotebook_path = notebooks[\"hello_world\"]\npm.execute_notebook(\n notebook_path,\n OUTPUT_NOTEBOOK,\n kernel_name=KERNEL_NAME,\n parameters=dict(\n x=args.x,\n y=args.y\n )\n)\n\n\nnb = pm.read_notebook(OUTPUT_NOTEBOOK)\n\n## Now log thing via AML \ntry:\n from azureml.core import Run\n run = Run.get_context()\nexcept ImportError:\n run = None\n\nprint('*** run value is:', run)\n\ndef _log(metric, value):\n if run is not None:\n print('logging variables with AML logging functions.')\n if type(value) == list and len(value) > 0 and (type(value[0]) == int or type(value[0]) == float):\n run.log_list(metric, value)\n else:\n run.log(metric, str(value))\n else:\n print(\"Not logging with AML logging functions. Just printing them.\")\n print(metric, \"=\", value)\n\nfor m, v in nb.data.items():\n _log(m, v)\n\n## for checking the script has changed and what is being logged.\n_log('msg2', 'run1')","sub_path":"projectDir/papermill_run_notebook.py","file_name":"papermill_run_notebook.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"516235293","text":"from DataFormats.FWLite import Events, Handle\nimport os\nimport math\nimport sys\nimport numpy as np\n#from ROOT import TH1F, TCanvas, TFile, TLegend, gStyle, TPaveText, TArrow\nfrom ROOT import *\nimport argparse\nimport tdrstyle, CMS_lumi\nimport ROOT\n\n#Supress the opening of many Canvas's\nROOT.gROOT.SetBatch(True) \n\n\ndef BDT_output():\n\n tdrstyle.setTDRStyle()\n iPeriod = 4\n iPos = 11\n CMS_lumi.lumiTextSize = 0.9\n CMS_lumi.cmsTextSize = 1.\n CMS_lumi.lumi_13TeV = \"39.54 fb^{-1}\"\n \n f = TFile(\"outputs/Nominal_training.root\")\n \n h_BDT_sig = f.Get(\"default/Method_BDT/BDT/MVA_BDT_S\")\n h_BDT_bkg = f.Get(\"default/Method_BDT/BDT/MVA_BDT_B\")\n\n h_BDT_Train_sig = f.Get(\"default/Method_BDT/BDT/MVA_BDT_Train_S\")\n h_BDT_Train_bkg = f.Get(\"default/Method_BDT/BDT/MVA_BDT_Train_B\")\n\n \n leg1 = TLegend(0.40,0.62,0.65,0.87)\n leg1.SetHeader(\"\")\n leg1.SetFillColor(0)\n leg1.SetBorderSize(0)\n leg1.SetLineColor(1)\n leg1.SetLineStyle(1)\n leg1.SetLineWidth(1)\n leg1.SetFillStyle(0)\n leg1.AddEntry(h_BDT_sig,\"Signal\",\"f\")\n leg1.AddEntry(h_BDT_bkg,\"Background\",\"f\")\n #leg1.AddEntry(h_BDT_data,\"Data\",\"ep\")\n\n channel_text = TPaveText(0.30,0.84,0.65,0.86,\"NB,NDC\")\n\n\n #channel_text.AddText(\"#phi#gamma channel\")\n arrow_SR = TArrow(0.292,2.6,0.59,2.6,0.02,\"<|>\")#The starting point in x should be 0.285, but then the two arrows overlap\n arrow_CR = TArrow(0.216,2.6,0.285,2.6,0.02,\"<|>\")\n SR_text = TPaveText(0.412,2.75,0.454,2.77,\"NB\")\n CR_text = TPaveText(0.230,2.75,0.272,2.77,\"NB\")\n\n\n channel_text.SetTextSize(0.04)\n channel_text.SetFillColor(0)\n channel_text.SetFillStyle(0)\n channel_text.SetLineColor(0)\n SR_text.AddText(\"SR\")\n CR_text.AddText(\"CR\")\n arrow_SR.SetLineColor(8)\n arrow_SR.SetLineWidth(2)\n arrow_SR.SetFillColor(8)\n arrow_CR.SetLineColor(kOrange+7)\n arrow_CR.SetLineWidth(2)\n arrow_CR.SetFillColor(kOrange+7)\n SR_text.SetTextSize(0.04)\n SR_text.SetFillColor(0)\n SR_text.SetFillStyle(0)\n SR_text.SetLineColor(0)\n SR_text.SetTextColor(8)\n CR_text.SetTextSize(0.04)\n CR_text.SetFillColor(0)\n CR_text.SetFillStyle(0)\n CR_text.SetLineColor(0)\n CR_text.SetTextColor(kOrange+7)\n\n gStyle.SetErrorX(0.)\n gStyle.SetOptStat(0)\n canvas1 = TCanvas()\n h_BDT_sig.SetTitle(\"\")\n h_BDT_sig.GetXaxis().SetTitle(\"BDT discriminant\")\n h_BDT_sig.GetXaxis().SetTitleSize(0.055)\n h_BDT_sig.GetYaxis().SetTitle(\"Arbitrary units\")\n h_BDT_sig.GetYaxis().SetTitleSize(0.055)\n h_BDT_bkg.SetTitle(\"\")\n h_BDT_sig.SetFillColor(38)\n h_BDT_sig.SetFillStyle(3002)\n #h_BDT_sig.SetLineColor(1)\n h_BDT_bkg.SetFillColor(2)\n h_BDT_bkg.SetLineColor(2)\n h_BDT_bkg.SetFillStyle(3002)\n h_BDT_sig.Draw(\"E1, hist\")\n h_BDT_bkg.Draw(\"SAME, E1, hist\")\n #h_BDT_data.Draw(\"SAME, lep\")\n h_BDT_Train_sig.SetLineColor(8)\n h_BDT_Train_sig.SetMarkerColor(8)\n h_BDT_Train_sig.SetMarkerStyle(21)\n h_BDT_Train_bkg.SetLineColor(9)\n h_BDT_Train_bkg.SetMarkerColor(9)\n h_BDT_Train_bkg.SetMarkerStyle(21)\n h_BDT_Train_sig.Draw(\"SAME, lep\")\n h_BDT_Train_bkg.Draw(\"SAME, lep\")\n h_BDT_sig.SetMaximum(6.0)\n leg1.Draw(\"SAME\")\n channel_text.Draw(\"SAME\")\n #SR_text.Draw(\"SAME\")\n #CR_text.Draw(\"SAME\")\n #arrow_SR.Draw()\n #arrow_CR.Draw()\n CMS_lumi.CMS_lumi(canvas1, iPeriod, iPos)\n\n canvas1.SaveAs(\"/afs/cern.ch/user/g/gumoret/cernbox/www/latest_production/MVA_latest_production/h_BDT_output.pdf\")\n canvas1.SaveAs(\"/afs/cern.ch/user/g/gumoret/cernbox/www/latest_production/MVA_latest_production/h_BDT_output.png\")\n \n\n raw_input()\n\ndef rejB_vs_S():\n\n f1 = TFile(\"outputs/Nominal_training.root\")\n\n h_rejB_vs_S_1 = f1.Get(\"default/Method_BDT/BDT/MVA_BDT_rejBvsS\")\n\n leg2 = TLegend(0.2,0.6,0.6,0.7)\n #leg1.SetHeader(\" \")\n leg2.SetFillColor(0)\n leg2.SetBorderSize(0)\n leg2.SetLineColor(1)\n leg2.SetLineStyle(1)\n leg2.SetLineWidth(1)\n leg2.SetFillStyle(0)\n #leg2.AddEntry(h_rejB_vs_S_1,\"with data sidebands\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_1,\"shifted\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_1,\"with m_{#pi#gamma}\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_1,\"with m_{T}(#lep,#MET)\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_1,\"sin^{2}#theta\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_1,\"train: 2018, test: 2017\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_1,\"cos#theta\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_1,\"testing\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_1,\"with signal scaled down\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_2,\"with MC\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_2,\"without #Delta#varphi_{l,#gamma}\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_2,\"without m_{#pi#gamma}\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_2,\"train: 2018, test: 2018\",\"l\")\n #leg2.AddEntry(h_rejB_vs_S_2,\"with signal non scaled\",\"l\")\n\n gStyle.SetOptStat(0)\n canvas2 = TCanvas()\n h_rejB_vs_S_1.SetTitle(\" \")\n h_rejB_vs_S_1.SetLineColor(1)\n h_rejB_vs_S_1.SetLineWidth(3)\n h_rejB_vs_S_1.Draw(\"hist\")\n leg2.Draw(\"SAME\")\n\n canvas2.SaveAs(\"/afs/cern.ch/user/g/gumoret/cernbox/www/latest_production/MVA_latest_production/h_rejBvsS.pdf\")\n canvas2.SaveAs(\"/afs/cern.ch/user/g/gumoret/cernbox/www/latest_production/MVA_latest_production/h_rejBvsS.png\")\n\n raw_input()\n\nif __name__ == \"__main__\":\n\n rejB_vs_S()\n BDT_output()\n","sub_path":"test/MVA/create_BDT_plots.py","file_name":"create_BDT_plots.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"248849694","text":"# データが半年ちょいで80GBとかになってしまったので、どうにかすべく。\n# mongodbにいれることに。\nfrom Novel import Novel\nn = Novel()\nkeys = n.load_keys_shelve('narou')\nlength = len(keys)\nnow = 1\nfor key in keys:\n print(key, now, '/', length, ' transferring')\n now += 1\n n1 = n.load_shelve('narou', key)\n n1.save()\n n1.del_con_shelve()\n try:\n n.load_shelve('narou', key)\n except KeyError:\n print('delete success')\n n2 = n.load('narou', key,)\n print(n2.con['ncode'], n2.con['title'], 'transfered')\n","sub_path":"DataTransfer.py","file_name":"DataTransfer.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"10100459","text":"import runpy\n\nprint(\"\"\"\nWelcome to the shapes program!\n\nPlease choose one of the following shapes:\n * Diamond\n * Square\n * Triangle\n * Exit\n\"\"\")\nprogram = input(\"Shape: \")\nprogram2 = program.lower()\nprogram3 = program2.replace(\" \",\"\")\nif program3 == str(\"diamond\"):\n runpy.run_path(\"Diamond.py\")\nelif program3 == str(\"square\"):\n runpy.run_path(\"Square.py\")\nelif program3 == str(\"triangle\"):\n runpy.run_path(\"Triangle.py\")\nelif program3 == (\"exit\"):\n runpy.run_path(\"Mainframe.py\")\nelse:\n print(\"\"\"That shape is not avaliable,\nTry another shape\"\"\")\n runpy.run_path(\"Shapes.py\")\n","sub_path":"S.H.E.L.L/Shapes.py","file_name":"Shapes.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"15120612","text":"import ecco_v4_py as ecco\n# import matplotlib.pyplot as plt\nimport numpy as np\n# import numpy.ma as ma\nimport xarray as xr\n\n# def isleap(year):\n# if (year % 4) == 0:\n# if (year % 100) == 0:\n# if (year % 400) == 0:\n# leap = True\n# else:\n# leap = False\n# else:\n# leap = True\n# else:\n# leap = False\n# return leap\n\ndir_ecco = '/Volumes/ECCO/ecco.jpl.nasa.gov/drive/files/Version4/Release4/'\ndir_monthly = dir_ecco + 'nctiles_monthly/'\ndir_grid = dir_ecco + '/nctiles_grid/'\ndir_daily = dir_ecco + 'nctiles_daily/'\n\ndir_output = '/Volumes/ECCO/ecco.jpl.nasa.gov/drive/files/Version4/Release4/interp_daily/SST/chinasea/'\n\nds_grid = ecco.load_ecco_grid_nc(dir_grid,'ECCOv4r3_grid.nc')\nmask_C = ds_grid.hFacC.isel(k=0)\nmask_C = mask_C.where(mask_C>0, np.nan)\n\n# resample\ndx = 0.25; dy = 0.25\nmin_lat = 0; max_lat = 50; min_lon = 100; max_lon = 140;\nn_lon = len(np.arange(min_lon+dx,max_lon-dx,dx))+1; n_lat = len(np.arange(min_lat+dy,max_lat-dy,dy))+1;\n#%% load data\n\nfor year in range(1992,2018):\n ds_data = ecco.load_ecco_var_from_years_nc(dir_daily + '/THETA/'+ str(year), var_to_load='THETA', years_to_load=[year],\n k_subset=[0])\n n_time = len(ds_data.time)\n sst = np.full([n_time, n_lat, n_lon], np.nan)\n\n for in_time in range(0,n_time):\n print(year,in_time)\n lon,lat,sst[in_time,:,:] = ecco.resample_to_latlon(ds_data.XC,ds_data.YC,ds_data.THETA.isel(time=in_time, k=0)*mask_C,\\\n min_lat+dy, max_lat-dy, dy,\\\n min_lon+dx, max_lon-dx, dx,\\\n mapping_method='nearest_neighbor',fill_value=np.nan)\n ds_sst = xr.Dataset({})\n ds_sst.coords['lon'] = lon[0,:]\n ds_sst.coords['lat'] = lat[:,0]\n ds_sst.coords['time'] = ds_data.time\n ds_sst['sst'] = (('time','lat','lon'),sst)\n # name\n ds_sst.lon['long_name'] = 'longitude (degree)'\n ds_sst.lat['long_name'] = 'latitude (degree)'\n ds_sst.sst['long_name'] = 'sea surface temperature (degree C)'\n # output\n file_output = dir_output + 'chinasea_sst_' + str(year) + '.nc'\n print('Saving '+file_output + '...')\n ds_sst.to_netcdf(path=file_output)\n print('Finish ' + file_output + '.')\n\n","sub_path":"ecco_v4_p_tutorial/resample_2_grid_chinasea.py","file_name":"resample_2_grid_chinasea.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"486397307","text":"#coding:utf-8\nimport datetime\nimport sys\nfrom util.save_out_put_fun import Los_Class\nfrom util import dat_log_util\n\nfrom util.logs_out_path_of_parse import get_parse_path\nfirst, second, third, fourth= 0,0,0,0\ndef start(search_date):\n \"\"\"\n 七天战力的action文件解析\n \"\"\"\n\n O, OUT_PUT_PATH_LST = get_parse_path(search_date)\n for server_id in OUT_PUT_PATH_LST.keys():\n try:\n row_list = make_action_file(search_date,server_id)\n # print row_list\n los = Los_Class(search_date,'tables','SEVENT_DAY_FIGHT')\n los.save_one_server(row_list,server_id)\n except:\n pass\n\n\ndef make_action_file(search_date,server_id):\n global first, second, third, fourth # 取事件的文件\n row = []\n table_lst = []\n seven_lv_data = dat_log_util.read_one_day_data('EVENT_ACTION_ACTIVITY_SEVEN_POWER_REWARD',search_date,'all_action',server_id)\n for _server_list in seven_lv_data:\n for _action_dict in _server_list:\n log_time = _action_dict['log_time'].strftime('%Y-%m-%d')\n if _action_dict['seven_power_id'] == 1 : first += 1\n elif _action_dict['seven_power_id'] == 2 : second += 1\n elif _action_dict['seven_power_id'] == 3 : third += 1\n elif _action_dict['seven_power_id'] == 4 : fourth += 1\n\n row = [log_time,first, second, third, fourth]\n table_lst.append(row)\n return table_lst\n\nif __name__ =='__main__':\n start(sys.argv)\n","sub_path":"catch_split_log/activity/seven_days_fight.py","file_name":"seven_days_fight.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"561055448","text":"#! /usr/bin/env python\n\"\"\"A helper program to test cartesian goals for the JACO arm.\"\"\"\n\"\"\"Daniel Fox\"\"\"\n\nimport roslib; roslib.load_manifest('jaco_demo')\nimport rospy\nfrom std_msgs.msg import String\nfrom array import *\n\nimport sys\nimport numpy as np\n\nimport actionlib\nimport jaco_msgs.msg\nimport std_msgs.msg\nimport geometry_msgs.msg\n\nimport goal_generators\n\n#Example of cartesian goal setting\ndef cartesian_pose_client(position, orientation):\n \"\"\"Send a cartesian goal to the action server.\"\"\"\n action_address = '/' + 'jaco' + '_arm_driver/arm_pose/arm_pose'\n client = actionlib.SimpleActionClient(action_address, jaco_msgs.msg.ArmPoseAction)\n client.wait_for_server()\n\n goal = jaco_msgs.msg.ArmPoseGoal()\n goal.pose.header = std_msgs.msg.Header(frame_id=('jaco' + '_api_origin'))\n goal.pose.pose.position = geometry_msgs.msg.Point(\n x=position[0], y=position[1], z=position[2])\n goal.pose.pose.orientation = geometry_msgs.msg.Quaternion(\n x=orientation[0], y=orientation[1], z=orientation[2], w=orientation[3])\n\n client.send_goal(goal)\n\n if client.wait_for_result(rospy.Duration(10.0)):\n return client.get_result()\n else:\n client.cancel_all_goals()\n print(' the cartesian action timed-out')\n return None\n\n\n#Example of gripper goal setting\ndef gripper_client(finger_positions):\n \"\"\"Send a gripper goal to the action server.\"\"\"\n action_address = '/' + 'jaco' + '_arm_driver/fingers/finger_positions'\n client = actionlib.SimpleActionClient(action_address,\n jaco_msgs.msg.SetFingersPositionAction)\n client.wait_for_server()\n\n goal = jaco_msgs.msg.SetFingersPositionGoal()\n goal.fingers.finger1 = float(finger_positions[0])\n goal.fingers.finger2 = float(finger_positions[1])\n goal.fingers.finger3 = float(finger_positions[2])\n\n client.send_goal(goal)\n if client.wait_for_result(rospy.Duration(5.0)):\n return client.get_result()\n else:\n client.cancel_all_goals()\n print(' the gripper action timed-out')\n return None\n\n#NOTE: Unfinished;\ndef callback(data):\n #rospy.loginfo(rospy.get_caller_id() + \"I heard %s\", data.data)\n #NOTE: The Pose does not include a Quaternion, only a point\n pos = [data.pose.position.x, data.pose.position.y, data.pose.position.z]\n #NOTE: This can be changed in the future\n orient = [0.732062321466, 0.0569922916504, -0.0673723200983, 0.675498043422]\n \n print(' position: {}, orientation: {}'.format(pos, orient))\n result = cartesian_pose_client(pos, orient) \n \n #Finger positions by angle (0 to ~60), realistically (0.25 to 56)\n print('Using the specified JACO finger positions:')\n raw_positions = [55, 55, 55]\n positions = [ raw_positions ]\n\n #Close the fingers\n for position in positions:\n print(' position: {}'.format(position))\n result = gripper_client(position)\n \n poses = goal_generators.poses_from_file('/home/sd/ws/src/jaco-ros/homePos.txt') \n\n\nif __name__ == '__main__':\n \n rospy.init_node('jaco' + '_full_test')\n rospy.Subscriber(\"/object_position\", geometry_msgs.msg.PoseStamped, callback)\n rospy.spin()\n \n","sub_path":"jaco_demo/nodes/jaco_demo/full_test.py","file_name":"full_test.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"426632907","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nos.chdir('d:/')\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport fix_yahoo_finance as yf\nimport random as rd\nimport statsmodels.api as sm \nfrom sklearn.model_selection import train_test_split\n\n\n# In[2]:\n\n\nglobal colorlist\n\ncolorlist=['#fffb77',\n '#fffa77',\n '#fff977',\n '#fff876',\n '#fff776',\n '#fff676',\n '#fff576',\n '#fff475',\n '#fff375',\n '#fff275',\n '#fff175',\n '#fff075',\n '#ffef74',\n '#ffef74',\n '#ffee74',\n '#ffed74',\n '#ffec74',\n '#ffeb73',\n '#ffea73',\n '#ffe973',\n '#ffe873',\n '#ffe772',\n '#ffe672',\n '#ffe572',\n '#ffe472',\n '#ffe372',\n '#ffe271',\n '#ffe171',\n '#ffe071',\n '#ffdf71',\n '#ffde70',\n '#ffdd70',\n '#ffdc70',\n '#ffdb70',\n '#ffda70',\n '#ffd96f',\n '#ffd86f',\n '#ffd76f',\n '#ffd66f',\n '#ffd66f',\n '#ffd56e',\n '#ffd46e',\n '#ffd36e',\n '#ffd26e',\n '#ffd16d',\n '#ffd06d',\n '#ffcf6d',\n '#ffce6d',\n '#ffcd6d',\n '#ffcc6c',\n '#ffcb6c',\n '#ffca6c',\n '#ffc96c',\n '#ffc86b',\n '#ffc76b',\n '#ffc66b',\n '#ffc56b',\n '#ffc46b',\n '#ffc36a',\n '#ffc26a',\n '#ffc16a',\n '#ffc06a',\n '#ffbf69',\n '#ffbe69',\n '#ffbd69',\n '#ffbd69',\n '#ffbc69',\n '#ffbb68',\n '#ffba68',\n '#ffb968',\n '#ffb868',\n '#ffb768',\n '#ffb667',\n '#ffb567',\n '#ffb467',\n '#ffb367',\n '#ffb266',\n '#ffb166',\n '#ffb066',\n '#ffaf66',\n '#ffad65',\n '#ffac65',\n '#ffab65',\n '#ffa964',\n '#ffa864',\n '#ffa763',\n '#ffa663',\n '#ffa463',\n '#ffa362',\n '#ffa262',\n '#ffa062',\n '#ff9f61',\n '#ff9e61',\n '#ff9c61',\n '#ff9b60',\n '#ff9a60',\n '#ff9860',\n '#ff975f',\n '#ff965f',\n '#ff955e',\n '#ff935e',\n '#ff925e',\n '#ff915d',\n '#ff8f5d',\n '#ff8e5d',\n '#ff8d5c',\n '#ff8b5c',\n '#ff8a5c',\n '#ff895b',\n '#ff875b',\n '#ff865b',\n '#ff855a',\n '#ff845a',\n '#ff8259',\n '#ff8159',\n '#ff8059',\n '#ff7e58',\n '#ff7d58',\n '#ff7c58',\n '#ff7a57',\n '#ff7957',\n '#ff7857',\n '#ff7656',\n '#ff7556',\n '#ff7455',\n '#ff7355',\n '#ff7155',\n '#ff7054',\n '#ff6f54',\n '#ff6d54',\n '#ff6c53',\n '#ff6b53',\n '#ff6953',\n '#ff6852',\n '#ff6752',\n '#ff6552',\n '#ff6451',\n '#ff6351',\n '#ff6250',\n '#ff6050',\n '#ff5f50',\n '#ff5e4f',\n '#ff5c4f',\n '#ff5b4f',\n '#ff5a4e',\n '#ff584e',\n '#ff574e',\n '#ff564d',\n '#ff544d',\n '#ff534d',\n '#ff524c',\n '#ff514c',\n '#ff4f4b',\n '#ff4e4b',\n '#ff4d4b',\n '#ff4b4a',\n '#ff4a4a']\n\n\n# In[3]:\n\n\n\ndef monte_carlo(data,testsize=0.5,simulation=100): \n \n df,test=train_test_split(data,test_size=testsize,shuffle=False)\n forecast_horizon=len(test)\n \n df=df.loc[:,['Close']]\n \n x=sm.add_constant(df['Close'].shift(1).dropna())\n y=df['Close'].iloc[1:]\n m=sm.OLS(y,x).fit()\n \n d={}\n \n for counter in range(simulation):\n d[counter]=[df['Close'].iloc[0]]\n for i in range(len(y)+forecast_horizon):\n e=rd.gauss(np.mean(m.resid),np.std(m.resid))\n \n temp=m.params@ np.mat([1,d[counter][-1]]).reshape(2,1)+e\n \n d[counter].append(temp.item())\n \n std=float('inf')\n pick=0\n for counter in range(simulation):\n \n temp=np.std(np.subtract(\n d[counter][:len(df)],df['Close']))\n if temp 30:\n img[i, j] = 1\n\ncv2.imwrite('girl5.png', img)\nimg2 = cv2.imread('girl5.png', 1)\ncv2.imshow('image', img2)\ncv2.waitKey()\ncv2.destroyAllWindows()\n","sub_path":"open_cv/learn/pixelimage.py","file_name":"pixelimage.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"366702690","text":"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport random\nrandom.seed(5) \n\n\ndef f_function (x):\n Fx = 1.1*x**2-7*x+6\n Fdx = 2.2*x+-7\n return Fx, Fdx\n\ndef g_function (a):\n Gx = (a**2-9)/(4**a)\n Gdx = ((2**(2*a+1)*a-np.log(2)*2**(2*a+1)*(a**2-9)))/(16**a)\n return Gx, Gdx\n\ndef train_min(alpha, epocs, MyFunc):\n\n # gues the minimum\n xmin = random.randrange(-10,10)\n\n for i in range (epocs):\n Fx, Fdx = MyFunc(xmin)\n if (Fdx>0):\n xmin -= Fdx*alpha\n else:\n xmin += Fdx*alpha\n Fx, Fdx = MyFunc(xmin)\n return xmin, Fx, Fdx\n\n\ndef train_max(alpha, epocs, MyFunc):\n xmax = 0\n for i in range (epocs):\n Fx, Fdx = MyFunc(xmax)\n if (Fdx>0):\n xmax += Fdx*alpha\n else:\n xmax -= Fdx*alpha\n Fx, Fdx = MyFunc(xmax)\n return xmax, Fx, Fdx\n\nprint(\"MIN INFO: \", train_min(0.001, 10000, f_function)) \nprint(\"MIN INFO: \", train_min(0.001, 100000, g_function), \"MAX INFO: \", train_max(0.001, 1000000, g_function))\n\n","sub_path":"DanielsTask/2350exe2.py","file_name":"2350exe2.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"521127413","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Tests for the GIFT PPA script writer.\"\"\"\n\nimport unittest\n\nfrom l2tdevtools import dependencies\nfrom l2tdevtools import projects\nfrom l2tdevtools.dependency_writers import linux_scripts\n\nfrom tests import test_lib\n\n\nclass UbuntuInstallationScriptWriterTest(test_lib.BaseTestCase):\n \"\"\"Tests the hared functionality for GIFT PPA installation script writer.\"\"\"\n\n # pylint: disable=protected-access\n\n def _CreateTestWriter(self):\n \"\"\"Creates a dependency file writer for testing.\n\n Returns:\n UbuntuInstallationScriptWriter: dependency file writer for testing.\n \"\"\"\n project_definition = projects.ProjectDefinition('test')\n dependencies_file = self._GetTestFilePath(['dependencies.ini'])\n test_dependencies_file = self._GetTestFilePath(['test_dependencies.ini'])\n dependency_helper = dependencies.DependencyHelper(\n dependencies_file=dependencies_file,\n test_dependencies_file=test_dependencies_file)\n\n return linux_scripts.UbuntuInstallationScriptWriter(\n '/fake/l2tdevtools/', project_definition, dependency_helper)\n\n def testFormatDPKGDebugDependencies(self):\n \"\"\"Tests the _FormatDPKGDebugDependencies function.\"\"\"\n test_writer = self._CreateTestWriter()\n\n expected_formatted_debug_dependencies = ''\n\n python_dependencies = test_writer._GetDPKGPythonDependencies()\n debug_dependencies = test_writer._GetDPKGDebugDependencies(\n python_dependencies)\n formatted_debug_dependencies = test_writer._FormatDPKGDebugDependencies(\n debug_dependencies)\n self.assertEqual(\n formatted_debug_dependencies, expected_formatted_debug_dependencies)\n\n def testFormatDPKGDevelopmentDependencies(self):\n \"\"\"Tests the _FormatDPKGDevelopmentDependencies function.\"\"\"\n test_writer = self._CreateTestWriter()\n\n expected_formatted_development_dependencies = (\n 'DEVELOPMENT_DEPENDENCIES=\"pylint\";')\n\n development_dependencies = ['pylint']\n formatted_development_dependencies = (\n test_writer._FormatDPKGDevelopmentDependencies(\n development_dependencies))\n self.assertEqual(\n formatted_development_dependencies,\n expected_formatted_development_dependencies)\n\n def testFormatDPKGPythonDependencies(self):\n \"\"\"Tests the _FormatDPKGPythonDependencies function.\"\"\"\n test_writer = self._CreateTestWriter()\n\n expected_formatted_python_dependencies = (\n 'PYTHON_DEPENDENCIES=\"python3-yaml\";')\n\n python_dependencies = test_writer._GetDPKGPythonDependencies()\n formatted_python_dependencies = test_writer._FormatDPKGPythonDependencies(\n python_dependencies)\n self.assertEqual(\n formatted_python_dependencies, expected_formatted_python_dependencies)\n\n def testFormatDPKGTestDependencies(self):\n \"\"\"Tests the _FormatDPKGTestDependencies function.\"\"\"\n test_writer = self._CreateTestWriter()\n\n expected_formatted_test_dependencies = (\n 'TEST_DEPENDENCIES=\"python3-distutils\\n'\n ' python3-mock\\n'\n ' python3-pbr\\n'\n ' python3-setuptools\";')\n\n python_dependencies = test_writer._GetDPKGPythonDependencies()\n test_dependencies = test_writer._GetDPKGTestDependencies(\n python_dependencies)\n formatted_test_dependencies = test_writer._FormatDPKGTestDependencies(\n test_dependencies)\n self.assertEqual(\n formatted_test_dependencies, expected_formatted_test_dependencies)\n\n def testGetDPKGDebugDependencies(self):\n \"\"\"Tests the _GetDPKGDebugDependencies function.\"\"\"\n test_writer = self._CreateTestWriter()\n\n expected_debug_dependencies = []\n\n python_dependencies = test_writer._GetDPKGPythonDependencies()\n debug_dependencies = test_writer._GetDPKGDebugDependencies(\n python_dependencies)\n self.assertEqual(debug_dependencies, expected_debug_dependencies)\n\n # TODO: Add test for the Write method.\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/dependency_writers/linux_scripts.py","file_name":"linux_scripts.py","file_ext":"py","file_size_in_byte":3995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"139601931","text":"import numpy as np\n\nclass ShoppingCart:\n # write your code here\n def __init__(self, emp_discount=None):\n self.total = 0\n self.employee_discount = emp_discount\n self.items = []\n \n def add_item(self, name, price, quantity=1):\n item_info = {'name':name, 'price':price}\n for i in range(quantity): \n self.items.append(item_info)\n self.total += price*quantity\n return self.total\n \n def mean_item_price(self):\n return(f\"The mean price is {self.total/len(self.items)}\")\n\n def median_item_price(self):\n prices_list = []\n prices_list = [item['price'] for item in self.items]\n length = len(prices_list)\n half = int(length/2)\n prices_list.sort()\n if length % 2 == 0:\n return(f\"The median price is {(prices_list[half-1]+prices_list[half])/2}\")\n else:\n return(f\"The median price is {prices_list[half]}\")\n \n def apply_discount(self):\n discount_total = None\n if self.employee_discount:\n discount_total = self.total * (1 - (self.employee_discount/100))\n return(discount_total)\n else:\n return(\"Sorry, there is no discount to apply to your cart :(\")\n\n def void_last_item(self):\n if not self.items:\n return(\"There are no items in your cart!\")\n else:\n removed_item = self.items.pop()\n self.total -= removed_item['price']\n return(self.total)\n ","sub_path":"shopping_cart.py","file_name":"shopping_cart.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"552021361","text":"from django.urls import path\n\nfrom SuperAdmin import views\n\nurlpatterns = [\n path('', views.dashboard, name='SuperAdminHome'),\n\n path('degree/list/', views.list_degree, name='list_degree'),\n path('degree/create/', views.create_degree, name='create_degree'),\n path('degree/update//', views.update_degree, name='update_degree'),\n path('degree/delete//', views.delete_degree, name='delete_degree'),\n\n path('specialist/list/', views.list_specialist, name='list_specialist'),\n path('specialist/create/', views.create_specialist, name='create_specialist'),\n path('specialist/update//', views.update_specialist, name='update_specialist'),\n path('specialist/delete//', views.delete_specialist, name='delete_specialist'),\n\n path('hospital/list/', views.list_hospital, name='list_hospital'),\n path('hospital/create/', views.create_hospital, name='create_hospital'),\n path('hospital/update//', views.update_hospital, name='update_hospital'),\n path('hospital/delete//', views.delete_hospital, name='delete_hospital'),\n\n path('doctor/list/', views.list_doctor, name='list_doctor'),\n path('doctor/create/', views.create_doctor, name='create_doctor'),\n path('doctor/view//', views.view_doctor, name='view_doctor'),\n path('doctor/delete//', views.delete_doctor, name='delete_doctor'),\n\n path('icu/list/', views.list_icu_bed_number, name='list_icu'),\n path('icu/create/', views.create_icu_bed_number, name='create_icu'),\n path('icu/update//', views.update_icu_bed_number, name='update_icu'),\n path('icu/delete//', views.delete_icu_bed_number, name='delete_icu'),\n\n path('oxygen/list/', views.list_oxygen_cylinder_number, name='list_oxygen'),\n path('oxygen/create/', views.create_oxygen_cylinder_number, name='create_oxygen'),\n path('oxygen/update//', views.update_oxygen_cylinder_number, name='update_oxygen'),\n path('oxygen/delete//', views.delete_oxygen_cylinder_number, name='delete_oxygen'),\n\n path('plasma/list/', views.list_plasma, name='list_plasma'),\n path('plasma/create/', views.create_plasma, name='create_plasma'),\n path('plasma/view//', views.view_plasma, name='view_plasma'),\n path('plasma/delete//', views.delete_plasma, name='delete_plasma'),\n\n path('location/list/', views.list_location, name='list_location'),\n path('location/create/', views.create_location, name='create_location'),\n path('location/update//', views.update_location, name='update_location'),\n path('location/delete//', views.delete_location, name='delete_location'),\n\n path('super_admin_profile/', views.super_admin_profile, name='super_admin_profile'),\n\n path('admin_view_appointment/', views.admin_view_appointment, name='admin_view_appointment'),\n path('admin_appointment_update//', views.admin_appointment_update, name='admin_appointment_update'),\n path('admin_appointment_delete//', views.admin_appointment_delete, name='admin_appointment_delete'),\n\n path('admin_view_vaccine_apply/', views.admin_view_vaccine_apply, name='admin_view_vaccine_apply'),\n path('admin_vaccine_delete//', views.admin_vaccine_delete, name='admin_vaccine_delete'),\n path('admin_vaccine_update//', views.admin_vaccine_update, name='admin_vaccine_update'),\n\n path('icu_booking_list/', views.icu_booking_list, name='icu_booking_list'),\n path('icu_booking_delete//', views.icu_booking_delete, name='icu_booking_delete'),\n path('icu_booking_status_change//', views.icu_booking_status_change, name='icu_booking_status_change'),\n\n path('oxygen_cylinder_booking_list/', views.oxygen_cylinder_booking_list, name='oxygen_cylinder_booking_list'),\n path('oxygen_cylinder_booking_status_change//', views.oxygen_cylinder_booking_status_change,\n name='oxygen_cylinder_booking_status_change'),\n\n path('password_change/', views.password_change, name='super_admin_password_change'),\n\n]\n","sub_path":"SuperAdmin/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"509904978","text":"import requests\nfrom exercise.ua import ua_list\nimport time\nimport random\nimport re\nimport os\nfrom urllib import parse\n\nclass BaiduImageSpider(object):\n def __init__(self):\n self.url = 'https://image.baidu.com/search/index?' \\\n 'tn=baiduimage&word={}'\n # 计数\n self.i = 1\n\n # 获取图片\n def get_image(self,url,word):\n headers = { 'User-Agent':random.choice(ua_list) }\n # 1. 获取图片链接列表\n html = requests.get(url=url,headers=headers).text\n pattern = re.compile('\"middleURL\":\"(.*?)\"',re.S)\n img_link_list = pattern.findall(html)\n # 创建对应文件夹,用来保存图片 /home/tarena/images/名字\n directory = '/images/{}/'.format(word)\n if not os.path.exists(directory):\n os.makedirs(directory)\n # 2. for循环遍历,下载每张图片\n for img_link in img_link_list:\n self.save_image(img_link,directory,word)\n # 控制爬取速率: 每爬完1张图片,休眠\n time.sleep(random.randint(1,2))\n\n # 保存图片函数\n def save_image(self,img_link,directory,word):\n headers = { 'User-Agent':random.choice(ua_list) }\n # 1. 向图片链接发请求,得到bytes类型\n print(img_link)\n try:\n html = requests.get(url=img_link,headers=headers).content\n # print(html)\n filename = directory + '{}_{}.jpg'.format(word,self.i)\n # 2. 命名文件名,wb方式保存图片\n with open(filename,'wb') as f:\n f.write(html)\n self.i += 1\n print(filename,'下载成功')\n except Exception as e:\n pass\n\n # 入口函数\n def run(self):\n word = input('你想要谁的图片:')\n word1 = parse.quote(word)\n url = self.url.format(word1)\n self.get_image(url,word)\n\nif __name__ == '__main__':\n spider = BaiduImageSpider()\n spider.run()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"baidu_img.py","file_name":"baidu_img.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"491864599","text":"import tensorflow as tf\r\nfrom tensorflow.contrib.rnn import LSTMCell, GRUCell, MultiRNNCell, DropoutWrapper\r\ndistr = tf.contrib.distributions\r\nfrom tqdm import tqdm\r\nimport random\r\nimport numpy as np\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import rcParams\r\n\r\n\r\n# Tensor summaries for TensorBoard visualization\r\ndef variable_summaries(name,var, with_max_min=False):\r\n with tf.name_scope(name):\r\n mean = tf.reduce_mean(var)\r\n tf.summary.scalar('mean', mean)\r\n with tf.name_scope('stddev'):\r\n stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))\r\n tf.summary.scalar('stddev', stddev)\r\n if with_max_min == True:\r\n tf.summary.scalar('max', tf.reduce_max(var))\r\n tf.summary.scalar('min', tf.reduce_min(var))\r\n\r\n\r\n############################\r\n### DEFINING THE NETWORK ###\r\n############################\r\n\r\n\r\nclass Actor(object):\r\n\r\n def __init__(self, config):\r\n self.batch_size = config.batch_size # batch size\r\n self.a_steps = config.a_steps # length of melody (listen)\r\n self.b_steps = config.b_steps # length of melody/harmony (attend & play)\r\n self.num_roots = config.num_roots # dimension of a keyboard\r\n self.threshold = config.threshold # for playing a note\r\n self.hidden_dimension = config.hidden_dimension # for melody / keyboard embedding, RNN modules...\r\n\r\n self.is_training = config.is_training # mode\r\n self.initializer = tf.contrib.layers.xavier_initializer() # variables initializer\r\n self.temperature = config.temperature\r\n\r\n self.global_step = tf.Variable(0, trainable=False, name=\"global_step\") # global step\r\n self.lr1_start = config.lr1_start # initial learning rate\r\n self.lr1_decay_rate = config.lr1_decay_rate # learning rate decay rate\r\n self.lr1_decay_step = config.lr1_decay_step # learning rate decay step\r\n\r\n # input and target of the model\r\n self.input = tf.placeholder(tf.float32, [None, self.a_steps+self.b_steps, self.num_roots+1+1]) # melody input [Batch Size, k * Sequence Length, Keyboard_dim] +1 +1 for silence & on_kick ft\r\n self.target = tf.placeholder(tf.float32, [None, self.b_steps, self.num_roots+1]) # target chords [Batch Size, Sequence Length, Keyboard_dim] +1 for silence\r\n \r\n with tf.variable_scope(\"encoder\"):\r\n # Encode melody\r\n self.encode_melody()\r\n # Encode instrument (piano)\r\n self.encode_instru()\r\n with tf.variable_scope(\"decoder\"):\r\n # Decode accompaniement\r\n self.listen()\r\n self.attend_n_play()\r\n with tf.variable_scope(\"training\"):\r\n # Training\r\n self.train()\r\n self.merged = tf.summary.merge_all()\r\n\r\n def encode_melody(self):\r\n # Embed input sequence\r\n W_embed =tf.get_variable(\"weights\", [1,self.num_roots+1+1,self.hidden_dimension])\r\n embedded_input = tf.nn.conv1d(self.input, W_embed, 1, \"VALID\", name=\"embedded_input\")\r\n # Batch Normalization\r\n embedded_input = tf.layers.batch_normalization(embedded_input, axis=2, training=self.is_training, name='layer_norm', reuse=None)\r\n self.melody = tf.transpose(embedded_input,[1,0,2]) # [Time steps, batch size, h_dim]\r\n \r\n def encode_instru(self):\r\n # Keyboard Representation\r\n positional_keyboard = tf.tile(tf.expand_dims(tf.range(self.num_roots+1), 0),[self.batch_size, 1])\r\n lookup_table = tf.get_variable('lookup_table', dtype=tf.float32, shape=[self.num_roots+1, self.hidden_dimension])\r\n self.keyboard_embedding = tf.nn.embedding_lookup(lookup_table, positional_keyboard, name=\"positional_encoding\")\r\n\r\n def listen(self):\r\n # Decoder LSTM cell \r\n self.cell1 = LSTMCell(self.hidden_dimension, initializer=self.initializer) # Melody LSTM cell (listen + attend_n_play)\r\n self.cell2 = LSTMCell(self.hidden_dimension, initializer=self.initializer) # Harmony LSTM cell (attend_n_play)\r\n\r\n # Pointing mechanism\r\n with tf.variable_scope(\"pointer\"):\r\n self.W_ref =tf.get_variable(\"W_ref\",[1,self.hidden_dimension,self.hidden_dimension],initializer=self.initializer)\r\n self.W_q =tf.get_variable(\"W_q\",[self.hidden_dimension,self.hidden_dimension],initializer=self.initializer)\r\n self.v =tf.get_variable(\"v\",[self.hidden_dimension],initializer=self.initializer)\r\n\r\n self.W1 =tf.get_variable(\"W1\",[self.num_roots+1,self.hidden_dimension],initializer=self.initializer)\r\n self.b1 =tf.get_variable(\"b1\",[self.hidden_dimension],initializer=None)\r\n self.W2 =tf.get_variable(\"W2\",[self.hidden_dimension,self.num_roots+1],initializer=self.initializer)\r\n self.b2 =tf.get_variable(\"b2\",[self.num_roots+1],initializer=None)\r\n\r\n # Loop the decoding process and collect results\r\n self.s = tf.zeros([self.batch_size,self.hidden_dimension]), tf.zeros([self.batch_size,self.hidden_dimension]) # Melody initial (LSTM) state\r\n for step in range(self.a_steps):\r\n if step > 0:\r\n tf.get_variable_scope().reuse_variables()\r\n # Run the cell on a combination of the input and state\r\n _, self.s = self.cell1(self.melody[step],self.s)\r\n\r\n def attend_n_play(self):\r\n # Output = Distribution over keyboard for music generation\r\n self.pointing_ = []\r\n\r\n # From a query (decoder output) [Batch size, n_hidden], predict a distribution over a set of reference vectors (Keyboard representation) [Batch size, seq_length, n_hidden]\r\n def attention(query):\r\n encoded_ref = tf.nn.conv1d(self.keyboard_embedding, self.W_ref, 1, \"VALID\", name=\"encoded_ref\") # [Batch size, seq_length, n_hidden]\r\n encoded_query = tf.expand_dims(tf.matmul(query, self.W_q, name=\"encoded_query\"), 1) # [Batch size, 1, n_hidden]\r\n scores = tf.reduce_sum(self.v * tf.tanh(encoded_ref + encoded_query), [-1], name=\"scores\") # [Batch size, seq_length]\r\n scores = 10.0*tf.tanh(scores) # control entropy\r\n pointing_0 = tf.nn.softmax(scores, name=\"attention\") # Pointer: [Batch size, Seq_length]\r\n return pointing_0\r\n\r\n # Loop the decoding process and collect results\r\n self.s_ = tf.zeros([self.batch_size,self.hidden_dimension]), tf.zeros([self.batch_size,self.hidden_dimension]) # Harmony initial (LSTM) state\r\n for step in range(self.b_steps):\r\n if step > 0:\r\n tf.get_variable_scope().reuse_variables()\r\n # Run the cell on a combination of the input and state\r\n output, self.s = self.cell1(self.melody[self.a_steps+step],self.s)\r\n # Attention mechanism\r\n pointing_0 = attention(output)\r\n # Additional RNN layer on pointing mechanism (piano) - because chords are non linear + recurrent relation\r\n pointing_1, self.s_ = self.cell2(tf.matmul(pointing_0, self.W1)+self.b1,self.s_)\r\n # Dense layer for final chord prediction\r\n pointing_2 = tf.tanh(tf.matmul(pointing_1, self.W2)+self.b2)\r\n if self.is_training == False:\r\n pointing_2 = pointing_2/self.temperature # control diversity of sampling (inference mode)\r\n pointing = tf.nn.softmax(10.0*pointing_2, name=\"attention\") # Pointer: [Batch size, Seq_length]\r\n self.pointing_.append(pointing)\r\n\r\n # Stack pointing distribution\r\n self.pointing_ = tf.stack(self.pointing_ ,axis=1) # [Batch,seq_length,Keyboard_dim]\r\n\r\n # Hard sample\r\n self.target_chords = tf.cast(self.target,tf.int32)\r\n self.played_chords = tf.cast(tf.greater_equal(self.pointing_,self.threshold),tf.int32)\r\n # Accuracy = ...\r\n errors = tf.cast(tf.minimum(tf.reduce_sum(tf.abs(self.target_chords-self.played_chords),2),1),tf.float32) # [batch_size,seq_length] \t0 if good chord, 1 if error.\r\n accuracies = 1-tf.reduce_mean(errors,1)\r\n variable_summaries('accuracy',accuracies, with_max_min = True)\r\n self.accuracy = tf.reduce_mean(accuracies,0)\r\n\r\n\r\n def train(self):\r\n\r\n # Update moving_mean and moving_variance for batch normalization layers\r\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n with tf.control_dependencies(update_ops):\r\n\r\n # Actor learning rate\r\n self.lr1 = tf.train.exponential_decay(self.lr1_start, self.global_step, self.lr1_decay_step,self.lr1_decay_rate, staircase=False, name=\"learning_rate1\")\r\n tf.summary.scalar('lr',self.lr1)\r\n # Optimizer\r\n optimizer = tf.train.AdamOptimizer(learning_rate=self.lr1,beta1=0.9,beta2=0.99, epsilon=0.0000001)\r\n \r\n # Rescale pointing_distribution (sum = 1) by number of target notes at each step, for each batch\r\n scale = tf.cast(tf.count_nonzero(self.target,axis=2,keep_dims=True),tf.float32)\r\n # Loss function = CROSS ENTROPY (supervised)\r\n self.cross_entropy = -tf.reduce_sum(self.target * tf.log(tf.clip_by_value(scale*self.pointing_,1e-10,4.0)),2) # cross entropy at each output step (Sum on Keyboard_dim)\r\n self.cross_entropy = tf.reduce_mean(self.cross_entropy,1) # mean entropy for each seq prediction (Mean on steps)\r\n variable_summaries('cross_entropy',self.cross_entropy, with_max_min = True)\r\n self.cross_entropy = tf.reduce_mean(self.cross_entropy,0) # mean entropy % batch\r\n\r\n # Minimize step\r\n gvs = optimizer.compute_gradients(self.cross_entropy)\r\n capped_gvs = [(tf.clip_by_norm(grad, 1.), var) for grad, var in gvs if grad is not None] # L2 clip\r\n self.minimize = optimizer.apply_gradients(capped_gvs, global_step=self.global_step)","sub_path":"archi_/actor.py","file_name":"actor.py","file_ext":"py","file_size_in_byte":9807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"636693750","text":"from rest_framework import serializers, validators\n\nfrom . import models\n\n\nclass PostSerializer(serializers.ModelSerializer):\n author = serializers.SlugRelatedField(slug_field='username',\n read_only=True)\n\n class Meta:\n fields = ('id', 'text', 'author', 'pub_date')\n model = models.Post\n\n\nclass CommentSerializer(serializers.ModelSerializer):\n author = serializers.SlugRelatedField(slug_field='username',\n read_only=True)\n\n class Meta:\n fields = ('id', 'author', 'post', 'text', 'created')\n model = models.Comment\n\n\nclass FollowSerializer(serializers.ModelSerializer):\n user = serializers.SlugRelatedField(\n slug_field='username',\n read_only=True,\n default=serializers.CurrentUserDefault()\n )\n following = serializers.SlugRelatedField(\n slug_field='username',\n queryset=models.User.objects.all()\n )\n\n class Meta:\n fields = ('user', 'following')\n model = models.Follow\n validators = [\n validators.UniqueTogetherValidator(\n queryset=models.Follow.objects.all(),\n fields=['user', 'following']\n )\n ]\n\n def validate_following(self, value):\n user = self.context['request'].user\n if value == user:\n raise serializers.ValidationError(\"You cannot follow yourself\")\n return value\n\n\nclass GroupSerializer(serializers.ModelSerializer):\n class Meta:\n fields = ('title', )\n model = models.Group\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"243807026","text":"import numpy as np\nimport math\nfrom tensor_graph.Operator import Operator\nfrom tensor_graph.Variable import Variable,GLOBAL_VARIABLE_SCOPE\nfrom tensor_graph.utils import img2col\n\nclass Conv2D(Operator):\n\n def __init__(self, kernel_shape=list, input_variable=Variable, name=str, scope='', stride=1, padding='SAME'):\n \"\"\"\n conv layer -> Operator\n :param kernel_shape:\n :param input_variable: only one and shape must be 4 dim\n get input variable and output variable to call Operator.__init__\n kernel params save as Variable(trainable=True)\n scope name of all variables is self.name\n \"\"\"\n # kernel_shape = [ksize, ksize, input_channels, output_channels]\n for i in kernel_shape:\n if not isinstance(i, int):\n raise Exception(\"Operator Conv2D name: %s kernel shape is not list of int\" % self.name)\n\n if not isinstance(input_variable, Variable):\n raise Exception(\"Operator Conv2D name: %s's input_variable is not instance of Variable\" % name)\n\n if len(input_variable.shape)!=4:\n raise Exception(\"Operator Conv2D name: %s's input_variable's shape != 4d Variable!\" % name)\n\n self.ksize = kernel_shape[0]\n self.stride = stride\n self.output_num = kernel_shape[-1]\n self.padding = padding\n\n self.col_image = []\n\n self.weights = Variable(kernel_shape, scope=name, name='weights',grad=True, trainable=True)\n self.bias = Variable([self.output_num], scope=name, name='bias', grad=True, trainable=True)\n\n self.batch_size = input_variable.shape[0]\n # calc output variable shape\n if self.padding == 'SAME':\n output_shape = [self.batch_size, input_variable.shape[1]//stride, input_variable.shape[2]//stride,\n self.output_num]\n if self.padding == 'VALID':\n output_shape = [self.batch_size, (input_variable.shape[1] - self.ksize + 1)//stride,\n (input_variable.shape[2] - self.ksize + 1)//stride, self.output_num]\n else:\n raise AttributeError('unsupported padding method')\n\n self.input_variables = input_variable\n self.output_variables = Variable(output_shape, name='out', scope=name) # .name\n\n Operator.__init__(self, [self.input_variables], [self.output_variables],name,scope)\n\n def forward(self):\n \"\"\"complete as needed by template\"\"\"\n if self.wait_forward:\n for parent in self.parent:\n GLOBAL_VARIABLE_SCOPE[parent].eval()\n self.wait_forward = False\n self.conv(self.input_variables, self.output_variables, self.weights, self.bias, self.ksize, self.stride)\n else:\n pass\n\n def backward(self):\n \"\"\"complete as needed by template\"\"\"\n if self.wait_forward:\n pass\n else:\n for child in self.child:\n GLOBAL_VARIABLE_SCOPE[child].diff_eval()\n self.deconv(self.input_variables, self.output_variables, self.weights, self.bias)\n self.wait_forward = True\n\n\n def conv(self, input=Variable, output=Variable, weights=Variable, bias=Variable ,ksize=int ,stride=int):\n \"\"\"\n weights and bias need not be Variable,because need not change value of input params\n convolution operation\n support outer call\n get input.data and output.data.shape -> calc output.data\n \"\"\"\n\n # padding input_img according to method\n if self.padding == 'SAME':\n batch_img = np.pad(input.data,((0, 0),(ksize//2,ksize//2),(ksize//2,ksize//2),(0, 0)),\n mode='constant', constant_values=0)\n else:\n batch_img = input.data\n\n # reshape weights to col\n col_weights = weights.data.reshape(-1, self.output_num)\n '''\n # through maxtrix op and for loop to each batch \n conv_out = []\n self.col_image = []\n # do dot for every image in batch by img2col dot col_weight\n for i in range(self.batch_size):\n img_i = batch_img[i][np.newaxis, :]\n col_image_i = img2col(img_i, ksize, stride)\n out = np.reshape(np.dot(col_image_i, col_weights) + bias, output.data[0].shape)\n self.col_image.append(col_image_i)\n conv_out.append(out)\n self.col_image = np.array(self.col_image)\n conv_out = np.array(conv_out)\n '''\n\n # through matrix operation is faster than for loop operation on each batch (统一处理batch)\n self.col_image = np.array([img2col(batch_img[i][np.newaxis,:],ksize,stride) for i in range(self.batch_size)])\n # print(self.col_image.shape,col_weights.shape,bias.shape)\n conv_out = np.reshape(np.dot(self.col_image,col_weights) + bias.data, output.shape)\n\n output.data = conv_out\n\n def deconv(self, input=Variable, output=Variable, weights=Variable, bias=Variable):\n \"\"\"\n weights and bias type should be Variable,because need to change value of input param (rather than quotation)\n deconvolution operation\n support outer call\n get weights grad and backward propagate delta to input of current layer\n -> weights.diff bias.diff and input.diff\n \"\"\"\n # 1. weights grad\n col_delta = np.reshape(output.diff, [self.batch_size, -1, self.output_num])\n for i in range(self.batch_size):\n # sum in batch\n weights.diff += np.dot(self.col_image[i].T, col_delta[i]).reshape(self.weights.shape)\n bias.diff += np.sum(col_delta, axis=(0, 1))\n # 2. input grad\n # deconv of padded delta with flippd kernel to get input_delta\n if self.padding == 'VALID':\n padded_delta = np.pad(output.diff,((0,0),(self.ksize-1,self.ksize-1),(self.ksize-1,self.ksize-1),(0,0)),\n mode='constant', constant_values=0)\n\n if self.padding == 'SAME':\n padded_delta = np.pad(output.diff,((0,0),(self.ksize//2,self.ksize//2),(self.ksize//2,self.ksize//2),(0, 0)),\n mode='constant', constant_values=0)\n\n # img2col\n col_padded_delta = [img2col(padded_delta[i][np.newaxis, :], self.ksize, self.stride) for i in range(self.batch_size)]\n col_padded_delta = np.array(col_padded_delta)\n\n # flip weights\n flip_weights = np.flipud(np.fliplr(weights.data))\n # [...,inputchannel,outputchannel] - > [...,outputchannel,inputchannel]\n flip_weights = flip_weights.transpose((0,1,3,2))\n col_flip_weights = flip_weights.reshape([-1, weights.shape[2]])\n\n \n input.diff = np.reshape(np.dot(col_padded_delta, col_flip_weights),input.shape)\n\n\n","sub_path":"lesson04_practice_on_cifar100/tensor_graph/Conv2D.py","file_name":"Conv2D.py","file_ext":"py","file_size_in_byte":6753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"424686281","text":"from celery import Celery\r\nfrom identity.config import IdentityConfig\r\n\r\n\r\ncelery = Celery(\r\n 'Identity',\r\n broker=IdentityConfig.BROKER_URL,\r\n backend=IdentityConfig.CELERY_RESULT_BACKEND,\r\n)\r\n\r\nclass Config():\r\n def __init__(self):\r\n self.broker_url = IdentityConfig.BROKER_URL\r\n self.result_backend = IdentityConfig.CELERY_RESULT_BACKEND\r\n self.task_default_rate_limit = IdentityConfig.CELERY_RATE_LIMIT\r\n self.worker_redirect_stdouts_level = IdentityConfig.CELERY_REDIRECT_STDOUTS_LEVEL\r\n self.task_default_queue = IdentityConfig.CELERY_DEFAULT_QUEUE\r\n\r\n\r\n\r\ndef init_celery(app):\r\n celery.config_from_object(Config())\r\n\r\n class ContextTask(celery.Task):\r\n rate_limit = app.config['CELERY_RATE_LIMIT']\r\n \r\n def __call__(self, *args, **kwargs):\r\n with app.app_context():\r\n return self.run(*args, **kwargs)\r\n\r\n celery.Task = ContextTask\r\n","sub_path":"identity/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"356663851","text":"import collections\nimport datetime\nimport gocept.lxml.objectify\nimport logging\nimport lxml.etree\nimport six.moves.urllib.parse\nimport six.moves.urllib.request\nimport threading\nimport time\nimport zeit.today.interfaces\nimport zope.interface\n\n\nlogger = logging.getLogger(__name__)\n\n\n@zope.interface.implementer(zeit.today.interfaces.ICountStorage)\nclass CountStorage(object):\n \"\"\"Central access to click counting.\"\"\"\n\n REFRESH_INTERVAL = 5 * 60 # 5 minutes\n\n def __init__(self, url_getter):\n self.url = url_getter\n self.id_to_count = collections.OrderedDict()\n self.id_to_date = collections.OrderedDict()\n self.update_lock = threading.Lock()\n self.last_refresh = None\n\n def get_count(self, unique_id):\n \"\"\"Return access count for given unique id.\"\"\"\n self._refresh()\n return self.id_to_count.get(unique_id)\n\n def get_count_date(self, unique_id):\n \"\"\"Return access count for given unique id.\"\"\"\n self._refresh()\n return self.id_to_date.get(unique_id)\n\n def __iter__(self):\n self._refresh()\n return iter(self.id_to_count)\n\n def _refresh(self):\n now = time.time()\n if (self.last_refresh and\n self.last_refresh + self.REFRESH_INTERVAL > now):\n return\n\n locked = self.update_lock.acquire(False)\n if not locked:\n # Some other thread is updating right now, wait until this is\n # finished\n self.update_lock.acquire()\n self.update_lock.release()\n return\n try:\n url = self.url()\n logger.info(\"Updating click counter from %s\" % url)\n request = six.moves.urllib.request.urlopen(url)\n try:\n xml = gocept.lxml.objectify.fromfile(request)\n except lxml.etree.XMLSyntaxError:\n # Hum. Sometimes we cannot parse it because the file is empty.\n # Just ignore this update.\n logger.error(\"XMLSyntaxError while updating %s\" % url,\n exc_info=True)\n else:\n if xml.find('article') is not None:\n id_to_count = collections.OrderedDict()\n id_to_date = collections.OrderedDict()\n for item in xml['article']:\n url = self._make_unique_id(item.get('url'))\n count = int(item.get('counter'))\n date = datetime.date(\n *(time.strptime(item.get('date'),\n '%Y-%m-%d')[0:3]))\n id_to_count.setdefault(url, 0)\n id_to_count[url] += count\n id_to_date[url] = date\n self.id_to_count = id_to_count\n self.id_to_date = id_to_date\n self.last_refresh = now\n finally:\n self.update_lock.release()\n\n @staticmethod\n def _make_unique_id(path):\n while '//' in path:\n path = path.replace('//', '/')\n return six.moves.urllib.parse.urljoin('http://xml.zeit.de/', path)\n\n\n@zope.interface.implementer(zeit.today.interfaces.ICountStorage)\ndef today_storage_factory():\n def url_getter():\n config = zope.app.appsetup.product.getProductConfiguration(\n 'zeit.today')\n return config['today-xml-url']\n return CountStorage(url_getter)\n","sub_path":"src/zeit/today/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":3452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"46441177","text":"import sys\ntot = 0\nwhile True:\n s = input()\n if not s:\n break\n values = s.split(\" \")\n opr = values[0]\n num = int(values[1])\n if opr == \"D\":\n tot += num\n elif opr == 'W':\n tot -= num\n else:\n sys.stderr.write(\"Can not identify pattern!\")\nprint(tot)\n","sub_path":"script/qs17.py","file_name":"qs17.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"495934226","text":"import json\nimport uuid\nfrom flask import Flask, request, abort, send_file, jsonify\nfrom flask_cors import CORS\nimport download\n\n\napp = Flask(__name__)\napp.config.from_pyfile('application.cfg', silent=True)\n\nCORS(app, resources={r\"/*\": {\"origins\": \"*\"}})\n\ndownload_requests = {}\n\n@app.route('/')\ndef root():\n #abort(403)\n return 'API root'\n\n\n@app.route('/request_download', methods = ['POST'])\ndef request_download():\n file_url = request.form.get('file_url')\n\n if file_url == None:\n abort(403)\n\n download_request = {\n 'file_id': None,\n 'file_url': file_url,\n 'file_name': file_url.split('/')[-1],\n 'download_progression': 0,\n 'md5sum': None,\n 'sha1sum': None,\n 'virus_report': None,\n 'vul_report': None,\n 'zip_path': None,\n 'zip_download_session': None,\n 'zip_download_timestamp': None\n }\n\n # Download and zip\n download_request=download.download_md5sum_zip(download_request)\n\n download_requests[file_url] = download_request\n\n return file_url\n\n@app.route('/get_download_state')\ndef get_download_state():\n file_url = request.args.get('file_url')\n return jsonify(download_requests[file_url])\n\n@app.route('/get_download_zip')\ndef get_download_zip():\n file_url = request.args.get('file_url')\n\n download_request = download_requests[file_url]\n\n # zip_download_timestamp = now\n # zip_download_session += 1\n # return zip stream\n # zip_download_session -= 1\n \n # Message cleanup\n # - user_session_id\n # - file_url\n return send_file(download_request['zip_path'], attachment_filename=download_request['file_name'] + '.zip')\n\n\nif __name__ == '__main__':\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"533929782","text":"#!/usr/bin/env python3\r\n\r\nimport sys\r\nimport turtle\r\nimport random\r\n\r\nmineChar = \"X\"\r\nclearChar = \".\"\r\n\r\n# Draw the starting grid\r\ndef grid(turtle, gridSize, xLimit, yLimit):\r\n for i in range(gridSize):\r\n draw(turtle,0,ylimit-(i+1)*(ylimit/gridSize),xLimit,ylimit-(i+1)*(ylimit/gridSize),\"grey\")\r\n draw(turtle,i*(xlimit/gridSize),0,i*(xlimit/gridSize),yLimit,\"grey\")\r\n\r\ndef move(turtle, x, y):\r\n turtle.pu()\r\n turtle.setx(x)\r\n turtle.sety(y)\r\n turtle.pd()\r\n\r\ndef draw(turtle, x1, y1, x2, y2, colour):\r\n move(turtle, x1, y1)\r\n turtle.pencolor(colour)\r\n turtle.setposition(x2, y2)\r\n\r\ndef cell(turtle, x, y, sx, sy, colour):\r\n draw(turtle,x,y,x+sx, y, colour)\r\n draw(turtle,x+sx, y, x+sx, y+sy, colour)\r\n draw(turtle,x+sx, y+sy, x, y+sy, colour)\r\n draw(turtle,x, y+sy, x, y, colour)\r\n\r\n# Create a maze that's full of mines!\r\ndef createMaze(xSize,ySize):\r\n # create an empty list\r\n mazeArray=[]\r\n # create a line of mines\r\n allMines=xSize*mineChar\r\n # now build a list of these\r\n for i in range(ySize):\r\n mazeArray.append(allMines)\r\n return(mazeArray)\r\n\r\n# Print a text representation of the minefield\r\ndef printMineField(mf):\r\n\r\n # Loop thru the list\r\n for i in range(len(mf)):\r\n print(mf[i])\r\n print()\r\n\r\ndef setMine(mf,x,y):\r\n s=list(mf[y])\r\n s[x]=mineChar\r\n mf[y]=\"\".join(s)\r\n return(mf)\r\n\r\ndef clearMine(mf,x,y):\r\n s=list(mf[y])\r\n s[x]=clearChar\r\n mf[y]=\"\".join(s)\r\n return(mf)\r\n\r\ndef inactiveMine(mf,x,y):\r\n return(mf[y][x]==clearChar)\r\n\r\n# A further sensible check, is the destination cell a valid one\r\ndef validDest(mf, curx, cury, x, y, gridSize):\r\n\r\n for i in range(-1,1):\r\n for j in range(-1,1):\r\n\r\n checkX = x + i\r\n checkY = y + j\r\n\r\n if (checkX != curx) and (checkY != cury):\r\n print(\"checking (\" + str(checkX) + \", \" + str(checkY) + \")\")\r\n if inactiveMine(mf,checkX, checkY):\r\n return(False)\r\n else:\r\n print(\"ignoring (\" + str(checkX) + \", \" + str(checkY) + \")\")\r\n return (True)\r\n\r\n\r\n# Make a route through the mines\r\ndef makeRoute(mf,x,y,gridSize):\r\n\r\n printMineField(mineField)\r\n\r\n # Are we done?\r\n if y == gridSize-1:\r\n mf=clearMine(mf,x,y)\r\n return mf\r\n else:\r\n sensible = False\r\n\r\n mf=clearMine(mf,x,y)\r\n\r\n while not sensible:\r\n dx = random.randint(-5,5)\r\n dy = random.randint(-5,5)\r\n\r\n if dx > 1:\r\n dx = 1\r\n if dx < -1:\r\n dx = -1\r\n if dy > 1:\r\n dy = 1\r\n if dy < -1:\r\n dy = -1\r\n\r\n if dx==0 and dy==0:\r\n sensible = False\r\n elif x+dx < 0:\r\n sensible = False\r\n elif x+dx > gridSize-1:\r\n sensible = False\r\n elif y+dy < 0:\r\n sensible = False\r\n elif y+dy > gridSize -1:\r\n sensible = False\r\n elif validDest(mf,x,y,x+dx,y+dy,gridSize)==False:\r\n sensible = False\r\n else:\r\n sensible = True\r\n\r\n \r\n\r\n makeRoute(mf, x+dx, y+dy, gridSize)\r\n \r\n# **********************************************************************\r\n# Set up some variables and do a bit of initialisation\r\n#\r\n# **********************************************************************\r\nxlimit = 700\r\nylimit = 700\r\ngridSize = 10\r\ncellSizeX = xlimit/gridSize\r\ncellSizeY = ylimit/gridSize\r\n\r\n# Create screen and turtle.\r\nscreen = turtle.Screen()\r\nscreen.title('Death Maze 2000!')\r\nscreen.setup (width=800, height=800, startx=0, starty=0)\r\nt = turtle.Turtle()\r\nt.speed(0)\r\n\r\n#screen.screensize(700,700)\r\nscreen.setworldcoordinates(0,0,700,700)\r\n\r\n# Plot the grid\r\n# grid(t, gridSize, xlimit, ylimit)\r\n\r\n# Set up a maze array, use a list of strings to do 2 dimensions\r\nmineField=createMaze(gridSize, gridSize)\r\n\r\n# Print off a text version\r\n# printMineField(mineField)\r\n\r\n# Build a path through\r\n# Start half way through the top row\r\nmyx = int(gridSize/2)-1\r\nmyy = 0\r\n\r\nmakeRoute(mineField,myx,myy, gridSize)\r\n\r\nprintMineField(mineField)\r\n\r\n","sub_path":"turtle01 _v002.py","file_name":"turtle01 _v002.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"210843467","text":"#!/bin/envrun\nimport dropbox\nimport pickle\nfrom sys import stderr\nfrom pathlib import Path\nfrom webbrowser import open as wbopen\n\nCHUNK_SIZE = 4 * 1024 * 1024\n\ndef loadcreds(location: Path):\n \"\"\"\n Load application credentials\n \"\"\"\n with open(location, 'r') as f:\n lines = list(map(str.strip, f))\n return lines[:2]\n\n\ndef connect(creds='creds.secret', access='client.secret') -> dropbox.Dropbox:\n \"\"\"\n Authorises application w/ user and loads client\n \"\"\"\n parent = Path(__file__).resolve().parent\n app = loadcreds(parent / creds)\n access_p = parent / access\n\n user = None\n if access_p.exists():\n with open(access_p, 'rb') as token:\n user = pickle.load(token)\n \n if not user:\n flow = dropbox.DropboxOAuth2FlowNoRedirect(*app)\n redirect = flow.start()\n print(f\"Redirecting for authorisation: {redirect}\\nCtl-C to continue...\")\n wbopen(redirect)\n token = input(\"Copy access token here: \").strip()\n if not token:\n print(\"Error: bad input\", file=stderr)\n exit(1)\n user = flow.finish(token)\n with open(access_p, 'wb+') as token:\n pickle.dump(user, token)\n return dropbox.Dropbox(user.access_token)\n\ndef pair(arg):\n return arg.split(',')\n\n\ndef large_upload(dbx, f, file_size, dest_path):\n upload_session_start_result = dbx.files_upload_session_start(\n f.read(CHUNK_SIZE))\n cursor = dropbox.files.UploadSessionCursor(\n upload_session_start_result.session_id, f.tell())\n commit = dropbox.files.CommitInfo(\n path=dest_path, mode=dropbox.files.WriteMode(\"overwrite\"))\n while f.tell() < file_size:\n if ((file_size - f.tell()) <= CHUNK_SIZE):\n dbx.files_upload_session_finish(\n f.read(CHUNK_SIZE), cursor, commit)\n else:\n dbx.files_upload_session_append_v2(\n f.read(CHUNK_SIZE), cursor.session_id, cursor.offset)\n cursor.offset = f.tell()\n\ndef small_upload(dbx, f, file_size, dest_path):\n dbx.files_upload(f.read(), dest_path,\n mode=dropbox.files.WriteMode(\"overwrite\"))\n\ndef upload(dbx, f, file_size, dest_path):\n try:\n small_upload(\n dbx, f, file_size, dest_path)\n except: # write timeout\n large_upload(\n dbx, f, file_size, dest_path)\n\ndef _main():\n import argparse\n parser = argparse.ArgumentParser(\"Upload directory to dropbox recursively\")\n parser.add_argument(\"pair\", type=pair, nargs='+',\n help=\"LOCAL,DROP directory pairs\")\n parser.add_argument(\"--dry\", \"-d\", action='store_true',\n help=\"Print changes w/o sending\")\n args = parser.parse_args()\n\n client = connect()\n for local, drop in args.pair:\n # enumerate local files recursively\n for local_path in Path(local).rglob(\"*\"):\n\n if local_path.is_dir():\n continue\n\n relative_path = local_path.relative_to(local)\n drop_path = str(Path(drop) / relative_path)\n\n if args.dry:\n print(f\"{local_path} -> {drop_path}\")\n else:\n # upload the file\n with open(local_path, 'rb') as f:\n upload(client, f, local_path.stat().st_size, drop_path)\n\n\nif __name__ == \"__main__\":\n _main()\n","sub_path":"Python/updir/updir.py","file_name":"updir.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"495736413","text":"import os\nfrom zipfile import ZipFile\n\n\ndef make_archive(source, dest, filename):\n try:\n prev_cwd = os.getcwd()\n source, dest = map(lambda x: os.path.abspath(x), (source, dest))\n os.chdir(source)\n except OSError:\n return False\n zf = ZipFile(os.path.join(dest, filename), 'w')\n for current_dir, _, files in os.walk(source):\n for file in files:\n if file != filename:\n zf.write(os.path.relpath(os.path.join(current_dir, file)))\n os.chdir(prev_cwd)\n return True","sub_path":"archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"29988740","text":"from django.shortcuts import render\nfrom boards.models import BoardTab\nfrom members.models import Users\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom datetime import datetime\nfrom django.http.response import HttpResponseRedirect\n\n# Create your views here.\n#게시판 전체목록 출력, GET방식으로 tag가져와서 tag에 해당되는 게시판만 출력하도록 설계 가능\n\ndef ListFunc(request):\n #-------------------SESSION CHECK------------------------------\n #checking login status\n logincheck(request)\n #print(request.session['islogin'])\n try:\n request.session['username']\n except KeyError:\n request.session['username']=''\n #-------------------SESSION CHECK END------------------------------\n \n #---------------------GET으로 가져온 게시판 타입에 따라 필터---------------------\n btype = request.GET.get('type') \n if btype=='free':\n datas = BoardTab.objects.filter(type='free').order_by('-gnum', 'onum')\n \n elif btype=='oldcar':\n datas = BoardTab.objects.filter(type='oldcar').order_by('-gnum', 'onum')\n \n elif btype=='travle':\n datas = BoardTab.objects.filter(type='travle').order_by('-gnum', 'onum')\n \n else:\n datas = BoardTab.objects.all().order_by('-gnum', 'onum')\n btype = ''\n \n #페이징 처리\n paginator = Paginator(datas, 10) #한화면에 10행씩출력\n page = request.GET.get('page') #get방식으로 정보를 받아오는 데이터\n try:\n data = paginator.page(page) #page번호를 받아 해당 페이지를 리턴\n except PageNotAnInteger: #들어갔을 때 페이지 번호를 1로\n data = paginator.page(1)\n except EmptyPage:\n data = paginator.page(paginator.num_pages)\n #---------------------------------------------------------------\n \n return render(request, 'board.html', {'data':data,'btype':request.GET.get('type'), 'islogin':request.session['islogin'], 'username':request.session['username']})\n\n#새로운 글\n#태그 목록: 중고차거래, 자유게시판, 여행\ndef NewPostFunc(request):\n #-------------------SESSION CHECK------------------------------\n #checking login status\n logincheck(request)\n #print(request.session['islogin'])\n try:\n request.session['username']\n except KeyError:\n request.session['username']=''\n #-------------------SESSION CHECK END------------------------------\n return render(request, 'newpost.html', {'islogin':request.session['islogin'], 'username':request.session['username']})\n\n#새 글 확인 (NewPostFunc에 POST처리 조건 추가하는 방법으로 NewPostFunc와 통합 가능)\ndef NewPostOkFunc(request):\n #POST일 경우 처리\n if request.method == \"POST\":\n try:\n #group 번호 얻기\n gbun = 1\n datas = BoardTab.objects.all()\n if datas.count() != 0:\n gbun = BoardTab.objects.latest('gnum').gnum + 1\n \n BoardTab(\n id=BoardTab.objects.latest('id').id+1,\n name = request.POST.get('name'),\n title = request.POST.get('title'),\n cont = request.POST.get('cont'),\n bdate = datetime.now(),\n readcnt = 0,\n gnum = gbun,\n onum = 0,\n nested = 0,\n type = request.POST.get('type')\n ).save()\n except Exception as e:\n print('NP 오류 : ', e)\n \n return HttpResponseRedirect('/boards/list') # 추가 후 목록보기\n#내용보기\ndef ContentFunc(request):\n #-------------------SESSION CHECK------------------------------\n #checking login status\n logincheck(request)\n #print(request.session['islogin'])\n try:\n request.session['username']\n except KeyError:\n request.session['username']=''\n #-------------------SESSION CHECK END------------------------------\n \n data = BoardTab.objects.get(id = request.GET.get('id'))\n data.readcnt = data.readcnt + 1 #조회수 증가\n data.save() #수정\n page = request.GET.get('page')\n return render(request, 'content.html', {'data_one':data, 'page':page, 'islogin':request.session['islogin'], 'username':request.session['username']})\n\n#글/댓글 수정\ndef UpdatePostFunc(request):\n #-------------------SESSION CHECK------------------------------\n #checking login status\n logincheck(request)\n #print(request.session['islogin'])\n try:\n request.session['username']\n except KeyError:\n request.session['username']=''\n #-------------------SESSION CHECK END------------------------------\n try:\n data = BoardTab.objects.get(id = request.GET.get('id'))\n except Exception as e:\n print('UpdateFunc err : ', e)\n \n return render(request, 'update.html', {'data_one':data, 'islogin':request.session['islogin'], 'username':request.session['username']})\n\n#글/댓글 수정 확인 (POST로 인한 통합 가능)\ndef UpdatePostOkFunc(request):\n upRec = BoardTab.objects.get(id = request.POST.get('id'))\n upRec.name = request.POST.get(\"name\")\n upRec.title = request.POST.get(\"title\")\n upRec.cont = request.POST.get(\"cont\")\n upRec.save()\n\n return HttpResponseRedirect('/boards/list') #수정 후 목록보기\n\n#글 삭제\ndef DeletePostFunc(request):\n #-------------------SESSION CHECK------------------------------\n #checking login status\n logincheck(request)\n #print(request.session['islogin'])\n try:\n request.session['username']\n except KeyError:\n request.session['username']=''\n #-------------------SESSION CHECK END------------------------------\n try:\n data = BoardTab.objects.get(id = request.GET.get('id'))\n except Exception as e:\n print('DeleteFunc err : ', e)\n \n return render(request, 'delete.html', {'data_one':data, 'islogin':request.session['islogin'], 'username':request.session['username']})\n\n#글 삭제 확인 (POST로 인한 통합 가능)\ndef DeletePostOkFunc(request):\n delRec = BoardTab.objects.get(id = request.POST.get(\"id\"))\n userpw=Users.objects.get(username=request.POST.get('username'))\n \n if userpw.password == request.POST.get('del_passwd'):\n delRec.delete()\n return HttpResponseRedirect('/boards/list') #삭제 후 목록보기\n else:\n return render(request, 'error.html')\n\n#댓글달기\ndef ReplyFunc(request):\n #-------------------SESSION CHECK------------------------------\n #checking login status\n logincheck(request)\n #print(request.session['islogin'])\n try:\n request.session['username']\n except KeyError:\n request.session['username']=''\n #-------------------SESSION CHECK END------------------------------\n try:\n data = BoardTab.objects.get(id = request.GET.get('id')) #댓글 대상 원글 읽기\n except Exception as e:\n print('ReplyFunc err : ', e)\n\n return render(request, 'reply.html', {'data_one':data, 'islogin':request.session['islogin'], 'username':request.session['username']})\n\n#댓글추가 확인 (POST로 인한 통합 가능)\ndef ReplyOkFunc(request):\n if request.method == 'POST':\n try:\n regnum = int(request.POST.get('gnum'))\n reonum = int(request.POST.get('onum'))\n \n tempRec = BoardTab.objects.get(id = request.POST.get('id')) #원게시글\n old_gnum = tempRec.gnum\n old_onum = tempRec.onum\n \n if old_onum >= reonum and old_gnum == regnum:\n old_onum = old_onum + 1 #onum 갱신 댓글카운트 \n #댓글 저장\n BoardTab(\n id = BoardTab.objects.latest('id').id + 1,\n name = request.POST.get('name'),\n title = request.POST.get('title'),\n cont = request.POST.get('cont'),\n bdate = datetime.now(),\n readcnt = 0,\n gnum = regnum,\n onum = old_onum,\n nested = int(request.POST.get('nested')) + 1,\n type = tempRec.type #원글에서\n ).save()\n \n except Exception as e:\n print('ReplyokFunc err : ', e)\n \n return HttpResponseRedirect('/boards/list')\n\n#글 검색\ndef SearchFunc(request):\n #-------------------SESSION CHECK------------------------------\n #checking login status\n logincheck(request)\n #print(request.session['islogin'])\n try:\n request.session['username']\n except KeyError:\n request.session['username']=''\n #-------------------SESSION CHECK END------------------------------\n if request.method == 'POST':\n s_type = request.POST.get('s_type')\n s_value = request.POST.get('s_value')\n #print(s_type, ' ', s_value)\n if s_type == 'title': #글제목 검색해서 찾기\n datas = BoardTab.objects.filter(title__contains = s_value).order_by('-id')\n elif s_type == 'name': #작성자 검색해서 찾기\n datas = BoardTab.objects.filter(name__contains = s_value).order_by('-id')\n \n paginator = Paginator(datas, 10) #한화면에 5행씩출력\n page = request.GET.get('page')\n \n try:\n data = paginator.page(page)\n except PageNotAnInteger:\n data = paginator.page(1)\n except EmptyPage:\n data = paginator.page(paginator.num_pages)\n \n return render(request, 'board.html', {'data':data, 'islogin':request.session['islogin'], 'username':request.session['username']})\n else: \n if request.GET.get('name'):\n datas=BoardTab.objects.filter(name__contains=request.GET.get('name')).order_by('-id')\n paginator = Paginator(datas, 10) #한화면에 5행씩출력\n page = request.GET.get('page')\n \n try:\n data = paginator.page(page)\n except PageNotAnInteger:\n data = paginator.page(1)\n except EmptyPage:\n data = paginator.page(paginator.num_pages) \n \n return render(request,'board.html', {'data':data, 'islogin':request.session['islogin'], 'username':request.session['username']})\n \n else:\n return HttpResponseRedirect('/boards/list')\n\n\ndef logincheck(request):\n try: \n request.session['islogin']\n except KeyError: \n request.session['islogin']=False\n except Exception as e:\n print(\"something's wrong\", e)\n return render(request, '../members/logout')\n\n#DB\n#boards: postid title content gnum onum nested +@ tag","sub_path":"midterm/boards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"231129720","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\nignore=[re.compile('make\\s.*check'), re.compile('make\\s.*test')]\nscraper = open('scrape.sh', 'w')\nscraper.write('set -e\\n')\nscraper.write('set -x\\n\\n')\nscraper.write('cd $LFS/sources\\n\\n')\nlfs = \"http://www.linuxfromscratch.org/lfs/view/stable/\"\nsrc = urlopen(lfs)\nparsedHtml = BeautifulSoup(src, 'lxml')\nchapter5 = parsedHtml.find_all('li', 'chapter')[4]\nsections = chapter5.find_all('li', 'sect1')\nsections = sections[10:-2]\nfor section in sections:\n link = lfs + section.contents[1]['href']\n packageSrc = urlopen(link)\n package = section.contents[1].string[:6].lower()\n scraper.write('tarball=`ls | grep \\'' + package + '\\' | tail -1`\\n')\n scraper.write('tar -xvf $tarball\\n')\n scraper.write('packageDir=`ls -d */`\\n')\n scraper.write('cd $packageDir\\n')\n packageBS = BeautifulSoup(packageSrc, 'lxml')\n commands = packageBS.find_all('kbd', 'command')\n for command in commands:\n command = command.string\n flag = 1\n for pattern in ignore:\n if re.search(pattern,command) is not None:\n flag = 0\n break\n if flag:\n scraper.write(command + '\\n')\n scraper.write('cd $LFS/sources\\n')\n scraper.write('rm -rf $packageDir\\n\\n')\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"328582752","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#coding=utf-8\n\"\"\"\nCreated on 2015年11月20日\n\n@deprecated: 对文件操作的工具模块\n@author: Linked\n\"\"\"\nfrom os.path import sys, os\n\n\n\"\"\"\n@deprecated: 获取当前文件的path\n\"\"\"\ndef get_current_path():\n path = sys.path[0]\n if os.path.isdir(path):\n return path\n elif os.path.isfile(path):\n return os.path.dirname(path)\n","sub_path":"features/util/file_util.py","file_name":"file_util.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"404149082","text":"from odoo import models, fields\nfrom uuid import uuid4\n\nclass ThingsRoute(models.Model):\n _name = 'things.route'\n _description = 'description'\n\n _sql_constraints = [ ( 'route_uniq',\n 'UNIQUE (route)',\n 'Route must be unique.')\n ]\n\n def generate_route(self):\n result = str(fields.Datetime.now())+str(uuid4())\n result = result.replace(\" \",\"\").replace(\":\",\"\").replace(\"-\",\"\")\n return result\n\n route =fields.Char(\n string = 'route',\n help = 'route to exchange data with \"things\"',\n default = generate_route,\n store = True,\n compute_sudo = False,\n readonly = True\n )\n","sub_path":"models/things_route.py","file_name":"things_route.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"343328077","text":"import os\r\nimport sys\r\nimport argparse\r\nimport time\r\nimport random\r\nimport warnings\r\nimport subprocess\r\nimport importlib\r\nimport torch.distributed as dist\r\nimport torch.multiprocessing as mp\r\nimport torch.backends.cudnn as cudnn\r\nimport torch.utils.data.distributed\r\n\r\n\r\nfrom torch.nn.parallel import DistributedDataParallel as DDP\r\nfrom SimDis.utils.log import setup_logger\r\nfrom SimDis.utils import adjust_learning_rate_iter, save_checkpoint, parse_devices, AvgMeter, load_checkpoint\r\nfrom SimDis.utils.torch_dist import configure_nccl, synchronize\r\n\r\n\r\ndef cleanup():\r\n dist.destroy_process_group()\r\n\r\ndef main():\r\n file_name = os.path.join(exp.output_dir, exp.exp_name)\r\n if args.rank == 0:\r\n if not os.path.exists(file_name):\r\n os.mkdir(file_name)\r\n\r\n logger = setup_logger(file_name, distributed_rank=args.local_rank, filename=\"train_log.txt\", mode=\"a\")\r\n logger.info(\"gpuid: {}, args: {}\".format(args.local_rank, args))\r\n\r\n data_loader = exp.get_data_loader(batch_size=args.batchsize, is_distributed=args.nr_gpu > 1, if_transformer=False)\r\n train_loader = data_loader[\"train\"]\r\n eval_loader = data_loader[\"eval\"]\r\n\r\n model = exp.get_model().to(device)\r\n model = DDP(model, device_ids=[args.local_rank], output_device=args.local_rank)\r\n \r\n optimizer = exp.get_optimizer(model.module, args.batchsize)\r\n\r\n start_epoch, model, optimizer = load_checkpoint(args, file_name, model, optimizer, args.linear, args.tea)\r\n\r\n if args.eval_method == 'knn':\r\n exp.eval_knn()\r\n return\r\n elif args.eval_method == 'ca':\r\n exp.eval_ca()\r\n return\r\n \r\n cudnn.benchmark = True\r\n\r\n if args.eval:\r\n model.train(False)\r\n exp.run_eval(model, eval_loader)\r\n return\r\n\r\n # -----------------------------start training-----------------------------#\r\n model.train()\r\n ITERS_PER_EPOCH = len(train_loader)\r\n if args.rank == 0:\r\n logger.info(\"Training start...\")\r\n logger.info(\"Here is the logging file\"+str(file_name))\r\n # logger.info(str(model))\r\n\r\n args.lr = exp.basic_lr_per_img * args.batchsize * args.nr_gpu * args.word_size\r\n args.warmup_epochs = exp.warmup_epochs\r\n args.total_epochs = exp.max_epoch\r\n iter_count = (start_epoch-1) * ITERS_PER_EPOCH\r\n model.module.current_train_iter = iter_count\r\n\r\n for epoch in range(start_epoch, args.total_epochs+1):\r\n if args.nr_gpu > 1:\r\n train_loader.sampler.set_epoch(epoch)\r\n batch_time_meter = AvgMeter()\r\n\r\n for i, (inps, target) in enumerate(train_loader):\r\n iter_count += 1\r\n iter_start_time = time.time()\r\n\r\n for indx in range(len(inps)):\r\n inps[indx] = inps[indx].to(device, non_blocking=True)\r\n\r\n data_time = time.time() - iter_start_time\r\n if args.linear: loss = model(inps, target)\r\n else: loss = model(inps, update_param=True)\r\n\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n\r\n lr = adjust_learning_rate_iter(optimizer, iter_count, args, ITERS_PER_EPOCH)\r\n batch_time_meter.update(time.time() - iter_start_time)\r\n\r\n if args.rank == 0 and (i + 1) % exp.print_interval == 0:\r\n remain_time = (ITERS_PER_EPOCH * exp.max_epoch - iter_count) * batch_time_meter.avg\r\n t_m, t_s = divmod(remain_time, 60)\r\n t_h, t_m = divmod(t_m, 60)\r\n t_d, t_h = divmod(t_h, 24)\r\n remain_time = \"{}d.{:02d}h.{:02d}m\".format(int(t_d), int(t_h), int(t_m))\r\n\r\n logger.info(\r\n \"[{}/{}], remain:{}, It:[{}/{}], Data-Time:{:.3f}, LR:{:.4f}, Loss:{:.2f}\".format(\r\n epoch, args.total_epochs, remain_time, i + 1, ITERS_PER_EPOCH, data_time, lr, loss\r\n )\r\n )\r\n \r\n if args.linear:\r\n model.train(False)\r\n exp.run_eval(model, eval_loader)\r\n model.train(True)\r\n\r\n if args.rank == 0:\r\n logger.info(\r\n \"Train-Epoch: [{}/{}], LR: {:.4f}, Con-Loss: {:.2f}\".format(epoch, args.total_epochs, lr, loss)\r\n )\r\n\r\n save_checkpoint(\r\n {\"start_epoch\": epoch, \"model\": model.state_dict(), \"optimizer\": optimizer.state_dict()},\r\n False,\r\n file_name,\r\n \"last_epoch\",\r\n args.linear,\r\n )\r\n\r\n save_checkpoint(\r\n {\"start_epoch\": epoch, \"model\": model.state_dict(), \"optimizer\": optimizer.state_dict()},\r\n False,\r\n file_name,\r\n str(epoch),\r\n args.linear,\r\n )\r\n\r\n if args.rank == 0:\r\n print(\"Pre-training of experiment: {} is done.\".format(args.exp_file))\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(\"SimDis\")\r\n parser.add_argument(\"-expn\", \"--experiment-name\", type=str, default=None)\r\n\r\n # optimization\r\n parser.add_argument(\"--scheduler\", type=str, default=\"warmcos\",\r\n choices=[\"warmcos\", \"cos\", \"linear\", \"multistep\", \"step\"], help=\"type of scheduler\")\r\n\r\n # distributed\r\n parser.add_argument(\"--distributed\", action='store_true')\r\n parser.add_argument(\"--dist-backend\", default=\"nccl\", type=str, help=\"distributed backend\")\r\n parser.add_argument(\"--dist-url\", default=None, type=str, help=\"url used to set up distributed training\")\r\n parser.add_argument(\"--local_rank\", type=int, default=0)\r\n parser.add_argument(\"--rank\", type=int, default=0)\r\n parser.add_argument(\"--word_size\", type=int, default=1)\r\n parser.add_argument(\"-d\", \"--devices\", default=\"0-7\", type=str, help=\"device for training\")\r\n\r\n # exp setting\r\n parser.add_argument(\"-n\", \"--n_views\", type=int, default=2)\r\n parser.add_argument(\"-b\", \"--batchsize\", type=int, default=64, help=\"batch size\")\r\n parser.add_argument(\"-f\", \"--exp_file\", default=None, type=str, help=\"pls input your expriment description file\")\r\n parser.add_argument(\"--epochs\", type=int, default=100)\r\n parser.add_argument(\"--basic_lr\", type=float, default=0.3)\r\n \r\n parser.add_argument('--method', type=str, default='BYOL', help='choose method')\r\n parser.add_argument('--optimizer', type=str, default='LARS', help='SGD, LARS')\r\n parser.add_argument('--syncBN', action='store_true', help='using synchronized batch normalization')\r\n parser.add_argument('--model_s', type=str, default=None)\r\n parser.add_argument('--model_t', type=str, default=None)\r\n parser.add_argument('--ema_moment', type=float, default=0.99, help='the moment to update target network')\r\n\r\n parser.add_argument(\"--offline\", action='store_true')\r\n parser.add_argument('--offline_resume', type=str, default='')\r\n \r\n parser.add_argument(\"--linear\", action='store_true')\r\n parser.add_argument(\"--tea\", action='store_true')\r\n parser.add_argument(\"--eval\", action='store_true')\r\n parser.add_argument('--eval_method', type=str, default=None, help='knn, ca')\r\n \r\n args = parser.parse_args()\r\n args.nr_gpu = torch.cuda.device_count()\r\n args.rank = args.rank*args.nr_gpu + args.local_rank\r\n \r\n if args.linear:\r\n args.batchsize = 256\r\n args.basic_lr = 0.001\r\n else:\r\n args.basic_lr = 0.3\r\n\r\n if args.local_rank == 0:\r\n print(\"V1 Using\", torch.cuda.device_count(), \"GPUs per node!\")\r\n\r\n from SimDis.exps.arxiv import base_exp_simDis\r\n sys.path.insert(0, os.path.dirname(args.exp_file))\r\n current_exp = importlib.import_module(os.path.basename(args.exp_file).split(\".\")[0])\r\n exp = current_exp.Exp(args)\r\n\r\n if args.distributed:\r\n torch.distributed.init_process_group(backend=\"nccl\", init_method='env://')\r\n\r\n print(\"Rank {} initialization finished.\".format(args.rank))\r\n torch.cuda.set_device(args.local_rank)\r\n device = torch.device(\"cuda\", args.local_rank)\r\n \r\n main()\r\n\r\n if args.distributed:\r\n cleanup()\r\n","sub_path":"SimDis/tools/run_SimDis.py","file_name":"run_SimDis.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"222291163","text":"import csv\ntexts=[]\nlabels=[]\nseq_len=0\n# reading the proceesed file i.e., removed punctuation and stopwords\nwith open(r\"G:\\computer\\pdf's\\data Analytics\\Project\\final_training.csv\", newline='',encoding='utf8') as myFile:\n reader = csv.reader(myFile)\n for row in reader:\n texts.append(row[0])\n seq_len += len(row[0].split())\n labels.append(row[1])\n\n# selecting 80000 news from the data set\ntexts=texts[1:20000]\nlabels=labels[1:20000]\n\nd = {'b':0,'m':1,'e':2,'t':3}\n\n# will contain the count of each news article type.\ncount=[0,0,0,0]\n\nclassified_labels=[]\nfor i in labels:\n j=d.get(i)\n count[j]=count[j]+1\n classified_labels.append(j)\n\nprint(count)\n\nfrom keras.utils.np_utils import to_categorical\n\n# converting our labels i.e., our news category into one-hot encoding\none_hot_train_labels=to_categorical(classified_labels)\nprint(one_hot_train_labels)\n\nprint (len(texts),len(labels))\nprint ('mean seq len is:', seq_len / len(texts))\n\nMAX_NB_WORDS = 5000 # signifies the vocabulary size\nMAX_SEQUENCE_LENGTH = 261\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n\ntokenizer = Tokenizer(num_words=MAX_NB_WORDS) #use this to convert text into numeric value based on position of words in vocab length selected.\ntokenizer.fit_on_texts(texts) #\nsequences = tokenizer.texts_to_sequences(texts) # convert text into tokens wnd give each token a numeric value.\n\nimport numpy as np\n\n#this function used to convert tokens converted into numeric value into one-hot vector\ndef vectorize_sequences(sequences, dimension=10000):\n results = np.zeros((len(sequences), dimension))\n for i, sequence in enumerate(sequences):\n results[i, sequence] = 1.\n return results\n\n# creating training and testing data\ntrain_data=sequences[:12000]\ntest_data=sequences[12000:]\ntrain_labels=one_hot_train_labels[:12000]\ntest_labels=one_hot_train_labels[12000:]\n\n# Our vectorized training data i.e., one-hot encoded format\nx_train = vectorize_sequences(train_data)\n# Our vectorized test data\nx_test = vectorize_sequences(test_data)\n\n# taking out validation set from training data\nx_val=x_train[:2000]\npartial_x_train=x_train[2000:]\ny_val=train_labels[:2000]\npartial_y_train=train_labels[2000:]\n\nfrom keras.layers import K\n\n# the below two function used is to get precision and recall\ndef precision(y_true, y_pred):\n \"\"\"Precision metric.\n Only computes a batch-wise average of precision.\n Computes the precision, a metric for multi-label classification of\n how many selected items are relevant.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n precision = true_positives / (predicted_positives + K.epsilon())\n return precision\n\n\ndef recall(y_true, y_pred):\n \"\"\"Recall metric.\n Only computes a batch-wise average of recall.\n Computes the recall, a metric for multi-label classification of\n how many relevant items are selected.\n \"\"\"\n true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n recall = true_positives / (possible_positives + K.epsilon())\n return recall\n\nfrom keras import models\nfrom keras import layers\n# building sequential model\nmodel = models.Sequential()\n# adding first hidden layer with 64 nodes and input vector to it will be nodes of dimension 10000 with activation function relu\nmodel.add(layers.Dense(64, activation='relu', input_shape=(10000,)))\n# 2nd hidden layer\nmodel.add(layers.Dense(64, activation='relu'))\n# output layer with 4 nodes each for each category\nmodel.add(layers.Dense(4, activation='softmax'))\n\nmodel.compile(optimizer='adam',\n loss='categorical_crossentropy',\n metrics=['accuracy', precision, recall])\n# this the variable where all the computation out put such as precision ,accuracy,loss,recall of the model will be stored\nhistory=model.fit(partial_x_train,partial_y_train,epochs=5,batch_size=512,validation_data=(x_val,y_val))\n\n# plot the graph\nimport matplotlib.pyplot as plt\nhistory_dict = history.history\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\nepochs = range(1, len(loss_values) + 1)\nimport pylab\npylab.plot(epochs, loss_values, 'ko', label='training',)\npylab.plot(epochs, val_loss_values, 'k+', label='validating')\npylab.title(\"Loss vs Epoch(training_size = 80000)\")\npylab.legend(loc='upper right')\npylab.xlabel(\"Epochs\")\npylab.ylabel(\"Loss\")\npylab.show()\n\nacc_values = history_dict['acc']\nval_acc_values = history_dict['val_acc']\npylab.plot(epochs, acc_values, 'ko', label='training',)\npylab.plot(epochs, val_acc_values, 'k+', label='validating')\npylab.title(\"Accuracy vs Epoch(training_size = 80000)\")\npylab.legend(loc='lower right')\npylab.xlabel(\"Epochs\")\npylab.ylabel(\"Accuracy\")\npylab.show()\n\nresults = model.evaluate(x_test, test_labels)\nprint(results)\n\n# here giving the user input to classify the given news into the set of predefined categories\n\n# \"Bharti Airtel signs deal with Ericsson for strategic partnership on 5G technology\"\n# \"Honda recalling 900,000 minivans because seats may tip forward\"\na=[\"Bharti Airtel signs deal with Ericsson for strategic partnership on 5G technology\"]\nx= tokenizer.texts_to_sequences(a)\nprint(x)\ny=vectorize_sequences(x)\nprint(y)\n\nres=model.predict(y)\nprint(res)\n\n# this would print the category with highest probability category.\nprint(np.argmax(res))\n\nprint(history.history)","sub_path":"neural_net.py.py","file_name":"neural_net.py.py","file_ext":"py","file_size_in_byte":5524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"69226943","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Python Team Awareness Kit (PyTAK) Module Class Definitions.\"\"\"\n\nimport asyncio\nimport logging\nimport os\nimport queue\nimport random\nimport urllib\n\nimport pycot\n\nimport pytak\n\n__author__ = \"Greg Albrecht W2GMD \"\n__copyright__ = \"Copyright 2020 Orion Labs, Inc.\"\n__license__ = \"Apache License, Version 2.0\"\n\n\nclass Worker: # pylint: disable=too-few-public-methods\n\n \"\"\"Meta class for all other Worker Classes.\"\"\"\n\n _logger = logging.getLogger(__name__)\n if not _logger.handlers:\n _logger.setLevel(pytak.LOG_LEVEL)\n _console_handler = logging.StreamHandler()\n _console_handler.setLevel(pytak.LOG_LEVEL)\n _console_handler.setFormatter(pytak.LOG_FORMAT)\n _logger.addHandler(_console_handler)\n _logger.propagate = False\n logging.getLogger(\"asyncio\").setLevel(pytak.LOG_LEVEL)\n\n def __init__(self, event_queue: asyncio.Queue) -> None:\n self.event_queue: asyncio.Queue = event_queue\n\n async def run(self) -> None:\n \"\"\"Placeholder Run Method for this Class.\"\"\"\n self._logger.warning(\"Overwrite this method!\")\n\n\nclass EventWorker(Worker): # pylint: disable=too-few-public-methods\n\n \"\"\"\n EventWorker handles getting Cursor on Target Events from a queue, and\n passing them off to a transport worker.\n\n You should create an EventWorker Instance using the\n `pytak.eventworker_factory` Function.\n\n CoT Events are put onto the CoT Event Queue using `pytak.MessageWorker`\n Class.\n \"\"\"\n\n def __init__(self, event_queue: asyncio.Queue, writer) -> None:\n super().__init__(event_queue)\n self.writer = writer\n\n async def run(self):\n \"\"\"Runs this Thread, reads in Message Queue & sends out CoT.\"\"\"\n self._logger.info('Running EventWorker')\n\n while 1:\n event = await self.event_queue.get()\n if not event:\n continue\n self._logger.debug(\"event='%s'\", event)\n\n if isinstance(event, pycot.Event):\n _event = event.render(encoding='UTF-8', standalone=True)\n else:\n _event = event\n\n if hasattr(self.writer, \"send\"):\n await self.writer.send(_event)\n else:\n self.writer.write(_event)\n await self.writer.drain()\n\n if not os.environ.get('DISABLE_RANDOM_SLEEP'):\n await asyncio.sleep(pytak.DEFAULT_SLEEP * random.random())\n\n\nclass MessageWorker(Worker): # pylint: disable=too-few-public-methods\n\n \"\"\"\n MessageWorker handles getting non-CoT messages from a non-CoT Input,\n encoding them as CoT, and putting them onto a CoT Event Queue.\n\n The CoT Event Queue is handled by the `pytak.EventWorker` Class.\n \"\"\"\n\n def __init__(self, event_queue: asyncio.Queue,\n cot_stale: int = None) -> None:\n super().__init__(event_queue)\n self.cot_stale = cot_stale or pytak.DEFAULT_COT_STALE\n\n async def _put_event_queue(self, event: pycot.Event) -> None:\n \"\"\"Puts Event onto the CoT Event Queue.\"\"\"\n try:\n await self.event_queue.put(event)\n except queue.Full:\n self._logger.warning(\n \"Lost CoT Event (queue full): '%s'\", event)\n\n\nclass EventTransmitter(Worker): # pylint: disable=too-few-public-methods\n\n \"\"\"\n EventWorker handles getting Cursor on Target Events from a queue, and\n passing them off to a transport worker.\n\n You should create an EventWorker Instance using the\n `pytak.eventworker_factory` Function.\n\n CoT Events are put onto the CoT Event Queue using `pytak.MessageWorker`\n Class.\n \"\"\"\n\n def __init__(self, tx_queue: asyncio.Queue, writer) -> None:\n super().__init__(tx_queue)\n self.writer = writer\n\n async def run(self):\n \"\"\"Runs this Thread, reads in Message Queue & sends out CoT.\"\"\"\n self._logger.info(\"Running EventTransmitter\")\n\n while 1:\n tx_event = await self.event_queue.get()\n if not tx_event:\n continue\n self._logger.debug(\"tx_event='%s'\", tx_event)\n\n if isinstance(tx_event, pycot.Event):\n _event = tx_event.render(encoding='UTF-8', standalone=True)\n else:\n _event = tx_event\n\n if hasattr(self.writer, \"send\"):\n await self.writer.send(_event)\n else:\n self.writer.write(_event)\n await self.writer.drain()\n\n if not os.environ.get('DISABLE_RANDOM_SLEEP'):\n await asyncio.sleep(pytak.DEFAULT_SLEEP * random.random())\n\n\nclass EventReceiver(Worker): # pylint: disable=too-few-public-methods\n\n def __init__(self, rx_queue: asyncio.Queue, reader) -> None:\n super().__init__(rx_queue)\n self.reader = reader\n\n async def run(self):\n self._logger.info(\"Running EventReceiver\")\n\n while 1:\n rx_event = await self.event_queue.get()\n self._logger.debug(\"rx_event='%s'\", rx_event)\n","sub_path":"pytak/classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"22176188","text":"from core.lexer import Lexer\n\n\nlexer = Lexer(\"\"\"\nint main(){\n int len = strlen(s);\n if (len == 0) {\n return -1;\n }\n for (int i = 0; i < len; ++i) {\n int a = 0;\n for (int j = 0; j < len; ++j) {\n if (*(i + s) == *(j + s)) {\n a++;\n }\n }\n if(a ==== 1){\n return i;\n }\n }\n return -1;\n}\n\"\"\" )\n\nif __name__ == '__main__':\n temp = ''\n for token in lexer.analyse():\n if token.value != '{' and token.value != '}':\n if token.name == 'keyword':\n token.value += ' '\n temp+=token.value\n else:\n temp+=\"%s\\n\"%token.value\n\n print(temp)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"309141301","text":"# Rewrite / Recode to python3\r\n# Original source: https://github.com/thelinuxchoice/instaspam\r\n\r\ntry:\r\n\timport requests,os,sys,time,readline,re\r\n\tfrom prompt_toolkit import prompt\r\nexcept:\r\n\timport os,sys,time\r\n\tprint(\"[!] requests and prompt_toolkit not installed\\n[!] installing module requirement\")\r\n\ttime.sleep(1.5)\r\n\tos.system('python3 -m pip install requests prompt_toolkit;python3 '+sys.argv[0])\r\n\tsys.exit()\r\n\t\r\nclass Menig:\r\n\tdef __init__(self):\r\n\t\tself.req=requests.Session()\r\n\t\tself.user_agent = 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'\r\n\t\tself.csrftoken = requests.get('https://www.instagram.com').cookies['csrftoken']\r\n\t\tself.login()\r\n\r\n\tdef login(self):\r\n\t\tuser=input(\"You Username: \")\r\n\t\tpas=prompt(\"You Password: \", is_password=True)\r\n\t\tself.log = self.req.post('https://www.instagram.com/accounts/login/ajax/', headers={\r\n\t\t\t'origin': 'https://www.instagram.com',\r\n\t\t\t'pragma': 'no-cache',\r\n\t\t\t'referer': 'https://www.instagram.com/accounts/login/',\r\n\t\t\t'user-agent': self.user_agent,\r\n\t\t\t'x-csrftoken': self.csrftoken,\r\n\t\t\t'x-requested-with': 'XMLHttpRequest'\r\n\t\t\t}, data={\r\n\t\t\t'username': user,\r\n\t\t\t'password': pas,\r\n\t\t\t'queryParams': '{}'\r\n\t\t\t})\r\n\r\n\t\tif '\"authenticated\": true' in self.log.text:\r\n\t\t\tprint(\"Login succesfully\\n\")\r\n\t\t\tself.grep()\r\n\t\telse:\r\n\t\t\tprint(\"Login failed. Try Again!\")\r\n\t\t\ttime.sleep(2)\r\n\t\t\tself.login()\r\n\r\n\tdef grep(self):\r\n\t\tC=1\r\n\t\tmyid=[]\r\n\t\tmsg=input(\"[info] use '\\\\n' for new line comments\\nCommnets: \").replace('\\\\n','\\n')\r\n\t\tcount=int(input(\"Commnets Loop: \"))\r\n\t\tmauapa=input(\"do you want spam specific post? [y/N] \")\r\n\r\n\t\tif mauapa.lower() == 'y':\r\n\t\t\tinlnk=input(\"Link post: \")\r\n\t\t\tcek=self.req.get(inlnk)\r\n\t\t\tif \"the page may have been removed\" in cek.text:\r\n\t\t\t\tprint(\"Invalid username. Try again!\\n\")\r\n\t\t\t\tself.grep()\r\n\t\t\tmid=re.findall('\"id\":\"..................[0-9]',cek.text)[0].replace('\"id\":\"','')\r\n\t\t\tself.send(mid,msg,count)\r\n\r\n\t\telse:\r\n\t\t\ttar=input(\"Target account: \")\r\n\t\t\tcek=self.req.get(\"https://www.instagram.com/\"+tar)\r\n\t\t\tif \"the page may have been removed\" in cek.text:\r\n\t\t\t\tprint(\"Invalid username. Try again!\\n\")\r\n\t\t\t\tself.grep()\r\n\t\t\tmid=re.findall('\"id\":\"..................[0-9]',cek.text)\r\n\t\t\tprint()\r\n\r\n\t\t\tmaugak=input(f\"success get [{len(mid)}] media id\\nwant to spam all? [y/N] \")\r\n\t\t\tif maugak.lower() == 'y':\r\n\t\t\t\tfor x in mid:\r\n\t\t\t\t\tself.send(x.replace('\"id\":\"',''),msg,count)\r\n\t\t\telse:\r\n\t\t\t\tfor i in mid:\r\n\t\t\t\t\tprint(\"#\"+str(C),i.replace('\"id\":\"',''))\r\n\t\t\t\t\tmyid.append(i.replace('\"id\":\"',''))\r\n\t\t\t\t\tC+=1\r\n\t\t\t\tpil=int(input(\"Choice: \"))\r\n\t\t\t\tself.send(myid[pil-1],msg,count)\r\n\t\treturn True\r\n#\t\tsys.exit()\r\n\r\n\tdef send(self,idku,msg,count):\r\n\t\tload = {'comment_text' : msg,\r\n\t\t'replied_to_comment_id=' : '',}\r\n\t\thead={'Accept': '*/*',\r\n\t\t\t'Accept-Language': 'en-US,en;q=0.5',\r\n\t\t\t'Accept-Encoding': 'gzip, deflate, br',\r\n\t\t\t'Host': 'www.instagram.com',\r\n\t\t\t'Referer': 'https://www.instagram.com/',\r\n\t\t\t'User-Agent': self.user_agent,\r\n\t\t\t'X-CSRFToken': self.log.cookies['csrftoken'],\r\n\t\t\t'csrftoken': self.log.cookies['csrftoken'],\r\n\t\t\t'X-Instagram-AJAX': '1',\r\n\t\t\t'Content-Type': 'application/x-www-form-urlencoded',\r\n\t\t\t'X-Requested-With': 'XMLHttpRequest',\r\n\t\t\t'Connection': 'close' }\r\n\r\n\t\tprint()\r\n\t\tcc=1\r\n\t\tfor i in range(count):\r\n\t\t\tpreq = self.req.post('https://www.instagram.com/web/comments/{}/add/'.format(idku),headers=head,data=load)\r\n\t\t\tif preq.text == \"Please wait a few minutes before you try again.\":\r\n\t\t\t\tprint(f\"{cc}. Spam failed [{idku}]\")\r\n\t\t\t\tfor i in range(120):\r\n\t\t\t\t\tprint(end=f\"\\r >> sleep {120-(i+1)}s << \",flush=True)\r\n\t\t\t\t\ttime.sleep(1)\r\n\t\t\t\tprint()\r\n\t\t\telif '\"status\": \"ok\"' in preq.text:\r\n\t\t\t\tprint(f\"{cc}. Spam succesfully [{idku}]\")\r\n\t\t\telse:\r\n\t\t\t\tprint(preq.text)\r\n\t\t\tcc+=1\r\n\t\t\ttime.sleep(2)\r\n\r\ntry:\r\n\tos.system('clear')\r\n\tprint(\"\"\"\r\n\t\t###########################\r\n\t\t# Instagram Auto Comments #\r\n\t\t###########################\r\n\t\t <|noobie|>\r\n\t\t\"\"\")\r\n\tMenig()\r\nexcept KeyboardInterrupt:\r\n\tsys.exit(\"\\nInterrupt: exit the program\")\r\nexcept Exception as Err:\r\n\tprint(f\"Error: {Err}\")\r\n","sub_path":"utilled.py","file_name":"utilled.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"64390524","text":"import bpy\n\ndef clear_scene():\n bpy.ops.object.select_all(action='SELECT')\n bpy.ops.object.delete(use_global=False)\n\ndef make_ground_plane_collider():\n bpy.ops.mesh.primitive_plane_add(size=50, location=(0,0,0))\n bpy.ops.rigidbody.object_add()\n bpy.context.object.rigid_body.type = 'PASSIVE'\n\ndef use_cycles():\n bpy.context.scene.render.engine = 'CYCLES'\n# bpy.context.window.workspace = bpy.data.workspaces[\"Layout\"]\n for area in bpy.context.screen.areas:\n if area.type == 'VIEW_3D':\n for space in area.spaces:\n print(space.type)\n if space.type == 'VIEW_3D':\n space.shading.type = 'RENDERED'\n \nclass Material:\n def __init__(self, name):\n self.name = name\n #\n # mat = bpy.data.materials.get(\"Material.001\")\n #mat_one.diffuse_color = (0.4,0.7,0.9)\n self.mat = bpy.data.materials.new(name=name)\n self.mat.use_nodes = True\n \n# self.mat_nodes = self.mat.node_tree.nodes\n# self.mat_links = self.mat.node_tree.links\n# self.output = self.mat_nodes['Material Output']\n# self.diffuse = self.mat_nodes['Diffuse BSDF']\n\n def set_color(self, red, green, blue, alpha):\n# self.mat.diffuse_color = (red, green, blue, alpha)\n self.mat.node_tree.nodes[\"Principled BSDF\"].inputs[0].default_value = (red, green, blue, alpha)\n\n\n def apply_to(self, object):\n if object.data.materials:\n object.data.materials[0] = self.mat\n else:\n object.data.materials.append(self.mat)\n\nclass Cube:\n def __init__(self):\n bpy.ops.mesh.primitive_cube_add()\n self.obj = bpy.context.active_object\n\nclass Light:\n def __init__(self):\n bpy.ops.object.light_add(type='AREA', radius=1, align='WORLD', location=(0, 0, 0), scale=(1, 1, 1))\n self.object = bpy.context.active_object\n self.object.data.size = 10\n self.object.location[2] = 10\n self.object.data.energy = 1000\n \n\ndef make_ground_plane_collider():\n bpy.ops.mesh.primitive_plane_add(size=50, location=(0,0,0))\n bpy.ops.rigidbody.object_add()\n bpy.context.object.rigid_body.type = 'PASSIVE' \n \ndef main():\n clear_scene()\n use_cycles()\n make_ground_plane_collider()\n cube1 = Cube()\n cube2 = Cube()\n cube1.obj.location[0] =2\n cube2.obj.location[0] = -2\n mat1 = Material(\"red-box-material\")\n mat1.set_color(0.98,0.1,0.2, 1)\n mat1.apply_to(cube1.obj)\n mat2 = Material(\"blue-box-material\")\n mat2.set_color(0.08,0.1,0.9, 1)\n mat2.apply_to(cube2.obj)\n light = Light()\n \nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"projects/datavis/axes-002.py","file_name":"axes-002.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"564878436","text":"'''\r\nThis script runs the full-data run of the ftrl-proximal model using \r\ndata from gl_features.features2(). This only runs one epoch (~200M rows).\r\nIt differs a little from run2.py in that the features2 data contains fields\r\nthat have to be removed (SearchID and SearchDate).\r\n\r\nauthor: David Thaler\r\ndate: July 2015\r\n'''\r\nimport avito2_io\r\nfrom hash_features import hash_features\r\nfrom ftrl_proximal import ftrl_proximal\r\nfrom datetime import datetime\r\nfrom math import log\r\nfrom eval import logloss\r\nimport os.path\r\nimport csv\r\nimport argparse\r\nimport pdb\r\n\r\n\r\nTRAIN_INFILE = 'gl_train2.csv'\r\nbeta = 1.0 # smoothing parameter, probably doesn't matter on big data\r\nD = 2**26 # feature space size\r\n\r\ndef run_val(alpha, l2, l1, maxlines, interact):\r\n val_ids = avito2_io.get_artifact('full_val_set.pkl')\r\n model = ftrl_proximal(alpha, beta, l1, l2, D, interact)\r\n train_path = os.path.join(avito2_io.PROCESSED, TRAIN_INFILE)\r\n with open(train_path) as train_file:\r\n input = csv.DictReader(train_file)\r\n for (k, x) in enumerate(input):\r\n if int(x['SearchID']) not in val_ids:\r\n y = float(x['IsClick'])\r\n del x['IsClick']\r\n del x['SearchDate']\r\n del x['SearchID']\r\n f = hash_features(x, D)\r\n p = model.predict(f)\r\n model.update(f, p, y)\r\n if k == maxlines:\r\n break\r\n if (k + 1) % 1000000 == 0:\r\n print('processed %d lines' % (k + 1))\r\n print('finished training')\r\n count = 0\r\n loss = 0.0\r\n with open(train_path) as train_file:\r\n input = csv.DictReader(train_file)\r\n for (k, x) in enumerate(input):\r\n if int(x['SearchID']) in val_ids:\r\n count += 1\r\n y = float(x['IsClick'])\r\n del x['IsClick']\r\n del x['SearchDate']\r\n del x['SearchID']\r\n f = hash_features(x, D)\r\n p = model.predict(f)\r\n loss += logloss(p, y)\r\n if k == maxlines:\r\n break\r\n if (k + 1) % 1000000 == 0:\r\n print('processed %d lines of raw train on validation pass' % (k + 1))\r\n print('validation loss: %.5f on %d rows' % (loss/count, count))\r\n\r\n\r\nif __name__=='__main__':\r\n start = datetime.now()\r\n parser = argparse.ArgumentParser(description=\r\n 'Trains with given parameters, then computes validation log-loss.')\r\n parser.add_argument('--alpha', type=float, default=0.1,\r\n help='initial learning rate')\r\n parser.add_argument('--l2', type=float, default=0.1, \r\n help='L2 regularization strength')\r\n parser.add_argument('--l1', type=float, default=0.0,\r\n help='L1 regularization strength')\r\n parser.add_argument('-m', '--maxlines',type=int, default=None,\r\n help='A max # of lines to use, if none, all data is used.')\r\n parser.add_argument('-i', '--interact', action='store_const', \r\n const=True, default=False,\r\n help='Create interaction features for all pairs of values')\r\n args = parser.parse_args()\r\n run_val(args.alpha, args.l2, args.l1, args.maxlines, args.interact)\r\n print('elapsed time: %s' % (datetime.now() - start))\r\n\r\n\r\n\r\n\r\n","sub_path":"data/external/repositories_2to3/197834/Kaggle_Avito-2015-master/val_run3.py","file_name":"val_run3.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"456873614","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.core.management.base import BaseCommand\nimport elasticsearch\nfrom intranet import settings\n\n\nclass Command(BaseCommand):\n help = \"Completely wipes the Elasticsearch index\"\n\n def handle(self, **options):\n self.stdout.write(\"Removing user index...\")\n es = elasticsearch.Elasticsearch()\n es.delete_by_query(\n index=settings.ELASTICSEARCH_INDEX,\n doc_type=settings.ELASTICSEARCH_USER_DOC_TYPE,\n body={\n \"query\": {\n \"match_all\": {}\n }\n }\n )\n self.stdout.write(\"Removed user index.\")\n","sub_path":"intranet/apps/search/management/commands/clear_index.py","file_name":"clear_index.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"366021290","text":"\nimport unittest\nfrom selenium import webdriver\nimport time\n\n\nclass TestRegistration(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.browser = webdriver.Chrome()\n\n def test_registration1(self):\n link = \"http://suninjuly.github.io/registration1.html\"\n self.__script(link)\n\n def test_registration2(self):\n link = \"http://suninjuly.github.io/registration2.html\"\n self.__script(link)\n\n def __script(self, link):\n\n self.browser.get(link)\n\n # Ваш код, который заполняет обязательные поля\n input1 = self.browser.find_element_by_css_selector(\".first_block .first\")\n input1.send_keys(\"Ivan\")\n input2 = self.browser.find_element_by_css_selector(\".first_block .second\")\n input2.send_keys(\"Petrov\")\n input3 = self.browser.find_element_by_css_selector(\".first_block .third\")\n input3.send_keys(\"test@mail.ru\")\n\n # Отправляем заполненную форму\n button = self.browser.find_element_by_css_selector(\"button.btn\")\n button.click()\n\n # Проверяем, что смогли зарегистрироваться\n # ждем загрузки страницы\n time.sleep(1)\n\n # находим элемент, содержащий текст\n welcome_text_elt = self.browser.find_element_by_tag_name(\"h1\")\n # записываем в переменную welcome_text текст из элемента welcome_text_elt\n welcome_text = welcome_text_elt.text\n\n # с помощью assert проверяем, что ожидаемый текст совпадает с текстом на странице сайта\n self.assertEqual(\"Congratulations! You have successfully registered!\", welcome_text)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n","sub_path":"src/part_3_frameworks/less_2__test_web_with_frameworks/13_t.py","file_name":"13_t.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"486574018","text":"\n# define\nstr_brackets = ''\nstr_open = '([{'\nstr_close = ')]}'\nstr_tmp = ''\nresult = True\nflag = 0\n\n# give a string from User\nstr_brackets = input('Enter string with brackets:')\n\n# delete spaces from string\nstr_brackets = str_brackets.replace(' ','')\n\nfor i in str_brackets:\n if str_open.find(i) != -1: # if symbol is open brackets then save it in temp string\n str_tmp += str(i)\n elif str_close.find(i) != -1 : # if next symbol is closed brackets\n if str_tmp != '' and str_close.index(i) == str_open.index(str_tmp[-1]): #compair it with last open\n str_tmp = str_tmp[:-1] # and delete \"pair\" if balance brackets correct\n else:\n flag = 1\n break\n\nif flag == 0 and str_tmp == '':\n result = True\nelse:\n result = False\n\nprint(\"Result of checking balance brackets in string %r is: %s\" % (str_brackets,result))\n","sub_path":"chck_balance_brack-v1.py","file_name":"chck_balance_brack-v1.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"407124702","text":"# -*- coding: utf-8 -*-\n\n# Author: Zhi Qiao \n\n# License: BSD 2 clause\n\nimport os\nimport torch\nimport torch.nn as nn\nimport pickle\nimport warnings\nimport torchvision.models as models\nfrom pyhealth.models.text._loss import callLoss\nfrom pyhealth.models.text._dlbase import BaseControler\nfrom pyhealth.data.data_reader.text import flatten_dl_reader as dl_reader\nfrom pyhealth.data.expdata_generator import textdata as expdata_generator\nfrom torch.nn.init import xavier_uniform_\nfrom torch.nn.utils import weight_norm\nimport torch.nn.functional as F\nwarnings.filterwarnings('ignore')\n\n\nclass OutputLayer(nn.Module):\n\n def __init__(self, input_size, label_size):\n super(OutputLayer, self).__init__()\n self.U = nn.Linear(input_size, label_size)\n self.final = nn.Linear(input_size, label_size)\n xavier_uniform_(self.U.weight)\n xavier_uniform_(self.final.weight)\n\n def forward(self, x):\n att = self.U.weight.matmul(x.transpose(1, 2))\n alpha = F.softmax(att, dim=2)\n m = alpha.matmul(x)\n logits = self.final.weight.mul(m).sum(dim=2).add(self.final.bias)\n return logits\n\nclass Chomp1d(nn.Module):\n\n def __init__(self, chomp_size):\n super(Chomp1d, self).__init__()\n self.chomp_size = chomp_size\n\n def forward(self, x):\n return x[:, :, :-self.chomp_size].contiguous()\n\nclass TemporalBlock(nn.Module):\n\n def __init__(self, n_inputs, n_outputs, kernel_size, stride, dilation, padding, dropout=0.2):\n super(TemporalBlock, self).__init__()\n self.conv1 = weight_norm(nn.Conv1d(n_inputs, n_outputs, kernel_size,\n stride=stride, padding=padding, dilation=dilation))\n self.chomp1 = Chomp1d(padding)\n self.relu1 = nn.ReLU()\n self.dropout1 = nn.Dropout(dropout)\n\n self.conv2 = weight_norm(nn.Conv1d(n_outputs, n_outputs, kernel_size,\n stride=stride, padding=padding, dilation=dilation))\n self.chomp2 = Chomp1d(padding)\n self.relu2 = nn.ReLU()\n self.dropout2 = nn.Dropout(dropout)\n\n self.net = nn.Sequential(self.conv1, self.chomp1, self.relu1, self.dropout1,\n self.conv2, self.chomp2, self.relu2, self.dropout2)\n self.downsample = nn.Conv1d(n_inputs, n_outputs, 1) if n_inputs != n_outputs else None\n self.relu = nn.ReLU()\n self.init_weights()\n\n def init_weights(self):\n xavier_uniform_(self.conv1.weight)\n xavier_uniform_(self.conv2.weight)\n if self.downsample is not None:\n xavier_uniform_(self.downsample.weight)\n \n def forward(self, x):\n out = self.net(x)\n res = x if self.downsample is None else self.downsample(x)\n return self.relu(out + res)\n\n\nclass TemporalConvNet(nn.Module):\n\n def __init__(self, num_inputs, num_channels, kernel_size=2, dropout=0.2):\n super(TemporalConvNet, self).__init__()\n layers = []\n num_levels = len(num_channels)\n for i in range(num_levels):\n dilation_size = 2 ** i\n in_channels = num_inputs if i == 0 else num_channels[i-1]\n out_channels = num_channels[i]\n layers += [TemporalBlock(in_channels, out_channels, kernel_size, stride=1, dilation=dilation_size,\n padding=(kernel_size-1) * dilation_size, dropout=dropout)]\n\n self.network = nn.Sequential(*layers)\n\n def forward(self, x):\n return self.network(x)\n\n\nclass callPredictor(nn.Module):\n\n def __init__(self, \n input_channel = 1,\n nhid = 8,\n n_level = 8,\n kernel_size = 2,\n hidden_size = 8,\n label_size = 1\n ):\n super(callPredictor, self).__init__()\n \n num_chans = [nhid] * n_level\n self.tcn = TemporalConvNet(input_channel, num_chans, kernel_size, True)\n self.lin = nn.Linear(num_chans[-1], hidden_size)\n self.output_layer = OutputLayer(hidden_size, label_size)\n xavier_uniform_(self.lin.weight)\n\n def forward(self, input_data):\n conv_result = []\n n_case, n_visit, n_feat = input_data['X'].shape\n x = input_data['X']\n hid_seq = self.tcn(x.transpose(1, 2)).transpose(1, 2) # [bs, seq_len, nhid]\n hid_seq = F.relu(self.lin(hid_seq))\n logits = self.output_layer(hid_seq)\n return None, logits\n\n\nclass DCAN(BaseControler):\n\n def __init__(self, \n expmodel_id = 'test.new', \n n_epoch = 100,\n n_batchsize = 5,\n nhid = 8,\n n_level = 8,\n kernel_size = 2,\n hidden_size = 8, \n learn_ratio = 1e-4,\n weight_decay = 1e-4,\n n_epoch_saved = 1,\n loss_name = 'L1LossSoftmax',\n aggregate = 'sum',\n optimizer_name = 'adam',\n use_gpu = False,\n gpu_ids = '0',\n embed_type = 'BioCharBERT'\n ):\n\n \"\"\"\n\n DCAN: Dilated Convolutional Attention Network for Medical Code Assignment from Clinical Text\n\n\n Parameters\n\n ----------\n exp_id : str, optional (default='init.test') \n name of current experiment\n \n n_epoch : int, optional (default = 100)\n number of epochs with the initial learning rate\n \n n_batchsize : int, optional (default = 5)\n batch size for model training\n \n nhid: int, optional (default = 5)\n \n \n n_level: int, optional (default = 5)\n \n\n kernel_size: int, optional (default = 2)\n \n \n hidden_size: int, optional (default = 8)\n \n \n learn_ratio : float, optional (default = 1e-4)\n initial learning rate for adam\n \n weight_decay : float, optional (default = 1e-4)\n weight decay (L2 penalty)\n \n n_epoch_saved : int, optional (default = 1)\n frequency of saving checkpoints at the end of epochs\n\n loss_name : str, optional (default='SigmoidCELoss') \n Name or objective function.\n\n use_gpu : bool, optional (default=False) \n If yes, use GPU recources; else use CPU recources \n\n\t\t\t\tgpu_ids : str, optional (default='') \n\t\t\t\t\t\t\t\t\t\tIf yes, assign concrete used gpu ids such as '0,2,6'; else use '0' \n\n \"\"\"\n \n super(DCAN, self).__init__(expmodel_id)\n self.n_batchsize = n_batchsize\n self.n_epoch = n_epoch\n self.nhid = nhid\n self.n_level = n_level\n self.kernel_size = kernel_size\n self.hidden_size = hidden_size\n self.learn_ratio = learn_ratio\n self.weight_decay = weight_decay\n self.n_epoch_saved = n_epoch_saved\n self.loss_name = loss_name\n self.aggregate = aggregate\n self.optimizer_name = optimizer_name\n self.use_gpu = use_gpu\n self.gpu_ids = gpu_ids\n self.embed_type = embed_type\n self._args_check()\n \n def _build_model(self):\n \"\"\"\n \n Build the crucial components for model training \n \n \n \"\"\"\n if self.is_loadmodel is False: \n _config = {\n 'input_channel': 768,\n 'nhid': self.nhid,\n 'n_level': self.n_level,\n 'kernel_size': self.kernel_size,\n 'hidden_size': self.hidden_size,\n 'label_size': self.label_size\n }\n self.predictor = callPredictor(**_config).to(self.device)\n self._save_predictor_config(_config)\n \n if self.dataparallal:\n self.predictor= torch.nn.DataParallel(self.predictor)\n self.criterion = callLoss(task = self.task_type,\n loss_name = self.loss_name,\n aggregate = self.aggregate)\n self.optimizer = self._get_optimizer(self.optimizer_name)\n\n def _get_reader(self, data, dtype = 'train'):\n \"\"\"\n Parameters\n\n ----------\n\n data : {\n 'x':list[episode_file_path], \n 'y':list[label], \n 'l':list[seq_len], \n 'feat_n': n of feature space, \n 'label_n': n of label space\n }\n\n The input samples dict.\n \n dtype: str, (default='train')\n \n dtype in ['train','valid','test'], different type imapct whether use shuffle for data\n \n Return\n \n ----------\n \n data_loader : dataloader of input data dict\n \n Combines a dataset and a sampler, and provides single- or multi-process iterators over the dataset.\n\n refer to torch.utils.data.dataloader\n \n \"\"\"\n _dataset = dl_reader.DatasetReader(data, device = self.device, embed_type = self.embed_type) \n _loader = torch.utils.data.DataLoader(_dataset,\n batch_size=self.n_batchsize,\n drop_last = True,\n shuffle=True if dtype == 'train' else False)\n return _loader\n\n\n def fit(self, train_data, valid_data, assign_task_type = None):\n \n \"\"\"\n Parameters\n\n ----------\n\n train_data : {\n 'x':list[episode_file_path], \n 'y':list[label], \n 'l':list[seq_len], \n 'feat_n': n of feature space, \n 'label_n': n of label space\n }\n\n The input train samples dict.\n \n valid_data : {\n 'x':list[episode_file_path], \n 'y':list[label], \n 'l':list[seq_len], \n 'feat_n': n of feature space, \n 'label_n': n of label space\n }\n\n The input valid samples dict.\n\n assign_task_type: str (default = None)\n predifine task type to model mapping \n current support ['binary','multiclass','multilabel','regression']\n\n Returns\n\n -------\n\n self : object\n\n Fitted estimator.\n\n \"\"\"\n self.task_type = assign_task_type\n self._data_check([train_data, valid_data])\n self._build_model()\n train_reader = self._get_reader(train_data, 'train')\n valid_reader = self._get_reader(valid_data, 'valid')\n self._fit_model(train_reader, valid_reader)\n \n def load_model(self, \n loaded_epoch = '',\n config_file_path = '',\n model_file_path = ''):\n \"\"\"\n Parameters\n\n ----------\n\n loaded_epoch : str, loaded model name \n \n we save the model by .epoch, latest.epoch, best.epoch\n\n Returns\n\n -------\n\n self : object\n\n loaded estimator.\n\n \"\"\"\n\n predictor_config = self._load_predictor_config(config_file_path)\n self.predictor = callPredictor(**predictor_config).to(self.device)\n self._load_model(loaded_epoch, model_file_path)\n \n\n def _args_check(self):\n \"\"\"\n \n Check args whether valid/not and give tips\n \n \n \"\"\"\n assert isinstance(self.n_batchsize,int) and self.n_batchsize>0, \\\n 'fill in correct n_batchsize (int, >0)'\n assert isinstance(self.n_epoch,int) and self.n_epoch>0, \\\n 'fill in correct n_epoch (int, >0)'\n assert isinstance(self.learn_ratio,float) and self.learn_ratio>0., \\\n 'fill in correct learn_ratio (float, >0.)'\n assert isinstance(self.weight_decay,float) and self.weight_decay>=0., \\\n 'fill in correct weight_decay (float, >=0.)'\n assert isinstance(self.n_epoch_saved,int) and self.n_epoch_saved>0 and self.n_epoch_saved < self.n_epoch, \\\n 'fill in correct n_epoch (int, >0 and <{0}).format(self.n_epoch)'\n assert isinstance(self.aggregate,str) and self.aggregate in ['sum','avg'], \\\n 'fill in correct aggregate (str, [\\'sum\\',\\'avg\\'])'\n assert isinstance(self.optimizer_name,str) and self.optimizer_name in ['adam'], \\\n 'fill in correct optimizer_name (str, [\\'adam\\'])'\n assert isinstance(self.use_gpu,bool), \\\n 'fill in correct use_gpu (bool)'\n assert isinstance(self.loss_name,str), \\\n 'fill in correct loss_name (int)'\n assert isinstance(self.nhid,int), \\\n 'fill in correct nhid (int)'\n assert isinstance(self.n_level,int), \\\n 'fill in correct n_level (int)'\n assert isinstance(self.kernel_size,int), \\\n 'fill in correct kernel_size (int)'\n assert isinstance(self.hidden_size,int), \\\n 'fill in correct hidden_size (int)'\n\n self.device = self._get_device()\n\n#expdata_id = '2021.0102.text'\n#\n#cur_dataset = expdata_generator(expdata_id, root_dir='./')\n#cur_dataset.load_exp_data()\n#\n#_dataset = dl_reader.DatasetReader(cur_dataset.valid)\n#\n##print (len(_dataset.label_list))\n#\n#model = DCAN()\n#dtype = 'train'\n#_loader = torch.utils.data.DataLoader(_dataset,\n# batch_size=3,\n# drop_last=True,\n# shuffle=True if dtype == 'train' else False)\n#model.fit(cur_dataset.valid, cur_dataset.valid)\n#for batch_idx, databatch in enumerate(_loader):\n# print (databatch['X'].shape)\n# print (databatch['M'].shape)\n# print (databatch['Y'].shape)\n# _, y = model.predictor({key: value.float() for key, value in databatch.items()})\n# print (y.shape)\n# break\n\n","sub_path":"pyhealth/models/text/dcan.py","file_name":"dcan.py","file_ext":"py","file_size_in_byte":13995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"261034681","text":"# coding: utf8\n\nimport sublime, sublime_plugin\nimport re\n\nclass CircleCommand(sublime_plugin.TextCommand):\n def run(self, edit):\n selection = self.view.sel()\n # 多個 select item\n for path in selection:\n if not path.empty():\n seltext = self.view.substr(path)\n seltext = self.circle(seltext)\n # 轉換成 php code\n #self.view.replace(edit, path, seltext)\n\n def circle(self, data):\n data = data.strip()\n pattern = r'array\\((\\d+)\\)\\s+{\\s*(\\[\\d+\\]\\s*=>\\s*int\\(\\d+\\)\\s*)+\\}'\n if re.match(pattern, data):\n nr = re.search(pattern, data).group(1)\n ret = range(int(nr))\n pattern = r'\\[(\\d+)\\]\\s*=>\\s*int\\((\\d+)\\)'\n for idx, v in re.findall(pattern, data):\n ret[int(idx)] = v\n\n rueslt = '$tmp = [{0}];'.format(','.join([_ for _ in ret]))\n return rueslt","sub_path":"CircleCode.py","file_name":"CircleCode.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"568022861","text":"import pandas as pd\n# Keras\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import model_from_json\nimport keras\n\n# NLTK\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import SnowballStemmer\n# Other\nimport re\nimport string\nimport numpy as np\nimport pandas as pd\nfrom sklearn.manifold import TSNE\njson_file = open('/Users/samshenoi/Documents/CPRIT/CPRIT/MachineLearning/Models/abstract_model_gloveFinal.json', 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nloaded_model = model_from_json(loaded_model_json)\n# load weights into new model\nloaded_model.load_weights(\"/Users/samshenoi/Documents/CPRIT/CPRIT/MachineLearning/Weights/abstract_model_gloveFinal.h5\")\n\n# evaluate loaded model on test data\nloaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n#Precompile regex\nfirst = re.compile(r\"\\[\\D\\S{6}:\\S{5}\\]\")\nsecond = re.compile(r\"\\/\")\nthird = re.compile(r\"\\\\n*\")\nf = re.compile(r\"\\'\")\nfive = re.compile(r'\\,|\\.|\\:|\\&')\nsix = re.compile(r'\\{|\\}|\\[|\\]')\ndef load_data(file):\n json_file = open(file, \"r\", encoding ='latin-1')\n data = json_file.read()\n json_file.close()\n return str(data)\nnltk.download('stopwords')\nnltk.download('wordnet')\nwn = nltk.WordNetLemmatizer()\ndef clean_text(text):\n ## Remove puncuation\n text = text.translate(string.punctuation)\n \n ## Convert words to lower case and split them\n text = text.lower().split()\n \n ## Remove stop words\n stops = set(stopwords.words(\"english\"))\n text = [w for w in text if not w in stops and len(w) >= 3]\n text = \" \".join(text)\n # Clean the text\n text = first.sub(\"\", text)\n text = second.sub(\"\", text)\n text = third.sub(\"\", text)\n text = f.sub(\"\", text)\n text = five.sub(\"\", text)\n text = six.sub(\"\", text)\n\t\n text = text.split()\n stemmer = SnowballStemmer('english')\n stemmed_words = [stemmer.stem(word) for word in text]\n text = [wn.lemmatize(word) for word in text]\n text = \" \".join(stemmed_words)\n text = pd.DataFrame({\"Abstracts\": [text]})\n return text\nvocabulary_size = 20000\ndef process(df):\n tokenizer = Tokenizer(num_words= vocabulary_size)\n tokenizer.fit_on_texts(df['Abstracts'])\n sequences = tokenizer.texts_to_sequences(df['Abstracts'])\n data = pad_sequences(sequences)\n return np.array(data)\n# load json and create model\ndef load_trained_model():\n json_file = open('/Users/samshenoi/Documents/CPRIT/CPRIT/MachineLearning/Models/clinical_model_masked_lstm.json', 'r')\n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n # load weights into new model\n loaded_model.load_weights(\"/Users/samshenoi/Documents/CPRIT/CPRIT/MachineLearning/Weights/clinical_model_masked_lstm.h5\")\n print(\"Loaded model from disk\")\n \n # evaluate loaded model on test data\n loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n return loaded_model\ndef predict(file):\n text = clean_text(file)\n x = process(text)\n x = keras.preprocessing.sequence.pad_sequences(x, maxlen=1007)\n model = loaded_model\n pred = model.predict_classes(x)\n pred_p=model.predict(x)\n\n prediction = pred[0][0]\n return prediction\n","sub_path":"BackendWebAPI/MachineLearning/DeepClincalPredict.py","file_name":"DeepClincalPredict.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"633950681","text":"# Copyright (c) 2012, GPy authors (see AUTHORS.txt).\n# Licensed under the BSD 3-clause license (see LICENSE.txt)\n\n\nimport numpy as np\nimport re\nimport copy\nimport cPickle\nimport os\nfrom ..util.squashers import sigmoid\n\ndef truncate_pad(string,width,align='m'):\n \"\"\"\n A helper function to make aligned strings for parameterised.__str__\n \"\"\"\n width=max(width,4)\n if len(string)>width:\n return string[:width-3]+'...'\n elif len(string)==width:\n return string\n elif len(string) 0, \"need at least something to tie together\"\n if len(self.tied_indices):\n assert not np.any(matches[:,None]==np.hstack(self.tied_indices)), \"Some indices are already tied!\"\n self.tied_indices.append(matches)\n #TODO only one of the priors will be evaluated. Give a warning message if the priors are not identical\n if hasattr(self,'prior'):\n pass\n\n self._set_params_transformed(self._get_params_transformed())# sets tied parameters to single value\n\n def untie_everything(self):\n \"\"\"Unties all parameters by setting tied_indices to an empty list.\"\"\"\n self.tied_indices = []\n\n def all_constrained_indices(self):\n \"\"\"Return a np array of all the constrained indices\"\"\"\n ret = [np.hstack(i) for i in [self.constrained_bounded_indices, self.constrained_positive_indices, self.constrained_negative_indices, self.constrained_fixed_indices] if len(i)]\n if len(ret):\n return np.hstack(ret)\n else:\n return []\n def grep_param_names(self, expr):\n \"\"\"\n Arguments\n ---------\n expr -- can be a regular expression object or a string to be turned into regular expression object.\n\n Returns\n -------\n the indices of self._get_param_names which match the regular expression.\n\n Notes\n -----\n Other objects are passed through - i.e. integers which were'nt meant for grepping\n \"\"\"\n\n if type(expr) in [str, np.string_, np.str]:\n expr = re.compile(expr)\n return np.nonzero([expr.search(name) for name in self._get_param_names()])[0]\n elif type(expr) is re._pattern_type:\n return np.nonzero([expr.search(name) for name in self._get_param_names()])[0]\n else:\n return expr\n\n def Nparam_transformed(self):\n ties = 0\n for ar in self.tied_indices:\n ties += ar.size - 1\n return self.Nparam - len(self.constrained_fixed_indices) - ties\n\n def constrain_positive(self, which):\n \"\"\"\n Set positive constraints.\n\n Arguments\n ---------\n which -- np.array(dtype=int), or regular expression object or string\n \"\"\"\n matches = self.grep_param_names(which)\n assert not np.any(matches[:,None]==self.all_constrained_indices()), \"Some indices are already constrained\"\n self.constrained_positive_indices = np.hstack((self.constrained_positive_indices, matches))\n #check to ensure constraint is in place\n x = self._get_params()\n for i,xx in enumerate(x):\n if (xx<0) & (i in matches):\n x[i] = -xx\n self._set_params(x)\n\n\n def unconstrain(self,which):\n \"\"\"Unconstrain matching parameters. does not untie parameters\"\"\"\n matches = self.grep_param_names(which)\n #positive/negative\n self.constrained_positive_indices = np.delete(self.constrained_positive_indices,np.nonzero(np.sum(self.constrained_positive_indices[:,None]==matches[None,:],1))[0])\n self.constrained_negative_indices = np.delete(self.constrained_negative_indices,np.nonzero(np.sum(self.constrained_negative_indices[:,None]==matches[None,:],1))[0])\n #bounded\n if len(self.constrained_bounded_indices):\n self.constrained_bounded_indices = [np.delete(a,np.nonzero(np.sum(a[:,None]==matches[None,:],1))[0]) for a in self.constrained_bounded_indices]\n if np.hstack(self.constrained_bounded_indices).size:\n self.constrained_bounded_uppers, self.constrained_bounded_lowers, self.constrained_bounded_indices = zip(*[(u,l,i) for u,l,i in zip(self.constrained_bounded_uppers, self.constrained_bounded_lowers, self.constrained_bounded_indices) if i.size])\n self.constrained_bounded_uppers, self.constrained_bounded_lowers, self.constrained_bounded_indices = list(self.constrained_bounded_uppers), list(self.constrained_bounded_lowers), list(self.constrained_bounded_indices)\n else:\n self.constrained_bounded_uppers, self.constrained_bounded_lowers, self.constrained_bounded_indices = [],[],[]\n #fixed:\n for i,indices in enumerate(self.constrained_fixed_indices):\n self.constrained_fixed_indices[i] = np.delete(indices,np.nonzero(np.sum(indices[:,None]==matches[None,:],1))[0])\n #remove empty elements\n tmp = [(i,v) for i,v in zip(self.constrained_fixed_indices, self.constrained_fixed_values) if len(i)]\n if tmp:\n self.constrained_fixed_indices, self.constrained_fixed_values = zip(*tmp)\n self.constrained_fixed_indices, self.constrained_fixed_values = list(self.constrained_fixed_indices), list(self.constrained_fixed_values)\n else:\n self.constrained_fixed_indices, self.constrained_fixed_values = [],[]\n\n\n\n def constrain_negative(self,which):\n \"\"\"\n Set negative constraints.\n\n :param which: which variables to constrain\n :type which: regular expression string\n\n \"\"\"\n matches = self.grep_param_names(which)\n assert not np.any(matches[:,None]==self.all_constrained_indices()), \"Some indices are already constrained\"\n self.constrained_negative_indices = np.hstack((self.constrained_negative_indices, matches))\n #check to ensure constraint is in place\n x = self._get_params()\n for i,xx in enumerate(x):\n if (xx>0.) and (i in matches):\n x[i] = -xx\n self._set_params(x)\n\n\n\n def constrain_bounded(self, which, lower, upper):\n \"\"\"Set bounded constraints.\n\n Arguments\n ---------\n which -- np.array(dtype=int), or regular expression object or string\n upper -- (float) the upper bound on the constraint\n lower -- (float) the lower bound on the constraint\n \"\"\"\n matches = self.grep_param_names(which)\n assert not np.any(matches[:,None]==self.all_constrained_indices()), \"Some indices are already constrained\"\n assert lower < upper, \"lower bound must be smaller than upper bound!\"\n self.constrained_bounded_indices.append(matches)\n self.constrained_bounded_uppers.append(upper)\n self.constrained_bounded_lowers.append(lower)\n #check to ensure constraint is in place\n x = self._get_params()\n for i,xx in enumerate(x):\n if ((xx<=lower)|(xx>=upper)) & (i in matches):\n x[i] = sigmoid(xx)*(upper-lower) + lower\n self._set_params(x)\n\n\n def constrain_fixed(self, which, value = None):\n \"\"\"\n Arguments\n ---------\n :param which: np.array(dtype=int), or regular expression object or string\n :param value: a float to fix the matched values to. If the value is not specified,\n the parameter is fixed to the current value\n\n Notes\n -----\n Fixing a parameter which is tied to another, or constrained in some way will result in an error.\n To fix multiple parameters to the same value, simply pass a regular expression which matches both parameter names, or pass both of the indexes\n \"\"\"\n matches = self.grep_param_names(which)\n assert not np.any(matches[:,None]==self.all_constrained_indices()), \"Some indices are already constrained\"\n self.constrained_fixed_indices.append(matches)\n if value != None:\n self.constrained_fixed_values.append(value)\n else:\n self.constrained_fixed_values.append(self._get_params()[self.constrained_fixed_indices[-1]])\n\n #self.constrained_fixed_values.append(value)\n self._set_params_transformed(self._get_params_transformed())\n\n def _get_params_transformed(self):\n \"\"\"use self._get_params to get the 'true' parameters of the model, which are then tied, constrained and fixed\"\"\"\n x = self._get_params()\n x[self.constrained_positive_indices] = np.log(x[self.constrained_positive_indices])\n x[self.constrained_negative_indices] = np.log(-x[self.constrained_negative_indices])\n [np.put(x,i,np.log(np.clip(x[i]-l,1e-10,np.inf)/np.clip(h-x[i],1e-10,np.inf))) for i,l,h in zip(self.constrained_bounded_indices, self.constrained_bounded_lowers, self.constrained_bounded_uppers)]\n\n to_remove = self.constrained_fixed_indices+[t[1:] for t in self.tied_indices]\n if len(to_remove):\n return np.delete(x,np.hstack(to_remove))\n else:\n return x\n\n\n def _set_params_transformed(self,x):\n \"\"\" takes the vector x, which is then modified (by untying, reparameterising or inserting fixed values), and then call self._set_params\"\"\"\n\n #work out how many places are fixed, and where they are. tricky logic!\n Nfix_places = 0.\n if len(self.tied_indices):\n Nfix_places += np.hstack(self.tied_indices).size-len(self.tied_indices)\n if len(self.constrained_fixed_indices):\n Nfix_places += np.hstack(self.constrained_fixed_indices).size\n if Nfix_places:\n fix_places = np.hstack(self.constrained_fixed_indices+[t[1:] for t in self.tied_indices])\n else:\n fix_places = []\n\n free_places = np.setdiff1d(np.arange(Nfix_places+x.size,dtype=np.int),fix_places)\n\n #put the models values in the vector xx\n xx = np.zeros(Nfix_places+free_places.size,dtype=np.float64)\n\n xx[free_places] = x\n [np.put(xx,i,v) for i,v in zip(self.constrained_fixed_indices, self.constrained_fixed_values)]\n [np.put(xx,i,v) for i,v in [(t[1:],xx[t[0]]) for t in self.tied_indices] ]\n xx[self.constrained_positive_indices] = np.exp(xx[self.constrained_positive_indices])\n xx[self.constrained_negative_indices] = -np.exp(xx[self.constrained_negative_indices])\n [np.put(xx,i,low+sigmoid(xx[i])*(high-low)) for i,low,high in zip(self.constrained_bounded_indices, self.constrained_bounded_lowers, self.constrained_bounded_uppers)]\n self._set_params(xx)\n\n def _get_param_names_transformed(self):\n \"\"\"\n Returns the parameter names as propagated after constraining,\n tying or fixing, i.e. a list of the same length as _get_params_transformed()\n \"\"\"\n n = self._get_param_names()\n\n #remove/concatenate the tied parameter names\n if len(self.tied_indices):\n for t in self.tied_indices:\n n[t[0]] = \"\".join([n[tt] for tt in t])\n remove = np.hstack([t[1:] for t in self.tied_indices])\n else:\n remove=np.empty(shape=(0,),dtype=np.int)\n\n #also remove the fixed params\n if len(self.constrained_fixed_indices):\n remove = np.hstack((remove, np.hstack(self.constrained_fixed_indices)))\n\n #add markers to show that some variables are constrained\n for i in self.constrained_positive_indices:\n n[i] = n[i]+'(+ve)'\n for i in self.constrained_negative_indices:\n n[i] = n[i]+'(-ve)'\n for i,l,h in zip(self.constrained_bounded_indices, self.constrained_bounded_lowers, self.constrained_bounded_uppers):\n for ii in i:\n n[ii] = n[ii]+'(bounded)'\n\n n = [nn for i,nn in enumerate(n) if not i in remove]\n return n\n\n def __str__(self,nw=30):\n \"\"\"\n Return a string describing the parameter names and their ties and constraints\n \"\"\"\n names = self._get_param_names()\n N = len(names)\n\n if not N:\n return \"This object has no free parameters.\"\n header = ['Name','Value','Constraints','Ties']\n values = self._get_params() #map(str,self._get_params())\n #sort out the constraints\n constraints = ['']*len(names)\n for i in self.constrained_positive_indices:\n constraints[i] = '(+ve)'\n for i in self.constrained_negative_indices:\n constraints[i] = '(-ve)'\n for i in self.constrained_fixed_indices:\n for ii in i:\n constraints[ii] = 'Fixed'\n for i,u,l in zip(self.constrained_bounded_indices, self.constrained_bounded_uppers, self.constrained_bounded_lowers):\n for ii in i:\n constraints[ii] = '('+str(l)+', '+str(u)+')'\n #sort out the ties\n ties = ['']*len(names)\n for i,tie in enumerate(self.tied_indices):\n for j in tie:\n ties[j] = '('+str(i)+')'\n\n values = ['%.4f' % float(v) for v in values]\n max_names = max([len(names[i]) for i in range(len(names))] + [len(header[0])])\n max_values = max([len(values[i]) for i in range(len(values))] + [len(header[1])])\n max_constraint = max([len(constraints[i]) for i in range(len(constraints))] + [len(header[2])])\n max_ties = max([len(ties[i]) for i in range(len(ties))] + [len(header[3])])\n cols = np.array([max_names, max_values, max_constraint, max_ties]) + 4\n columns = cols.sum()\n\n header_string = [\"{h:^{col}}\".format(h = header[i], col = cols[i]) for i in range(len(cols))]\n header_string = map(lambda x: '|'.join(x), [header_string])\n separator = '-'*len(header_string[0])\n param_string = [\"{n:^{c0}}|{v:^{c1}}|{c:^{c2}}|{t:^{c3}}\".format(n = names[i], v = values[i], c = constraints[i], t = ties[i], c0 = cols[0], c1 = cols[1], c2 = cols[2], c3 = cols[3]) for i in range(len(values))]\n\n\n return ('\\n'.join([header_string[0], separator]+param_string)) + '\\n'\n","sub_path":"Moduleita/GPy-0.2/GPy/core/parameterised.py","file_name":"parameterised.py","file_ext":"py","file_size_in_byte":15261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"216870454","text":"# 2. Написать программу сложения и умножения двух шестнадцатеричных чисел.\n# При этом каждое число представляется как массив, элементы которого — цифры числа.\n# Например, пользователь ввёл A2 и C4F. Нужно сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно.\n# Сумма чисел из примера: [‘C’, ‘F’, ‘1’], произведение - [‘7’, ‘C’, ‘9’, ‘F’, ‘E’].\n\nimport sys\nfrom collections import ChainMap\nfrom collections import deque\n\ndic1 = {}\ndic2 = {}\ndic3 = {}\nfor k, v in enumerate([str(i) for i in range(10)] + ['A', 'B', 'C', 'D', 'E', 'F']):\n dic1[k] = v\n dic2[v] = k\n dic3[str(k)] = v\ndct = ChainMap(dic1, dic2, dic3)\n\nfir = input('Первое число в 16-ричной системе: ')\nsec = input('Второе число в 16-ричной системе: ')\n\n# проверка корректности введенного числа\nz = 0\nfor i in fir.upper():\n if i not in dct:\n z += 1\nfor j in sec.upper():\n if j not in dct:\n z += 2\nif z != 0:\n if z == 1:\n print('Первое число введено не корректно.')\n elif z == 2:\n print('Второе число введено не корректно.')\n elif z == 3:\n print('Оба числа введены не корректно.')\n sys.exit()\n\nfirst = list(fir.upper())[:: -1]\nsecond = list(sec.upper())[:: -1]\n\n# определение очередности для функции сложения\nif len(second) > len(first):\n first, second = second, first\n\n# функция возврата значения второго числа\ndef num_second(n):\n if n + 1 <= len(second):\n return dct[str(second[n])]\n else:\n return '0'\n\n# функция сложения\ndef get_summ(first):\n summ = []\n k = 0\n for i in range(len(first)):\n num = num_second(i)\n res = int(dct[str(first[i])]) + int(num)\n summ.append(str((res + k) % 16))\n if res + k > 15:\n k = 1\n else:\n k = 0\n if k:\n summ.append(str(k))\n result = []\n for i in summ[:: -1]:\n result.append(str(dct[i]))\n return ''.join(result)\n\nprint(f'Сумма введенных чисел = {get_summ(first)}')\n\nfirst_m = list(fir.upper())\nsecond_m = list(sec.upper())\n\n# функция умножения\ndef get_mult(first, second):\n result = deque()\n spam = deque([deque() for _ in range(len(second))])\n first, second = first.copy(), deque(second)\n for i in range(len(second)):\n m = int(dct[second.pop()])\n for j in range(len(first) - 1, -1, -1):\n spam[i].appendleft(m * int(dct[first[j]]))\n for _ in range(i):\n spam[i].append(0)\n k = 0\n for _ in range(len(spam[-1])):\n res = k\n for i in range(len(spam)):\n if spam[i]:\n res += spam[i].pop()\n if res < 16:\n result.appendleft(dct[res])\n else:\n result.appendleft(dct[res % 16])\n k = res // 16\n if k:\n result.appendleft(dct[k])\n return ''.join(result)\n\nprint(f'Произведение введенных чисел = {get_mult(first_m, second_m)}')","sub_path":"05. Модуль Collections/2. Hex калькулятор(ChainMap, deque).py","file_name":"2. Hex калькулятор(ChainMap, deque).py","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"441110902","text":"import os\nfrom app import create_app, db\nfrom flask.ext.script import Manager, Shell\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'manage')\nmanager = Manager(app)\n\n@manager.command\ndef create():\n \"Creates database tables from sqlalchemy models\"\n db.create_all()\n db.session.commit()\n\n# def make_shell_context():\n# return dict(app=app, db=db, User=User, Role=Role)\n# manager.add_command(\"shell\", Shell(make_context=make_shell_context))\n# manager.add_command('db', MigrateCommand)\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"267196531","text":"import matplotlib.pyplot as plt\n#Importamos la liberia matplotlib para poder graficar\n \ndef DDA(x1, y1, x2, y2, color):\n #Se hacen las operaciones para definir dx, dy\n dx = abs(x2 - x1)\n dy = abs(y2 - y1)\n steps = 0\n \n #Se hacen las comparaciones para saber cual es mayor\n if (dx) > (dy):\n steps = (dx)\n else:\n steps = (dy)\n #Se optinen los incrementos para x, y\n xInc = float(dx / steps)\n yInc = float(dy / steps)\n\n #Redondeamos los incrementos\n xInc = round(xInc,1)\n yInc = round(yInc,1)\n\n #Se crea un ciclo para ir asignando los incrementos \n for i in range(0, int(steps + 1)):\n #Dibuja la grafica con rrespecto a las coordenadas en x1, y1\n plt.plot(round(x1),round(y1), color)\n #Hace el incremento\n x1 += xInc\n y1 += yInc\n \n #Imprimimos los valores de x, y para cada caso\n print('X =',x1)\n print('Y = ',y1)\n #Mostramos la grafica\n plt.show()\n \n #Imprimimos los demas valores de DDA\n print()\n print(\"Valores:\")\n print(\"dx = \",dx)\n print(\"dy = \",dy)\n print(\"steps = \",steps)\n print(\"Xinc = \",xInc)\n print(\"Yinc\",yInc)\n\ndef main():\n x1 = int(input(\"Ingresa el valor para X1: \"))\n y1 = int(input(\"Ingresa el valor para Y1: \"))\n x2 = int(input(\"Ingresa el valor para X2: \"))\n y2 = int(input(\"Ingresa el valor para Y2: \"))\n color = \"b.\"\n \n DDA(x1, y1, x2, y2, color)\n\nif __name__ == '__main__':\n main()\n \n","sub_path":"AlgoritmoDDA_RodrigoJavierMtz_3061.py","file_name":"AlgoritmoDDA_RodrigoJavierMtz_3061.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"541843866","text":"\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nfrom time import time\nfrom time import sleep\nimport numpy as np\nfrom IPython.core.display import clear_output\nfrom random import randint\n\n#To configure webdriver to use Chrome browser, we have to set the path to chromedriver\ndriver = webdriver.Chrome(\"E:\\chromedriver_win32\\chromedriver.exe\")\n#driver = webdriver.Ie(\"E:\\IEDriverServer_x64_3.9.0\\IEDriverServer.exe\")\n\ntimes=[]\ndates=[]\nsources=[] \nheadlines=[]\n\n#pages = [30,16,10]\n#years = [2011,2010,2009]\n\npages = [8,13]\nyears = [2018,2017]\n \n\n\ndef fun():\n # Preparing the monitoring of the loop\n start_time = time()\n requests = 0\n for (year,i) in zip(years,pages):\n \n for n in range(i):\n page = n+1\n # Pause the loop\n sleep(randint(8,15))\n # Monitor the requests\n requests += 1\n elapsed_time = time() - start_time\n print('Request:{}; Frequency: {} requests/s'.format(requests, requests/elapsed_time))\n clear_output(wait = True)\n # Break the loop if the number of requests is greater than expected\n # if requests > 110:\n # print('Number of requests was greater than expected.')\n # break\n \n url = \"https://www.moneycontrol.com/stocks/company_info/stock_news.php?sc_id=MM&scat=&pageno=\" + str(page) + \"&next=0&durationType=Y&Year=\" + str(year) + \"&duration=1&news_type=\"\n try: \n driver.get(url)\n except Exception:\n print(\"ERROR\")\n return\n \n content = driver.page_source\n soup = BeautifulSoup(content,'lxml')\n \n \n for a in soup.findAll('div',attrs={'class':'MT15 PT10 PB10'}):\n #print(str(a) + '\\n')\n info=a.find('p',attrs={'class':'PT3 a_10dgry'})\n if info is None:\n continue\n info = info.text\n #print(date.text)\n temp = info.split('|')\n if(len(temp) == 3):\n times.append(temp[0])\n dates.append(temp[1])\n sources.append(temp[2])\n elif(len(temp) == 2):\n times.append(temp[0])\n dates.append(temp[1])\n sources.append(\"@\")\n else:\n dates.append(\"@\")\n sources.append(\"@\")\n times.append(temp[0])\n \n headline=a.find('strong')\n #print(headline.text)\n \n headlines.append(headline.text)\n \nfun()\ndf = pd.DataFrame({'Time':times,'Dates':dates,'Sources': sources ,'Headlines':headlines}) \ndf.to_csv('news_mahindra_18_17.csv', index=False, encoding='utf-8') \nprint('---------DONE-----------')","sub_path":"NEWS/News Scrapper.py","file_name":"News Scrapper.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"429463053","text":"from .import views\nfrom django.urls import path\n\nurlpatterns=[\n path('',views.PostList.as_view(), name='home_new'),\n path('/',views.post_detail, name='post_detail'),\n path('post/new/', views.BlogCreateView.as_view(), name='post_new'),\n \n \n]","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"520854223","text":"import numpy as np\nimport random\nfrom modelling.agent import Agent\n\n\nclass Grid:\n\n def __init__(self, size):\n self._size = size\n self._grid = np.zeros((size, size), int)\n self._occupied_tile_coordinates = []\n\n def has_empty_tiles(self):\n if len(self._occupied_tile_coordinates) >= self._size * self._size:\n return False\n return True\n\n def is_tile_vacant(self, coordinate):\n if 0 <= coordinate[0] < self._size and 0 <= coordinate[1] < self._size:\n if self._grid[coordinate[0], coordinate[1]] == 0:\n return True\n\n return False\n\n def get_random_empty_square_coordinates(self):\n empty_square = None\n for i in range(0, 100):\n rand_x = random.randint(0, self._size-1)\n rand_y = random.randint(0, self._size-1)\n if self._grid[rand_x, rand_y] == 0:\n return rand_x, rand_y\n\n raise Exception('Could not find empty square, try threshold reached')\n\n def get_occupied_tile_coordinates(self):\n return list(self._occupied_tile_coordinates)\n\n def get_occupied_neighbour_tile_coordinates(self, coordinate):\n neighbours = []\n\n if self.is_tile_occupied((coordinate[0] - 1, coordinate[1])):\n neighbours.append((coordinate[0] - 1, coordinate[1]))\n if self.is_tile_occupied((coordinate[0] + 1, coordinate[1])):\n neighbours.append((coordinate[0] + 1, coordinate[1]))\n if self.is_tile_occupied((coordinate[0], coordinate[1] - 1)):\n neighbours.append((coordinate[0], coordinate[1] - 1))\n if self.is_tile_occupied((coordinate[0], coordinate[1] + 1)):\n neighbours.append((coordinate[0], coordinate[1] + 1))\n\n return neighbours\n\n def is_tile_occupied(self, coordinate):\n if 0 <= coordinate[0] < self._size and 0 <= coordinate[1] < self._size:\n if not self._grid[coordinate[0], coordinate[1]] == 0:\n return True\n return False\n\n def get_shuffled_occupied_tile_coordinates(self):\n coordinates = self.get_occupied_tile_coordinates()\n random.shuffle(coordinates)\n return coordinates\n\n def set_agent(self, agent, square):\n self._grid[square[0], square[1]] = agent.to_bitmap()\n if not self._occupied_tile_coordinates.__contains__((square[0], square[1])):\n self._occupied_tile_coordinates.append((square[0], square[1]))\n\n def get_agent(self, coordinates):\n agent_bits = self._grid[coordinates[0], coordinates[1]]\n return Agent.bits_to_agent(agent_bits)\n\n def remove_agent(self, coordinates):\n self._grid[coordinates[0], coordinates[1]] = 0\n self._occupied_tile_coordinates.remove((coordinates[0], coordinates[1]))\n\n def __str__(self):\n sb = ''\n sb += '[\\n'\n for x in range(0, self._size):\n for y in range(0, self._size):\n agent_bits = self._grid[x, y]\n if agent_bits == 0:\n sb += ' < EMPTY TILE > '\n else:\n sb += ' <{0}> '.format(Agent.bits_to_agent(self._grid[x, y]))\n sb += '\\n'\n sb += ']'\n\n return sb","sub_path":"modelling/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":3220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"585948616","text":"import h5py\nimport re\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport scipy.signal\nfrom datetime import datetime\nimport pytz\nimport os\nimport sys\n\ndef print_time_for_timezone(timezone, time_sec):\n \"\"\" Function for printing time in the given timezone \n Parameters\n ----------\n timezone : str\n Timezone for which time has to be printed.\n time : float\n Time in Seconds\n \"\"\"\n datetimeob_utc = datetime.utcfromtimestamp(time_sec)\n print(\"TIME-UTC\",datetimeob_utc)\n timezone_cern = pytz.timezone(timezone)\n datetimeob_cern = pytz.utc.localize(datetimeob_utc, is_dst=None).astimezone(timezone_cern)\n print(\"TIME\",timezone, datetimeob_cern)\n\ndef check_function(name, node):\n \"\"\" Function for traversing a given hdf5 file\n Parameters\n ----------\n name : h5py object\n Object returned after hdf5 file opened with h5py\n node : h5py object\n Either Group or Dataset of hdf5 format\n \"\"\"\n if isinstance(node, h5py.Dataset):\n try:\n temp = [str(node.name), 'Dataset', node.shape, node.size, str(node.dtype)]\n info_list.append(temp)\n except TypeError:\n temp = [str(node.name),'Dataset', node.shape, node.size, \"Error\"]\n info_list.append(temp)\n else:\n temp = [str(node.name),'Group', np.nan, np.nan, np.nan]\n info_list.append(temp)\n\ndef make_dataframe_from_hdf5(file_main):\n \"\"\" Function for creating dataframe from hdf5 hierarical format\n Parameters\n ----------\n file_main : h5py object\n Object returned after hdf5 file opened with h5py\n \"\"\"\n file_main.visititems(check_function)\n info_dataframe_copy = info_dataframe.append(info_list)\n info_dataframe_copy.rename(columns = {0: 'Name',1: 'Type',2: 'Shape' ,3: 'Size', 4:'DataType'}, inplace = True)\n print(\"DataFrame Created Successfully and saved as Task2.csv\")\n info_dataframe_copy.to_csv('Task2.csv', index = False)\n\ndef reshape_process_and_save(imagedata_dataset, imageheight_dataset, imagewidth_dataset,file_main):\n \"\"\" Function for reading data from path from h5py parser, reshaping\n 1-D array to 2-D array applying filter and saving as image.\n Parameters\n ----------\n imagedata_dataset: String\n Path to image data in hdf5 file\n imageheight_dataset: String\n Path to image height in hdf5 file\n imagewidth_dataset: String\n Path to image width in hdf5 file\n file_main : h5py object\n Object returned after hdf5 file opened with h5py\n \"\"\"\n image_1d = np.array(file_main.get(imagedata_dataset))\n height = list(file_main.get(imageheight_dataset))[0]\n width = list(file_main.get(imagewidth_dataset))[0]\n image_final = np.reshape(image_1d, (height,width))\n image_final_processed = scipy.signal.medfilt(image_final)\n print(\"Image Created Successfully and saved as Task3.png\")\n plt.imsave('Task3.png', image_final_processed)\n\ndef main():\n \"\"\"\n Main function to excecute all tasks\n \"\"\"\n global info_list, info_dataframe\n files = os.listdir()\n try:\n fname = [x for x in files if '.h5' in x][0]\n except:\n print(\"No hdf5 file found, Terminating\")\n sys.exit()\n time_nano = fname.split('_')[0]\n time_sec = float(time_nano)/(10**9)\n file_main = h5py.File(fname, 'r')\n info_dataframe = pd.DataFrame()\n info_list = []\n path_to_data = '/AwakeEventData/XMPP-STREAK/StreakImage/streakImageData'\n path_to_width = '/AwakeEventData/XMPP-STREAK/StreakImage/streakImageWidth'\n path_to_height = '/AwakeEventData/XMPP-STREAK/StreakImage/streakImageHeight'\n time_zone = \"Europe/Zurich\"\n print_time_for_timezone(time_zone,time_sec) #Task1\n make_dataframe_from_hdf5(file_main) #Task2\n reshape_process_and_save(path_to_data,path_to_height,path_to_width,file_main) #Task3\n file_main.close()\n\nif __name__ == '__main__':\n main()\n\n\n\n\n","sub_path":"Task_1_2_3.py","file_name":"Task_1_2_3.py","file_ext":"py","file_size_in_byte":4030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"344490257","text":"import os\nimport re\nimport sys\nimport webbrowser\nimport subprocess\nimport threading\nimport signal\n\nfrom setup import *\nimport python_core.lmk.lmk1.listeObject as listeObject\nimport python_core.lmk.lmk1.lmk1creator as lmk1creator\nimport python_core.lmk.lmk1.lmk1parser as lmk1parser\nfrom python_core.lmk.lmk1.viewer import LMK1Viewer\nfrom python_core.cutils import *\nfrom python_core import get_all_lmk_data\n\n# Fonctions\ndef get_files():\n\treturn get_all_lmk_data(LMK_DATA_DIR)\n\n\ndef get_file_by_str_id(str_id):\n\tliste = get_files()\n\treturn liste[int(str_id) - 1]\n\ndef get_file_path(filename):\n\treturn os.path.join(PATH_FOLDER_FILES_CREATED,filename)\n\ndef get_file_object_by_str_id(liste_id):\n\tfilename = get_file_by_str_id(liste_id)\n\tpath = get_file_path(filename)\n\tparser = lmk1parser.LMK1PARSER(path)\n\treturn parser.parse(), os.path.abspath(path)\n\n# Commandes\ndef view_all():\n\tprint(\"\\nListes:\",PATH_FOLDER_FILES_CREATED)\n\tshow_list(get_files())\n\ndef view(liste_id):\n\tliste, path = get_file_object_by_str_id(liste_id) \n\tprint(\"Fichier:{}\".format(path))\n\tLMK1Viewer.direct_viewer(liste)\n\ndef open_cmd(liste_id):\n\tliste, path = get_file_object_by_str_id(liste_id)\n\tcmd = \"python {} -f {}\".format(CONFIG[\"GUI_LMK_VIEWER\"],path)\n\tos.system(cmd)\n\ndef info(liste_id):\n\tliste, path = get_file_object_by_str_id(liste_id) \n\tprint(\"\\nID:\",liste_id)\n\tprint(\"Liste:\",path)\n\tprint(\"Colonnes:\",\", \".join(liste.get_cols()))\n\tprint(\"Nombres de lignes:\",liste.get_nbr_lines())\n\ndef create_liste_cmd(liste_name):\n\t# Créer de la liste: Définition des colonnes\n\tcols_csv_lite_str = input(\"Colonnes > \")\n\tif cols_csv_lite_str == \"@t\":\n\t\tcols = [\"A\",\"B\",\"C\"]\n\telse:\n\t\tcols = cols_csv_lite_str.split(lmk1creator.LMK1Creator.FORMAT_SEPARATOR)\n\tliste = listeObject.Liste(cols)\n\t# Sauvegarde view_table\n\tlmk_creator = lmk1creator.LMK1Creator(liste)\n\tlmk_creator.set_name(liste_name)\n\tsave_path = get_file_path(lmk_creator.get_filename())\n\tlmk_creator.save(save_path)\n\tprint(\"Liste {} créée.\".format(save_path))\n\ndef insert():\n\tglobal Manager\n\t# Ajout d'une ligne\n\tcols = Manager.liste_object_selected.get_cols() \n\tnbr_col = len(cols)\n\tindex_col = 0\n\tcan_save = True\n\tnew_lines = []\n\tprint(\"\\nChamps: \",' | '.join(cols))\n\twhile index_col < nbr_col: \n\t\tdata = input(\"{}: \".format(cols[index_col]))\n\t\tif data == \"@skip\":\n\t\t\tdata = \" \"\n\t\telif data == \"@stop\":\n\t\t\tcan_save = False\n\t\t\tbreak\n\t\telse:\n\t\t\tnew_lines.append(data) \n\t\tindex_col += 1\n\tif can_save == True:\n\t\tManager.liste_object_selected.add_line(new_lines)\n\t\tLMK1Viewer.direct_viewer(Manager.liste_object_selected)\n\t\tManager.liste_has_changed = True\t\n\ndef save():\n\tglobal Manager\n\tif Manager.liste_has_changed:\n\t\tlmk_creator = lmk1creator.LMK1Creator(Manager.liste_object_selected)\n\t\tlmk_creator.save(parser.get_path())\n\t\tprint(\"Modifications enregistrées\")\n\t\tManager.liste_has_changed = False\n\telse:\n\t\tprint(\"Aucune modification éffectuée\")\n\t\tinput(\"--OK--\")\n\ndef create_liste():\n\t# Créer de la liste: Définition des colonnes\n\tliste_name = input(\"Nom de la liste > \")\n\tcreate_liste_cmd(liste_name)\n\ndef del_cmd(liste_id):\n\tliste, path = get_file_object_by_str_id(liste_id) \n\tLMK1Viewer.direct_viewer(liste)\n\tprint(\"\\nVoulez vous vraiment supprimer cette liste ? (Oui/Non)\")\n\tuser_input = input(\"> \")\n\tif user_input == \"Oui\":\n\t\tos.remove(path)\n\t\tprint(\"Liste {} supprimée\".format(path))\n\telse:\n\t\tprint(\"\\nSupression annulée\")\n\n# Fin commandes\nliste_selected = \"\"\nliste_id_selected = \"\"\nliste_object_selected = None\nliste_has_changed = False\n\n# tests\nclass test:\n\t@classmethod\n\tdef cmd_open(cls):\n\t\tfiles = get_files()\n\t\tfiles_path = [os.path.abspath(get_file_path(filename)) for filename in files]\n\t\trtel1_file_path = files_path[4]\n\n\t\ttry:\n\t\t\topen(rtel1_file_path)\n\t\texcept FileNotFoundError:\n\t\t\tprint(\"Fichier introuvable: {}\".format(rtel1_file_path))\n\t\telse:\n\t\t\tcmd = \"python LmkViewer1.py open -f {}\".format(rtel1_file_path)\n\t\t\tos.system(cmd)\n\n\t@classmethod\n\tdef django_server(cls):\n\t\tos.system(\"start python CitySelector\\\\manage.py runserver\")\n\n\t@classmethod\n\tdef django_server_subprocess(cls):\n\t\tdef open_webviewer():\n\t\t\tp = subprocess.Popen([\"python\",\"CitySelector\\\\manage.py\",\"runserver\"], universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,shell=True)\n\t\t#threading.Thread(target=open_webviewer,args=()).start()\n\n\n\nclass CliManager:\n\tdef __init__(self):\n\t\tself.init()\n\n\tdef init(self):\n\t\tself.liste_selected = \"\"\n\t\tself.liste_id_selected = \"\"\n\t\tself.liste_object_selected = None\n\t\tself.liste_has_changed = False\n\nManager = CliManager()\n\ndef main():\n\tglobal Manager\n\n\tclear(\"ListMaker CLI 2\")\n\twhile True:\n\t\tif Manager.liste_selected:\n\t\t\tif Manager.liste_has_changed:\n\t\t\t\textra_tag = \"~ \"\n\t\t\telse:\n\t\t\t\textra_tag = \"\"\n\t\t\tprint(\"\\n{}Fichier: {}\".format(extra_tag,Manager.liste_selected))\n\t\t\tuser_input = input(\"> \")\n\t\telse:\n\t\t\tuser_input = input(\"\\n> \")\n\n\t\tif user_input == \"exit\":\n\t\t\tbreak\n\n\t\telif user_input == \"clear\":\n\t\t\tclear()\n\t\t\n\t\telif user_input == \"list\":\n\t\t\tview_all()\n\n\t\telif re.match(\"^select: (.)+\",user_input):\n\t\t\tManager.liste_id_selected = user_input[8:]\n\t\t\tManager.liste_selected = get_file_by_str_id(Manager.liste_id_selected)\n\t\t\tpath = get_file_path(Manager.liste_selected)\n\t\t\tparser = lmk1parser.LMK1PARSER(path)\n\t\t\tManager.liste_object_selected = parser.parse()\n\n\t\telif user_input == \"unselect\":\n\t\t\tManager.init()\n\n\t\telif re.match(\"^view: [0-9]+\",user_input):\n\t\t\tview(user_input[6:])\n\n\t\telif re.match(\"^open: [0-9]+\",user_input):\n\t\t\topen_cmd(user_input[6:])\n\n\t\telif re.match(\"^info: [0-9]+\",user_input):\n\t\t\tinfo(user_input[6:])\n\n\t\telif re.match(\"^create: (.)+\",user_input):\n\t\t\tprint(\"Nouvelle liste:\")\n\t\t\tcreate_liste_cmd(user_input[8:])\n\n\t\telif re.match(\"^del: [0-9]+\",user_input):\n\t\t\tdel_cmd(user_input[5:])\n\n\t\telif re.match(\"^runserver\",user_input):\n\t\t\tos.system(\"start python server\\\\manage.py runserver 0.0.0.0:8000\")\n\t\t\tprint(\"Serveur ListMaker lancé\")\n\t\t\turl\t= \"http://{host}/\".format(host=\"localhost:8000\")\n\t\t\twebbrowser.open(url)\n\n\t\telif Manager.liste_selected != \"\":\n\t\t\tif re.match(\"^view\",user_input):\n\t\t\t\tview(Manager.liste_id_selected)\n\t\t\telif re.match(\"^open\",user_input):\n\t\t\t\topen_cmd(Manager.liste_id_selected)\n\t\t\telif re.match(\"^info\",user_input):\n\t\t\t\tinfo(Manager.liste_id_selected)\n\t\t\telif re.match(\"^insert\",user_input):\n\t\t\t\tinsert()\n\t\t\telif re.match(\"^save\",user_input):\n\t\t\t\tsave()\n\t\t\telse:\n\t\t\t\tprint(\"Commande inconnue\")\n\t\telse:\n\t\t\tprint(\"Commande inconnue\")\n\nif __name__ == \"__main__\":\n\tmain()\n\t#get_all_lmk_data(LMK_DATA_DIR)","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":6438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"95685675","text":"try:\r\n # for Python2\r\n from Tkinter import *\r\nexcept ImportError:\r\n # for Python3\r\n from tkinter import *\r\n from tkinter import *\r\n import tkinter as tk\r\n from tkinter import ttk\r\n import tkinter.filedialog as fd\r\n\r\nimport threading\r\nimport queue\r\nimport time\r\nimport download as d\r\nimport utils as u\r\nimport htmlprocessor as h\r\n\r\n# TODO: using a listbox instead of a textarea to display messages\r\nclass MainWindow(tk.Tk):\r\n bookmarksFileLocation = None\r\n bookmarksFolderName = None\r\n\r\n # Window initialization\r\n root = Tk()\r\n root.title(\"Bookmarks to mp3\")\r\n root.resizable(width=False, height=False)\r\n\r\n # Main frame initialization\r\n mainframe = ttk.Frame(root, padding=\"3 3 12 12\")\r\n mainframe.grid(column=0, row=0, sticky=(N, W, E, S))\r\n mainframe.columnconfigure(0, weight=1)\r\n mainframe.rowconfigure(0, weight=1)\r\n\r\n # Row 1\r\n bookmarksLocationLabel = ttk.Label(mainframe)\r\n bookmarksLocationField = ttk.Entry(mainframe)\r\n fileBrowsingButton = ttk.Button(mainframe)\r\n # Row 2\r\n bookmarkFolderNameLabel = ttk.Label(mainframe)\r\n bookmarkFolderNameField = ttk.Entry(mainframe)\r\n # Row 3\r\n downloadButton = ttk.Button(mainframe)\r\n # Row 4\r\n totalProgress = ttk.Progressbar(mainframe)\r\n # Row 5\r\n currentVideoProgress = ttk.Progressbar(mainframe)\r\n # Row 6\r\n outputTextArea = Text(mainframe)\r\n\r\n\r\n\r\n def checkqueue(self):\r\n while self.queue.qsize():\r\n try:\r\n msg = self.queue.get(0)\r\n self.totalProgress.step(1)\r\n except Queue.Empty:\r\n print('empty')\r\n pass\r\n\r\n def periodiccall(self):\r\n self.checkqueue()\r\n if self.thread.is_alive():\r\n self.after(100, self.periodiccall)\r\n else:\r\n self.downloadButton.config(state=\"active\")\r\n\r\n\r\n def startDownload(self):\r\n print(\"File location : \" + self.bookmarksFileLocation.get())\r\n print(\"Folder name : \" + self.bookmarksFolderName.get())\r\n\r\n # File location then folder\r\n u.initializeVariables(self.bookmarksFileLocation.get(), self.bookmarksFolderName.get())\r\n\r\n # Opens and splits bookmarks file's content\r\n h.initBookmarks()\r\n # Fills videos list\r\n h.fillList()\r\n\r\n self.totalProgress[\"maximum\"] = u.howManyVideos()\r\n self.totalProgress[\"value\"] = 1\r\n # Starts downloads\r\n self.downloadButton.config(state=\"disabled\")\r\n self.thread = DownloadCaller(self.queue)\r\n self.thread.start()\r\n self.periodiccall()\r\n return\r\n\r\n def filename(self):\r\n filename = fd.askopenfilename( filetypes = ( (\"HTML files\", \"*.html;*.htm\"), (\"All files\", \"*.*\") ) )\r\n # open file on your own\r\n if filename:\r\n self.bookmarksFileLocation.set(filename)\r\n\r\n def __init__(self):\r\n tk.Tk.__init__(self)\r\n self.queue = queue.Queue()\r\n # test\r\n\r\n\r\n # Initializing variables that can be bound to an entry\r\n self.bookmarksFolderName = StringVar()\r\n self.bookmarksFileLocation = StringVar()\r\n\r\n # Row 1\r\n # Label next to the bookmarks location field\r\n self.bookmarksLocationLabel.configure(text=\"Bookmarks file location\")\r\n self.bookmarksLocationLabel.grid(column=1, row=1, sticky=E)\r\n\r\n # Bookmarks location field\r\n self.bookmarksLocationField.configure(width=30, textvariable=self.bookmarksFileLocation)\r\n self.bookmarksLocationField.grid(column=2, row=1, sticky=(W, E))\r\n\r\n # Button that's gonna show the file dialog\r\n self.fileBrowsingButton.configure(text=\"Browse files\", command=self.filename)\r\n self.fileBrowsingButton.grid(column=3, row=1, sticky=W)\r\n\r\n # Row 2\r\n # Music folder label\r\n self.bookmarkFolderNameLabel.configure(text=\"Bookmarks folder name\")\r\n self.bookmarkFolderNameLabel.grid(column=1, row=2, sticky=E)\r\n\r\n # Music folder name field\r\n self.bookmarkFolderNameField.configure(width=30, textvariable=self.bookmarksFolderName)\r\n self.bookmarkFolderNameField.grid(column=2, row=2, sticky=(W, E))\r\n\r\n # Row 3\r\n # Downloading button\r\n self.downloadButton.configure(text=\"Start downloading\", command=self.startDownload)\r\n self.downloadButton.grid(column=2, row=3)\r\n\r\n # Row 4\r\n # Initializes 1st progress bar with the frame length\r\n self.root.update()\r\n self.totalProgress.configure(orient=\"horizontal\", length=self.mainframe.winfo_width(), mode=\"determinate\" )\r\n self.totalProgress.grid(row=4, columnspan=4)\r\n\r\n # Row 5\r\n # Initializes 2nd progress bar with the frame length\r\n self.currentVideoProgress.configure(orient=\"horizontal\", length=self.mainframe.winfo_width(), mode=\"determinate\" )\r\n self.currentVideoProgress.grid(row=5, columnspan=4)\r\n\r\n # Row 6\r\n # Output text area\r\n self.outputTextArea.configure(height=5, state=DISABLED)\r\n self.outputTextArea.grid(column=1, row=6, columnspan=4)\r\n\r\n # Adding padding\r\n for child in self.mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)\r\n\r\n # Sets start position to the center of the display\r\n # Thanks xxmbabanexx !\r\n self.root.update()\r\n w = self.root.winfo_width()\r\n h = self.root.winfo_height()\r\n ws = self.root.winfo_screenwidth() # width of the screen\r\n hs = self.root.winfo_screenheight() # height of the screen\r\n\r\n # calculate x and y coordinates for the Tk root window\r\n x = (ws/2) - (w/2)\r\n y = (hs/2) - (h/2)\r\n\r\n # set the dimensions of the screen and where it is placed\r\n self.root.geometry('%dx%d+%d+%d' % (w, h, x, y))\r\n\r\n # GOGOGOGOGO\r\n self.root.mainloop()\r\n\r\n\r\nclass DownloadCaller(threading.Thread):\r\n\r\n def __init__(self, queue):\r\n threading.Thread.__init__(self)\r\n self.queue = queue\r\n\r\n def run(self):\r\n for i in range(0, u.howManyVideos()):\r\n d.DownloadVideo(i)\r\n msg = \" Video \" + str(i) + \" processed.\"\r\n self.queue.put(msg)\r\n print(\"thread's loop over, going for what's next\")\r\n # Creates the output bookmark file\r\n h.outputBookmarks()\r\n # After downloading, prints the errors if relevant\r\n u.errorsAssessment()\r\n # Removes video folder and closes errorlog file handler\r\n u.cleanup()\r\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":6516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"120986475","text":"\r\nimport json\r\nimport time\r\nimport datetime\r\nimport requests\r\nfrom kafka import KafkaProducer\r\nfrom sseclient import SSEClient as EventSource\r\n\r\n\r\ndef get_lang(language):\r\n if language =='en':\r\n language = 'English'\r\n elif language == 'de':\r\n language = 'German'\r\n elif language == 'fr':\r\n language = 'French'\r\n elif language == 'es':\r\n language = 'Spanish'\r\n elif language == 'ru':\r\n language = 'Russian'\r\n elif language == 'ja':\r\n language = 'Japanese'\r\n elif language == 'nl':\r\n language = 'Dutch'\r\n elif language == 'it':\r\n language = 'Italian'\r\n elif language == 'sv':\r\n language = 'Swedish'\r\n elif language == 'pl':\r\n language = 'Polish'\r\n elif language == 'vi':\r\n language = 'Vietnamese'\r\n elif language == 'pt':\r\n language = 'Portuguese'\r\n elif language == 'ar':\r\n language = 'Arabic'\r\n else:\r\n language = 'Other'\r\n return language\r\n\r\nurl = 'https://stream.wikimedia.org/v2/stream/recentchange'\r\n\r\nwikidata = 'wikidata'\r\nwiktionary = 'wiktionary'\r\nwikipedia = 'wikipedia'\r\nwikimedia = 'wikimedia'\r\n\r\nproducer = KafkaProducer(bootstrap_servers='localhost:9092')\r\ncounter = 0\r\n\r\nstart_time = time.time()\r\ndelay = 5\r\ndata = {'linechart': {'wikidata': 0, 'wiktionary': 0, 'wikipedia': 0, 'wikimedia': 0}, 'languages': {}, 'wordcloud': ''}\r\n\r\nfor event in EventSource(url):\r\n producer.send('test', value= json.dumps(event.data).encode('utf-8'))\r\n counter += 1\r\n \r\n if event.event == 'message':\r\n try:\r\n change = json.loads(event.data)\r\n except ValueError:\r\n continue\r\n \r\n if wikidata in change['server_url']:\r\n data['linechart'][wikidata] += 1\r\n\r\n if wiktionary in change['server_url']:\r\n data['linechart'][wiktionary] += 1\r\n\r\n if wikipedia in change['server_url']:\r\n data['linechart'][wikipedia] += 1\r\n data['wordcloud'] = data['wordcloud'] + ' ' + change['title']\r\n language = change['server_name'][:change['server_name'].find(wikipedia) - 1]\r\n language = get_lang(language)\r\n\r\n try:\r\n lang_count = data['languages'][language]\r\n data['languages'][language] += 1\r\n except:\r\n data['languages'][language] = 1\r\n \r\n\r\n if wikimedia in change['server_url']:\r\n data['linechart'][wikimedia] += 1\r\n\r\n if time.time() - start_time > delay:\r\n # sql = \"INSERT INTO {} (date,wiki_commons, wiki_data) VALUES (%s, %s,%s)\".format(table_name)\r\n # val = (str(datetime.datetime.now()), commonswiki_count,datawiki_count)\r\n # mycursor.execute(sql, val)\r\n try:\r\n requests.post('http://localhost:3001/post',json=data)\r\n except:\r\n pass\r\n# print(data)\r\n start_time = time.time()\r\n data = {'linechart': {'wikidata': 0, 'wiktionary': 0, 'wikipedia': 0, 'wikimedia': 0}, 'languages': {'English':0, 'German':0, 'French':0, 'Spanish':0, 'Russian':0, 'Russian':0, 'Japanese':0, 'Dutch':0, 'Italian':0, 'Swedish':0, 'Polish':0, 'Vietnamese':0, 'Portuguese':0 , 'Arabic':0, 'Other':0}, 'wordcloud': ''}\r\n # mydb.commit()\r\n\t\r\n\r\n\r\n\r\n","sub_path":"together/cassandra/mostafa-hosein/wikidemo.py","file_name":"wikidemo.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"119958487","text":"'''\nCreated on 23/03/2011\n\n@author: Michael Jensen\n'''\nimport sys\nimport pygame\nimport random\nfrom pprint import pprint\nfrom pygame.locals import * #@UnusedWildImport\n\n\nfrom .PlanetWars import PlanetWars\nfrom .Logger import Logger\n\n\n\n\n\n\nMAX_GAME_TICKS = 500\n\nGAME_SIZE = (500, 500)\nSCREEN_SIZE = (3 * GAME_SIZE[0], GAME_SIZE[1])\nCOLOUR = {\n \"0\": (200, 200, 200),\n \"1\": (255, 0, 0),\n \"2\": (0, 255, 0),\n \"3\": (0, 0, 255)\n}\nPLANET_MIN_R = 1\nPLANET_FACTOR = 0.1\nMARGIN = 20\nDISPLAY = True\n\nIMAGES = {}\n\nPLANET_ADDRES = './planets/planet%d.png'\nMAPS_ADDRES = './newmaps/%s.txt'\nBACKGROUND_IMAGE = \"./space.jpg\"\n\nclass Drawer():\n\n\n def __init__(self, world, display,list_of_planets, background=None,clock = None, offset=(0, 0)):\n self.world = world\n self.display = display\n self.list_of_planets = list_of_planets\n self.background = background\n self.clock = clock\n self.offset = offset\n self.list_rand_planets = {}\n\n self.display_size = []\n self.display_offset = []\n self.display_res = 0\n\n self.world_size = []\n self.world_offset = []\n self.world_res = 0\n self.factor = 0\n\n self.has_fog = False\n self.fog = None\n self.surf = None\n\n self._init_params()\n\n def _init_params(self):\n self.display_size = [\n self.display.get_size()[0] - (MARGIN * 2),\n self.display.get_size()[1] - (MARGIN * 2)\n ]\n self.display_offset = [\n self.offset[0] + MARGIN, self.offset[1] + MARGIN\n ]\n self.display_res = float(self.display_size[0]) / float(\n self.display_size[1])\n\n self.world_size = self.world.GetSize()\n self.world_offset = self.world.GetOffset()\n\n self.world_res = float(self.world_size[0]) / float(\n self.world_size[1])\n\n if self.world_res > self.display_res:\n self.display_offset[1] += int((self.display_size[1] - self.display_size[0] / self.world_res) / 2.0)\n self.display_size[1] = self.display_size[0] / self.world_res\n else:\n self.display_offset[0] += int((self.display_size[0] - self.display_size[1] * self.world_res) / 2.0)\n self.display_size[0] = self.display_size[1] * self.world_res\n\n self.background = pygame.transform.scale(self.background, (int(self.display_size[0]),\n int(self.display_size[1])) )\n self.factor = (float(self.display_size[0]) / float(self.world_size[0]))\n self.surf = pygame.Surface(self.display_size)\n\n\n for p in self.world.Planets():\n randPl = self.list_of_planets[p.ID()]\n plimg = pygame.image.load(PLANET_ADDRES % randPl)\n plimg = plimg.convert_alpha()\n self.list_rand_planets[p.ID()] = plimg\n\n self.has_fog = self.world.PlayerID() != 0\n self.fog = pygame.Surface(self.display_size, flags=SRCALPHA)\n\n def colorize(self, image, newColor):\n\n image = image.copy()\n # zero out RGB values\n image.fill(newColor + (255,), None, pygame.BLEND_RGBA_MULT)\n # add in new RGB values\n #image.fill(newColor[0:3], None, pygame.BLEND_RGB_ADD)\n\n return image\n\n def draw_planets(self):\n for p in self.world.Planets():\n radius = int((PLANET_MIN_R * self.factor) +\n ((PLANET_FACTOR * self.factor) * p.GrowthRate()))\n screen_x = int(float(p.X() + self.world_offset[0]) * self.factor)\n screen_y = int(float(p.Y() + self.world_offset[1]) * self.factor)\n #pygame.draw.circle(self.surf, COLOUR[p.Owner()], (screen_x, screen_y), radius)\n plimg = self.list_rand_planets[p.ID()]\n plimg = pygame.transform.scale(plimg, (2*radius ,2*radius))\n plimg = self.colorize(plimg, COLOUR[p.Owner()])\n self.surf.blit(plimg, (screen_x - radius, screen_y-radius))\n if ((p.Owner() == self.world.PlayerID()) and self.has_fog):\n pygame.draw.circle(self.fog, (0, 0, 0, 0), (screen_x,\n screen_y),\n int(p.VisionRange() * self.factor))\n text = pygame.font.Font(None, 20).render(\n str(p.NumShips()), False, (255,255,255))\n text_pos = (screen_x - (text.get_width() / 2),\n screen_y - (text.get_height() / 2))\n self.surf.blit(text, text_pos)\n pid = pygame.font.Font(None, 18).render(\n str(p.ID()), False, (255, 255, 255))\n self.surf.blit(pid, (screen_x - radius, screen_y - radius))\n\n def draw_fleet(self):\n for f in self.world.Fleets():\n screen_x = int(float(f.X() + self.world_offset[0]) * self.factor)\n screen_y = int(float(f.Y() + self.world_offset[1]) * self.factor)\n text = pygame.font.Font(None, 16).render(\n str(f.NumShips()), False, COLOUR[f.Owner()])\n text_pos = (screen_x - (text.get_width() / 2),\n screen_y - (text.get_height() / 2))\n self.surf.blit(text, text_pos)\n if ((f.Owner() == self.world.PlayerID()) and self.has_fog):\n pygame.draw.circle(self.fog, (0, 0, 0, 0), (screen_x,\n screen_y),\n int(f.VisionRange() * self.factor))\n\n def draw(self):\n self.surf.fill((128, 128, 128, 0))\n self.surf.blit(self.background, (0,0))\n self.fog.fill((128, 128, 128, 0))\n self.draw_fleet()\n self.draw_planets()\n if (self.has_fog):\n self.surf.blit(self.fog, (0, 0), special_flags=BLEND_SUB)\n self.surf.blit(\n pygame.font.Font(None, 22).render(\n str(self.world.CurrentTick()), False, (255, 255, 255)), \n (20, 20))\n self.surf.blit(\n pygame.font.Font(None, 22).render(\n str(self.clock.get_fps()), False, (255, 255, 255)),\n (self.display_size[0] - 20, self.display_size[1] - 20))\n self.display.blit(self.surf, self.display_offset)\n pygame.display.update()\n\n\ndef do_game(\n game_id, # int\n logger, # Logger()\n p1, # BasePlayer()\n p2, # BasePlayer()\n pw, # PlanetWars()\n show_gui=False, # bool\n):\n\n #we want to:\n # - Load the map\n # - instantiate two players (objects that respond to player.DoTurn(PlanetWars)\n # (we'll substitute a \"real\" planetwars object above with a proxy for each\n # player. This proxy will have an output queue of commands rather than dealing with\n # stdio)\n # - instantiate two proxies, which will remember what the player knows,\n # rather than the actual state of the game.\n\n #then, while not [victory conditions]\n # - get an array of moves from p1's proxy world\n # - get an array of moves from p2's proxy world\n # - apply the moves to the world\n # - update each proxy with the real world\n # - render the current state\n # - pause for framerate?\n\n p1Proxy = pw.MakeProxy(\"1\", logger.p1log)\n p2Proxy = pw.MakeProxy(\"2\", logger.p2log)\n fps = 4\n if show_gui:\n pygame.init()\n view = 'world'\n if view == 'all':\n window_size = SCREEN_SIZE\n else:\n window_size = GAME_SIZE\n\n screen = pygame.display.set_mode(window_size, 0, 32)\n background = pygame.image.load(BACKGROUND_IMAGE).convert_alpha()\n clock = pygame.time.Clock()\n paused = True\n list_of_planets = {p.ID():random.randint(1,18) for p in pw.Planets()}\n p1view = Drawer(p1Proxy, screen, list_of_planets, background, clock, )\n p2view = Drawer(p2Proxy, screen, list_of_planets, background, clock)\n pwview = Drawer(pw, screen, list_of_planets, background, clock)\n #allview = Drawer()\n else:\n paused = False\n\n #min_100_ships = lambda p, pw: 100\n #p1 = VariableAggressionPlayer(0.2, min_100_ships)\n #p2 = VariableAggressionPlayer(0.2, min_100_ships)\n \n\n while pw.IsAlive(p1Proxy.PlayerID()) and \\\n pw.IsAlive(p2Proxy.PlayerID()) and \\\n pw.CurrentTick() < MAX_GAME_TICKS:\n onestep = False\n if show_gui:\n \n for event in pygame.event.get():\n if event.type == QUIT:\n return\n if event.type == KEYDOWN:\n if event.key == K_p:\n paused = not paused\n elif (event.key == K_PLUS) or (event.key == K_EQUALS):\n fps = fps + 1\n elif event.key == K_MINUS:\n fps = fps - 1\n if fps < 1: fps = 1\n elif event.key == K_n:\n onestep = True\n elif event.key == K_a:\n if (view != 'all'):\n screen = pygame.display.set_mode(\n SCREEN_SIZE, 0, 32)\n view = 'all'\n elif event.key == K_e:\n if (view != 'world'):\n screen = pygame.display.set_mode(GAME_SIZE, 0, 32)\n view = 'world'\n elif event.key == K_1:\n if (view != 'p1'):\n screen = pygame.display.set_mode(GAME_SIZE, 0, 32)\n view = 'p1'\n elif event.key == K_2:\n if (view != 'p2'):\n screen = pygame.display.set_mode(GAME_SIZE, 0, 32)\n view = 'p2'\n if (view == 'world'):\n pwview.draw()\n elif (view == 'p1'):\n p1view.draw()\n elif (view == 'p2'):\n p2view.draw()\n elif (view == 'all'):\n pass\n\n # draw(p1Proxy, screen,background,(-GAME_SIZE[0],0))\n # draw(pw, screen, background, (0,0))\n # draw(p2Proxy, screen, background, )\n time_passed = clock.tick(fps)\n\n if ((not paused) or onestep):\n p1.DoTurn(p1Proxy)\n p2.DoTurn(p2Proxy)\n pw.ProcessOrders(p1Proxy.PlayerID(), p1Proxy._GetOrders())\n pw.ProcessOrders(p2Proxy.PlayerID(), p2Proxy._GetOrders())\n\n p1Proxy._ClearOrders()\n p2Proxy._ClearOrders()\n\n pw.Tick()\n\n p1Proxy._Update(pw)\n p2Proxy._Update(pw)\n\n if p1Proxy.TotalShips() == p2Proxy.TotalShips():\n #tie\n winner = \"no\"\n elif p1Proxy.TotalShips() > p2Proxy.TotalShips():\n #p1 wins!\n winner = p1.__module__.split('.')[1] # Player.BotName\n else:\n #p2 wins!\n winner = p2.__module__.split('.')[1]\n\n logger.result(\"Game {0}: {1} victory at turn {2} \\n {3}: {4}, {5}: {6}\".\n format(game_id, winner,\n pw.CurrentTick(), p1.__module__.split('.')[1],\n p1Proxy.TotalShips(), p2.__module__.split('.')[1], p2Proxy.TotalShips()))\n logger.data(\"{0}:{1}:{2}:{3}:{4},{5}:{6},{7}\".format(\n game_id, pw._gameid, winner,\n pw.CurrentTick(), p1.__module__.split('.')[1],\n p1Proxy.TotalShips(), p2.__module__.split('.')[1], p2Proxy.TotalShips()))\n return 1\n\n\n\nif __name__ == '__main__':\n log = Logger('./Log/')\n try:\n #import the two players\n from .Players.VariableAggressionPlayer import VariableAggressionPlayer\n from .Players.Dave2Player import Dave2Player\n from .Players.Dave2Player_old import Dave2Player_old\n from .Players.ScoutPlayer import ScoutPlayer\n bot1 = Dave2Player() #your player!\n bot2 = Dave2Player_old()\n\n pw = PlanetWars(open(MAPS_ADDRES % sys.argv[1]).read(), logger=log.turn)\n do_game(1, log, bot1, bot2, pw, show_gui=True)\n except KeyboardInterrupt:\n print('ctrl-c, leaving ...')\n finally:\n log.flush()\n","sub_path":"src/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":12179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"108948982","text":"import datetime\nimport json\nimport shelve\nimport sys\n\nimport torch\nfrom sklearn.linear_model import SGDClassifier\nfrom vowpalwabbit import pyvw\n\nfrom river import (\n base,\n compat,\n drift,\n dummy,\n ensemble,\n evaluate,\n linear_model,\n metrics,\n naive_bayes,\n neighbors,\n)\nfrom river import neural_net as nn\nfrom river import optim, preprocessing, rules, stats, tree\n\n\ndef run_track(models, track, benchmarks):\n print(track.name)\n if track.name in benchmarks:\n completed = set((cr[\"Dataset\"], cr[\"Model\"]) for cr in benchmarks[track.name])\n else:\n completed = set()\n\n for model_name, model in models.items():\n print(f\"\\t{model_name}\")\n for dataset in track:\n data_name = dataset.__class__.__name__\n if (data_name, model_name) in completed:\n print(f\"\\t\\t[skipped] {data_name}\")\n continue\n # Get cached data from the shelf\n if track.name in benchmarks:\n results = benchmarks[track.name]\n else:\n results = []\n res = next(track.run(model, dataset, n_checkpoints=1))\n res[\"Dataset\"] = data_name\n res[\"Model\"] = model_name\n for k, v in res.items():\n if isinstance(v, metrics.base.Metric):\n res[k] = v.get()\n res[\"Time\"] = res[\"Time\"] / datetime.timedelta(milliseconds=1)\n res.pop(\"Step\")\n results.append(res)\n\n # Writes updated version to the shelf\n benchmarks[track.name] = results\n print(f\"\\t\\t[done] {data_name}\")\n\n\ntracks = [\n evaluate.BinaryClassificationTrack(),\n evaluate.MultiClassClassificationTrack(),\n evaluate.RegressionTrack(),\n]\n\n\nclass PyTorchLogReg(torch.nn.Module):\n def __init__(self, n_features):\n super().__init__()\n self.linear = torch.nn.Linear(n_features, 1)\n self.sigmoid = torch.nn.Sigmoid()\n torch.nn.init.constant_(self.linear.weight, 0)\n torch.nn.init.constant_(self.linear.bias, 0)\n\n def forward(self, x):\n return self.sigmoid(self.linear(x))\n\n\nclass PyTorchModel:\n def __init__(self, network_func, loss, optimizer_func):\n self.network_func = network_func\n self.loss = loss\n self.optimizer_func = optimizer_func\n\n self.network = None\n self.optimizer = None\n\n def learn_one(self, x, y):\n\n # We only know how many features a dataset contains at runtime\n if self.network is None:\n self.network = self.network_func(n_features=len(x))\n self.optimizer = self.optimizer_func(self.network.parameters())\n\n x = torch.FloatTensor(list(x.values()))\n y = torch.FloatTensor([y])\n\n y_pred = self.network(x)\n loss = self.loss(y_pred, y)\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n return self\n\n\nclass PyTorchBinaryClassifier(PyTorchModel, base.Classifier):\n def predict_proba_one(self, x):\n\n # We only know how many features a dataset contains at runtime\n if self.network is None:\n self.network = self.network_func(n_features=len(x))\n self.optimizer = self.optimizer_func(self.network.parameters())\n\n x = torch.FloatTensor(list(x.values()))\n p = self.network(x).item()\n return {True: p, False: 1.0 - p}\n\n\nclass VW2RiverBase:\n def __init__(self, *args, **kwargs):\n self.vw = pyvw.Workspace(*args, **kwargs)\n\n def _format_x(self, x):\n return \" \".join(f\"{k}:{v}\" for k, v in x.items())\n\n\nclass VW2RiverClassifier(VW2RiverBase, base.Classifier):\n def learn_one(self, x, y):\n\n # Convert {False, True} to {-1, 1}\n y = int(y)\n y_vw = 2 * y - 1\n\n ex = self._format_x(x)\n ex = f\"{y_vw} | {ex}\"\n self.vw.learn(ex)\n return self\n\n def predict_proba_one(self, x):\n ex = \"| \" + self._format_x(x)\n y_pred = self.vw.predict(ex)\n return {True: y_pred, False: 1.0 - y_pred}\n\n\nLEARNING_RATE = 0.005\n\nmodels = {\n \"Binary classification\": {\n \"Logistic regression\": (\n preprocessing.StandardScaler()\n | linear_model.LogisticRegression(optimizer=optim.SGD(LEARNING_RATE))\n ),\n \"ALMA\": preprocessing.StandardScaler() | linear_model.ALMAClassifier(),\n \"Stochastic Gradient Tree\": tree.SGTClassifier(),\n \"sklearn SGDClassifier\": (\n preprocessing.StandardScaler()\n | compat.SKL2RiverClassifier(\n SGDClassifier(\n loss=\"log_loss\", learning_rate=\"constant\", eta0=LEARNING_RATE, penalty=\"none\"\n ),\n classes=[False, True],\n )\n ),\n \"PyTorch logistic regression\": (\n preprocessing.StandardScaler()\n | PyTorchBinaryClassifier(\n network_func=PyTorchLogReg,\n loss=torch.nn.BCELoss(),\n optimizer_func=lambda params: torch.optim.SGD(params, lr=LEARNING_RATE),\n )\n ),\n \"Vowpal Wabbit logistic regression\": VW2RiverClassifier(\n sgd=True,\n learning_rate=LEARNING_RATE,\n loss_function=\"logistic\",\n link=\"logistic\",\n adaptive=False,\n normalized=False,\n invariant=False,\n l2=0.0,\n l1=0.0,\n power_t=0,\n quiet=True,\n ),\n },\n \"Multiclass classification\": {\n \"Naive Bayes\": naive_bayes.GaussianNB(),\n \"Hoeffding Tree\": tree.HoeffdingTreeClassifier(),\n \"Hoeffding Adaptive Tree\": tree.HoeffdingAdaptiveTreeClassifier(seed=42),\n \"Extremely Fast Decision Tree\": tree.ExtremelyFastDecisionTreeClassifier(),\n \"Adaptive Random Forest\": ensemble.AdaptiveRandomForestClassifier(seed=42),\n \"Streaming Random Patches\": ensemble.SRPClassifier(),\n \"k-Nearest Neighbors\": preprocessing.StandardScaler()\n | neighbors.KNNClassifier(window_size=100),\n \"ADWIN Bagging\": ensemble.ADWINBaggingClassifier(tree.HoeffdingTreeClassifier(), seed=42),\n \"AdaBoost\": ensemble.AdaBoostClassifier(tree.HoeffdingTreeClassifier(), seed=42),\n \"Bagging\": ensemble.BaggingClassifier(\n tree.HoeffdingAdaptiveTreeClassifier(bootstrap_sampling=False),\n seed=42\n ),\n \"Leveraging Bagging\": ensemble.LeveragingBaggingClassifier(\n tree.HoeffdingTreeClassifier(), seed=42\n ),\n \"Stacking\": ensemble.StackingClassifier(\n [\n preprocessing.StandardScaler() | linear_model.SoftmaxRegression(),\n naive_bayes.GaussianNB(),\n tree.HoeffdingTreeClassifier(),\n preprocessing.StandardScaler() | neighbors.KNNClassifier(window_size=100),\n ],\n meta_classifier=ensemble.AdaptiveRandomForestClassifier(seed=42),\n ),\n \"Voting\": ensemble.VotingClassifier(\n [\n preprocessing.StandardScaler() | linear_model.SoftmaxRegression(),\n naive_bayes.GaussianNB(),\n tree.HoeffdingTreeClassifier(),\n preprocessing.StandardScaler() | neighbors.KNNClassifier(window_size=100),\n ]\n ),\n # Baseline\n \"[baseline] Last Class\": dummy.NoChangeClassifier(),\n },\n \"Regression\": {\n \"Linear Regression\": preprocessing.StandardScaler() | linear_model.LinearRegression(),\n \"Linear Regression with l1 regularization\": preprocessing.StandardScaler()\n | linear_model.LinearRegression(l1=1.0),\n \"Linear Regression with l2 regularization\": preprocessing.StandardScaler()\n | linear_model.LinearRegression(l2=1.0),\n \"Passive-Aggressive Regressor, mode 1\": preprocessing.StandardScaler()\n | linear_model.PARegressor(mode=1),\n \"Passive-Aggressive Regressor, mode 2\": preprocessing.StandardScaler()\n | linear_model.PARegressor(mode=2),\n \"k-Nearest Neighbors\": preprocessing.StandardScaler()\n | neighbors.KNNRegressor(window_size=100),\n \"Hoeffding Tree\": preprocessing.StandardScaler() | tree.HoeffdingTreeRegressor(),\n \"Hoeffding Adaptive Tree\": preprocessing.StandardScaler()\n | tree.HoeffdingAdaptiveTreeRegressor(seed=42),\n \"Stochastic Gradient Tree\": tree.SGTRegressor(),\n \"Adaptive Random Forest\": preprocessing.StandardScaler()\n | ensemble.AdaptiveRandomForestRegressor(seed=42),\n \"Adaptive Model Rules\": preprocessing.StandardScaler()\n | rules.AMRules(),\n \"Streaming Random Patches\": preprocessing.StandardScaler() | ensemble.SRPRegressor(seed=42),\n \"Bagging\": preprocessing.StandardScaler() | ensemble.BaggingRegressor(\n model=tree.HoeffdingAdaptiveTreeRegressor(bootstrap_sampling=False),\n seed=42\n ),\n \"Exponentially Weighted Average\": preprocessing.StandardScaler()\n | ensemble.EWARegressor(\n models=[\n linear_model.LinearRegression(),\n tree.HoeffdingAdaptiveTreeRegressor(),\n neighbors.KNNRegressor(window_size=100),\n rules.AMRules(),\n ],\n ),\n \"Multi-layer Perceptron\": preprocessing.StandardScaler()\n | nn.MLPRegressor(\n hidden_dims=(5,),\n activations=(\n nn.activations.ReLU,\n nn.activations.ReLU,\n nn.activations.Identity,\n ),\n optimizer=optim.SGD(1e-3),\n seed=42,\n ),\n # Baseline\n \"[baseline] Mean predictor\": dummy.StatisticRegressor(stats.Mean()),\n },\n}\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1 and sys.argv[1] == \"force\":\n benchmarks = shelve.open(\"results\", flag=\"n\")\n else:\n benchmarks = shelve.open(\"results\", flag=\"c\")\n\n # Every multiclass model can also handle binary classification\n models[\"Binary classification\"].update(models[\"Multiclass classification\"])\n details = {}\n\n for track in tracks:\n run_track(models=models[track.name], track=track, benchmarks=benchmarks)\n details[track.name] = {\"Dataset\": {}, \"Model\": {}}\n for dataset in track.datasets:\n details[track.name][\"Dataset\"][dataset.__class__.__name__] = repr(dataset)\n for model_name, model in models[track.name].items():\n details[track.name][\"Model\"][model_name] = repr(model)\n\n log = {}\n for track in tracks:\n log[track.name] = benchmarks[track.name]\n\n with open(\"results.json\", \"w\") as f:\n json.dump(log, f, sort_keys=True, indent=4)\n\n # Close the shelf\n benchmarks.close()\n\n with open(\"details.json\", \"w\") as f:\n json.dump(details, f, sort_keys=True, indent=4)\n","sub_path":"benchmarks/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":10811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"139967530","text":"import os\nfrom .settings import BASE_DIR\n\nDEBUG = True\n\nCSRF_COOKIE_SECURE = False\nSESSION_COOKIE_SECURE = False\nSECURE_SSL_REDIRECT = False\n\n# https://docs.djangoproject.com/en/1.10/ref/databases/#caveats\n\nDEBUG_TOOLBAR_CONFIG = {\n 'SHOW_COLLAPSED': True,\n}\n\n# If INTERNAL_IPS becomes a problem, can override SHOW_TOOLBAR_CALLBACK function\n# See https://django-debug-toolbar.readthedocs.io/en/stable/configuration.html#debug-toolbar-config\nINTERNAL_IPS = ['127.0.0.1', 'localhost']\nCORS_ORIGIN_ALLOW_ALL = True\nALLOWED_HOSTS = ['*']\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n }\n}\nEMAIL_HOST = 'smtp.mailtrap.io'\nEMAIL_HOST_USER = 'c2d573d0bb5e43'\nEMAIL_HOST_PASSWORD = '8ba6f95986c533'\nEMAIL_PORT = '2525'","sub_path":"targendaapi/settings/local_settings.py","file_name":"local_settings.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"237965391","text":"n, k = map(int, input().split())\nratingArray = [int(x) for x in input().split()]\nuniqueRating = []\nindex = []\nfor i in range(n):\n if ratingArray[i] not in uniqueRating:\n uniqueRating.append(ratingArray[i])\n index.append(i+1)\nif len(uniqueRating) >= k:\n print(\"YES\")\n for i in range(k):\n print(index[i], end=\" \")\nelse: print(\"NO\")\n","sub_path":"Week01-Intro/988A.py","file_name":"988A.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"219707517","text":"import tensorflow as tf\nimport numpy as np\nimport sys\nfrom PIL import Image\n\ndef LoadVGG16():\n\treturn tf.keras.applications.vgg16.VGG16(include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000)\n\ndef CheckImgData(img):\n\tprint(img.format, img.size, img.mode)\n\timg.show()\n\n\n# -- AAA -- #\n# check image file\nif len(sys.argv) != 2:\n\tprint(\"python *.py [image_file]\")\n\tsys.exit(1)\n\n# Load VGG16 model\nmodel = LoadVGG16()\n\n# Resize image to fit VGG16 model\nfile_name = sys.argv[1]\nimg = tf.keras.preprocessing.image.load_img(file_name, target_size=(224,224))\n\n# Transform image to PIL-array\nimg_array = tf.keras.preprocessing.image.img_to_array(img)\n# 3-dim-tensor(rows,cols,channels) to 4-dim-tensor(samples, rows, cols, channels)\nimg_data = np.expand_dims(img_array, axis=0)\n\n# Predict class\npreds = model.predict(tf.keras.applications.vgg16.preprocess_input(img_data))\n# Transform class to label\nresults = tf.keras.applications.vgg16.decode_predictions(preds, top=5)[0]\nfor result in results:\n\tprint(result)\n","sub_path":"vgg16/predict_vgg16.py","file_name":"predict_vgg16.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"493836547","text":"arq = open('mat.txt')\r\nq = arq.read()\r\nmat = q.split('\\n')\r\nprint(q)\r\nmat2 = []\r\nmatriz = ''\r\nstate = 'lendo'\r\n\r\nfor i in range (len(mat)):\r\n line = []\r\n j = 0\r\n while j < len(mat[i]) - 1:\r\n if state == 'lendo':\r\n if mat[i][j] == '1':\r\n line.append(1)\r\n j += 1\r\n if mat[i][j] == '0':\r\n line.append(0)\r\n state = 'prenchendo'\r\n j += 1\r\n if state == 'prenchendo':\r\n if mat[i][j] == '1':\r\n line.append(0)\r\n j += 1\r\n if mat[i][j] == '0':\r\n line.append(0)\r\n state = 'lendo'\r\n j += 1\r\n mat2.append(line)\r\n \r\n","sub_path":"ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"219042778","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nINTEL CONFIDENTIAL\nCopyright 2017-2020 Intel Corporation.\nThis software and the related documents are Intel copyrighted materials, and\nyour use of them is governed by the express license under which they were\nprovided to you (License).Unless the License provides otherwise, you may not\nuse, modify, copy, publish, distribute, disclose or transmit this software or\nthe related documents without Intel's prior written permission.\n\nThis software and the related documents are provided as is, with no express or\nimplied warranties, other than those that are expressly stated in the License.\n\"\"\"\n\nfrom ..utils import parse_json_str\nfrom ..LibException import DependencyException\nfrom ..UniqueKey import UniqueKey, VersionedName\nfrom ..LibConfig import LibConfig\n\n\nclass Dependency:\n tag = None\n value_list = None\n bit_low = None\n bit_high = None\n src_setting_ref = None\n dst_setting_ref = None\n referenced_set_name = None\n setting_property = None\n unique_key = None\n\n class Tags:\n getTag = \"get\"\n switchTag = \"switch\"\n setTag = \"set\"\n pathTag = \"path\"\n bitLowTag = \"bit_low\"\n bitHighTag = \"bit_high\"\n sourceTag = \"source\"\n valueListTag = \"value_list\"\n defaultTag = \"default\"\n\n def __init__(self, properties, owner_setting_ref, is_duplicate=False):\n self.owner_setting_ref = owner_setting_ref\n self.is_duplicate = is_duplicate\n\n # If 'properties' is of type str then assume that it's simply a path to some other setting\n if isinstance(properties, str):\n self._parse_referenced_setting_path(properties)\n elif isinstance(properties, dict):\n self._parse_properties_dict(properties)\n else:\n raise DependencyException(f\"Unsupported type of dependency properties: {type(properties).__name__} \"\n f\"for dependency: {self.tag}\", self)\n\n def _parse_referenced_setting_path(self, path):\n if not path.strip():\n raise DependencyException(f\"Specified dependency path cannot be empty, in dependency: {self.tag}\", self)\n parts = path.split(LibConfig.pathSeparator)\n self.referenced_set_name, self.setting_property, self.unique_key = self._parse_dependency_path(parts)\n\n def _parse_dependency_path(self, parts):\n plug_key = VersionedName()\n cont_key = VersionedName()\n\n if len(parts) == 3: # parse plugin_key/cont_key/setting\n plug_key = VersionedName(name_ver=parts[0])\n cont_key = VersionedName(name_ver=parts[1])\n set_subparts = parts[2].rsplit(\".\", maxsplit=1)\n elif len(parts) == 2: # parse cont_key/setting\n cont_key = VersionedName(name_ver=parts[0])\n set_subparts = parts[1].rsplit(\".\", maxsplit=1)\n elif len(parts) == 1: # parse this/setting\n set_subparts = parts[0].rsplit(\".\", maxsplit=1)\n else:\n raise DependencyException(f\"Failed to parse dependency: {parts}\", self)\n\n set_name = set_subparts[0]\n set_property = set_subparts[1] if len(set_subparts) == 2 else None\n unique_key = UniqueKey(cont_key, plug_key)\n return set_name, set_property, unique_key\n\n def _parse_properties_dict(self, properties):\n if self.Tags.pathTag not in properties:\n raise DependencyException(f\"{self.Tags.pathTag} is missing from dependency: {self.tag}\", self)\n self._parse_referenced_setting_path(properties[self.Tags.pathTag])\n if self.Tags.bitLowTag in properties or self.Tags.bitHighTag in properties:\n if self.Tags.bitLowTag not in properties or self.Tags.bitHighTag not in properties:\n raise DependencyException(f\"Both {self.Tags.bitLowTag} and {self.Tags.bitHighTag} must be specified if \"\n f\"at least one of them is given\", self)\n self.bit_low = properties[self.Tags.bitLowTag]\n self.bit_high = properties[self.Tags.bitHighTag]\n\n if self.bit_low > self.bit_high:\n raise DependencyException(f\"{self.Tags.bitLowTag} cannot be greater then {self.Tags.bitHighTag}\", self)\n\n def set_referenced_setting(self, referenced_setting_ref):\n if self.get_bit_count() and (not isinstance(referenced_setting_ref.get_default_value(), int) or\n not isinstance(self.owner_setting_ref.get_default_value(), int)):\n raise DependencyException(\"Bit range can be applied only to numbers\", self)\n self._set_referenced_setting(referenced_setting_ref)\n\n def _set_referenced_setting(self, referenced_setting_ref):\n self.dst_setting_ref = self.owner_setting_ref\n self.src_setting_ref = referenced_setting_ref\n\n def get_bit_count(self) -> (int, None):\n if self.bit_low is not None and self.bit_high is not None:\n return self.bit_high - self.bit_low + 1\n return None\n\n def execute(self):\n raise DependencyException(f\"Not implemented - {type(self)} is abstract and cannot be instantiated\", self)\n\n def set_default_value(self):\n raise DependencyException(f\"Not implemented - {type(self)} is abstract and cannot be instantiated\", self)\n\n @staticmethod\n def get_bits_name(setting_ref):\n if setting_ref.has_dependencies():\n try:\n dependency_dict = parse_json_str(setting_ref.dependency_formula)[0]['get']\n source = dependency_dict['path']\n if source.endswith('.value'):\n return '{} [{}:{}]'.format(source[:-6], dependency_dict['bit_low'], dependency_dict['bit_high'])\n except (IndexError, KeyError, TypeError):\n return None\n return None\n\n def inconsistency_warn(self):\n return f'Warning: inconsistency of input values. \"{self.destination_name}\" will be overwritten by \"{self.source_name}\".'\n","sub_path":"Intel/EagleStreamRpPkg/Tool/FTool/SPS/Tools/FlashImageTool/FITm_Python_Version/library/tool/dependencies/Dependency.py","file_name":"Dependency.py","file_ext":"py","file_size_in_byte":5984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"172713615","text":"from pathlib import Path\nimport logging\nfrom src.plotting.plot_tools import (\n add_plot_directory,\n remove_plot_directory,\n get_plot_directories,\n)\nfrom src.plotting.create_plots import create_plots\nfrom src.plotting.check_plots import check_plots\nfrom src.util.logging import initialize_logging\n\n\nlog = logging.getLogger(__name__)\n\n\ncommand_list = [\"create\", \"check\", \"add\", \"remove\", \"show\"]\n\n\ndef help_message():\n print(\"usage: chia plots command\")\n print(f\"command can be any of {command_list}\")\n print(\"\")\n print(\n \"chia plots create -k [size] -n [number of plots] -b [memory buffer size MiB]\"\n + \" -r [number of threads] -u [number of buckets] -s [stripe size]\"\n + \" -a [fingerprint] -f [farmer public key] -p [pool public key]\"\n + \" -t [tmp dir] -2 [tmp dir 2] -d [final dir] (creates plots)\"\n )\n print(\"-e disables bitfield plotting\")\n print(\"-x skips adding [final dir] to harvester for farming\")\n print(\"-i [plotid] -m [memo] are available for debugging\")\n print(\"chia plots check -n [challenges] -g [string] -l (checks plots)\")\n print(\" Default: check all plots in every directory with 30 challenges\")\n print(\" -n: number of challenges; 0 = skip opening plot files; can be used with -l\")\n print(\" -g: checks plots with file or directory name containing [string]\")\n print(\" -l: list plots with duplicate IDs\")\n print(\" Debugging options for chia plots check\")\n print(\" --debug-show-memo: shows memo to recreate the same exact plot\")\n print(\" --challenge-start [start]: begins at a different [start] for -n [challenges]\")\n print(\"chia plots add -d [directory] (adds a directory of plots)\")\n print(\"chia plots remove -d [directory] (removes a directory of plots from config)\")\n print(\"chia plots show (shows the directory of current plots)\")\n\n\ndef make_parser(parser):\n parser.add_argument(\"-k\", \"--size\", help=\"Plot size\", type=int, default=32)\n parser.add_argument(\"-n\", \"--num\", help=\"Number of plots or challenges\", type=int, default=None)\n parser.add_argument(\"-b\", \"--buffer\", help=\"Mebibytes for sort/plot buffer\", type=int, default=4608)\n parser.add_argument(\"-r\", \"--num_threads\", help=\"Number of threads to use\", type=int, default=2)\n parser.add_argument(\"-u\", \"--buckets\", help=\"Number of buckets\", type=int, default=0)\n parser.add_argument(\"-s\", \"--stripe_size\", help=\"Stripe size\", type=int, default=0)\n parser.add_argument(\n \"-a\",\n \"--alt_fingerprint\",\n type=int,\n default=None,\n help=\"Enter the alternative fingerprint of the key you want to use\",\n )\n parser.add_argument(\n \"-c\",\n \"--pool_contract_address\",\n type=str,\n default=None,\n help=(\n \"Address of where the pool reward will be sent to. Only used \"\n \"if alt_fingerprint and pool public key are None\"\n ),\n )\n parser.add_argument(\n \"-f\",\n \"--farmer_public_key\",\n help=\"Hex farmer public key\",\n type=str,\n default=None,\n )\n parser.add_argument(\"-p\", \"--pool_public_key\", help=\"Hex public key of pool\", type=str, default=None)\n parser.add_argument(\n \"-g\",\n \"--grep_string\",\n help=\"Shows only plots that contain the string in the filename or directory name\",\n type=str,\n default=None,\n )\n parser.add_argument(\n \"-t\",\n \"--tmp_dir\",\n help=\"Temporary directory for plotting files\",\n type=Path,\n default=Path(\".\"),\n )\n parser.add_argument(\n \"-2\",\n \"--tmp2_dir\",\n help=\"Second temporary directory for plotting files\",\n type=Path,\n default=None,\n )\n parser.add_argument(\n \"-d\",\n \"--final_dir\",\n help=\"Final directory for plots (relative or absolute)\",\n type=Path,\n default=Path(\".\"),\n )\n parser.add_argument(\n \"-i\",\n \"--plotid\",\n help=\"PlotID in hex for reproducing plots (debugging only)\",\n type=str,\n default=None,\n )\n parser.add_argument(\n \"-m\",\n \"--memo\",\n help=\"Memo in hex for reproducing plots (debugging only)\",\n type=str,\n default=None,\n )\n parser.add_argument(\n \"-e\",\n \"--nobitfield\",\n help=\"Disable bitfield\",\n default=False,\n action=\"store_true\",\n )\n parser.add_argument(\n \"-x\",\n \"--exclude_final_dir\",\n help=\"Skips adding [final dir] to harvester for farming\",\n default=False,\n action=\"store_true\",\n )\n parser.add_argument(\n \"-l\",\n \"--list_duplicates\",\n help=\"List plots with duplicate IDs\",\n default=False,\n action=\"store_true\",\n )\n parser.add_argument(\n \"--debug-show-memo\",\n help=\"Shows memo to recreate the same exact plot\",\n default=False,\n action=\"store_true\",\n )\n parser.add_argument(\n \"--challenge-start\",\n help=\"Begins at a different [start] for -n [challenges]\",\n type=int,\n default=None,\n )\n parser.add_argument(\n \"command\",\n help=f\"Command can be any one of {command_list}\",\n type=str,\n nargs=\"?\",\n )\n\n parser.set_defaults(function=handler)\n parser.print_help = lambda self=parser: help_message()\n\n\ndef show(root_path):\n print(\"Directories where plots are being searched for:\")\n print(\"Note that subdirectories must be added manually.\")\n print(\n \"Add with 'chia plots add -d [dir]' and remove with\"\n + \" 'chia plots remove -d [dir]'.\"\n + \" Scan and check plots with 'chia plots check'\"\n )\n print()\n for str_path in get_plot_directories(root_path):\n print(f\"{str_path}\")\n\n\ndef handler(args, parser):\n if args.command is None or len(args.command) < 1:\n help_message()\n parser.exit(1)\n\n root_path: Path = args.root_path\n if not root_path.is_dir():\n raise RuntimeError(\"Please initialize (or migrate) your config directory with chia init.\")\n\n initialize_logging(\"\", {\"log_stdout\": True}, root_path)\n command = args.command\n if command not in command_list:\n help_message()\n parser.exit(1)\n\n if command == \"create\":\n create_plots(args, root_path)\n elif command == \"check\":\n check_plots(args, root_path)\n elif command == \"add\":\n str_path = args.final_dir\n add_plot_directory(str_path, root_path)\n elif command == \"remove\":\n str_path = args.final_dir\n remove_plot_directory(str_path, root_path)\n elif command == \"show\":\n show(root_path)\n","sub_path":"src/cmds/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":6641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"171118659","text":"import librosa\r\nimport librosa.display\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport torch\r\n\r\nfrom trainer.base_trainer import BaseTrainer\r\nfrom utils.utils import compute_STOI, compute_PESQ\r\nplt.switch_backend('agg')\r\n\r\n\r\nclass Trainer(BaseTrainer):\r\n def __init__(\r\n self,\r\n config,\r\n resume: bool,\r\n model,\r\n loss_function,\r\n optimizer,\r\n train_dataloader,\r\n validation_dataloader,\r\n ):\r\n super(Trainer, self).__init__(config, resume, model, loss_function, optimizer)\r\n self.train_data_loader = train_dataloader\r\n self.validation_data_loader = validation_dataloader\r\n\r\n def _train_epoch(self, epoch):\r\n loss_total = 0.0\r\n\r\n for i, (mixture, clean, name) in enumerate(self.train_data_loader):\r\n mixture = mixture.to(self.device)\r\n clean = clean.to(self.device)\r\n\r\n self.optimizer.zero_grad()\r\n enhanced = self.model(mixture)\r\n loss = self.loss_function(clean, enhanced)\r\n loss.backward()\r\n self.optimizer.step()\r\n\r\n loss_total += loss.item()\r\n\r\n dl_len = len(self.train_data_loader)\r\n self.viz.writer.add_scalar(f\"Train/Loss\", loss_total / dl_len, epoch)\r\n\r\n @torch.no_grad()\r\n def _validation_epoch(self, epoch):\r\n sample_length = self.validation_data_loader.dataset.sample_length\r\n stoi_c_n = []\r\n stoi_c_d = []\r\n pesq_c_n = []\r\n pesq_c_d = []\r\n\r\n for i, (mixture, clean, name) in enumerate(self.validation_data_loader):\r\n assert len(name) == 1, \"Only support batch size is 1 in enhancement stage.\"\r\n name = name[0]\r\n\r\n # [1, 1, T]\r\n mixture = mixture.to(self.device)\r\n clean = clean.to(self.device)\r\n\r\n # Input of model should fixed length\r\n mixture_chunks = torch.split(mixture, sample_length, dim=2)\r\n if mixture_chunks[-1].shape[-1] != sample_length:\r\n mixture_chunks = mixture_chunks[:-1]\r\n\r\n enhanced_chunks = []\r\n for chunk in mixture_chunks:\r\n enhanced_chunks.append(self.model(chunk).detach().cpu())\r\n\r\n enhanced = torch.cat(enhanced_chunks, dim=2)\r\n\r\n # Back to numpy array\r\n mixture = mixture.cpu().numpy().reshape(-1)\r\n enhanced = enhanced.numpy().reshape(-1)\r\n clean = clean.cpu().numpy().reshape(-1)\r\n\r\n min_len = min(len(mixture), len(clean), len(enhanced))\r\n\r\n mixture = mixture[:min_len]\r\n clean = clean[:min_len]\r\n enhanced = enhanced[:min_len]\r\n\r\n if i <= self.visualize_audio_limit:\r\n # Audio\r\n self.viz.writer.add_audio(f\"{name}Mixture\", mixture, epoch, sample_rate=16000)\r\n self.viz.writer.add_audio(f\"{name}Enhanced\", enhanced, epoch, sample_rate=16000)\r\n self.viz.writer.add_audio(f\"{name}Clean\", clean, epoch, sample_rate=16000)\r\n\r\n if i <= self.visualize_waveform_limit:\r\n # Waveform\r\n fig, ax = plt.subplots(3, 1)\r\n for j, y in enumerate([mixture, enhanced, clean]):\r\n ax[j].set_title(\"mean: {:.3f}, std: {:.3f}, max: {:.3f}, min: {:.3f}\".format(\r\n np.mean(y),\r\n np.std(y),\r\n np.max(y),\r\n np.min(y)\r\n ))\r\n librosa.display.waveplot(y, sr=16000, ax=ax[j])\r\n plt.tight_layout()\r\n self.viz.writer.add_figure(f\"Waveform/{name}\", fig, epoch)\r\n\r\n # Metric\r\n stoi_c_n.append(compute_STOI(clean, mixture, sr=16000))\r\n stoi_c_d.append(compute_STOI(clean, enhanced, sr=16000))\r\n pesq_c_n.append(compute_PESQ(clean, mixture, sr=16000))\r\n pesq_c_d.append(compute_PESQ(clean, enhanced, sr=16000))\r\n\r\n get_metrics_ave = lambda metrics: np.sum(metrics) / len(metrics)\r\n self.viz.writer.add_scalars(f\"评价指标均值/STOI\", {\r\n \"clean 与 noisy\": get_metrics_ave(stoi_c_n),\r\n \"clean 与 denoisy\": get_metrics_ave(stoi_c_d)\r\n }, epoch)\r\n self.viz.writer.add_scalars(f\"评价指标均值/PESQ\", {\r\n \"clean 与 noisy\": get_metrics_ave(pesq_c_n),\r\n \"clean 与 denoisy\": get_metrics_ave(pesq_c_d)\r\n }, epoch)\r\n\r\n score = (get_metrics_ave(stoi_c_d) + self._transform_pesq_range(get_metrics_ave(pesq_c_d))) / 2\r\n return score\r\n","sub_path":"trainer/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"429336014","text":"import requests, json, random, time\n\nBASE_URL = \"https://api.smartthings.com/v1/devices\"\nTOKEN = 'Bearer 752ce680-b34d-4988-bf5b-b68023edcc80'\n\n\ndef call_api_request(device_id, sub_url):\n url = BASE_URL\n if device_id is not None and sub_url is not None:\n url = url + \"/\" + device_id + \"/\" + sub_url\n payload = {}\n headers = {\n 'Authorization': TOKEN\n }\n response = requests.request(\"GET\", url, headers=headers, data=payload)\n print(\"api request response: \", response.json())\n return response.json()\n\n\ndef send_command_device(key, command):\n url = BASE_URL + \"/\" + key + \"/commands\"\n payload = command\n headers = {\n 'Authorization': TOKEN,\n 'Content-Type': 'application/json'\n }\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n print(\"send_command_device response: \", response.text.encode('utf8'))\n","sub_path":"SmartThings/SmartThingsConnector.py","file_name":"SmartThingsConnector.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"139254351","text":"# Script Name\t: Apriori.py \n# Author\t: Wang Binru\n# Created\t: 15th Oct 2015 \n# Version\t: 1.0 \n# Description : This script is an implement of apriori algorithm\n# which takes as an input the file named assignment2-data.txt\n\n\nimport os\nimport itertools\n\n\nclass Node:\n\n def __init__(self, isleaf = 0, children = None, members = None):\n self.isleaf = isleaf\n self.children = [None, None, None] if children is None else children\n self.members = [] if members is None else members\n \n\nclass HashTree:\n\n def __init__(self):\n \n self.root = Node()\n\n \n def traverse_leaf(self, current_root, candidates, mincount, supportlist, k):\n \"\"\"traverse the whole tree\n\n current_root -- the node where you want to start traversing\n candidates -- C[k+1]\n mincount -- minsup*(len(transactions)-1)\n supportlist -- a list to store support counts of frequent itemsets F\n k -- means we already have F[k]\n \"\"\"\n \n if current_root == None:\n return\n if current_root.isleaf == 1: # at a leaf\n for elem in current_root.members:\n if elem[1] > mincount:\n candidates.append(elem[0])\n supportlist[k + 1].append(elem[1])\n else: # not a leaf, then go to next level\n self.traverse_leaf(current_root.children[0], candidates, mincount, supportlist, k)\n self.traverse_leaf(current_root.children[1], candidates, mincount, supportlist, k)\n self.traverse_leaf(current_root.children[2], candidates, mincount, supportlist, k)\n\n\n def insert(self, root, data, k, maxlevel):\n \"\"\"insert data into the tree at root\n\n data -- a candidate like [1,4,9] whose length is depend on self.maxlevel\n root -- the node you want to start inserting under\n k -- the depth of current_root's children, thus, k>=1\n maxlevel -- the max depth the tree can be\n \"\"\"\n\n hash_value = data[k-1] % 3\n \n if root.children[hash_value] == None:\n # the node does not exist\n root.children[hash_value] = Node(1, None, [[data, 0]]) # insert as a leaf\n return\n \n elif root.children[hash_value].isleaf == 0:\n # it's a internal node\n self.insert(root.children[hash_value], data, k + 1, maxlevel) # go to the next level\n return \n\n elif len(root.children[hash_value].members) < 3:\n # it's a leaf and the leaf is not full yet\n root.children[hash_value].members.append([data, 0])\n return\n\n elif k == maxlevel:\n # the leaf is at bottom level\n root.children[hash_value].members.append([data, 0]) # insert the node anyway\n return\n\n else:\n # it's a full leaf, and the leaf is not at the bottom level\n # Thus, we split the node up\n\n # get the members of the node we are splitting\n mem = [elem for elem in root.children[hash_value].members] \n\n # first insert a internal node\n root.children[hash_value] = Node()\n\n # then insert 4 data into the tree whose root is current_root\n self.insert(root.children[hash_value], data, k + 1, maxlevel)\n for i in range(3):\n self.insert(root.children[hash_value], mem[i][0], k + 1, maxlevel)\n\n\n\n\n\ndef generate_candidates(itemset, candidates, k):\n \"\"\"as the first step, generate all the candidates without pruning\n\n itemset -- here the itemset is F[k]\n candidates -- to store the generated candidates C[k+1]\n k -- means we already have F[k]\n \"\"\"\n\n length = len(itemset)\n if k == 1: # when k=1, we dont have to check whether itemset[j][0:k-2] != itemset[j][0:k-2]\n for i in range(length-1):\n for j in range(i+1, length):\n candidates.append(itemset[i] + itemset[j])\n else:\n for i in range(length-1):\n for j in range(i+1, length):\n if itemset[j][0:k-2] != itemset[j][0:k-2]:\n break\n else:\n l = list(set(itemset[i])|set(itemset[j]))\n l.sort()\n candidates.append(l)\n\n \n\ndef prune_downward_closure(itemset, candidates, k):\n \"\"\"prune the candidates based on downward closure property\n\n itemset -- here the itemset is F[k]\n candidates -- to store the generated candidates C[k+1]\n k -- means we already have F[k]\n \"\"\"\n can = []\n for elem in candidates:\n elem_subsets = list(itertools.combinations(elem, k))\n for sets in elem_subsets:\n elem_list = list(sets)\n if elem_list not in itemset:\n break\n else:\n can.append(elem)\n candidates = can\n\n\n\ndef prune_based_on_support(transactions, candidates, minsup, supportlist, k):\n \"\"\"prune the candidates based on their support counts \n\n transactions -- clear to see what it is \n candidates -- the remaining candidates after 2 steps of sanitization(prune) and it will be F[k+1] after this function\n minsup -- the lower bound of the support count\n supportlist -- the list to store the support count of the frequent itemsets in F\n k -- means we already have F[k], and now generating candidates C[k+1]\n \"\"\"\n \n tree = HashTree() # build a tree\n for elem in candidates: # insert all the candidates\n tree.insert(tree.root, elem, 1, k + 1)\n\n \n # count the support count of every candidate \n for trans in transactions: # traverse every transaction T\n if len(trans) > k:\n trans_subsets = list(itertools.combinations(trans, k + 1)) #generate all valid subsets that has at least k+1 elements\n\n for elem in trans_subsets: # traverse every valid subset and check whether it's in tree\n current_root = tree.root\n current_level = 0\n while True:\n hash_value = elem[current_level] % 3\n if current_root.children[hash_value] == None: # means elem is not in the tree\n break\n if current_root.children[hash_value].isleaf == 0: # means we have to go deeper\n current_level = current_level + 1\n current_root = current_root.children[hash_value]\n continue\n\n # here the we are at a leaf's parent\n leng = len(current_root.children[hash_value].members)\n for i in range(leng):\n if list(elem) == current_root.children[hash_value].members[i][0]: # if elem is in tree\n current_root.children[hash_value].members[i][1] = current_root.children[hash_value].members[i][1] + 1\n break # a match is found, so break\n\n break # we are at a leaf's parent, so there's no need to do the loop\n \n\n # get the candidates with support counts no less than mincount=minsup*(len(transactions)-1)\n candidates.clear()\n mincount = minsup * (len(transactions) - 1)\n tree.traverse_leaf(tree.root, candidates, mincount, supportlist, k)\n pass\n\n\n\n\n\ndef apriori(transactions, minsup):\n \"\"\"get all the frequent itemsets and write them to a file\"\"\"\n \n transcount = len(transactions) - 1\n mincount = minsup * (transcount)\n \n F = [] # F[k] denotes all the frequent k-itemsets\n supportlist = [] # a list to store support counts of frequent itemsets F\n \n for p in range(len(transactions[0]) + 1):\n F.append([]) # make F look like [[], [], ... ,[]]\n supportlist.append([]) # make supportlist look like [[], [], ... ,[]]\n \n\n # generate F[1] and supportlist[1]\n for elem in transactions[0]:\n scount = 0\n for trans in transactions:\n if elem in trans:\n scount = scount + 1\n if scount > mincount:\n F[1].append([elem])\n supportlist[1].append(scount)\n \n\n k = 1 # we already have F[1], so we start with k=1\n while (F[k] != [] and k < len(transactions[0])):\n # for every level F[k], do the following 3 steps to get F[k+1] \n candidates = []\n generate_candidates(F[k], candidates, k) \n prune_downward_closure(F[k], candidates, k) \n prune_based_on_support(transactions, candidates, minsup, supportlist, k)\n k = k + 1\n F[k] = candidates\n print('generating level complete!')\n\n # write the file \n result_path = os.getcwd() + '\\\\result.txt'\n result_file = open(result_path, 'w')\n \n for i in range(1, len(F)):\n for j in range(len(F[i])): # write frequent itemsets and their support count\n result_file.write(str(F[i][j])[1:-1]) \n result_file.write(' ')\n result_file.write(str(supportlist[i][j] / transcount))\n result_file.write('\\n')\n print('writing complete!')\n result_file.close()\n\n\n\n# __main__ begins here\n# get the transactions\n\npath = os.getcwd() + '\\\\assignment2-data.txt'\nfile = open(path, 'r')\ntransactions = []\n# read all the original text to the list transactions\nwhile True:\n line = file.readline()\n if line == '':\n break\n transactions.append(line[:-1])\nfile.close()\n\n# convert every line of transactions to an itemset like [1,4,7,8]\nlength = len(transactions)\ntransactions[0] = transactions[0].split(' ')\nlength_of_line = len(transactions[0])\nfor i in range(length_of_line):\n transactions[0][i] = int(transactions[0][i])\n\nfor i in range(1,length):\n transactions[i] = transactions[i].split(' ')\n listtemp = []\n for j in range(length_of_line):\n if transactions[i][j] == '1':\n listtemp.append(transactions[0][j])\n transactions[i] = listtemp\n\napriori(transactions, 0.144)\n","sub_path":"Frequent Itemset Mining/Apriori.py","file_name":"Apriori.py","file_ext":"py","file_size_in_byte":9953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"289579824","text":"from keras.models import load_model\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.preprocessing import image\nfrom flask import Flask,render_template,request,url_for\napp =Flask(__name__)\nmodel = load_model('crop.h5')\ndef prepare(img_path):\n img = image.load_img(img_path, target_size=(256, 256))\n x = image.img_to_array(img)\n x = x/255\n return np.expand_dims(x, axis=0)\n@app.route('/')\ndef hello_world():\n return render_template('demo.html')\n@app.route('/predict',methods=['POST','GET'])\ndef predict():\n \n Classes = [\"Potato___Early_blight\",\"Potato___Late_blight\",\"Potato___healthy\"]\n result = model.predict_classes([prepare('C:/Users/vaibavalaxmi/Downloads/archive/test_set/Potato___Late_blight/2.JPG')])\n disease=image.load_img('C:/Users/vaibavalaxmi/Downloads/archive/test_set/Potato___Late_blight/2.JPG')\n \n val=Classes[int(result)]\n return render_template('demo.html',pred='The analysis says {}'.format(val))\nif __name__== '__main__':\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"166884742","text":"# 1074 / find index of number\ndef find(ln, si, ei, sj, ej, r, c, idx):\n # ln : len of mat, i & j : index of mat\n # r & c : original row and column, idx : start index of mat\n global res\n\n if ln == 2: # if len of mat is 2 x 2\n points = [(si, sj), (si, sj + 1), (si + 1, sj), (si + 1, sj + 1)]\n for k in range(4):\n if points[k] == (r, c): # if row and col of point is same as target\n res = idx + k # return sum of start index and k\n return\n\n if si <= r <= si - 1 + ln // 2: # if point is in 1st or 4th quadrant\n ei //= 2\n if sj <= c <= sj - 1 + ln // 2: # if point is in 4th quadrant\n ej //= 2\n position = 0\n else: # if point is in 1st quadrant\n sj += ln // 2\n position = 1\n else: # if point is in 2nd or 3rd quadrant\n si += ln // 2\n if sj <= c <= sj - 1 + ln // 2: # if point is in 3rd quadrant\n ej //= 2\n position = 2\n else: # if point is in 2nd quadrant\n sj += ln // 2\n position = 3\n\n idx += (ln ** 2) // 4 * position # renewal start index\n\n find(ln // 2, si, ei, sj, ej, r, c, idx) # recursive\n\n\n# calculate index number of row and column\nN, r, c = map(int, input().split())\n\nres = 0\nfind(2 ** N, 0, 2 ** N - 1, 0, 2 ** N - 1, r, c, 0)\n\nprint(res)\n","sub_path":"division_conquest/1074.py","file_name":"1074.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"90014182","text":"# A class is like a blueprint for creating objects. An object has properties and methods(functions) associated with it. Almost everything in Python is an object\n\n# create class\nclass User:\n # constructor\n def __init__(self, name, email, age):\n self.name = name\n self.email = email\n self.age = age\n\n def greeting(self):\n return f'My name is {self.name} and I am {self.age}'\n\n def has_birthday(self):\n self.age += 1\n\n\n\n# Init user object\nbrad = User('Brad Traversy', 'brad@gmail.com', 37)\njanet = User('Janet Williams', 'janet@gmail.com', 20)\n\nprint(brad.name)\nprint(brad.age)\nprint(brad.email)\n\nbrad.age = 38\nprint(brad.age)\n\nprint(janet.age)\n\njanet.has_birthday()\nprint('now I am ', janet.age)\n\n\n# call method(function) in a class (the name as js)\nprint(janet.greeting())\n\n\nclass Customer(User):\n def __init__(self, name, email, age):\n self.name = name\n self.email = email\n self.age = age\n self.balance = 0\n\n def set_balance(self, balance):\n self.balance = balance\n\n def greeting(self):\n return f'My name is {self.name} and I am {self.age} and I owe a balance of {self.balance}'\n\n\n# Init Customer\n\njohn = Customer('John Doe', 'johdoe@gmail.com', 30)\n\nprint(john.name)\njohn.set_balance(500)\nprint(john.balance)\nprint(john.greeting())","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"295234240","text":"from core import VK\r\nfrom plugins.db import cursor as db, con\r\nimport config, sys\r\n\r\n\r\nclass main:\r\n triggers = ['addmoder', 'delmoder']\r\n target = True\r\n\r\n def execute(self, vk : VK, peer, **mess):\r\n userinfo = db.execute(\"SELECT * FROM admins WHERE vk_id = ?\", (mess['from_id'],))\r\n if len(userinfo.fetchall()) == 1:\r\n db.execute(\"CREATE TABLE IF NOT EXISTS moders (vk_id INT NOT NULL, event INT DEFAULT 0, days_without_posts INT DEFAULT 0)\")\r\n\r\n data = db.execute(\"SELECT * FROM moders WHERE vk_id = ?\", (mess['userId'],)).fetchall()\r\n \r\n name = vk.api(\"users.get\", user_ids=mess['userId'])[0]\r\n\r\n managers = vk.api(\"groups.getMembers\", group_id=config.GROUP_ID, filter='managers')\r\n found = False\r\n \r\n for manager in managers['items']:\r\n if manager['id'] == mess['userId'] and manager['role'] == 'editor': #блок снятия других админов админами через бота, только вручную\r\n found = True\r\n break\r\n\r\n isModer = found\r\n #Назначение модером\r\n if mess['cmd'] == \"addmoder\":\r\n if len(data) == 0:\r\n db.execute(\"INSERT INTO moders(vk_id) VALUES(?)\", (mess['userId'],))\r\n\r\n m = f\"[BOT]\\n{name['first_name']} {name['last_name']} назначен модером в боте\"\r\n\r\n if not isModer:\r\n if not \"-dev\" in sys.argv:\r\n vk.api(\"groups.editManager\", group_id=config.GROUP_ID, user_id=mess['userId'], role=\"editor\")\r\n else:\r\n m += \"[TEST MODE]\"\r\n m += \" и в группе\"\r\n\r\n r = vk.api(\"messages.addChatUser\", chat_id=config.CONVERSATIONS['flood'], user_id=mess['userId'])\r\n if not r:\r\n m += \"\\n Ошибка приглашения во Flood Chat\"\r\n\r\n r = vk.api(\"messages.addChatUser\", chat_id=config.CONVERSATIONS['new'], user_id=mess['userId'])\r\n if not r:\r\n m += \"\\n Ошибка приглашения в New Chat\"\r\n\r\n vk.api(\"messages.send\", peer_id=peer, reply_to=mess['id'], message=m)\r\n \r\n else:\r\n vk.api(\"messages.send\", peer_id=peer, reply_to=mess['id'], message=\"[BOT]\\nУказанный пользователь уже является модером\")\r\n #Снятие с поста модера\r\n else:\r\n if len(data) > 0:\r\n db.execute(\"DELETE FROM moders WHERE vk_id=?\", (mess['userId'],))\r\n m = f\"[BOT]\\n{name['first_name']} {name['last_name']} снят с поста модера в боте\"\r\n if isModer:\r\n if not \"-dev\" in sys.argv:\r\n vk.api(\"groups.editManager\", group_id=config.GROUP_ID, user_id=mess['userId'])\r\n else:\r\n m += \"[TEST MODE]\"\r\n m += \" и в группе\"\r\n\r\n r = vk.api(\"messages.removeChatUser\", chat_id=config.CONVERSATIONS['flood'], user_id=mess['userId'])\r\n if not r:\r\n m += \"\\n Ошибка исключения из Flood Chat\"\r\n r = vk.api(\"messages.removeChatUser\", chat_id=config.CONVERSATIONS['new'], user_id=mess['userId'])\r\n if not r:\r\n m += \"\\n Ошибка исключения из New Chat\"\r\n r = vk.api(\"messages.removeChatUser\", chat_id=config.CONVERSATIONS['events'], user_id=mess['userId'])\r\n if not r:\r\n m += \"\\n Ошибка исключения из Event Chat\"\r\n \r\n vk.api(\"messages.send\", peer_id=peer, reply_to=mess['id'], message=m)\r\n else:\r\n vk.api(\"messages.send\", peer_id=peer, reply_to=mess['id'], message=\"[BOT]\\nУказанный пользователь не является модером\")\r\n\r\n con.commit()\r\n else:\r\n vk.api(\"messages.send\", peer_id=peer, reply_to=mess['id'], message=\"[BOT]\\nВы не можете использовать эту команду\")","sub_path":"plugins/moder_managment.py","file_name":"moder_managment.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"406127647","text":"import sys\nimport time\nimport random\n\nimport numpy as np\n\nimport point\nimport gridmap\nimport convertc\n\nclass AStar:\n class Node: # AStar算法中的节点数据\n def __init__(self, point, endPoint, g=0):\n self.point = point # 自己的坐标\n self.father = None # 父节点\n self.g = g # 自己距离起点的距离\n x_dis = abs(endPoint.x - point.x) # x方向距离\n y_dis = abs(endPoint.y - point.y) # y方向距离\n self.h = x_dis + y_dis + (np.sqrt(2) - 2) * min(x_dis, y_dis) # 启发函数h,距终点的欧式距离\n\n\n def __init__(self, map, startPoint, endPoint):\n self.map = map # 地图\n self.carSize = map.carSize # 车辆尺寸\n self.startPoint = startPoint # 起始点坐标\n self.endPoint = endPoint # 终点坐标\n\n self.open_list = [] # 开列表\n self.close_list = [] # 闭列表\n self.res_path = [] # 结果路径\n\n\n def update(self, map, startPoint, endPoint, selfNum):\n self.map = map\n self.carSize = map.carSize\n self.startPoint = startPoint\n self.endPoint = endPoint \n \n self.open_list = []\n self.close_list = []\n self.res_path = []\n\n\n def getMinNode(self):\n \"\"\"\n 获得openlist中F值最小的节点\n :return: Node\n \"\"\"\n\n currentNode = self.open_list[0]\n for node in self.open_list:\n if node.g + node.h < currentNode.g + currentNode.h:\n currentNode = node\n return currentNode\n\n\n def GetPosWithG(self, path_list, g):\n \"\"\"\n 根据g值找出路径上最接近的点\n :param path_list: 待检查路径点列表\n :param g: (x,y)距离起点的距离\n :return: Bool\n \"\"\"\n\n g_cur = 0 # 当前g值\n pathLen = len(path_list)\n\n if pathLen == 0 or pathLen == 1: # 路径列表为空或仅有单个点\n return None\n else: \n for i in range(pathLen-1):\n p_now = path_list[i]\n p_next = path_list[i+1]\n g_cur = g_cur + ((p_next.x-p_now.x) ** 2 + (p_next.y-p_now.y) ** 2) ** 0.5 # 计算新的g值\n dg = g - g_cur\n if dg < 1.5:\n return p_next # 找到相近点并返回\n else:\n return None # 未找到相近点,不会发生路径冲突\n\n\n def IsValidPoint(self, curNode, x, y, step):\n \"\"\"\n 检查是否为可行点\n :param curNode: AStar算法计算过程中当前节点\n :param x: 待检查点-x坐标\n :param y: 待检查点-y坐标\n :param step: 当前节点至(x,y)的距离\n :return: Bool\n \"\"\"\n\n # 是否越界\n if x < 1 or y < 1:\n return False\n if x > self.map.L or y > self.map.W:\n return False\n # 是否为障碍\n if self.map.IsCarHitObstacle(x, y):\n return False\n return True\n\n\n def pointInPointList(self, p, point_list):\n \"\"\"\n 检查该点是否在点列表中\n :param p: 待检查节点\n :param point_list: 待搜索点列表\n :return: Node\n \"\"\"\n\n for node in point_list:\n if node.point == p:\n return node\n return None\n\n\n def pointInOpenList(self, p):\n \"\"\"\n 检查该点是否在开列表中\n :param p: 待检查节点\n :return: Node\n \"\"\"\n\n return self.pointInPointList(p, self.open_list)\n\n\n def pointInCloseList(self, p):\n \"\"\"\n 检查该点是否在闭列表中\n :param p: 待检查节点\n :return: Node\n \"\"\"\n\n return self.pointInPointList(p, self.close_list)\n\n\n def endPointInCloseList(self): # 终点是否在闭列表中\n \"\"\"\n 检查终点是否在闭列表中\n :return: Node\n \"\"\"\n\n for node in self.close_list:\n if node.point == self.endPoint:\n return node\n return None\n\n\n def searchNear(self, minF, offsetX, offsetY, step):\n \"\"\"\n 搜索节点周围的点\n :param minF: F值最小的节点\n :param offsetX: X坐标偏移量\n :param offsetY: Y坐标偏移量\n :param step: 步长(1 or sqrt(2))\n :return:\n \"\"\"\n\n # 可行性检测\n if not self.IsValidPoint(minF, minF.point.x + offsetX, minF.point.y + offsetY, step):\n return\n # 如果在close_list中,忽略该节点\n currentPoint = point.Point(minF.point.x + offsetX, minF.point.y + offsetY)\n if self.pointInCloseList(currentPoint):\n return\n # 如果不在open_list中,就把它加入open_list\n currentNode = self.pointInOpenList(currentPoint)\n if not currentNode:\n currentNode = AStar.Node(currentPoint, self.endPoint, g=minF.g+step)\n currentNode.father = minF\n self.open_list.append(currentNode)\n return\n # 如果在open_list中,判断minF到当前点的g是否更小\n if minF.g + step < currentNode.g: # 如果更小,就重新计算g值,并且更改父节点\n currentNode.g = minF.g + step\n currentNode.father = minF\n\n\n def start(self):\n \"\"\"\n 开始寻路\n :return: None或Point列表(路径)\n \"\"\"\n\n # 判断寻路终点是否可行\n if not self.IsValidPoint(None, self.endPoint.x, self.endPoint.y, 0):\n return []\n \n # 1.将起点放入开启列表\n startNode = AStar.Node(self.startPoint, self.endPoint)\n self.open_list.append(startNode)\n # 2.主循环逻辑\n while True:\n # 找到F值最小的点\n minF = self.getMinNode()\n # 把这个点加入close_list中,并且在open_list中删除它\n self.close_list.append(minF)\n self.open_list.remove(minF)\n # 判断这个节点的上下左右节点\n self.searchNear(minF, 0, -1, 1)\n self.searchNear(minF, 0, 1, 1)\n self.searchNear(minF, -1, 0, 1)\n self.searchNear(minF, 1, 0, 1)\n self.searchNear(minF, 1, -1, np.sqrt(2))\n self.searchNear(minF, 1, 1, np.sqrt(2))\n self.searchNear(minF, -1, -1, np.sqrt(2))\n self.searchNear(minF, -1, 1, np.sqrt(2))\n\n # 判断是否终止\n node = self.endPointInCloseList()\n\n if node: # 如果终点在关闭表中,就返回结果\n cPoint = node\n path_list = []\n while True:\n if cPoint.father:\n path_list.append(cPoint.point)\n cPoint = cPoint.father\n else:\n return list(reversed(path_list))\n\n if len(self.open_list) == 0: # 如果无法到达终点,返回空列表\n return []\n\n\n def GetPath(self):\n \"\"\"\n 获取该辆车辆的到目标点的路径(不考虑车辆碰撞)\n :return res_path\n \"\"\"\n\n self.res_path = self.start()\n return self.res_path\n\n\nif __name__ == \"__main__\":\n # 默认实际地图长度为800,比例尺 ratio = 800/栅格地图长度\n # 初始化起点终点坐标\n #[50,50] [50,175] [50,300] [50,425] [50,550]\n t0 = time.time()\n StartPoint = point.Point(50, 550)\n EndPoint = point.Point(500, 550)\n gmap = gridmap.GridMap(32,24)\n ratio = gmap.ratio\n\n # 坐标转换\n startPoint = convertc.real2grid([StartPoint], ratio)[0]\n endPoint = convertc.real2grid([EndPoint], ratio)[0]\n\n # 寻找路径\n astar = AStar(gmap, startPoint, endPoint)\n path = astar.GetPath()\n \n # 坐标转换\n path_real = convertc.grid2real(path, ratio)\n t1 = time.time()\n\n # 输出\n print('Real startPoint:', StartPoint.x, StartPoint.y ,'Grid StartPoint:', startPoint.x, startPoint.y)\n print('Real endPoint:', EndPoint.x, EndPoint.y, 'Grid EndPoint:', endPoint.x, endPoint.y)\n print('Real path:\\n', [[rp[0],rp[1]] for rp in path_real])\n print('Grid path:\\n', [[gp.x,gp.y] for gp in path])\n print('Consume time:', t1-t0)","sub_path":"RoboSim-master/sim_v1.0/demo/a_star.py","file_name":"a_star.py","file_ext":"py","file_size_in_byte":8251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"2901872","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 01 15:11:58 2017\n\n@author: Jacky Lei\n\"\"\"\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\nimport sys\nimport os\nimport glob\nimport re\n\n## figure setup\nparams = {\n 'axes.labelsize': 14,\n 'font.size': 14,\n 'legend.fontsize': 10,\n 'xtick.labelsize': 12,\n 'ytick.labelsize': 12,\n 'text.usetex': False,\n 'figure.figsize': [9, 6.6]\n }\nplt.rcParams.update(params)\n\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nax.set_xlabel(r\"x [$\\mu$m]\")\nax.set_ylabel(r\"y [$\\mu$m]\")\nax.set_zlabel(r\"z [$\\mu$m]\")\n\n\nCASE=5\niBatch = 67\n\n###############################################################################\n# setup data\ntry:\n fileName = sys.argv[1]\nexcept Exception:\n fileName = None\ntry:\n isImagedCells = bool(int(sys.argv[2]))\nexcept Exception:\n isImagedCells = True\ntry:\n nBatch = int(sys.argv[3])\nexcept Exception:\n nBatch = 78 #len(glob.glob(\"case%s/*\"%CASE)) - 3\n\nif fileName == None:\n allfiles=glob.glob(\"../plot-traces/case%s/*\"%CASE)\n fileName = [a for a in allfiles if \"_p_1_\" in a][0]\nfileDir = os.path.dirname(fileName)\nfileBase = os.path.basename(fileName)\nfileIdx = re.findall(\".*model_(\\d+)_morphology_(\\d+)_seed_(\\d+)_mode_(\\d+)_.*\",fileName)\nfileId = \"model_%s_morphology_%s_seed_%s_mode_%s\"%fileIdx[0]\nmode = int(fileIdx[0][3])\nshape = re.findall('.*_(\\w+)x(\\w+)\\.dat',fileName)[0]\nshapeX = (int(shape[0]),int(shape[1]))\nif nBatch>0:\n filePrefix,startBatch = re.findall(\"(.*)_p_(\\d+)_.*\",fileName)[0]\n fileNameBatch = []\n shapeXBatch = []\n for i in range(1,nBatch+1):\n getBatch = int(startBatch)+i\n tempfilename = glob.glob(filePrefix+\"_p_%d_*\"%getBatch)[0]\n tempshape = re.findall('.*_(\\w+)x(\\w+)\\.dat',tempfilename)[0]\n shapeXBatch.append((int(tempshape[0]),int(tempshape[1])))\n fileNameBatch.append(tempfilename)\nvarName = r\"[Ca]$_i$ [$\\mu$M]\" if \"Ca\" in fileName else r\"$V_m$ [mV]\"\ntitle = \"short simulation homogeneous GJ @ mouse 40-3\"\nif isImagedCells:\n saveName = os.path.join(fileDir,'imaged_'+fileBase[:-4]+'.png')\nelse:\n saveName = os.path.join(fileDir,'whole_'+fileBase[:-4]+'.png')\n\n# load data\nstartName = \"#dt = \"\nwith open(os.path.join(fileDir,fileId+'.log'),\"r\") as fi:\n for ln in fi:\n if ln.startswith(startName):\n temp = ln[len(startName):]\ndt = float(temp)\nstartName = \"#downSampling = \"\nwith open(os.path.join(fileDir,fileId+'.log'),\"r\") as fi:\n for ln in fi:\n if ln.startswith(startName):\n temp = ln[len(startName):]\ndownSampling = float(temp)\ntstep = dt*downSampling\n\nshapeX = shapeXBatch[iBatch]\nX = np.memmap(fileNameBatch[iBatch], dtype='float64', mode='r', shape=shapeX)*1000.\n\n\n###############################################################################\nmorphology = 1\npathToFile = \"./\"\ncoorDataFile = \"Mouse 40-%d\"%morphology\nCoorData = np.loadtxt(pathToFile+coorDataFile+\".txt\")\n# proceed CoorData to be acceptable format in genCoupleMatrix()\nCoorData = CoorData[CoorData[:,0]==11][:,1:4]\ncentreCoorData = np.mean(CoorData,0)\nCoorData = CoorData - centreCoorData\n\n###############################################################################\nxs,ys,zs = CoorData.T\nvalues = X[:,0]\n\np = ax.scatter3D(xs, ys, zs=zs, c=values, cmap='hot', s=30)\n\ncb = fig.colorbar(p, ax=ax)\ncb.set_label(r'[Ca]$_i$ [$\\mu$M]')\n\nplt.savefig(\"../figures/3dheatmap-%d.png\"%CASE,bbox_inches='tight')\nplt.savefig(\"../figures/3dheatmap-%d.pdf\"%CASE,format='pdf',bbox_inches='tight')","sub_path":"figures/plot-3dheatmap/figure1b.py","file_name":"figure1b.py","file_ext":"py","file_size_in_byte":3560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"330309388","text":"'''\r\n20200612\r\nฝนสะสมราย24ชั่วโมงของสถานีที่มีข้อมูลฝนสมบูรณ์ ปรับปรุงจาก \"110\"\r\n\r\n'''\r\n\r\nimport csv\r\nimport numpy as np\r\nimport os\r\nimport fnmatch\r\n\r\ngaugeName='D:/tmp/PyQGIS/Plugin_practice/1data/1gauges_yom2018/' #เป็นโฟลเดอร์ของไฟล์ชื่อสถานีพร้อมพิกัด\r\npathGauge='D:/tmp/PyQGIS/Plugin_practice/1data/1gauges_yom2018/1gauge_org/' #เป็นโฟลเดอร์เก็บข้อมูลดิบฝนแต่ละสถานี\r\noutpRain24h='D:/tmp/PyQGIS/Plugin_practice/z_temp/1outp_gauge_temp/1gauge24h/'#เป็นโฟลเดอร์เก็บข้อมูลผลลัพธ์ฝนราย24ชมของสถานีที่สมบูรณ์ที่ได้จากไฟล์\"105\"\r\n\r\n#สถานีวัดฝนที่สมบูรณ์จากไฟล์\"105\"\r\nwith open(gaugeName+'list_passedQG_gauges.csv', 'r') as f:\r\n st = list(csv.reader(f, delimiter=','))[0]\r\nprint(st)\r\n\r\nprint('เริ่มการสะสมฝน24ชั่วโมงจากการดึงข้อมูลฝนราย15นาทีของแต่ละสถานีฝน..............')\r\n#วันเวลาที่ต้องการรวมไฟล์ฝนราย24ชั่วโมง\r\ntime=['20180717','20180718'] #เพิ่มวันที่ต้องการ\r\n#ลูปเวลาเพื่อดึงตามเวลา 15 นาทีในแต่ละไฟล์\r\nfor dd in time: #วัน\r\n #ลูป 1 รอบใน 1 วัน\r\n for n in range(1): #2 คือ 24/24 สะสมฝนทุกๆ12ชม.\r\n print('ทำการสะสมฝนราย24ชั่วโมง...'+dd+\"{:02d}\".format(n*24))\r\n start=n*24\r\n stop=start+24\r\n \r\n gg=[] #ลิสเก็บชื่อไฟล์ที่หาได้ในแต่ละชั่วโมงที่ต้องการ ในที่นี้ทีละ24ชั่วโมง\r\n #ลูปเพื่อเปิดแต่ละสถานีเพื่อที่จะดึงตามเวลา 15 นาทีในแต่ละไฟล์\r\n for s in st:#สถานีวัดฝนที่สมบูรณ์จากไฟล์\"105\"\r\n gf=pathGauge+s+'.csv' #ข้อมูลไฟล์สถานีไหม\r\n if os.path.isfile(gf): #ตรวจว่ามีข้อมูลไฟล์สถานีไหม\r\n \r\n #เปิดไฟล์สถานี s\r\n with open(gf, 'r') as f:\r\n g = list(csv.reader(f, delimiter=','))\r\n g=np.asarray(g)\r\n \r\n #กรองเอาแถวที่มีเวลาตรงกับ pat \r\n #1.ต้องจัดระเบียบไฟล์ก่อน โดยเอาวันเดือนปี+ชั่วโมงของคอลัมน์2ไปแทนคอลัมน์1 ของ g\r\n a=[]\r\n a+=[re.sub(i[-6:], '', i) for i in g[:,1]]\r\n g[:,1]=a\r\n \r\n sum_rr=0.0\r\n i=1\r\n for hh in range(start,stop): #ลูป12ชั่วโมงที่ต้องการ \r\n \r\n pat=dd[6:]+'/'+dd[4:6]+'/'+dd[0:4]+' '+\"{:02d}\".format(hh) #ใช้คอลัมน์1 ของ g\r\n if i==1:hh_start=dd+\"{:02d}\".format(start) #ชื่อไฟล์ชั่วโมงแรกของ24ชั่วโมงที่กำลังสะสม\r\n tt=dd+\"{:02d}\".format(hh) #เวลา yyyymmddhh\r\n# print('>>>','tt:',tt,'pat:',pat) \r\n \r\n #ใช้ pat (ymd) หาว่าช่วงเวลาที่ต้องการอยู่ในแถวใดบ้าง\r\n data=g[np.where(np.isin(g[:,1], pat))] \r\n rr=sum([float(data[i][2])for i in range(len(data))]) #รวมฝนในชั่วโมงที่ตรงกับ pat\r\n sum_rr+=rr\r\n i+=1\r\n \r\n# print('.....',len(data),rr,sum_rr) \r\n data=[str(s),hh_start,str(sum_rr)]\r\n \r\n #เก็บข้อมูลฝนสะสมราย24 ชั่วโมงที่ดึงมาจากฝน15นาทีมาเก็บในลิสจนครบทุกสถานี\r\n gg.append((data))\r\n \r\n #เซฟ gg เป็น csv ตามชื่อไฟล์\r\n #เซฟเป็นไฟล์ csv ของเวลาราย15นาทีนั้นๆ tt+'.csv'\r\n gf = open(outpRain24h+hh_start+'.csv', 'w',newline='') #newline='' เพื่อป้องกันการเพิ่มบรรทัดตอนเซฟ csv\r\n with gf:\r\n w = csv.writer(gf)\r\n w.writerows(gg) \r\n# break\r\n# break\r\nprint('เสร็จสิ้นการสะสมฝน24ชั่วโมงจากการดึงข้อมูลฝนราย15นาทีของแต่ละสถานีฝน..............')\r\n","sub_path":"1codes/111RainAcc24h_perfectStions.py","file_name":"111RainAcc24h_perfectStions.py","file_ext":"py","file_size_in_byte":5702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"90210110","text":"#IMPORTANT!!!\n#Use Table \"datatable\" for testing &\n#table \"vision\" for final robot code.\n#DO NOT implement \"vision\" in simulated robot code!\n\n#Imports\nimport cv2\nimport urllib\nimport numpy as np\nfrom time import time\nfrom pynetworktables import *\n\n#Debug Flag\ndebug = False\n\n#Source variables\nret = False\ncamClosed = True\ninternalCam = 0\nrobotCamIP = 'http://10.25.76.11/mjpg/video.mjpg'\nbytes=''\n\n#Robot Variables\nuseLocalRobot = True\nrobotIP = '10.25.76.2'\nlocalIP = '127.0.0.1'\nallianceIsRed = True\nisConnected = False\n\n#Thresholding HSV Values\nredMin = np.array([160, 50, 50], np.uint8)\nredMax = np.array([180, 200, 200], np.uint8)\nblueMin = np.array([70, 50, 50], np.uint8)\nblueMax = np.array([135, 200, 200], np.uint8)\n\n#Function Parameters\nseSize = (2, 2) #Element for morphology\nse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, seSize) #Create structuring element before loop\nminDist = 100 #Minimum distance between circle center points\nradMin = 50 #Minimum detected circle radius\nradMax = 250 #Maximum detected circle radius\nframeInterval = 33 #Time in ms in between frames\ngaussian_power = 5 #Gaussian blur parameter\nparam1ForCircles = 50 #First Parameter for HoughCircles -\nparam2ForCircles = 25 #Second Parameter for HoughCircles -\ndpForCircles = 2 #DP parameter for HoughCircles -\n\n#Circle Parameters\ncenterPoint = 0 #Circle center point\nradius = 0 #Circle radius\n##largestRadius = 0\n##largestCircle = (0, 0, 0)\nprev_x = 0\nprev_y = 0\nprev_r = 0\n\n#FPS Calculation\nstartAtFrame = 10\ntotalTime = 0\nnumberOfFrames = 0\ntime1 = time()\ntime2 = 0\nfps = 0\nfpsTextPos = (5, 25)\nfpsTextColor = (255, 255, 255)\n\n#Define setting variables\nCV_CAP_PROP_FRAME_WIDTH = 3\nCV_CAP_PROP_FRAME_HEIGHT = 4\n\n#Window\n#cv2.namedWindow(\"Vision DS\", 1)\n\n#Extra Images\n#errorScreen = cv2.imread(\"system_down.jpg\")\n#blank = np.zeros((400, 400, 3), np.uint8)\n#canvas = np.zeros((645, 645, 3), np.uint8)\n#canvas[245:645, :] = (145, 145, 145)\n\n#NetworkTables Client Init\nif useLocalRobot:\n NetworkTable.SetIPAddress(localIP)\nelse:\n NetworkTable.SetIPAddress(robotIP)\nNetworkTable.SetClientMode()\nNetworkTable.Initialize()\n\n#Table Object\nif useLocalRobot:\n table = NetworkTable.GetTable(\"datatable\")\nelse:\n table = NetworkTable.GetTable(\"vision\")\n\n#Check robot color alliance\ndef checkAlliance():\n global allianceIsRed\n global isConnected\n try:\n allianceIsRed = table.GetBoolean(\"allianceRed\")\n except TableKeyNotDefinedException:\n isConnected = False\n\n#Initial Robot Connection\ndef connect():\n global isConnected\n isConnected = False\n while not isConnected:\n #cv2.imshow(\"Vision DS\", errorScreen)\n try:\n isConnected = table.GetBoolean(\"connection\")\n except TableKeyNotDefinedException:\n isConnected = False\n checkAlliance()\n if cv2.waitKey(frameInterval) == 27:\n #cv2.destroyAllWindows()\n exit(0)\n\n#Callback Function\n#def callBack(event, x, y, flags, param):\n# if event == cv2.cv.EVENT_LBUTTONDOWN:\n# print(img[x, y])\n# if debug:\n# print(\"Click\")\n\n#cv2.setMouseCallback(\"canvas\", callBack)\n\n#Choose source for cam\n\ncam = cv2.VideoCapture(internalCam)\ncam.set(CV_CAP_PROP_FRAME_WIDTH, 320)\ncam.set(CV_CAP_PROP_FRAME_HEIGHT, 240)\n\n\n#Verify cam\nwhile camClosed:\n if cam.isOpened():\n #Read Cam\n ret, img = cam.read()\n if ret:\n camClosed = False\n else:\n camClosed = True\n\n#Call connect function\nconnect()\n\n#Main Loop\nwhile ret:\n if allianceIsRed:\n #Ball Detection for Red\n #Convert & Threshold\n redHSVImage = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n redDetectImage = cv2.inRange(redHSVImage, redMin, redMax)\n #Morphology\n redOpenMorphImage = cv2.morphologyEx(redDetectImage, cv2.MORPH_OPEN, se)\n redCloseMorphImage = cv2.morphologyEx(redOpenMorphImage, cv2.MORPH_CLOSE, se)\n #Gaussian Blur\n redBlurredImage = cv2.GaussianBlur(redCloseMorphImage, (0, 0), gaussian_power)\n #Detect Circles\n circles = cv2.HoughCircles(redBlurredImage, cv2.cv.CV_HOUGH_GRADIENT, dpForCircles,\n minDist, param1=param1ForCircles, param2=param2ForCircles,\n minRadius=radMin, maxRadius=radMax)\n else:\n #Ball Detection for Blue\n #Convert & Threshold\n blueHSVImage = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n blueDetectImage = cv2.inRange(blueHSVImage, blueMin, blueMax)\n #Morphology\n blueOpenMorphImage = cv2.morphologyEx(blueDetectImage, cv2.MORPH_OPEN, se)\n blueCloseMorphImage = cv2.morphologyEx(blueOpenMorphImage, cv2.MORPH_CLOSE, se)\n #Gaussian Blur\n blueBlurredImage = cv2.GaussianBlur(blueCloseMorphImage, (0, 0), gaussian_power)\n #Detect Circles\n circles = cv2.HoughCircles(blueBlurredImage, cv2.cv.CV_HOUGH_GRADIENT, dpForCircles,\n minDist, param1=param1ForCircles, param2=param2ForCircles,\n minRadius=radMin, maxRadius=radMax)\n if circles != None:\n for i in circles[0, :]:\n centerPoint = (i[0], i[1])\n radius = i[2]\n cv2.circle(img, centerPoint, radius, (0, 255, 0), thickness=2)\n## if radius > largestRadius:\n## largestRadius = radius\n## largestCircle[2] = largestRadius\n## largestCircle[1] = y\n## largestCircle[0] = x\n\n #FPS Calculation\n time2 = time()\n intervalBetweenFrames = time2 - time1\n if numberOfFrames > startAtFrame:\n totalTime += intervalBetweenFrames\n fps = int(round(1 / (totalTime / (numberOfFrames - startAtFrame))))\n time1 = time2\n numberOfFrames += 1\n #cv2.putText(img, \"FPS: %d\" % fps, fpsTextPos, cv2.FONT_HERSHEY_SIMPLEX, 0.65, fpsTextColor, 2)\n\n #Send data via NetworkTables\n table.PutNumber(\"FPS\", fps)\n if centerPoint != 0 and prev_x != centerPoint[0] and prev_y != centerPoint[1]:\n prev_x = centerPoint[0]\n prev_y = centerPoint[1]\n table.PutNumber(\"X\", int(centerPoint[0]))\n table.PutNumber(\"Y\", int(centerPoint[1]))\n #canvas[245:645, :] = (145, 145, 145)\n #cv2.putText(canvas, \"X Point: %d\" % centerPoint[0], (5, 360), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 2)\n #cv2.putText(canvas, \"Y Point: %d\" % centerPoint[1], (5, 420), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 2)\n if radius != 0:\n table.PutNumber(\"R\", int(radius))\n #cv2.putText(canvas, \"Radius: %d\" % radius, (5, 480), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 2)\n\n #FPS Debug Messages\n if debug:\n print(\"totalTime: %f\" % totalTime)\n print(\"numberOfFrames: %d\" % numberOfFrames)\n print(\"startAtFrame: %d\" % startAtFrame)\n print(\"intervalBetweenFrames: %f\" % intervalBetweenFrames)\n print(\"FPS: %d\" % fps)\n print(\" \")\n\n #Stitch Images\n #Paints borders according to alliance color\n #Show Alliance\n \"\"\"\n if allianceIsRed:\n canvas[:240, 0:320] = cv2.cvtColor(redBlurredImage, cv2.COLOR_GRAY2RGB)\n canvas[:240, 320:325] = (0, 0, 255)\n canvas[240:245, :] = (0, 0, 255)\n cv2.putText(canvas, \"Current Alliance is: \", (5, 300), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 2)\n canvas[274:309, 360:550] = (0, 0, 255)\n cv2.putText(canvas, \"Red\", (418, 301), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 2)\n\n else:\n canvas[:240, 0:320] = cv2.cvtColor(blueBlurredImage, cv2.COLOR_GRAY2RGB)\n canvas[:240, 320:325] = (255, 0, 0)\n canvas[240:245, :] = (255, 0, 0)\n cv2.putText(canvas, \"Current Alliance is: \", (5, 300), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 2)\n canvas[274:309, 360:550] = (255, 0, 0)\n cv2.putText(canvas, \"Blue\", (410, 301), cv2.FONT_HERSHEY_TRIPLEX, 1, (255, 255, 255), 2)\n\n canvas[:240, 325:] = img\n \"\"\"\n\n #Display Image\n #cv2.imshow(\"Vision DS\", canvas)\n\n #Read Cam\n ret, img = cam.read()\n\n \n #Verify connection\n try:\n isConnected = table.GetBoolean(\"connection\")\n except TableKeyNotDefinedException:\n isConnected = False\n\n if not isConnected:\n connect()\n\n #Check alliance every cycle...unnecessary\n #checkAlliance()\n\n #Delay and exit program\n cv2.waitKey(frameInterval)\n #if key == 27:\n #break\n\n#Cleanly exit program\ntry:\n table.PutBoolean(\"connection\", False)\nexcept TableKeyNotDefinedException:\n pass\n#cv2.destroyAllWindows()\nexit(0)\n","sub_path":"DS_Vision_No_GUI.py","file_name":"DS_Vision_No_GUI.py","file_ext":"py","file_size_in_byte":8641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"171855070","text":"import numpy as np\nimport cv2\nimport math\nimport pandas as pd\nfrom rotate import rotate, rotate_image, rotate_image2\nfrom scipy.spatial import distance\n\nname = '016_1_1'\npts_path = '/home/han/Desktop/Photo-Sketch/CUFS/XM2VTS DB (295 faces)/Sketches/sketch_points/'+ name +'_sz1.dat'\nimg_path = '/home/han/Desktop/Photo-Sketch/CUFS/XM2VTS DB (295 faces)/Sketches/sketch/'+ name +'_sz1.jpg'\nsave_path = '/home/han/Desktop/Python/'+ name +'_sz1.jpg'\n\ndf = pd.read_csv(pts_path, header=None, delimiter=' ')\npoints = df.values\n# print points.shape\n# print points\n# font = cv2.FONT_HERSHEY_SIMPLEX\n# img = cv2.imread(img_path)\n# for i, point in enumerate(points):\n# # print point\n# cv2.circle(img, tuple(point), 7, (0,0,255), -1)\n# cv2.putText(img, str(i), tuple(point), font, .7,(255,255,255),2)\n# cv2.imshow('jaja', img)\n# cv2.waitKey(0)\n\neye_left = (int(points[16][0]), int(points[16][1]))\neye_right = (int(points[18][0]), int(points[18][1]))\nmid_point = ((eye_left[0]+eye_right[0])/2, (eye_left[1]+eye_right[1])/2)\n\ndist = distance.euclidean(eye_left, eye_right)\nratio = abs(75./dist)\n\nimg = cv2.imread(img_path)\n\ncv2.circle(img, eye_left, 7, (0,0,255), -1)\ncv2.circle(img, eye_right, 7, (0,0,255), -1)\ncv2.circle(img, mid_point, 7, (0,0,255), -1)\ncv2.line(img,eye_left,eye_right,(255,0,0),2)\n\nres_size = cv2.resize(img, (512, 768), interpolation=cv2.INTER_AREA)\ncv2.imwrite('test1.tif',img)\n\ndy = eye_left[1] - eye_right[1]\ndx = eye_left[0] - eye_right[0]\nangle = np.arctan2(dy, dx)\nangle_deg = np.rad2deg(angle)+180\n\nimg_rotation = rotate_image2(img, mid_point, angle_deg)\ncv2.imwrite('test3.tif',img_rotation)\n\nrotated_mid = rotate(mid_point, mid_point, angle)\ncv2.imwrite('test4.tif',img_rotation)\n\n# 75 pixels between two eyes\nmid_point_new = (int(rotated_mid[0]*ratio), int(rotated_mid[1]*ratio))\n\nres_size2 = cv2.resize(img_rotation, None, fx=ratio, fy =ratio, interpolation=cv2.INTER_AREA)\ncv2.circle(res_size2, mid_point_new, 5, (0,255,255), -1)\ncv2.imwrite('test5.tif',res_size2)\na = 115\nb = 250-a\ncropped_img = res_size2[mid_point_new[1]-a:mid_point_new[1]+b, mid_point_new[0]-100:mid_point_new[0]+100]\ncv2.imshow('haha', cropped_img)\ncv2.imwrite('test6.tif',cropped_img)\ncv2.imwrite(save_path,cropped_img)\n# cv2.waitKey(0)\n","sub_path":"180427_MI_DetectFaces/MILab/Cropping/Heterogeneous_Coding/XM2VTS_Resize.py","file_name":"XM2VTS_Resize.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"218521615","text":"# -*- coding:utf-8 -*-\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\nclass Solution:\n # 返回构造的TreeNode根节点\n def reConstructBinaryTree(self, pre, tin):\n if len(pre) > 0:\n root = TreeNode(pre[0])\n root_id = tin.index(pre[0])\n root.left = self.reConstructBinaryTree(pre[1:root_id], tin[:root_id])\n root.right = self.reConstructBinaryTree(pre[root_id+1:], tin[root_id+1:])\n return root\n","sub_path":"reConstructBinaryTree.py","file_name":"reConstructBinaryTree.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"119475532","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 29 10:48:09 2018\n\n@author: iamav\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 27 21:37:49 2018\n\n@author: USER\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport random\nfrom scipy.spatial import distance\nclass nKmeans(object):\n def __init__(self,dataframe,numMeans,maxIter=None,path=\"\"):\n random.seed(145)\n self.numMeans=numMeans\n self.path=path\n self.maxIter=maxIter\n #Loading the Dataset \n self.df=dataframe\n self.numAttri=len(self.df.iloc[0])\n self.numObs=len(self.df) \n #Preprocessing the Data\n# from sklearn.preprocessing import Imputer\n# imputer=Imputer(strategy=\"mean\",axis=0)\n# imputer=imputer.fit(df)\n# self.df=imputer.transform(df).tolist()\n self.df=self.df.values.tolist() \n self.means=random.sample(self.df,self.numMeans)\n \n \n def getDF(self):\n return self.df\n def getNumMeans(self):\n return self.numMeans\n \n def getMeans(self):\n return self.means\n \n def getNewMeans(self):\n return self.nmeans\n \n def createClusters(self):\n self.clusters=[]\n for x in range(self.numMeans):\n self.clusters.append([])\n \n def getClusters(self):\n return self.clusters\n\n def process(self):\n \n #Dataframe that stores the Distances of Data Points from the Chosen means\n mdf=pd.DataFrame() \n \n for x1 in range(self.numMeans):\n x=self.means[x1]\n distances=[]\n \n for y in self.df:\n t=distance.euclidean(x,y)\n distances.append(t) \n \n mdf[x1]=distances\n \n #Creating new Clusters for each Function call \n self.createClusters()\n \n for x in range(len(self.df)):\n s=list(mdf.loc[x,:])\n ci=s.index(min(s))\n self.clusters[ci].append(list(self.df[x]))\n \n #Calculating the new Means of the Clusters\n self.nmeans=[]\n for f in (self.clusters):\n self.nmeans.append(np.mean(f,axis=0))\n #Calculating the distances between the New Means and the Previously Selected Means \n self.mdist=[]\n for x in range(self.numMeans):\n self.mdist.append(distance.euclidean(self.nmeans[x],self.means[x])) \n self.means=self.nmeans[:] \n #Returning the clusters and Distances of means\n return (self.mdist,self.clusters)\n \n def writeCluster(self,df):\n f=open(self.path,\"w\")\n for x in df:\n if type(x[0])==list:\n for y in x:\n for z in y:\n f.write(str(z)+\"\\t\")\n f.write(str(df.index(x))+\"\\n\")\n else:\n for z in x:\n f.write(str(z)+\"\\t\")\n f.write(str(df.index(x))+\"\\n\")\n f.close()\n def job(self):\n g,clusters=self.process()\n n=0\n if self.maxIter==None: \n while(sum(g)>0):\n g,clusters=self.process() \n n+=1 \n elif type(self.maxIter)==int:\n while(sum(g)>0 and n<=self.maxIter):\n g,clusters=self.process() \n n+=1\n if self.path==\"\":\n return clusters\n else: \n self.writeCluster(clusters) \n def getdict(df):\n d={}\n for x in df:\n d[df.index(x)]=x\n return d\n def getResults(self):\n #return AGNES_single.getdict(self.df)\n return self.df \n \n def getAttributes(self):\n return (self.clusters,self.means,self.nmeans,self.numMeans,self.df)\n def __str__(self):\n return \"KMeans Clustering Algorithm.\\nGive the Data in form of Dataframe, No. of Means in form of 'numMeans' argument, Maximum Iterations in form of 'maxIter' argument. Then, you have 2 choices:\\n\\\n 1>Give the 'path' parameter and have the final cluster written to a file.\\n\\\n 2>Leave the 'path' parameter unused and obtain the clusters as a nested list at the end of the iterations.\"+\\\n \"\\n\\n Info:\\nNumber of Means Selected=\"+str(self.numMeans)+\\\n \"\\nMax Iteration Allowed=\"+str(self.maxIter)+\"\\n\\nNo. of Attributes in Data-\"+str(self.numAttri)+\\\n \"\\nNo. of Observations in Data-\"+str(self.numObs)\n \n\n\"\"\"\nUncomment anyone of the following blocks for demo.\n\"\"\"\n#from sklearn.datasets import load_iris\n#d=load_iris()\n#df=d.data\n#cols=d.feature_names[0:2]\n#df=pd.DataFrame(data=df[:,0:2])\n \n\n#d=pd.read_csv('C:/Users/USER/Downloads/wine.data',header=None)\n#df=d.iloc[:,1:13].values.tolist()\n\n\n\"\"\"\nUncomment this block for actual execution\n\"\"\"\n#a=nKmeans(df,6)\n#results=a.job()\n\n\"\"\"\nThe code below is used for visualizing the clusters upto 20 clusters.\nPlease note:\n if you want to visualize, just remove the path parameter and\n comment the 'a.job() line and uncomment the lines below.\n\"\"\"\n\n#from matplotlib import pyplot as plt\n#clusters=a.job()\n#plt.style.use('ggplot')\n#\n##plt.scatter(df[col[0]],df[col[1]],s=7)\n#colr=('#008000','black','#FF6A6A','#FFF68F','#F08080','#FF8000','#FFFF00','#FF3E96','#FF6347','#63B8FF','#97FFFF','#CAFF70','#8B6508','#FFB90F','#FFF8DC','#76EE00','#98F5FF','#8A360F','#A52A2A','#0000FF','#000000')\n#for x in clusters:\n# for y in x:\n# plt.scatter(y[0],y[1],s=7,c=colr[clusters.index(x)])\n#\n#\n#for t in clusters:\n# x1=[]\n# y1=[]\n# for z in t:\n# x1.append(z[0])\n# y1.append(z[1])\n# plt.scatter(np.mean(x1),np.mean(y1),s=100,marker='*',c=colr[clusters.index(t)])\n# ","sub_path":"kmeans_trial_2.py","file_name":"kmeans_trial_2.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"542147930","text":"import exifread\nimport os\nimport errno\nimport calendar\nimport shutil\nfrom collections import namedtuple\n\n#Collects a list of path and fileNames for every file in directory that ends with .ARW | .CR2 | .JPG\nclass File():\n\t__slots__ = ['Name','Location','Destination','YearCreated','MonthCreated','xmpFile']\n\n\tdef __init__(self,*,Name,Location,Destination = None, YearCreated=None,MonthCreated=None,xmpFile = None):\n\t\tself.Name = Name\n\t\tself.Location = Location\n\t\tself.Destination = Destination\n\t\tself.YearCreated = YearCreated\n\t\tself.MonthCreated = MonthCreated\n\t\tself.xmpFile = xmpFile\n\nclass SortPhotos():\n\tdef __init__(self,source,destinaton):\n\t\tself.path = source\n\t\tself.destination = destinaton\n\t\tself.imageFiles = []\n\n\t#File is a namedtuple, data is a list formated like: [2010:08]\n\tdef sort(self):\n\t\tself.imageFiles = self.fileNames(self.path)\n\t\tself.exifData(self.imageFiles)\n\t\tself.makeDir(self.imageFiles)\n\t\tself.moveFiles(self.imageFiles)\n\n\tdef fileNames(self,path):\n\t\tfileList = []\n\t\txmpList = []\n\t\tfor dir, subDir, files in os.walk(path,topdown=False):\n\t\t\tfor name in files:\n\t\t\t\tif name.endswith('.ARW') or name.endswith('.CR2') or name.endswith('.JPG') or name.endswith('.NEF') or name.endswith('.tif'):\n\t\t\t\t\tfileData = File(Name = name,Location = os.path.join(dir,name))\n\t\t\t\t\tfileList.append(fileData)\n\t\t\t\telif name.endswith('.xmp'):\n\t\t\t\t\txmpList.append(os.path.join(dir,name))\n\n\t\tfor file in fileList:\n\t\t\tfor xmp in xmpList:\n\t\t\t\tif os.path.splitext(file.Location)[0] == os.path.splitext(xmp)[0]:\n\t\t\t\t\tfile.xmpFile = xmp\n\n\t\treturn fileList\n\n\tdef fileTimeCreated(self,File,Exifdata):\n\t\tlistExif = list(Exifdata)\n\t\tif Exifdata != '0000:00':\n\t\t\tFile.YearCreated = ''.join(listExif[0:4])\n\t\t\tMonthCreated = ''.join(listExif[5:7])\n\t\t\tFile.MonthCreated = calendar.month_name[int(MonthCreated)]\n\t\telse:\n\t\t\tFile.YearCreated = 'NoYear'\n\t\t\tFile.MonthCreated = 'NoMonth'\n\n\t\tFile.Destination = self.destination + '\\\\' + File.YearCreated + '\\\\' + File.MonthCreated\n\n\t#pass List of File NameTuples\n\tdef exifData(self,fileList):\n\t\tfor file in fileList:\n\t\t\ttry:\n\t\t\t\tf=open(file.Location,'rb')\n\t\t\t\texif = exifread.process_file(f,details = False)\n\t\t\texcept:\n\t\t\t\treturn\n\n\t\t\ttry:\n\t\t\t\tdateTime = str(exif['Image DateTime'])\n\t\t\texcept:\n\t\t\t\tdateTime = '0000:00'\n\t\t\tself.fileTimeCreated(file,dateTime)\n\t\t\tprint(file.Location)\n\t\t\tf.close()\n\n\t#Give List of paths, if path exists os.makedirs will raise an exception\n\tdef makeDir(self,Files):\n\t\tdirectories = []\n\t\tfor file in Files:\n\t\t\tdirectories.append(file.Destination)\n\n\t\tuniquePaths =set(directories)\n\t\tfor path in uniquePaths:\n\t\t\ttry:\n\t\t\t\tprint(path)\n\t\t\t\tos.makedirs(path)\n\t\t\texcept:\n\t\t\t\tprint('Cannot make Directories')\n\t\t\t\tpass\n\n\tdef moveFiles(self,Files):\n\t\tfor file in Files:\n\t\t\tif file.Destination:\n\t\t\t\timageDestination= file.Destination + '\\\\' + file.Name\n\t\t\t\t#print(imageDestination)\n\t\t\t\tif os.path.isfile(imageDestination) == False:\n\t\t\t\t\tshutil.move(file.Location,imageDestination)\n\t\t\t\telse:\n\t\t\t\t\tprint('Image already exists')\n\t\t\tif file.xmpFile:\n\t\t\t\txmpDestination = file.Destination + '\\\\' + os.path.basename(file.xmpFile)\n\t\t\t\tif os.path.isfile(xmpDestination) == False:\n\t\t\t\t\tshutil.move(file.xmpFile,xmpDestination)\n\t\t\t\telse:\n\t\t\t\t\tprint('XMP already exists')\n\ntest = SortPhotos('E:\\Google Drive\\Photos\\Georgia','E:\\Google Drive\\Photos')\n\ntest.sort()\n","sub_path":"OrganizePhotos/OrganizePhotos.py","file_name":"OrganizePhotos.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"496533907","text":"class Item:\n id = \"\"\n title = \"\"\n desc = \"\"\n\n def __init__(self, id, title, desc):\n self.id = id\n self.title = title\n self.desc = desc\n\n def toJson(self):\n in_json = {\"id\":self.id, \"title\":self.title, \"desc\":self.desc}\n return in_json\n\n def toJson2(self):\n return self.__dict__\n\ntoDoList = []\n\nitem1 = Item(id=\"1\", title=\"Learn Flask\", desc=\"Start Learning Flask\")\nitem2 = Item(id=\"2\", title=\"Learn Spring\", desc=\"Start Learning Spring Framework\")\n\ntoDoList.append(item1.toJson())\ntoDoList.append(item2.toJson2())\n","sub_path":"models/Item.py","file_name":"Item.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"565727501","text":"\nfrom item_borrowing import User, Artist, Item\n\n\ndef act(user: User,\n type_of_action: str):\n \"\"\"\n Depending on type_of_action, user can register some items they own,\n borrow some items available, return some items they've borrowed\n or withdraw some items they had previously registered\n :return:\n \"\"\"\n if type_of_action not in [\"register\", \"borrow\", \"return\", \"withdraw\"]:\n raise ValueError(f\"Invalid action. type_of_action was {type_of_action} instead of\" \\\n f\" one of ['register', 'borrow', 'return', 'withdraw'] \")\n\n # If the user already has a book, then they should get a warning when trying to borrow it\n\n # If the user doesn't have at least half of the items of the same category\n # as the one they're trying to borrow, they should be redirected to\n # the page where a book is registered with a warning\n\n\n\n\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"299107741","text":"from varglas import D2Model, MomentumHybrid\nfrom fenics import Point, RectangleMesh, Expression, sqrt, pi\n\nalpha = 0.5 * pi / 180 \nL = 40000\n\np1 = Point(0.0, 0.0)\np2 = Point(L, L)\nmesh = RectangleMesh(p1, p2, 25, 25)\n\nmodel = D2Model(out_dir = './results_hybrid/')\nmodel.set_mesh(mesh)\nmodel.generate_function_spaces(use_periodic = True)\n\nsurface = Expression('- x[0] * tan(alpha)', alpha=alpha,\n element=model.Q.ufl_element())\nbed = Expression( '- x[0] * tan(alpha) - 1000.0 + 500.0 * ' \\\n + ' sin(2*pi*x[0]/L) * sin(2*pi*x[1]/L)',\n alpha=alpha, L=L, element=model.Q.ufl_element())\n\nmodel.init_S(surface)\nmodel.init_B(bed)\nmodel.init_mask(1.0) # all grounded\nmodel.init_beta(1000)\nmodel.init_b(model.A0(0)**(-1/model.n(0)))\nmodel.init_E(1.0)\n\nmom = MomentumHybrid(model, isothermal=True)\nmom.solve()\n\nmodel.save_pvd(model.U3, 'U')\n\n\n\n","sub_path":"simulations/ISMIP-HOM/A/ISMIP_HOM_A_hybrid.py","file_name":"ISMIP_HOM_A_hybrid.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"514832262","text":"from zope.testing import doctest\nimport unittest\nimport zeit.cms.testing\nimport zeit.solr.testing\n\n\ndef test_suite():\n suite = unittest.TestSuite()\n suite.addTest(zeit.cms.testing.FunctionalDocFileSuite(\n 'converter.txt',\n package='zeit.solr',\n layer=zeit.solr.testing.ZCML_LAYER,\n ))\n suite.addTest(doctest.DocFileSuite(\n 'query.txt',\n package='zeit.solr',\n ))\n return suite\n","sub_path":"src/zeit/solr/tests/test_doctest.py","file_name":"test_doctest.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"474236994","text":"# -*- coding: utf-8 -*-\n#\n# ramstk.controllers.requirement.py is part of The RAMSTK Project\n#\n# All rights reserved.\n# Copyright 2007 - 2020 Doyle Rowland doyle.rowland reliaqual com\n\"\"\"Requirement Package Data Model.\"\"\"\n\n# Standard Library Imports\nimport inspect\nfrom typing import Any, Dict\n\n# Third Party Imports\nfrom pubsub import pub\nfrom treelib.exceptions import NodeIDAbsentError\n\n# RAMSTK Package Imports\nfrom ramstk.controllers import RAMSTKDataManager\nfrom ramstk.exceptions import DataAccessError\nfrom ramstk.models.programdb import RAMSTKRequirement\n\n\nclass DataManager(RAMSTKDataManager):\n \"\"\"Contain the attributes and methods of the Requirement data manager.\n\n This class manages the requirement data from the RAMSTKRequirement\n and RAMSTKStakeholder data models.\n \"\"\"\n # Define private dictionary class attributes.\n\n # Define private list class attributes.\n\n # Define private scalar class attributes.\n _tag = 'requirements'\n\n # Define public dictionary class attributes.\n\n # Define public list class attributes.\n\n # Define public scalar class attributes.\n\n def __init__(self, **kwargs: Dict[Any, Any]) -> None:\n \"\"\"Initialize a Requirement data manager instance.\"\"\"\n super().__init__(**kwargs)\n\n # Initialize private dictionary attributes.\n self._pkey = {'requirement': ['revision_id', 'requirement_id']}\n\n # Initialize private list attributes.\n\n # Initialize private scalar attributes.\n\n # Initialize public dictionary attributes.\n\n # Initialize public list attributes.\n\n # Initialize public scalar attributes.\n\n # Subscribe to PyPubSub messages.\n pub.subscribe(super().do_get_attributes,\n 'request_get_requirement_attributes')\n pub.subscribe(super().do_set_attributes,\n 'request_set_requirement_attributes')\n pub.subscribe(super().do_set_attributes, 'mvw_editing_requirement')\n pub.subscribe(super().do_set_attributes, 'wvw_editing_requirement')\n pub.subscribe(super().do_update_all, 'request_update_all_requirements')\n pub.subscribe(super().do_create_all_codes,\n 'request_create_all_requirement_codes')\n\n pub.subscribe(self.do_select_all, 'selected_revision')\n pub.subscribe(self.do_update, 'request_update_requirement')\n pub.subscribe(self.do_get_tree, 'request_get_requirements_tree')\n pub.subscribe(self.do_create_code, 'request_create_requirement_code')\n\n pub.subscribe(self._do_delete, 'request_delete_requirement')\n pub.subscribe(self._do_insert_requirement,\n 'request_insert_requirement')\n\n def do_create_code(self, node_id: int, prefix: str) -> None:\n \"\"\"Request to create the requirement code.\n\n :param node_id: the Requirement ID to create the code for.\n :param prefix: the code prefix to use for the requested code.\n :return: None\n :rtype: None\n \"\"\"\n try:\n _requirement = self.tree.get_node(node_id).data['requirement']\n _requirement.create_code(prefix=prefix)\n\n pub.sendMessage('succeed_create_code')\n pub.sendMessage(\n 'succeed_create_requirement_code',\n requirement_code=_requirement.get_attributes()\n ['requirement_code'],\n )\n except (TypeError, AttributeError):\n if node_id != 0:\n _method_name: str = inspect.currentframe( # type: ignore\n ).f_code.co_name\n pub.sendMessage(\n 'fail_create_requirement_code',\n error_message=('{1}: No data package found for '\n 'requirement ID {0:s}.').format(\n str(node_id), _method_name),\n )\n\n def do_get_tree(self) -> None:\n \"\"\"Retrieve the requirement treelib Tree.\n\n :return: None\n :rtype: None\n \"\"\"\n pub.sendMessage(\n 'succeed_get_requirements_tree',\n tree=self.tree,\n )\n\n def do_select_all(self, attributes: Dict[str, Any]) -> None:\n \"\"\"Retrieve all the Requirement data from the RAMSTK Program database.\n\n :param attributes: the attributes for the selected Revision.\n :return: None\n :rtype: None\n \"\"\"\n self._revision_id = attributes['revision_id']\n\n for _node in self.tree.children(self.tree.root):\n self.tree.remove_node(_node.identifier)\n\n for _requirement in self.dao.do_select_all(\n RAMSTKRequirement,\n key=['revision_id'],\n value=[self._revision_id],\n order=RAMSTKRequirement.requirement_id):\n\n self.tree.create_node(tag='requirement',\n identifier=_requirement.requirement_id,\n parent=_requirement.parent_id,\n data={'requirement': _requirement})\n\n self.last_id = max(self.tree.nodes.keys())\n\n pub.sendMessage(\n 'succeed_retrieve_requirements',\n tree=self.tree,\n )\n\n def do_update(self, node_id: int) -> None:\n \"\"\"Update record associated with node ID in RAMSTK Program database.\n\n :param node_id: the node (requirement) ID of the requirement to save.\n :return: None\n :rtype: None\n \"\"\"\n try:\n self.dao.do_update(self.tree.get_node(node_id).data['requirement'])\n\n pub.sendMessage(\n 'succeed_update_requirement',\n tree=self.tree,\n )\n except AttributeError:\n _method_name: str = inspect.currentframe( # type: ignore\n ).f_code.co_name\n _error_msg: str = (\n '{1}: Attempted to save non-existent requirement with '\n 'requirement ID {0}.').format(str(node_id), _method_name)\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error_msg,\n )\n pub.sendMessage(\n 'fail_update_requirement',\n error_message=_error_msg,\n )\n except KeyError:\n _method_name: str = inspect.currentframe( # type: ignore\n ).f_code.co_name\n _error_msg = (\n '{1}: No data package found for requirement ID {0}.').format(\n str(node_id), _method_name)\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error_msg,\n )\n pub.sendMessage(\n 'fail_update_requirement',\n error_message=_error_msg,\n )\n except TypeError:\n if node_id != 0:\n _method_name: str = inspect.currentframe( # type: ignore\n ).f_code.co_name\n _error_msg = ('{1}: The value for one or more attributes for '\n 'requirement ID {0} was the wrong type.').format(\n str(node_id), _method_name)\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error_msg,\n )\n pub.sendMessage(\n 'fail_update_requirement',\n error_message=_error_msg,\n )\n\n def _do_delete(self, node_id: int) -> None:\n \"\"\"Remove a requirement.\n\n :param node_id: the node (requirement) ID to be removed from the\n RAMSTK Program database.\n :return: None\n :rtype: None\n \"\"\"\n try:\n # Delete the children (if any), then the parent node that was\n # passed.\n for _child in self.tree.children(node_id):\n super().do_delete(_child.identifier, 'requirement')\n super().do_delete(node_id, 'requirement')\n\n self.tree.remove_node(node_id)\n self.last_id = max(self.tree.nodes.keys())\n\n pub.sendMessage(\n 'succeed_delete_requirement',\n tree=self.tree,\n )\n except (AttributeError, DataAccessError, NodeIDAbsentError):\n _method_name: str = inspect.currentframe( # type: ignore\n ).f_code.co_name\n _error_msg: str = (\n '{1}: Attempted to delete non-existent requirement ID {'\n '0}.').format(str(node_id), _method_name)\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error_msg,\n )\n pub.sendMessage(\n 'fail_delete_requirement',\n error_message=_error_msg,\n )\n\n def _do_insert_requirement(self, parent_id: int = 0) -> None:\n \"\"\"Add a new requirement.\n\n :param parent_id: the parent (requirement) ID the new requirement\n will be a child (derived) of.\n :return: None\n :rtype: None\n \"\"\"\n try:\n _requirement = RAMSTKRequirement()\n _requirement.revision_id = self._revision_id\n _requirement.requirement_id = self.last_id + 1\n _requirement.parent_id = parent_id\n _requirement.description = 'New Requirement'\n\n self.dao.do_insert(_requirement)\n\n self.last_id = _requirement.requirement_id\n self.tree.create_node(tag='requirement',\n identifier=self.last_id,\n parent=parent_id,\n data={'requirement': _requirement})\n\n pub.sendMessage(\n 'succeed_insert_requirement',\n node_id=self.last_id,\n tree=self.tree,\n )\n except NodeIDAbsentError:\n _method_name: str = inspect.currentframe( # type: ignore\n ).f_code.co_name\n _error_msg: str = (\n '{1}: Attempted to insert child requirement under '\n 'non-existent requirement ID {0}.').format(\n str(parent_id), _method_name)\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error_msg,\n )\n pub.sendMessage(\n \"fail_insert_requirement\",\n error_message=_error_msg,\n )\n except DataAccessError as _error:\n pub.sendMessage(\n 'do_log_debug',\n logger_name='DEBUG',\n message=_error.msg,\n )\n pub.sendMessage(\n \"fail_insert_requirement\",\n error_message=_error.msg,\n )\n","sub_path":"src/ramstk/controllers/requirement/datamanager.py","file_name":"datamanager.py","file_ext":"py","file_size_in_byte":10879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"380584175","text":"import sqlite3\n# Luodaan database yhteys\nconn = sqlite3.connect('database.sqlite')\n\ncursor = conn.cursor()\n# Luodaan taulut tietokantaan pohjaksi\ncursor.execute('''CREATE TABLE EVENT\n (ID INTEGER PRIMARY KEY AUTOINCREMENT,\n PAIVA TEXT NOT NULL,\n TEKSTI TEXT NOT NULL);''')\n\n#cursor.execute(\"INSERT INTO EVENT (TEKSTI)\\\n # VALUES ('Koira')\");\n\n\n# Suoritetaan ja suljetaan tietokanta\nconn.commit()\ncursor.close()","sub_path":"src/databasethings.py","file_name":"databasethings.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"516319813","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport datetime\nimport json\nimport unittest\nfrom six.moves import html_parser as HTMLParser\n\nfrom django.apps import apps\nfrom django.core.urlresolvers import reverse\nfrom django.http import Http404, HttpRequest, HttpResponse\nfrom django.template.defaultfilters import slugify\nfrom django.test import RequestFactory, TestCase\nfrom django.utils import html, timezone\nfrom django.utils.translation import ugettext as _\nfrom haystack.models import SearchResult\nfrom haystack.query import SearchQuerySet\n\nfrom wagtail.tests.utils import WagtailTestUtils\n\nimport mock\nfrom mock import mock_open, patch\nfrom model_mommy import mommy\n\nfrom ask_cfpb.models.django import (\n ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG, Answer, Audience, Category,\n NextStep, SubCategory, generate_short_slug\n)\nfrom ask_cfpb.models.pages import (\n JOURNEY_PATHS, AnswerAudiencePage, AnswerCategoryPage, AnswerPage\n)\nfrom ask_cfpb.scripts.export_ask_data import (\n assemble_output, clean_and_strip, export_questions\n)\nfrom v1.models import BrowsePage, CFGOVImage, HomePage\nfrom v1.tests.wagtail_pages import helpers\nfrom v1.util.migrations import get_free_path, get_or_create_page\n\n\nhtml_parser = HTMLParser.HTMLParser()\nnow = timezone.now()\n\n\nclass AnswerSlugCreationTest(unittest.TestCase):\n\n def test_long_slug_string(self):\n long_string = (\n \"This string is more than 100 characters long, I assure you. \"\n \"No, really, more than 100 characters loooong.\")\n self.assertEqual(\n generate_short_slug(long_string),\n ('this-string-is-more-than-100-characters-long-'\n 'i-assure-you-no-really-more-than-100-characters'))\n\n def test_short_slug_string(self):\n short_string = \"This string is less than 100 characters long.\"\n self.assertEqual(\n generate_short_slug(short_string), slugify(short_string))\n\n def test_slug_string_that_will_end_with_a_hyphen(self):\n \"\"\"\n It's possible for slug truncation to result in a slug that ends\n on a hypthen. In that case the function should strip the ending hyphen.\n \"\"\"\n will_end_with_hyphen = (\n \"This string is more than 100 characters long, I assure you. \"\n \"No, really, more than 100 characters looong and end on a hyphen.\")\n self.assertEqual(\n generate_short_slug(will_end_with_hyphen),\n 'this-string-is-more-than-100-characters-long-i-assure-you-'\n 'no-really-more-than-100-characters-looong')\n\n\nclass ExportAskDataTests(TestCase, WagtailTestUtils):\n\n def setUp(self):\n self.mock_assemble_output_value = [{\n 'ASK_ID': 123456,\n 'Question': \"Question\",\n 'ShortAnswer': \"Short answer.\",\n 'Answer': \"Long answer.\",\n 'URL': \"fakeurl.com\",\n 'SpanishQuestion': \"Spanish question.\",\n 'SpanishAnswer': \"Spanish answer\",\n 'SpanishURL': \"fakespanishurl.com\",\n 'Topic': \"Category 5 Hurricane\",\n 'SubCategories': \"Subcat1 | Subcat2\",\n 'Audiences': \"Audience1 | Audience2\",\n 'RelatedQuestions': \"1 | 2 | 3\",\n 'RelatedResources': \"Owning a Home\"}]\n\n def test_clean_and_strip(self):\n raw_data = \"

    If you have been scammed, file a complaint.

    \"\n clean_data = \"If you have been scammed, file a complaint.\"\n self.assertEqual(clean_and_strip(raw_data), clean_data)\n\n @mock.patch('ask_cfpb.scripts.export_ask_data.assemble_output')\n def test_export_questions(self, mock_output):\n mock_output.return_value = self.mock_assemble_output_value\n timestamp = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n slug = 'ask-cfpb-{}.csv'.format(timestamp)\n m = mock_open()\n with patch('six.moves.builtins.open', m, create=True):\n export_questions()\n self.assertEqual(mock_output.call_count, 1)\n m.assert_called_once_with(\"/tmp/{}\".format(slug), 'w')\n\n @mock.patch('ask_cfpb.scripts.export_ask_data.assemble_output')\n def test_export_from_admin_post(self, mock_output):\n self.login()\n mock_output.return_value = self.mock_assemble_output_value\n response = self.client.post('/admin/export-ask/')\n self.assertEqual(response.status_code, 200)\n # Check that fields from the mock value are included\n self.assertContains(response, 'fakespanishurl.com')\n self.assertContains(response, 'fakeurl.com')\n\n def test_export_from_admin_get(self):\n self.login()\n response = self.client.get('/admin/export-ask/')\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, 'Download a spreadsheet')\n\n\nclass AnswerModelTestCase(TestCase):\n\n def prepare_answer(self, **kwargs):\n kwargs.setdefault('answer', 'Mock answer')\n kwargs.setdefault('slug', 'mock-answer')\n return mommy.prepare(Answer, **kwargs)\n\n def create_answer_page(self, **kwargs):\n kwargs.setdefault(\n 'path', get_free_path(apps, self.english_parent_page))\n kwargs.setdefault('depth', self.english_parent_page.depth + 1)\n kwargs.setdefault('slug', 'mock-answer-page-en-1234')\n kwargs.setdefault('title', 'Mock answer page title')\n page = mommy.prepare(AnswerPage, **kwargs)\n page.save()\n return page\n\n def create_category_page(self, **kwargs):\n kwargs.setdefault(\n 'path', get_free_path(apps, self.english_parent_page))\n kwargs.setdefault('depth', self.english_parent_page.depth + 1)\n kwargs.setdefault('slug', 'category-mortgages')\n kwargs.setdefault('title', 'Mortgages')\n return AnswerCategoryPage(**kwargs)\n\n def create_audience_page(self, **kwargs):\n kwargs.setdefault(\n 'path', get_free_path(apps, self.english_parent_page))\n kwargs.setdefault('depth', self.english_parent_page.depth + 1)\n kwargs.setdefault('slug', 'audience-students')\n kwargs.setdefault('title', 'Students')\n return AnswerAudiencePage.objects.create(**kwargs)\n\n def setUp(self):\n self.factory = RequestFactory()\n ROOT_PAGE = HomePage.objects.get(slug='cfgov')\n self.audience = mommy.make(Audience, name='stub_audience')\n self.category = mommy.make(\n Category, name='stub_cat', name_es='que', slug='stub-cat')\n self.subcategories = mommy.make(\n SubCategory, name='stub_subcat', parent=self.category, _quantity=3)\n self.category.subcategories.add(self.subcategories[0])\n self.category.save()\n self.test_image = mommy.make(CFGOVImage)\n self.test_image2 = mommy.make(CFGOVImage)\n self.next_step = mommy.make(NextStep, title='stub_step')\n page_clean = patch('ask_cfpb.models.pages.CFGOVPage.clean')\n page_clean.start()\n self.addCleanup(page_clean.stop)\n self.english_parent_page = get_or_create_page(\n apps,\n 'ask_cfpb',\n 'AnswerLandingPage',\n 'Ask CFPB',\n ENGLISH_PARENT_SLUG,\n ROOT_PAGE,\n language='en',\n live=True)\n self.spanish_parent_page = get_or_create_page(\n apps,\n 'ask_cfpb',\n 'AnswerLandingPage',\n 'Obtener respuestas',\n SPANISH_PARENT_SLUG,\n ROOT_PAGE,\n language='es',\n live=True)\n self.tag_results_page_en = get_or_create_page(\n apps,\n 'ask_cfpb',\n 'TagResultsPage',\n 'Tag results page',\n 'search-by-tag',\n ROOT_PAGE,\n language='en',\n live=True)\n self.tag_results_page_es = get_or_create_page(\n apps,\n 'ask_cfpb',\n 'TagResultsPage',\n 'Tag results page',\n 'buscar-por-etiqueta',\n ROOT_PAGE,\n language='es',\n live=True)\n self.answer1234 = self.prepare_answer(\n id=1234,\n answer='Mock answer 1',\n answer_es='Mock Spanish answer',\n slug='mock-answer-en-1234',\n slug_es='mock-spanish-answer-es-1234',\n question='Mock question1',\n question_es='Mock Spanish question1',\n search_tags='hippodrome',\n search_tags_es='hipotecas',\n update_english_page=True,\n update_spanish_page=True)\n self.answer1234.save()\n self.page1 = self.answer1234.english_page\n self.page1.live = True\n self.page1.save()\n self.page1_es = self.answer1234.spanish_page\n self.page1_es.live = True\n self.page1_es.save()\n self.answer5678 = self.prepare_answer(\n id=5678,\n answer='Mock answer 2',\n question='Mock question2',\n search_tags='hippodrome',\n search_tags_es='hipotecas')\n self.answer5678.save()\n self.page2 = self.create_answer_page(slug='mock-answer-page-en-5678')\n self.page2.answer_base = self.answer5678\n self.page2.parent = self.english_parent_page\n self.page2.save()\n\n def test_export_script_assemble_output(self):\n expected_urls = ['/ask-cfpb/mock-question1-en-1234/',\n '/ask-cfpb/mock-answer-page-en-5678/']\n expected_questions = ['Mock question1', 'Mock question2']\n test_output = assemble_output()\n for obj in test_output:\n self.assertIn(obj.get('ASK_ID'), [1234, 5678])\n self.assertIn(obj.get('URL'), expected_urls)\n self.assertIn(obj.get('Question'), expected_questions)\n\n def test_spanish_print_page(self):\n response = self.client.get(reverse(\n 'ask-spanish-print-answer',\n args=['slug', 'es', '1234']))\n self.assertEqual(response.status_code, 200)\n\n def test_spanish_print_page_no_answer_404(self):\n response = self.client.get(reverse(\n 'ask-spanish-print-answer',\n args=['slug', 'es', '9999']))\n self.assertEqual(response.status_code, 404)\n\n def test_spanish_page_print_blank_answer_404(self):\n test_answer = self.prepare_answer(\n id=999,\n answer_es='',\n slug_es='mock-spanish-answer-es-999',\n question_es='Mock Spanish question1',\n update_spanish_page=True)\n test_answer.save()\n response = self.client.get(reverse(\n 'ask-spanish-print-answer',\n args=['slug', 'es', 999]))\n self.assertEqual(response.status_code, 404)\n\n def test_english_page_context(self):\n from v1.models.snippets import ReusableText\n from ask_cfpb.models.pages import get_reusable_text_snippet\n rt = ReusableText(title='About us (For consumers)')\n rt.save()\n page = self.page1\n page.language = 'en'\n page.save()\n test_context = page.get_context(HttpRequest())\n self.assertEqual(\n test_context['about_us'],\n get_reusable_text_snippet('About us (For consumers)'))\n\n def test_english_page_get_template(self):\n page = self.page1\n self.assertEqual(\n page.get_template(HttpRequest()),\n 'ask-cfpb/answer-page.html')\n\n def create_live_answer(self, answer_id=None, question=None):\n kwargs = {}\n\n if answer_id is not None:\n kwargs['id'] = answer_id\n\n if question is not None:\n kwargs['question'] = question\n\n answer = self.prepare_answer(update_english_page=True, **kwargs)\n answer.save()\n\n answer_english_page = answer.english_page\n answer_english_page.live = True\n answer_english_page.save()\n\n return answer\n\n def test_category_facet_map_includes_answer_and_question(self):\n answer = self.create_live_answer(\n answer_id=999,\n question='test question'\n )\n\n category = mommy.make(Category)\n answer.category.add(category)\n\n category_facet_map = json.loads(category.facet_map)\n self.assertEqual(\n category_facet_map['answers']['999']['question'],\n 'test question'\n )\n\n def test_category_facet_map_includes_audience_name(self):\n answer = self.create_live_answer()\n\n audience = mommy.make(Audience, id=123, name='test audience')\n answer.audiences.add(audience)\n\n category = mommy.make(Category)\n answer.category.add(category)\n\n category_facet_map = json.loads(category.facet_map)\n self.assertEqual(\n category_facet_map['audiences']['123']['name'],\n 'test audience'\n )\n\n def test_category_facet_map_includes_subcategories_with_answer_ids(self):\n category = mommy.make(Category)\n subcategory = mommy.make(SubCategory, parent=category, id=7)\n category.subcategories.add(subcategory)\n\n answer1 = self.create_live_answer(answer_id=14)\n answer1.subcategory.add(subcategory)\n\n answer2 = self.create_live_answer(answer_id=21)\n answer2.subcategory.add(subcategory)\n\n category_facet_map = json.loads(category.facet_map)\n self.assertEqual(\n sorted(category_facet_map['subcategories']['7']),\n sorted(['14', '21'])\n )\n\n def test_facet_map_skips_draft_page(self):\n self.answer1234.category.add(self.category)\n self.answer1234.audiences.add(self.audience)\n self.answer1234.subcategory.add(self.subcategories[1])\n self.page1.live = False\n self.page1.save()\n facet_map = self.category.facet_map\n self.assertEqual(\n json.loads(facet_map)['answers'].get('1234'), None)\n\n def test_answer_valid_tags(self):\n test_dict = Answer.valid_tags()\n self.assertIn('hippodrome', test_dict['valid_tags'])\n\n def test_answer_valid_es_tags(self):\n test_dict = Answer.valid_tags(language='es')\n self.assertIn('hipotecas', test_dict['valid_tags'])\n\n def test_answer_invalid_tag(self):\n test_dict = Answer.valid_tags(language='es')\n self.assertNotIn('hippopotamus', test_dict['valid_tags'])\n\n def test_routable_category_page_view(self):\n cat_page = self.create_category_page(\n ask_category=self.category)\n response = cat_page.category_page(HttpRequest())\n self.assertEqual(response.status_code, 200)\n\n def test_routable_category_page_bad_pagination(self):\n cat_page = self.create_category_page(\n ask_category=self.category)\n request = HttpRequest()\n request.GET['page'] = 50\n response = cat_page.category_page(request)\n self.assertEqual(response.status_code, 200)\n\n def test_routable_category_page_invalid_pagination(self):\n cat_page = self.create_category_page(\n ask_category=self.category)\n request = HttpRequest()\n request.GET['page'] = 'A50'\n response = cat_page.category_page(request)\n self.assertEqual(response.status_code, 200)\n\n def test_routable_subcategory_page_view(self):\n cat_page = self.create_category_page(\n ask_category=self.category)\n response = cat_page.subcategory_page(\n HttpRequest(), subcat=self.subcategories[0].slug)\n self.assertEqual(response.status_code, 200)\n\n def test_routable_subcategory_page_bad_subcategory(self):\n cat_page = self.create_category_page(\n ask_category=self.category)\n with self.assertRaises(Http404):\n cat_page.subcategory_page(HttpRequest(), subcat=None)\n\n def test_routable_subcategory_page_bad_pagination(self):\n cat_page = self.create_category_page(\n ask_category=self.category)\n request = HttpRequest()\n request.GET['page'] = 100\n response = cat_page.subcategory_page(\n request, subcat=self.subcategories[0].slug)\n self.assertEqual(response.status_code, 200)\n\n def test_routable_tag_page_en_template(self):\n page = self.tag_results_page_en\n self.assertEqual(\n page.get_template(HttpRequest()),\n 'ask-cfpb/answer-search-results.html')\n\n def test_routable_tag_page_es_template(self):\n page = self.tag_results_page_es\n self.assertEqual(\n page.get_template(HttpRequest()),\n 'ask-cfpb/answer-tag-spanish-results.html')\n\n def test_routable_tag_page_base_returns_404(self):\n page = self.tag_results_page_en\n response = self.client.get(\n page.url + page.reverse_subpage(\n 'tag_base'))\n self.assertEqual(response.status_code, 404)\n\n def test_routable_tag_page_es_bad_tag_returns_404(self):\n page = self.tag_results_page_es\n response = self.client.get(\n page.url + page.reverse_subpage(\n 'tag_search',\n kwargs={'tag': 'hippopotamus'}))\n self.assertEqual(response.status_code, 404)\n\n def test_routable_tag_page_en_bad_tag_returns_404(self):\n page = self.tag_results_page_en\n response = self.client.get(\n page.url + page.reverse_subpage(\n 'tag_search',\n kwargs={'tag': 'hippopotamus'}))\n self.assertEqual(response.status_code, 404)\n\n def test_routable_tag_page_es_handles_bad_pagination(self):\n page = self.tag_results_page_es\n response = self.client.get(\n page.url + page.reverse_subpage(\n 'tag_search',\n kwargs={'tag': 'hipotecas'}), {'page': '100'})\n self.assertEqual(response.status_code, 200)\n\n def test_routable_tag_page_en_handles_bad_pagination(self):\n page = self.tag_results_page_en\n response = self.client.get(\n page.url + page.reverse_subpage(\n 'tag_search',\n kwargs={'tag': 'hippodrome'}), {'page': '100'})\n self.assertEqual(response.status_code, 200)\n\n def test_routable_tag_page_es_valid_tag_returns_200(self):\n page = self.tag_results_page_es\n response = self.client.get(\n page.url + page.reverse_subpage(\n 'tag_search',\n kwargs={'tag': 'hipotecas'}))\n self.assertEqual(response.status_code, 200)\n\n def test_routable_tag_page_en_valid_tag_returns_200(self):\n page = self.tag_results_page_en\n response = self.client.get(\n page.url + page.reverse_subpage(\n 'tag_search',\n kwargs={'tag': 'hippodrome'}))\n self.assertEqual(response.status_code, 200)\n\n def test_routable_tag_page_es_returns_url_suffix(self):\n page = self.tag_results_page_es\n response = page.reverse_subpage(\n 'tag_search', kwargs={'tag': 'hipotecas'})\n self.assertEqual(response, 'hipotecas/')\n\n def test_routable_tag_page_en_returns_url_suffix(self):\n page = self.tag_results_page_en\n response = page.reverse_subpage(\n 'tag_search', kwargs={'tag': 'hippodrome'})\n self.assertEqual(response, 'hippodrome/')\n\n def test_view_answer_exact_slug(self):\n page = self.page1\n page.slug = 'mock-answer-en-1234'\n page.save()\n revision = page.save_revision()\n revision.publish()\n response = self.client.get(reverse(\n 'ask-english-answer', args=['mock-answer', 'en', 1234]))\n self.assertEqual(response.status_code, 200)\n\n def test_view_answer_301_for_healed_slug(self):\n page = self.page1\n revision = page.save_revision()\n revision.publish()\n response = self.client.get(reverse(\n 'ask-english-answer', args=['mock-slug', 'en', 1234]))\n self.assertEqual(response.status_code, 301)\n\n def test_view_answer_redirected(self):\n page = self.page1\n page.redirect_to = self.page2.answer_base\n page.save()\n revision = page.save_revision()\n revision.publish()\n response_302 = self.client.get(reverse(\n 'ask-english-answer', args=['mocking-answer-page', 'en', 1234]))\n self.assertTrue(isinstance(response_302, HttpResponse))\n self.assertEqual(response_302.status_code, 301)\n\n def test_answer_deletion(self):\n \"\"\"deleting an answer should also delete its related pages\"\"\"\n answer = self.prepare_answer(\n created_at=now,\n question='Mock question',\n question_es='Mock Spanish question',\n answer_es='Mock Spanish Answer.')\n answer.save()\n answer.create_or_update_pages()\n ID = answer.id\n self.assertEqual(Answer.objects.get(id=ID), answer)\n self.assertEqual(\n AnswerPage.objects.filter(answer_base=answer).count(), 2)\n answer.delete()\n self.assertEqual(\n AnswerPage.objects.filter(answer_base=answer).count(), 0)\n self.assertEqual(\n Answer.objects.filter(id=ID).count(), 0)\n\n def test_audience_page_add_js(self):\n test_page = self.create_audience_page(language='en')\n self.assertEqual(test_page.page_js, ['secondary-navigation.js'])\n\n def test_audience_page_add_js_wrong_language(self):\n \"\"\"page_js should only be added on English Audience pages\"\"\"\n test_page = self.create_audience_page(language='es')\n self.assertFalse(test_page.page_js)\n\n def test_spanish_template_used(self):\n path = reverse(\n 'ask-spanish-answer',\n args=['mock-spanish-question1', 'es', '1234']\n )\n response = self.client.get(path)\n self.assertContains(\n response,\n (\n ''\n '> Oficina para la Protección Financiera del Consumidor'\n ''\n ),\n html=True\n )\n\n def test_spanish_answer_page_handles_referrer_with_unicode_accents(self):\n referrer_unicode = (\n 'https://www.consumerfinance.gov/es/obtener-respuestas/'\n 'buscar-por-etiqueta/empresas_de_informes_de_cr\\xe9dito/')\n spanish_answer = self.prepare_answer(\n answer_es='Spanish answer',\n slug_es='spanish-answer',\n update_spanish_page=True)\n spanish_answer.save()\n spanish_page = spanish_answer.spanish_page\n request = HttpRequest()\n request.POST['referrer'] = referrer_unicode\n response = spanish_page.serve(request)\n self.assertEqual(response.status_code, 200)\n\n def test_create_or_update_page_unsuppoted_language(self):\n answer = self.prepare_answer()\n answer.save()\n with self.assertRaises(ValueError):\n answer.create_or_update_page(language='zz')\n\n def test_create_or_update_pages_english_only(self):\n answer = self.prepare_answer()\n answer.save()\n result = answer.create_or_update_pages()\n self.assertEqual(result, 1)\n\n def test_create_or_update_pages_spanish_only(self):\n answer = self.prepare_answer(answer='', answer_es='vamos')\n answer.save()\n result = answer.create_or_update_pages()\n self.assertEqual(result, 1)\n\n def test_create_or_update_pages_both_languages(self):\n answer = self.prepare_answer(answer_es='vamos')\n answer.save()\n result = answer.create_or_update_pages()\n self.assertEqual(result, 2)\n\n @mock.patch('ask_cfpb.models.django.Answer.create_or_update_page')\n def test_save_skip_page_update(self, mock_create_page):\n answer = self.prepare_answer(\n question='Test question.',\n question_es='Test Spanish question.',\n answer_es='vamos',\n update_english_page=True,\n update_spanish_page=True)\n answer.save(skip_page_update=True)\n self.assertEqual(mock_create_page.call_count, 0)\n\n @mock.patch('ask_cfpb.models.django.Answer.create_or_update_page')\n def test_save_english_to_page(self, mock_create_page):\n answer = self.prepare_answer(\n question='Test question.',\n question_es='Test Spanish question.',\n answer_es='vamos',\n update_english_page=True,\n update_spanish_page=False)\n answer.save()\n mock_create_page.assert_called_with(language='en')\n self.assertEqual(mock_create_page.call_count, 1)\n\n @mock.patch('ask_cfpb.models.django.Answer.create_or_update_page')\n def test_save_spanish_to_page(self, mock_create_page):\n answer = self.prepare_answer(\n question='Test question.',\n question_es='Test Spanish question.',\n answer_es='vamos',\n update_english_page=False,\n update_spanish_page=True)\n answer.save()\n mock_create_page.assert_called_with(language='es')\n self.assertEqual(mock_create_page.call_count, 1)\n\n @mock.patch('ask_cfpb.models.django.Answer.create_or_update_page')\n def test_save_both_languages_to_page(self, mock_create_page):\n answer = self.prepare_answer(\n question='Test question.',\n question_es='Test Spanish question.',\n answer_es='vamos',\n update_english_page=True,\n update_spanish_page=True)\n answer.save()\n mock_create_page.assert_called_with(language='es')\n self.assertEqual(mock_create_page.call_count, 2)\n\n def test_has_live_page(self):\n answer = self.prepare_answer()\n answer.save()\n self.assertEqual(answer.has_live_page(), False)\n answer.update_english_page = True\n answer.save()\n _page = answer.answer_pages.get(language='en')\n self.assertEqual(answer.has_live_page(), False)\n _revision = _page.save_revision()\n _revision.publish()\n self.assertEqual(answer.has_live_page(), True)\n\n def test_available_subcategories_qs(self):\n parent_category = self.category\n for sc in self.subcategories:\n sc.parent = parent_category\n sc.save()\n answer = self.prepare_answer()\n answer.save()\n answer.category.add(parent_category)\n answer.save()\n for subcat in self.subcategories:\n self.assertIn(subcat, answer.available_subcategory_qs)\n\n def test_bass_string_no_base(self): # sic\n test_page = self.create_answer_page()\n result = test_page.__str__()\n self.assertEqual(result, test_page.title)\n\n def test_bass_string_with_base(self): # sic\n mock_answer = self.prepare_answer()\n mock_answer.save()\n test_page = self.create_answer_page(answer_base=mock_answer)\n result = test_page.__str__()\n self.assertEqual(result, \"{}: {}\".format(\n mock_answer.id, test_page.title))\n\n def test_audience_strings(self):\n \"\"\"Test the generator produced by answer.audience_strings()\"\"\"\n audience = Audience.objects.first()\n answer = self.prepare_answer()\n answer.save()\n answer.audiences.add(audience)\n answer.save()\n self.assertIn(audience.name, answer.audience_strings())\n\n def test_search_tags(self):\n \"\"\"Test the list produced by answer.tags()\"\"\"\n answer = self.prepare_answer(search_tags='Chutes, Ladders')\n answer.save()\n taglist = answer.clean_tags\n for name in ['Chutes', 'Ladders']:\n self.assertIn(name, taglist)\n\n def test_search_tags_es(self):\n \"\"\"Test the list produced by answer.tags_es()\"\"\"\n answer = self.prepare_answer(search_tags_es='sistema judicial, tipos')\n answer.save()\n taglist = answer.clean_tags_es\n for term in ['sistema judicial', 'tipos']:\n self.assertIn(term, taglist)\n\n def test_category_text(self):\n answer = self.prepare_answer()\n answer.save()\n answer.category.add(self.category)\n answer.save()\n self.assertEqual(answer.category_text(), [self.category.name])\n self.assertEqual(answer.category_text_es(), [self.category.name_es])\n\n def test_category_text_no_category(self):\n answer = self.prepare_answer()\n answer.save()\n self.assertEqual(answer.category_text(), '')\n self.assertEqual(answer.category_text_es(), '')\n\n def test_answer_text(self):\n raw_snippet = \"Snippet.\"\n raw_answer = \"Clean answer test \"\n combo = \"{} {}\".format(raw_snippet, raw_answer)\n clean = html.strip_tags(html_parser.unescape(combo)).strip()\n answer = self.prepare_answer(\n snippet=raw_snippet,\n answer=raw_answer,\n snippet_es=raw_snippet,\n answer_es=raw_answer)\n answer.save()\n self.assertEqual(answer.answer_text, clean)\n self.assertEqual(answer.answer_text_es, clean)\n\n def test_cleaned_questions(self):\n answer = self.prepare_answer(\n question=\"Clean question test \",\n question_es=\"Clean question test \")\n raw = \"Clean question test \"\n clean = html.strip_tags(html_parser.unescape(raw)).strip()\n answer.save()\n self.assertEqual(answer.cleaned_questions(), [clean])\n self.assertEqual(answer.cleaned_questions_es(), [clean])\n\n def test_answer_str(self):\n answer = self.prepare_answer(question=\"Let's test an English slug\")\n answer.save()\n self.assertEqual(\n answer.__str__(),\n \"{} {}\".format(answer.id, answer.slug))\n\n def test_category_str(self):\n category = self.category\n self.assertEqual(category.__str__(), category.name)\n\n def test_category_featured_answers(self):\n category = self.category\n mock_answer = self.answer1234\n mock_answer.featured = True\n mock_answer.category.add(category)\n mock_answer.save()\n self.assertIn(mock_answer, category.featured_answers())\n\n def test_subcategory_str(self):\n subcategory = self.subcategories[0]\n self.assertEqual(\n subcategory.__str__(),\n \"{}: {}\".format(self.category.name, subcategory.name))\n\n def test_nextstep_str(self):\n next_step = self.next_step\n self.assertEqual(next_step.__str__(), next_step.title)\n\n def test_audience_str(self):\n audience = self.audience\n self.assertEqual(audience.__str__(), audience.name)\n\n def test_status_string(self):\n answer1 = self.prepare_answer()\n answer1.save()\n answer2 = self.prepare_answer()\n answer2.save()\n test_page = self.create_answer_page(answer_base=answer1)\n test_page.live = False\n test_redirect_page = self.create_answer_page(answer_base=answer2)\n test_page.redirect_to = test_redirect_page.answer_base\n self.assertEqual(\n test_page.status_string.lower(),\n _(\"redirected but not live\").lower())\n test_page.live = True\n self.assertEqual(\n test_page.status_string.lower(), _(\"redirected\").lower())\n test_page.redirect_to = None\n self.assertEqual(\n test_page.status_string.lower(), _(\"live\").lower())\n\n def test_get_ask_nav_items(self):\n from ask_cfpb.models import get_ask_nav_items\n mommy.make(Category, name='test_cat')\n test_nav_items = get_ask_nav_items({}, {})[0]\n self.assertEqual(\n len(test_nav_items),\n Category.objects.count())\n\n def test_get_ask_breadcrumbs(self):\n from ask_cfpb.models import get_ask_breadcrumbs\n breadcrumbs = get_ask_breadcrumbs()\n self.assertEqual(len(breadcrumbs), 1)\n self.assertEqual(breadcrumbs[0]['title'], 'Ask CFPB')\n\n def test_get_ask_breadcrumbs_with_category(self):\n from ask_cfpb.models import get_ask_breadcrumbs\n test_category = mommy.make(Category, name='breadcrumb_cat')\n breadcrumbs = get_ask_breadcrumbs(test_category)\n self.assertEqual(len(breadcrumbs), 2)\n self.assertEqual(breadcrumbs[0]['title'], 'Ask CFPB')\n self.assertEqual(breadcrumbs[1]['title'], test_category.name)\n\n def test_audience_page_get_english_template(self):\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n audience_page = self.create_audience_page(\n ask_audience=self.audience, language='en')\n test_get_template = audience_page.get_template(mock_request)\n self.assertEqual(\n test_get_template,\n 'ask-cfpb/audience-page.html')\n\n def test_audience_page_context(self):\n from ask_cfpb.models import get_ask_nav_items\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n audience_page = self.create_audience_page(\n ask_audience=self.audience, language='en')\n test_context = audience_page.get_context(mock_request)\n self.assertEqual(\n test_context['get_secondary_nav_items'],\n get_ask_nav_items)\n\n def test_audience_page_handles_bad_pagination(self):\n audience_page = self.create_audience_page(\n ask_audience=self.audience, language='en')\n request = HttpRequest()\n request.GET['page'] = '100'\n response = audience_page.serve(request)\n self.assertEqual(response.status_code, 200)\n\n def test_category_page_context(self):\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n cat_page = self.create_category_page(ask_category=self.category)\n test_context = cat_page.get_context(mock_request)\n self.assertEqual(\n test_context['choices'].count(),\n self.category.subcategories.count())\n\n def test_category_page_truncation(self):\n answer = self.answer1234\n answer.answer_es = (\"We need an answer with more than 40 words to\"\n \"prove that truncation is working as expected.\"\n \"It just so happens that the standard maximum \"\n \"length for a news story's lead graph is around \"\n \"40 words, which I have now managed to exceed.\")\n answer.category.add(self.category)\n answer.save()\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n cat_page = self.create_category_page(\n ask_category=self.category, language='es')\n test_context = cat_page.get_context(mock_request)\n self.assertTrue(\n test_context['answers'][0]['answer_es'].endswith('...'))\n\n def test_category_page_context_es(self):\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n cat_page = self.create_category_page(\n ask_category=self.category, language='es')\n test_context = cat_page.get_context(mock_request)\n self.assertEqual(\n test_context['choices'].count(),\n self.category.subcategories.count())\n\n @mock.patch('ask_cfpb.models.pages.SearchQuerySet.models')\n def test_category_page_context_no_elasticsearch_count(self, mock_es_query):\n \"\"\"Ensure we fall back to the slower model method if ES returns 0.\"\"\"\n mock_es_query.return_value = SearchQuerySet().none()\n request = self.factory.get('/ask-cfpb/category-stub-cat/')\n cat_page = self.create_category_page(ask_category=self.category)\n test_context = cat_page.get_context(request)\n self.assertEqual(len(test_context['facets']), 3)\n\n @mock.patch('ask_cfpb.models.pages.SearchQuerySet.models')\n def test_category_page_context_elasticsearch_count_1(\n self, mock_sqs):\n mock_return = mock.Mock(SearchResult)\n blank_facets = {'answers': {},\n 'audiences': {},\n 'subcategories': {}}\n mock_return.facet_map = json.dumps(blank_facets)\n mock_queryset = SearchQuerySet().all()\n mock_queryset._result_count = 1\n mock_queryset._result_cache = [mock_return]\n mock_sqs.return_value = mock_queryset\n request = self.factory.get('/ask-cfpb/category-stub-cat/')\n cat_page = self.create_category_page(ask_category=self.category)\n test_context = cat_page.get_context(request)\n self.assertEqual(len(test_context['facets']), 3)\n\n def test_category_page_get_english_template(self):\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n cat_page = self.create_category_page(\n ask_category=self.category, language='en')\n test_get_template = cat_page.get_template(mock_request)\n self.assertEqual(\n test_get_template,\n 'ask-cfpb/category-page.html')\n\n def test_category_page_get_spanish_template(self):\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n cat_page = self.create_category_page(\n ask_category=self.category, language='es')\n test_get_template = cat_page.get_template(mock_request)\n self.assertEqual(\n test_get_template,\n 'ask-cfpb/category-page-spanish.html')\n\n def test_landing_page_context(self):\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n landing_page = self.english_parent_page\n test_context = landing_page.get_context(mock_request)\n self.assertEqual(\n test_context['categories'].count(),\n Category.objects.count())\n self.assertEqual(\n len(test_context['audiences']),\n Audience.objects.count())\n\n def test_landing_page_get_english_template(self):\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n landing_page = self.english_parent_page\n test_get_template = landing_page.get_template(mock_request)\n self.assertEqual(\n test_get_template,\n 'ask-cfpb/landing-page.html')\n\n def test_landing_page_get_spanish_template(self):\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n landing_page = self.spanish_parent_page\n test_get_template = landing_page.get_template(mock_request)\n self.assertEqual(\n test_get_template,\n 'ask-cfpb/landing-page-spanish.html')\n\n def test_category_page_add_js_function(self):\n cat_page = self.create_category_page(ask_category=self.category)\n self.assertEqual(cat_page.page_js, ['secondary-navigation.js'])\n\n def test_answer_language_page_exists(self):\n self.assertEqual(self.answer5678.english_page, self.page2)\n\n def test_answer_language_page_nonexistent(self):\n self.assertEqual(self.answer5678.spanish_page, None)\n\n def test_answer_page_print_template_used(self):\n answer_page = self.create_answer_page(language='es')\n mock_site = mock.Mock()\n mock_site.hostname = 'localhost'\n mock_request = HttpRequest()\n mock_request.site = mock_site\n mock_request.GET = {'print': 'true'}\n self.assertEqual(\n answer_page.get_template(mock_request),\n 'ask-cfpb/answer-page-spanish-printable.html')\n\n def test_get_reusable_text_snippet(self):\n from ask_cfpb.models import get_reusable_text_snippet\n from v1.models.snippets import ReusableText\n test_snippet = ReusableText.objects.create(title='Test Snippet')\n self.assertEqual(\n get_reusable_text_snippet('Test Snippet'),\n test_snippet)\n\n def test_get_nonexistent_reusable_text_snippet(self):\n from ask_cfpb.models import get_reusable_text_snippet\n self.assertEqual(\n get_reusable_text_snippet('Nonexistent Snippet'),\n None)\n\n def test_category_meta_image_undefined(self):\n \"\"\" Category page's meta image is undefined if the category has\n no image\n \"\"\"\n category_page = self.create_category_page(ask_category=self.category)\n self.assertIsNone(category_page.meta_image)\n\n def test_category_meta_image_uses_category_image(self):\n \"\"\" Category page's meta image is its category's image \"\"\"\n category = mommy.make(Category, category_image=self.test_image)\n category_page = self.create_category_page(ask_category=category)\n self.assertEqual(category_page.meta_image, self.test_image)\n\n def test_answer_meta_image_undefined(self):\n \"\"\" Answer page's meta image is undefined if social image is\n not provided\n \"\"\"\n answer = self.prepare_answer()\n answer.save()\n page = self.create_answer_page(answer_base=answer)\n self.assertIsNone(page.meta_image)\n\n def test_answer_meta_image_uses_social_image(self):\n \"\"\" Answer page's meta image is its answer's social image \"\"\"\n answer = self.prepare_answer(social_sharing_image=self.test_image)\n answer.save()\n page = self.create_answer_page(answer_base=answer)\n self.assertEqual(page.meta_image, self.test_image)\n\n def test_answer_meta_image_uses_category_image_if_no_social_image(self):\n \"\"\" Answer page's meta image is its category's image \"\"\"\n category = mommy.make(Category, category_image=self.test_image)\n answer = self.prepare_answer()\n answer.save()\n answer.category.add(category)\n page = self.create_answer_page(answer_base=answer)\n self.assertEqual(page.meta_image, self.test_image)\n\n def test_answer_meta_image_uses_social_image_not_category_image(self):\n \"\"\" Answer page's meta image pulls from its social image instead\n of its category's image\n \"\"\"\n category = mommy.make(Category, category_image=self.test_image)\n answer = self.prepare_answer(social_sharing_image=self.test_image2)\n answer.save()\n answer.category.add(category)\n page = self.create_answer_page(answer_base=answer)\n self.assertEqual(page.meta_image, self.test_image2)\n\n def test_answer_page_context_collects_subcategories(self):\n \"\"\" Answer page's context delivers all related subcategories \"\"\"\n answer = self.answer1234\n answer.category.add(self.category)\n related_subcat = mommy.make(\n SubCategory,\n name='related_subcat',\n parent=self.category)\n subcat1 = self.subcategories[0]\n subcat1.related_subcategories.add(related_subcat)\n for each in self.subcategories:\n answer.subcategory.add(each)\n answer.update_english_page = True\n answer.save()\n page = answer.english_page\n request = HttpRequest()\n context = page.get_context(request)\n self.assertEqual(len(context['subcategories']), 4)\n\n def test_answer_page_context_collects_subcategories_with_same_parent(self):\n \"\"\" Answer page's context delivers only subcategories that\n share the selected parent category \"\"\"\n answer = self.answer1234\n test_category = mommy.make(\n Category, name='Test cat', slug='test-cat')\n test_subcategory = mommy.make(\n SubCategory, name='test_subcat', parent=test_category)\n test_category.subcategories.add(test_subcategory)\n answer.category.add(test_category)\n answer.subcategory.add(test_subcategory)\n answer.category.add(self.category)\n for each in self.subcategories:\n answer.subcategory.add(each)\n answer.update_english_page = True\n answer.save()\n page = answer.english_page\n request = HttpRequest()\n context = page.get_context(request)\n first_category = answer.category.first()\n self.assertEqual(context['category'], first_category)\n self.assertEqual(len(context['subcategories']),\n first_category.subcategories.count())\n\n def test_answer_page_breadcrumbs_and_subcategories_with_no_referrer(self):\n \"\"\" If there is no referrer, category/breadcrumbs should reflect\n first category on answer.\"\"\"\n answer = self.answer1234\n test_category = mommy.make(\n Category, name='Test cat', slug='test-cat')\n answer.category.add(self.category)\n answer.category.add(test_category)\n page = answer.english_page\n request = HttpRequest()\n request.META['HTTP_REFERER'] = ''\n context = page.get_context(request)\n default_category = answer.category.first()\n self.assertEqual(context['category'], default_category)\n self.assertEqual(len(context['breadcrumb_items']), 2)\n self.assertEqual(context['breadcrumb_items'][1]['title'],\n default_category.name)\n\n def test_answer_page_context_with_category_referrer(self):\n \"\"\" If the referrer is a category page and category is on answer,\n breadcrumbs should lead back to category page,\n context['category'] should be referring category, and subcategories\n should be any on answer from referring category.\"\"\"\n answer = self.answer1234\n test_category = mommy.make(\n Category, name='Test cat', slug='test-cat')\n test_subcategory = mommy.make(\n SubCategory, name='test_subcat', parent=test_category)\n test_category.subcategories.add(test_subcategory)\n answer.category.add(test_category)\n answer.subcategory.add(test_subcategory)\n answer.category.add(self.category)\n for each in self.subcategories:\n answer.subcategory.add(each)\n page = answer.english_page\n request = HttpRequest()\n request.META['HTTP_REFERER'] = 'https://www.consumerfinance.gov/' \\\n + 'ask-cfpb/category-' + test_category.slug + '/subcategory/'\n context = page.get_context(request)\n breadcrumbs = context['breadcrumb_items']\n self.assertEqual(len(breadcrumbs), 2)\n self.assertEqual(breadcrumbs[1]['title'], test_category.name)\n self.assertEqual(context['category'], test_category)\n self.assertEqual(len(context['subcategories']), 1)\n\n def test_answer_page_context_with_portal_referrer_and_category(self):\n \"\"\" If the referrer is a portal page and portal's related category\n appears on answer page, breadcrumbs should lead back to portal,\n category should be portal's related category, and subcategories\n should be any on answer from portal related category.\"\"\"\n from ask_cfpb.models import CONSUMER_TOOLS_PORTAL_PAGES as portals\n portal_path = list(portals.keys())[0]\n data = portals[portal_path]\n portal_title = data[0]\n category_slug = data[1]\n test_category = mommy.make(\n Category, name=\"test\", slug=category_slug)\n answer = self.answer1234\n answer.category.add(self.category)\n answer.category.add(test_category)\n page = answer.english_page\n request = HttpRequest()\n request.META['HTTP_REFERER'] = \\\n 'https://www.consumerfinance.gov' + portal_path\n context = page.get_context(request)\n breadcrumbs = context['breadcrumb_items']\n self.assertEqual(len(breadcrumbs), 1)\n self.assertEqual(breadcrumbs[0]['title'], portal_title)\n self.assertEqual(breadcrumbs[0]['href'], portal_path)\n self.assertEqual(context['category'].slug, category_slug)\n\n def test_answer_context_with_portal_referrer_and_no_category(self):\n \"\"\" If the referrer is a portal page but portal's related category\n does not appear on answer page, breadcrumbs should lead back to portal\n but there should be no category or subcategories on context.\"\"\"\n from ask_cfpb.models import CONSUMER_TOOLS_PORTAL_PAGES as portals\n portal_path = list(portals.keys())[0]\n portal_title = portals[portal_path][0]\n answer = self.answer1234\n answer.category.add(self.category)\n for each in self.subcategories:\n answer.subcategory.add(each)\n page = answer.english_page\n request = HttpRequest()\n request.META['HTTP_REFERER'] = \\\n 'https://www.consumerfinance.gov' + portal_path\n context = page.get_context(request)\n breadcrumbs = context['breadcrumb_items']\n self.assertEqual(len(breadcrumbs), 1)\n self.assertEqual(breadcrumbs[0]['title'], portal_title)\n self.assertEqual(breadcrumbs[0]['href'], portal_path)\n self.assertEqual(context['category'], None)\n self.assertEqual(context['subcategories'], set())\n\n def test_answer_context_with_journey_referrer_and_mortgages_category(self):\n \"\"\" If the referrer is a Buying a House journey page and 'mortgages'\n category appears on answer page, breadcrumbs should lead back to BAH &\n referrer pages, and category should be 'mortgages'.\"\"\"\n\n bah_page = BrowsePage(title='Buying a House', slug='owning-a-home')\n helpers.publish_page(child=bah_page)\n journey_path = JOURNEY_PATHS[0]\n journey_page = BrowsePage(\n title='Journey page',\n slug=journey_path.strip('/').split('/')[-1]\n )\n helpers.save_new_page(journey_page, bah_page)\n mortgage_category = mommy.make(\n Category, name='mortgages', slug='mortgages'\n )\n answer = self.answer1234\n answer.category.add(mortgage_category)\n page = answer.english_page\n\n mock_site = mock.Mock()\n mock_site.root_page = HomePage.objects.get(slug='cfgov')\n request = HttpRequest()\n request.META['HTTP_REFERER'] = \\\n 'https://www.consumerfinance.gov' + journey_path\n request.site = mock_site\n\n context = page.get_context(request)\n breadcrumbs = context['breadcrumb_items']\n self.assertEqual(len(breadcrumbs), 2)\n self.assertEqual(breadcrumbs[0]['title'], 'Buying a House')\n self.assertEqual(breadcrumbs[1]['title'], 'Journey page')\n self.assertEqual(context['category'], mortgage_category)\n\n def test_answer_context_with_journey_referrer_and_default_category(self):\n \"\"\" If the referrer is a Buying a House journey page and 'mortgages'\n category does not appear on answer page, breadcrumbs should lead\n back to BAH & referrer pages, and category should default to first\n category on answer.\"\"\"\n bah_page = BrowsePage(title='Buying a House', slug='owning-a-home')\n helpers.publish_page(child=bah_page)\n journey_path = JOURNEY_PATHS[0]\n journey_page = BrowsePage(\n title='Journey page',\n slug=journey_path.strip('/').split('/')[-1]\n )\n helpers.save_new_page(journey_page, bah_page)\n answer = self.answer1234\n answer.category.add(self.category)\n page = answer.english_page\n\n mock_site = mock.Mock()\n mock_site.root_page = HomePage.objects.get(slug='cfgov')\n request = HttpRequest()\n request.META['HTTP_REFERER'] = \\\n 'https://www.consumerfinance.gov' + journey_path\n request.site = mock_site\n\n context = page.get_context(request)\n breadcrumbs = context['breadcrumb_items']\n self.assertEqual(len(breadcrumbs), 2)\n self.assertEqual(breadcrumbs[0]['title'], 'Buying a House')\n self.assertEqual(breadcrumbs[1]['title'], 'Journey page')\n self.assertEqual(context['category'], self.category)\n\n def test_answer_context_with_nested_journey_referrer(self):\n \"\"\"If the referrer is a nested Buying a House journey page,\n breadcrumbs should reflect the BAH page hierarchy.\"\"\"\n bah_page = BrowsePage(title='Buying a House', slug='owning-a-home')\n helpers.publish_page(child=bah_page)\n journey_path = JOURNEY_PATHS[0]\n journey_page = BrowsePage(\n title='Journey page',\n slug=journey_path.strip('/').split('/')[-1]\n )\n helpers.save_new_page(journey_page, bah_page)\n journey_child_page = BrowsePage(\n title='Journey child page',\n slug='child'\n )\n helpers.save_new_page(journey_child_page, journey_page)\n page = self.page1\n\n mock_site = mock.Mock()\n mock_site.root_page = HomePage.objects.get(slug='cfgov')\n request = HttpRequest()\n request.META['HTTP_REFERER'] = \\\n 'https://www.consumerfinance.gov' + journey_path + '/child'\n request.site = mock_site\n\n context = page.get_context(request)\n breadcrumbs = context['breadcrumb_items']\n self.assertEqual(len(breadcrumbs), 3)\n self.assertEqual(breadcrumbs[0]['title'], 'Buying a House')\n self.assertEqual(breadcrumbs[1]['title'], 'Journey page')\n self.assertEqual(breadcrumbs[2]['title'], 'Journey child page')\n\n def test_answer_context_with_process_as_journey_referrer(self):\n \"\"\"If the referrer is a nested Buying a House journey page,\n breadcrumbs should reflect the BAH page hierarchy.\"\"\"\n bah_page = BrowsePage(title='Buying a House', slug='owning-a-home')\n helpers.publish_page(child=bah_page)\n journey_page = BrowsePage(\n title='Prepare page',\n slug='prepare'\n )\n helpers.save_new_page(journey_page, bah_page)\n\n page = self.page1\n\n mock_site = mock.Mock()\n mock_site.root_page = HomePage.objects.get(slug='cfgov')\n request = HttpRequest()\n request.META['HTTP_REFERER'] = \\\n 'https://www.consumerfinance.gov/owning-a-home/process/'\n request.site = mock_site\n\n context = page.get_context(request)\n breadcrumbs = context['breadcrumb_items']\n self.assertEqual(len(breadcrumbs), 2)\n self.assertEqual(breadcrumbs[0]['title'], 'Buying a House')\n self.assertEqual(breadcrumbs[1]['title'], 'Prepare page')\n\n def test_answer_context_with_process_segment_in_journey_referrer(self):\n \"\"\"If the referrer is a nested Buying a House journey page,\n breadcrumbs should reflect the BAH page hierarchy.\"\"\"\n bah_page = BrowsePage(title='Buying a House', slug='owning-a-home')\n helpers.publish_page(child=bah_page)\n journey_page = BrowsePage(\n title='Compare page',\n slug='compare'\n )\n helpers.save_new_page(journey_page, bah_page)\n\n page = self.page1\n\n mock_site = mock.Mock()\n mock_site.root_page = HomePage.objects.get(slug='cfgov')\n request = HttpRequest()\n request.META['HTTP_REFERER'] = \\\n 'https://www.consumerfinance.gov/owning-a-home/process/compare/'\n request.site = mock_site\n\n context = page.get_context(request)\n breadcrumbs = context['breadcrumb_items']\n self.assertEqual(len(breadcrumbs), 2)\n self.assertEqual(breadcrumbs[0]['title'], 'Buying a House')\n self.assertEqual(breadcrumbs[1]['title'], 'Compare page')\n\n def test_answer_split_testing_id(self):\n \"\"\"Confirm AnswerPage's split_testing_id is set to its answer_base.id,\n which is checked by the core.feature_flags.in_split_testing_cluster\n flag condition when doing split testing on Ask CFPB answer pages.\"\"\"\n answer = self.answer1234\n page = answer.english_page\n self.assertEqual(page.split_test_id, answer.id)\n","sub_path":"cfgov/ask_cfpb/tests/models/test_pages.py","file_name":"test_pages.py","file_ext":"py","file_size_in_byte":55997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"97971417","text":"#!/usr/bin/env python3\n# coding=utf-8\n\nimport os\nimport sys\nimport time\nimport datetime\nimport random\nimport pathlib\nimport logging\n\n# daemon server\ndef recordtime():\n # recording\n logging.debug(\"daemon[{}] is recording log\\n\".format(os.getpid()))\n # for system feature\n num = random.randint(10, 20)\n while num > 0:\n # proc for loop\n # get current time and print\n logging.debug(\"{}: doing something...\\n\".format(time.asctime(time.localtime())))\n sys.stdout.flush()\n time.sleep(4)\n\ndef generatefilenamewithdir(filename=\"/usr/log/python-1700-1-1/mydaemon.py\"):\n # get string of date\n date = \"python-\" + datetime.date.today().isoformat()\n # generate dir\n newdir = pathlib.Path(filename).parents[1].joinpath(date)\n # create dir\n if True != pathlib.Path(newdir).is_dir():\n pathlib.Path(newdir).mkdir(parents=True)\n # get filename\n newfilename = pathlib.Path(filename).name\n # generate new filename\n return pathlib.Path(newdir).joinpath(newfilename)\n\n# create daemon process\ndef mydaemon(stdin=\"/dev/null\", stdout=\"/dev/null\", stderr=\"/dev/null\"):\n # generate filename with dir\n stdout = generatefilenamewithdir(stdout)\n # set logging\n logging.basicConfig(filename=stdout,\n level=logging.DEBUG,\n datefmt='%Y-%m-%d %H:%M:%S',\n format='%(asctime)s %(name)-8s %(levelname)-8s [line: %(lineno)d] %(message)s')\n\n logging.debug(\"daemon process starting...\")\n try:\n # create first subprocess\n pid = os.fork()\n # first prarent process\n if pid > 0:\n logging.debug(\"first parent process exit\")\n exit(0)\n # for error\n except OSError as oserr:\n logging.error(\"create first subprocess failed, reason: {}\".format(oserr))\n sys.exit(1)\n\n # config env\n os.chdir(\"/\")\n os.umask(0)\n os.setsid()\n\n try:\n # create second subprocess // daemon\n pid = os.fork()\n if pid > 0:\n logging.debug(\"second parent process exit\")\n exit(0)\n except OSError as oserr:\n logging.error(\"create subprocess failed, reason: {}\\n\".format(oserr))\n sys.exit(1)\n\n # notify daemon is runging\n logging.debug(\"daemon[{}] runing...\\n\".format(os.getpid()))\n\n # clean buffer\n sys.stdout.flush()\n sys.stderr.flush()\n\n # create new fd\n newin = open(stdin,\"r\")\n newout = open(stdout, \"a+\")\n newerr = open(stderr, \"w\")\n\n # close old fd, and cp form new fd\n os.dup2(newin.fileno(), sys.stdin.fileno())\n os.dup2(newout.fileno(), sys.stdout.fileno())\n os.dup2(newerr.fileno(), sys.stderr.fileno())\n\n # daemon server\n recordtime()\n\n\nif __name__ == \"__main__\":\n mydaemon(\"/dev/null\", \"/var/log/python-1700-1-1/mydaemon.log\", \"/dev/null\")\n","sub_path":"week01/mydaemon.py","file_name":"mydaemon.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"531064858","text":"\n\nfrom xai.brain.wordbase.nouns._macro import _MACRO\n\n#calss header\nclass _MACROS(_MACRO, ):\n\tdef __init__(self,): \n\t\t_MACRO.__init__(self)\n\t\tself.name = \"MACROS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"macro\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_macros.py","file_name":"_macros.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"334832584","text":"#!/usr/bin/env python \n\nfrom util import * \nfrom numpy import *\n# from math import log\nimport copy\nimport sys\n\n\n# Pretty printing for 1D/2D numpy arrays\nMAX_PRINTING_SIZE = 30\n\ndef format_array(arr):\n s = shape(arr)\n if s[0] > MAX_PRINTING_SIZE or (len(s) == 2 and s[1] > MAX_PRINTING_SIZE):\n return \"[ too many values (%s) ]\" % s\n\n if len(s) == 1:\n return \"[ \" + (\n \" \".join([\"%.6f\" % float(arr[i]) for i in range(s[0])])) + \" ]\"\n else:\n lines = []\n for i in range(s[0]):\n lines.append(\"[ \" + \" \".join([\"%.6f\" % float(arr[i,j]) for j in range(s[1])]) + \" ]\")\n return \"\\n\".join(lines)\n\n\n\ndef format_array_print(arr):\n print(format_array(arr))\n\n\ndef string_of_model(model, label):\n (initial, tran_model, obs_model) = model\n return \"\"\"\nModel: %s \ninitial: \n%s\n\ntransition: \n%s\n\nobservation: \n%s\n\"\"\" % (label, \n format_array(initial),\n format_array(tran_model),\n format_array(obs_model))\n\n \ndef check_model(model):\n \"\"\"Check that things add to one as they should\"\"\"\n (initial, tran_model, obs_model) = model\n for state in range(len(initial)):\n assert((abs(sum(tran_model[state,:]) - 1)) <= 0.01)\n assert((abs(sum(obs_model[state,:]) - 1)) <= 0.01)\n assert((abs(sum(initial) - 1)) <= 0.01)\n\n\ndef print_model(model, label):\n check_model(model)\n print(string_of_model(model, label))\n\ndef max_delta(model, new_model):\n \"\"\"Return the largest difference between any two corresponding \n values in the models\"\"\"\n return max( [(abs(model[i] - new_model[i])).max() for i in range(len(model))] )\n\n\nclass HMM:\n \"\"\" HMM Class that defines the parameters for HMM \"\"\"\n def __init__(self, states, outputs):\n \"\"\"If the hmm is going to be trained from data with labeled states,\n states should be a list of the state names. If the HMM is\n going to trained using EM, states can just be range(num_states).\"\"\"\n self.states = states\n self.outputs = outputs\n n_s = len(states)\n n_o = len(outputs)\n self.num_states = n_s\n self.num_outputs = n_o\n self.initial = zeros(n_s)\n self.transition = zeros([n_s,n_s])\n self.observation = zeros([n_s, n_o])\n\n def set_hidden_model(self, init, trans, observ):\n \"\"\" Debugging function: set the model parameters explicitly \"\"\"\n self.num_states = len(init)\n self.num_outputs = len(observ[0])\n self.initial = array(init)\n self.transition = array(trans)\n self.observation = array(observ)\n \n def get_model(self):\n return (self.initial, self.transition, self.observation)\n\n def compute_logs(self):\n \"\"\"Compute and store the logs of the model (helper)\"\"\"\n raise Exception(\"Not implemented\")\n\n def __repr__(self):\n return \"\"\"states = %s\nobservations = %s\n%s\n\"\"\" % (\" \".join(array_to_string(self.states)), \n \" \".join(array_to_string(self.outputs)), \n string_of_model((self.initial, self.transition, self.observation), \"\"))\n\n \n # declare the @ decorator just before the function, invokes print_timing()\n # @print_timing\n def learn_from_labeled_data(self, state_seqs, obs_seqs):\n\n theta_hat = zeros(self.num_states)\n\n for i in range(0,self.num_states):\n summer = 1.0\n for j in state_seqs:\n if(i==j[0]):\n summer+=1\n\n # print(\"HERE BE SUMMER\",summer)\n # print(\"HERE BE self.num_states\",self.num_states)\n # print(\"HERE BE state_seqs\",len(state_seqs))\n theta_hat[i]=(summer/(self.num_states+len(state_seqs)))\n # print(\"HERE IS THETAHAT SUBSET\",theta_hat[i])\n # print(\"YO HERE's 1. by 6\",1.0/6)\n\n\n\n t_hat = ones((self.num_states,self.num_states))\n count = self.num_states*ones(self.num_states)\n\n for i in state_seqs:\n for j in range(0,len(i)-1):\n t_hat[i[j]][i[j+1]]+=1\n count[i[j]]+=1\n\n for i in range(0,t_hat.shape[0]):\n t_hat[i]=divide(t_hat[i],count)\n\n\n\n pi_hat = ones((self.num_states,self.num_outputs))\n count2 = self.num_states*ones(self.num_states)\n\n for i in range(0,len(state_seqs)):\n for j in range(0,len(state_seqs[i])):\n pi_hat[state_seqs[i][j]][obs_seqs[i][j]]+=1\n count2[state_seqs[i][j]]+=1\n\n for i in range(0,pi_hat.shape[1]):\n pi_hat[:,i]=divide(pi_hat[:,i],count2)\n # print(\"HIIIII\")\n # print(pi_hat[:,i])\n\n # print(\"HSDSFDF ITS THETA HAT\",theta_hat)\n # print(\"PI HAT IS\", pi_hat)\n self.initial = theta_hat\n self.transition = t_hat\n self.observation = pi_hat\n\n\n \"\"\"\n Learn the parameters given state and observations sequences. \n The ordering of states in states[i][j] must correspond with observations[i][j].\n Use Laplacian smoothing to avoid zero probabilities.\n Implement for (a).\n \"\"\"\n\n # Fill this in...\n #raise Exception(\"Not implemented\")\n \n\n def most_likely_states(self, sequence, debug=True):\n \"\"\"Return the most like sequence of states given an output sequence.\n Uses Viterbi algorithm to compute this.\n Implement for (b) and (c).\n \"\"\"\n # Fill this in...\n t1=zeros((len(sequence),self.num_states))\n t2=zeros((len(sequence),self.num_states))\n \n for i in range(0,self.num_states):\n # self.observation[i][sequence[0]]\n #t1[0][i] = self.initial[i]*self.observation[i][sequence[0]]\n t1[0][i] = log(self.initial[i]*self.observation[i][sequence[0]])\n print(t1[0][i])\n t2[0][i] = 0\n\n for i in range(1,len(sequence)):\n for j in range(0,self.num_states):\n #t1[i,j] = self.observation[j,sequence[i]]*max(t1[i-1,:]*self.transition[:,j])\n # print(\"is array?\", self.observation[j,sequence[i]]*self.transition[:,j])\n # print(\"will this print\", log(self.observation[j,sequence[i]]*self.transition[:,j]))\n t1[i,j] = max(log(self.observation[j,sequence[i]]*self.transition[:,j])+t1[i-1,:])\n #t2[i,j] = argmax(t1[i-1,:]*self.transition[:,j])\n t2[i,j] = argmax(t1[i-1,:]+log(self.transition[:,j]))\n\n print(t1[2])\n\n statesequences = zeros(len(sequence))\n # print(z.shape)\n x = zeros(len(sequence))\n # print(\"len sequence\",len(sequence))\n # print(\"TIS x\",x)\n # print(x.shape)\n\n for i in range(len(sequence)-1,-1,-1):\n if i == len(sequence)-1:\n statesequences[i] = int(argmax(t1[-1,:]))\n # print(\"statesequences here!\",statesequences[len(sequence)-1])\n # print(t1[len(sequence)-1,:])\n #x[len(sequence)-1] = t2[len(sequence)-1,statesequences[len(sequence)-1]]\n x = t2[i,argmax(t1[-1,:])]\n else:\n statesequences[i] = int(x)\n #statesequences[i] = x[i+1]\n #t2[i,int(statesequences[i+1])]\n #print(statesequences[i])\n x = t2[i,int(x)]\n #x[i] = t2[i][int(x[i+1])]\n #statesequences[i]\n\n # print(\"ABOUT TO DO THIS FDSIOSDOPJF\")\n # print(x)\n # print(len(x))\n x = x.tolist()\n statesequences = statesequences.tolist()\n final = zeros(len(sequence),dtype=int)\n print(\"FINAL\",final)\n for i in range(0,len(statesequences)):\n final[i] = int(statesequences[i])\n print(\"FINAL\",final)\n # print(\"VS\",statesequences)\n # print(\"int test\",int(statesequences[0]))\n # print(\"TIS stateseqs\",int(statesequences))\n return final\n \ndef get_wikipedia_model():\n # From the rainy/sunny example on wikipedia (viterbi page)\n hmm = HMM(['Rainy','Sunny'], ['walk','shop','clean'])\n init = [0.6, 0.4]\n trans = [[0.7,0.3], [0.4,0.6]]\n observ = [[0.1,0.4,0.5], [0.6,0.3,0.1]]\n hmm.set_hidden_model(init, trans, observ)\n return hmm\n\ndef get_toy_model():\n hmm = HMM(['h1','h2'], ['A','B'])\n init = [0.6, 0.4]\n trans = [[0.7,0.3], [0.4,0.6]]\n observ = [[0.1,0.9], [0.9,0.1]]\n hmm.set_hidden_model(init, trans, observ)\n return hmm\n \n\n","sub_path":"h5/code/hmm.py","file_name":"hmm.py","file_ext":"py","file_size_in_byte":8395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"561881554","text":"import os\nimport sys\nimport numpy as np\nimport random\nimport cv2\nimport pathlib\nimport matplotlib.pyplot as plt\nimport skimage\n\nfrom skimage.filters import threshold_otsu\nROOT_DIR = os.path.abspath(\"../../\")\nsys.path.append(ROOT_DIR) # To find local version of the library\nimport mrcnn.model as modellib\nfrom mrcnn import visualize\nfrom mrcnn.model import log\nfrom mrcnn import utils\nfrom mrcnn.config import Config\n\nclass ShapesConfig(Config):\n # Give the configuration a recognizable name\n NAME = \"fibroblast\"\n GPU_COUNT = 1\n IMAGES_PER_GPU = 8\n NUM_CLASSES = 1 + 2 # background + 2 young and old\n IMAGE_MIN_DIM = 10\n IMAGE_MAX_DIM = 128\n RPN_ANCHOR_SCALES = (2, 4, 8, 16, 32) # anchor side in pixels\n TRAIN_ROIS_PER_IMAGE = 8\n STEPS_PER_EPOCH = 1000\n VALIDATION_STEPS = 5\n LEARNING_RATE = 0.001\nconfig = ShapesConfig()\n\nclass InferenceConfig(ShapesConfig):\n GPU_COUNT = 1\n IMAGES_PER_GPU = 1\n IMAGE_MAX_DIM = 128\ninference_config = InferenceConfig()\n\ndef get_ax(rows=1, cols=1, size=8):\n _, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows))\n return ax\n\nclass ShapesDataset(utils.Dataset):\n def list_images(self,data_dir):\n # Add classes\n self.add_class(\"fibroblast\",1,CLASS_NAMES[0])\n self.add_class(\"fibroblast\",2,CLASS_NAMES[1])\n train_images = list(data_dir.glob('*\\*\\image\\*.jpg'))\n\n # Add images\n for idx,train_image in enumerate(train_images):\n ground = os.path.normpath(train_image).split(os.path.sep)[-4]\n self.add_image(\"fibroblast\",image_id=idx,path=train_image,truth=ground,\n height=config.IMAGE_SHAPE[0],width=config.IMAGE_SHAPE[1])\n\n def load_image(self, image_id):\n \"\"\"Load the specified image and return a [H,W,3] Numpy array.\n \"\"\"\n info = self.image_info[image_id]\n # Load image\n image = skimage.io.imread(self.image_info[image_id]['path'])\n # If grayscale. Convert to RGB for consistency.\n if image.ndim != 3:\n print('grayscale to rgb')\n image = skimage.color.gray2rgb(image)\n # If has an alpha channel, remove it for consistency\n if image.shape[-1] == 4:\n print('rgba to rgb')\n image = image[..., :3]\n image = cv2.resize(image,dsize=(128,128))\n return image\n\n def load_mask(self, image_id):\n # Load binary mask\n info = self.image_info[image_id]\n impath = info['path']\n maskpath = pathlib.Path(str(impath).replace(\"image\", \"label\"))\n instancenum = 1\n mask = np.zeros([info['height'], info['width'], instancenum], dtype=np.uint8)\n label = info['truth']\n # 0 is background\n labelidx = np.argwhere(CLASS_NAMES == label).flat[0]+1\n masklayer = skimage.io.imread(maskpath)\n masklayer = cv2.resize(masklayer,dsize=(128,128))\n thresh = threshold_otsu(masklayer)\n binary = masklayer > thresh\n mask[:, :, 0] = binary\n class_ids = np.array([labelidx])\n return mask.astype(np.bool), class_ids.astype(np.int32)\n\ndata_dir = pathlib.Path(r'C:\\Users\\kuki\\OneDrive - Johns Hopkins\\Research\\Skin\\RCNN data\\RCNNtrain')\nCLASS_NAMES = np.array([item.name for item in data_dir.glob('*') if item.name != \".DS_store\"])\nprint(CLASS_NAMES)\n\ndataset_train = ShapesDataset()\ndataset_train.list_images(data_dir)\ndataset_train.prepare()\n\ndata_dir_val = pathlib.Path(r'C:\\Users\\kuki\\OneDrive - Johns Hopkins\\Research\\Skin\\RCNN data\\RCNNtest')\ndataset_val = ShapesDataset()\ndataset_val.list_images(data_dir_val)\ndataset_val.prepare()\n\nMODEL_DIR = os.path.join(ROOT_DIR, \"logs\")\n\nmodel = modellib.MaskRCNN(mode=\"inference\",\n config=inference_config,\n model_dir=MODEL_DIR)\n\nmodel_path = model.find_last()\n\n# Load trained weights\nprint(\"Loading weights from \", model_path)\nmodel.load_weights(model_path, by_name=True)\n\n# Test on a random image\nimage_id = random.choice(dataset_val.image_ids)\noriginal_image, image_meta, gt_class_id, gt_bbox, gt_mask, masksizes =\\\n modellib.load_image_gt(dataset_val, inference_config, image_id, sixth=True)\n\n\nlog(\"original_image\", original_image)\nlog(\"image_meta\", image_meta)\nlog(\"gt_class_id\", gt_class_id)\nlog(\"gt_bbox\", gt_bbox)\nlog(\"gt_mask\", gt_mask)\n\nvisualize.display_instances(original_image, gt_bbox, gt_mask, gt_class_id,\n dataset_train.class_names, figsize=(8, 8))\n\ngt_mask2 = skimage.morphology.binary_opening(gt_mask)\nvisualize.display_instances(original_image, gt_bbox, gt_mask2, gt_class_id,\n dataset_train.class_names, figsize=(8, 8))\n\n\nresults = model.detect([original_image], verbose=1)\nr = results[0]\nvisualize.display_instances(original_image, r['rois'], r['masks'], r['class_ids'],\n dataset_val.class_names, r['scores'])\n\nrr2 = skimage.morphology.binary_opening(r['masks'])\nvisualize.display_instances(original_image, r['rois'], rr2, r['class_ids'],\n dataset_val.class_names, r['scores'])\n\n# Compute VOC-Style mAP @ IoU=0.5\n# Running on 10 images. Increase for better accuracy.\nimage_ids = np.random.choice(dataset_val.image_ids, 50)\nAPs = []\nAPs_open = []\nprs =[]\nrcs =[]\novl =[]\nfor image_id in image_ids:\n # Load image and ground truth data\n image, image_meta, gt_class_id, gt_bbox, gt_mask =\\\n modellib.load_image_gt(dataset_val, inference_config,\n image_id, use_mini_mask=False)\n molded_images = np.expand_dims(modellib.mold_image(image, inference_config), 0)\n # Run object detection\n results = model.detect([image], verbose=0)\n r = results[0]\n if len(r['class_ids'])<1 : print('nothing detected'); continue\n r_open = skimage.morphology.binary_opening(r['masks'])\n visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'],\n dataset_val.class_names, r['scores'])\n # Compute AP\n AP, precisions, recalls, overlaps =\\\n utils.compute_ap(gt_bbox, gt_class_id, gt_mask,\n r[\"rois\"], r[\"class_ids\"], r[\"scores\"], r['masks'])\n\n\n AP_open, precisions2, recalls2, overlaps2 = \\\n utils.compute_ap(gt_bbox, gt_class_id, gt_mask,\n r[\"rois\"], r[\"class_ids\"], r[\"scores\"], r_open)\n APs.append(AP)\n APs_open.append(AP_open)\n prs.append(precisions)\n rcs.append(recalls)\n ovl.append(overlaps)\n\nprint(\"mAP: \", np.mean(APs))\nprint(\"mAP: \", np.mean(APs_open))\nprint(\"precisions: \", np.mean(prs))\nprint(\"recalls: \", np.mean(rcs))\nprint(\"overlaps: \", np.mean(ovl))","sub_path":"samples/shapes/applycustom.py","file_name":"applycustom.py","file_ext":"py","file_size_in_byte":6641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"61897921","text":"import random\nfrom tkinter import *\nfrom tkinter.ttk import *\n\nfrom parte_grafica import TelaCenario\nfrom criador_testes import teste_cenarios\nfrom parte_grafica import TelaCronologia\nfrom Historia import GrafoHistoria\n\n\nclass JanelaPrincipal:\n\n def __init__(self):\n\n self.canvasx=0\n self.canvasy=0\n self.raiz = Tk()\n self.raiz.geometry(\"{0}x{1}+0+0\".format(self.raiz.winfo_screenwidth(), self.raiz.winfo_screenheight()))\n self.menuPrincipal = Menu(self.raiz)\n self.raiz.attributes ('-fullscreen', True)\n\n\n mygreen = \"#72b5a4\"\n myred = \"#595757\"\n\n style = Style()\n\n style.theme_create (\"yummy\", parent=\"alt\", settings={\n \"TNotebook\": {\"configure\": {\"tabmargins\": [2, 5, 2, 0]}},\n \"TNotebook.Tab\": {\n \"configure\": {\"padding\": [25, 8], \"background\": mygreen},\n \"map\": {\"background\": [(\"selected\", myred)],\n \"expand\": [(\"selected\", [1, 1, 1, 0])]}}})\n\n style.theme_use (\"yummy\")\n\n\n self.subMenuArquivo = Menu(self.menuPrincipal)\n self.subMenuConfig = Menu (self.menuPrincipal)\n self.raiz.config(menu=self.menuPrincipal)\n\n\n self.menuPrincipal.add_cascade(label=\"Arquivo\", menu=self.subMenuArquivo)\n self.subMenuArquivo.add_command(label=\"Novo\")\n self.subMenuArquivo.add_command(label=\"Abrir..\")\n self.subMenuArquivo.add_command(label=\"Salvar\")\n\n self.menuPrincipal.add_cascade (label=\"Configurações\", menu=self.subMenuConfig)\n\n #abas\n self.abas=Notebook(self.raiz)\n self.frame_aba1 = Frame (self.abas,width=300, height=200)\n self.frame_aba2 = Frame (self.abas,width=300, height=200)\n self.frame_aba3 = Frame (self.abas,width=300, height=200)\n\n self.label1 = Label (self.frame_aba1, text=\"Esta é a aba\")\n\n self.canvasCenario=Canvas(self.frame_aba1, bg=\"#f2ceab\")\n self.canvasCenario.pack(fill=BOTH, expand=1)\n\n self.canvasCronologia = Canvas (self.frame_aba3, bg=\"#72b5a4\")\n self.canvasCronologia.pack (fill=BOTH, expand=1)\n\n self.abas.add(self.frame_aba1,text=\"Cenarios\")\n self.abas.add(self.frame_aba2, text=\"Personagens\")\n self.abas.add(self.frame_aba3,tex=\"Cronologia\")\n\n self.abas.pack (expand=1, fill='both', padx=5, pady=5)\n\n\n teste=teste_cenarios.TesteCenarios()\n\n\n self.h= GrafoHistoria(\"projetoTeste\")\n self.h2 = GrafoHistoria (\"projetoTeste\")\n\n print (self.h.adicione_novo_cenario ())\n print (self.h.adicione_novo_cenario ())\n print (self.h.adicione_novo_cenario ())\n print (self.h.adicione_novo_cenario ())\n print (self.h.adicione_novo_cenario ())\n print (self.h.adicione_novo_cenario ())\n print (self.h.adicione_novo_cenario ())\n self.h.altere_nome_do_cenario (0, \"Sala\")\n self.h.altere_nome_do_cenario (1, \"Jardim\")\n self.h.altere_nome_do_cenario (2, \"Quarto\")\n self.h.adicione_conexao_entre_dois_cenarios (0, 1)\n #self.h.adicione_conexao_entre_dois_cenarios (0, 3)\n #self.h.adicione_conexao_entre_dois_cenarios (3, 1)\n self.h.adicione_conexao_entre_dois_cenarios (0, 2)\n #self.h.adicione_conexao_entre_dois_cenarios (3, 4)\n self.h.adicione_conexao_entre_dois_cenarios (2, 1)\n\n print (self.h2.adicione_novo_cenario ())\n print (self.h2.adicione_novo_cenario ())\n print (self.h2.adicione_novo_cenario ())\n print (self.h2.adicione_novo_cenario ())\n print (self.h2.adicione_novo_cenario ())\n print (self.h2.adicione_novo_cenario ())\n print (self.h2.adicione_novo_cenario ())\n self.h2.altere_nome_do_cenario (0, \"Prologo Inicial\")\n self.h2.altere_nome_do_cenario (1, \"Conversa Pai\")\n self.h2.altere_nome_do_cenario (2, \"Fugir de Casa\")\n self.h2.altere_nome_do_cenario (3, \"Ir Quarto\")\n self.h2.altere_nome_do_cenario (4, \"Fazer Dever\")\n self.h2.altere_nome_do_cenario (5, \"Festa\")\n\n self.h2.adicione_conexao_entre_dois_cenarios (0, 1,False)\n self.h2.adicione_conexao_entre_dois_cenarios (0, 2,False)\n self.h2.adicione_conexao_entre_dois_cenarios (1, 3,False)\n self.h2.adicione_conexao_entre_dois_cenarios (1, 2,False)\n self.h2.adicione_conexao_entre_dois_cenarios (3, 4,False)\n self.h2.adicione_conexao_entre_dois_cenarios (3, 5,False)\n\n\n\n\n\n telaCenario=TelaCenario.TelaCenario(self.canvasCenario, self.h, self.raiz,self.frame_aba1)\n telaCronologia = TelaCronologia.TelaCronologia(self.canvasCronologia, self.h2, self.raiz,self.frame_aba3)\n\n\n\n\n\n self.canvasCenario.initAresta = False\n self.raiz.title('ViNovelist')\n self.raiz.iconbitmap('icon.ico')\n self.raiz.mainloop ()\n\n\n\n def initArestaTrue(self):\n print(\"s\")\n self.canvasCenario.initAresta=True\n def initArestaFalse(self):\n print(\"n\")\n self.canvasCenario.initAresta=False\n\n","sub_path":"parte_grafica/JanelaPrincipal.py","file_name":"JanelaPrincipal.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"435495996","text":"import vcf\nimport pandas as pd\nimport os\nimport re\nimport urllib.request\nfrom collections import OrderedDict\nfrom typing import (\n Union,\n Optional,\n)\nfrom io import StringIO\nfrom viola.core.bedpe import Bedpe\nfrom viola.core.vcf import Vcf\nfrom viola.core.bed import Bed\nfrom viola.utils.utils import is_url\nfrom viola.io._vcf_parser import (\n read_vcf_manta,\n read_vcf_delly,\n read_vcf_lumpy,\n read_vcf_gridss,\n)\npd.set_option('display.max_columns', 10)\npd.set_option('display.max_colwidth', 30)\npd.set_option('display.width', 1000) \n\n\ndef read_vcf(filepath_or_buffer: Union[str, StringIO], variant_caller: str = \"manta\"):\n \"\"\"\n read_vcf(filepath_or_buffer, variant_callser = \"manta\")\n Read vcf file of SV and return Vcf object.\n\n Parameters\n ---------------\n filepath_or_buffer: str or StringIO\n String path to the vcf file. StringIO is also acceptable.\n (Wether URL is acceptable or not hasn't been tested.)\n (Acceptable types should be extended in the future)\n variant_caller: str\n Let this function know which SV caller was used to create vcf file.\n \n Returns\n ---------------\n A Vcf object\n \"\"\"\n # read vcf files using PyVcf package\n if isinstance(filepath_or_buffer, str) and is_url(filepath_or_buffer):\n b = StringIO(urllib.request.urlopen(filepath_or_buffer).read().decode('utf-8'))\n vcf_reader = vcf.Reader(b)\n elif isinstance(filepath_or_buffer, str):\n vcf_reader = vcf.Reader(open(filepath_or_buffer, 'r'))\n elif isinstance(filepath_or_buffer, StringIO):\n vcf_reader = vcf.Reader(filepath_or_buffer)\n else:\n vcf_reader = vcf.Reader(filepath_or_buffer)\n #raise TypeError(\"should be file or buffer\")\n\n if variant_caller == 'manta':\n return read_vcf_manta(vcf_reader)\n elif variant_caller == 'delly':\n return read_vcf_delly(vcf_reader)\n elif variant_caller == 'lumpy':\n return read_vcf_lumpy(vcf_reader)\n elif variant_caller == 'gridss':\n return read_vcf_gridss(vcf_reader)\n\n # obtain header informations\n odict_contigs = vcf_reader.contigs\n df_contigs_meta = pd.DataFrame(odict_contigs, index=('id', 'length')).T.reset_index(drop=True)\n\n # obtain alteration class informations\n odict_alts = vcf_reader.alts\n df_alts_meta = pd.DataFrame(odict_alts, index=('id', 'description')).T.reset_index(drop=True)\n\n # obtain info field information\n odict_infos = vcf_reader.infos\n df_infos_meta = pd.DataFrame(odict_infos, index=('id', 'number', 'type', 'description', 'source', 'version')).T.reset_index(drop=True)\n\n # obtain FORMAT informations\n odict_formats = vcf_reader.formats\n df_formats_meta = pd.DataFrame(odict_formats, index=('id', 'number', 'type','description')).T.reset_index(drop=True)\n\n # obtain FILTER informations\n odict_filters = vcf_reader.filters\n df_filters_meta = pd.DataFrame(odict_filters, index=('id', 'description')).T.reset_index(drop=True)\n\n # obtain SAMPLE informations\n ls_samples = vcf_reader.samples\n df_samples = pd.DataFrame(ls_samples, columns=['id'])\n\n odict_df_headers = OrderedDict(\n contigs_meta = df_contigs_meta,\n alts_meta = df_alts_meta, \n infos_meta = df_infos_meta, \n formats_meta = df_formats_meta, \n filters_meta = df_filters_meta, \n samples_meta = df_samples)\n\n \n ls_pos = []\n ls_filters = []\n dict_infos = {k: [] for k in df_infos_meta.id}\n ls_df_formats = []\n\n \n for record in vcf_reader:\n dict_row = {}\n # ex: Record(CHROM=chr1, POS=9163435, REF=G, ALT=[])\n row_ID = record.ID\n row_CHROM1 = record.CHROM\n row_POS1 = record.POS\n row_REF = record.REF\n row_ALT = record.ALT[0] # This operation is safe when parsing manta vcf files, but potential cause of information loss in another callers.\n row_QUAL = record.QUAL\n \n \n #####FILTER\n ls_filter = record.FILTER\n if ls_filter is None:\n ls_filter = ['PASS']\n elif len(ls_filter) == 0:\n ls_filter = ['PASS'] \n row_FILTER = ls_filter\n for filter_ in row_FILTER:\n ls_filters.append({'id': row_ID, 'filter': filter_})\n #####/FILTER \n\n #####INFO\n row_INFO = record.INFO\n for info in df_infos_meta.id:\n values = row_INFO.get(info, 'none')\n if values == 'none':\n continue\n if not isinstance(values, list):\n values = [values]\n ls_keys = ['id', 'value_idx', info.lower()] \n for idx, value in enumerate(values):\n ls_value = [row_ID, idx, value]\n dict_a_info = {k: v for k, v in zip(ls_keys, ls_value)}\n dict_infos[info].append(dict_a_info)\n #####/INFO\n\n ###POS\n if isinstance(row_ALT, vcf.model._Breakend):\n row_CHROM2 = row_ALT.chr\n row_POS2 = row_ALT.pos\n row_STRAND1 = '-' if row_ALT.orientation else '+'\n row_STRAND2 = '-' if row_ALT.remoteOrientation else '+'\n elif row_INFO['SVTYPE'] == 'INV': # manta-specific operation\n row_CHROM2 = row_CHROM1\n row_POS2 = row_INFO['END']\n # manta\n if variant_caller == \"manta\":\n if row_INFO.get('INV3', False):\n row_STRANDs = '+'\n else:\n row_POS1 += 1\n row_POS2 += 1\n row_STRANDs = '-'\n # /manta\n # delly\n elif variant_caller == \"delly\":\n if row_INFO['CT'] == '3to3':\n row_STRANDs = '+'\n else:\n row_POS1 += 1\n row_POS2 += 1\n row_STRANDs = '-'\n # /delly\n row_STRAND1, row_STRAND2 = row_STRANDs, row_STRANDs\n elif row_INFO['SVTYPE'] == 'DEL':\n row_CHROM2 = row_CHROM1\n row_POS2 = row_INFO['END'] + 1\n row_STRAND1 = '+'\n row_STRAND2 = '-'\n elif row_INFO['SVTYPE'] == 'DUP':\n row_CHROM2 = row_CHROM1\n row_POS2 = row_INFO['END']\n row_POS1 += 1\n row_STRAND1 = '-'\n row_STRAND2 = '+'\n else:\n row_CHROM2 = row_CHROM1\n row_POS2 = row_INFO['END']\n row_STRAND1 = '.'\n row_STRAND2 = '.'\n\n row_SVTYPE = row_INFO['SVTYPE']\n ls_pos.append({\n 'id': row_ID, \n 'chrom1': row_CHROM1, \n 'pos1': row_POS1, \n 'chrom2': row_CHROM2, \n 'pos2': row_POS2, \n 'strand1': row_STRAND1, \n 'strand2': row_STRAND2,\n 'ref': row_REF,\n 'alt': row_ALT,\n 'qual': row_QUAL,\n 'svtype': row_SVTYPE\n })\n ###/POS\n\n ####FORMAT\n format_ = record.FORMAT\n\n # operation below is limited for manta\n ls_formats = []\n for a_sample in record.samples:\n for a_format in format_.split(':'):\n values = eval('a_sample.data.' + str(a_format))\n if not isinstance(values, list):\n values = [values]\n for value_idx in range(len(values)):\n ls_formats.append([row_ID, a_sample.sample, a_format, value_idx, values[value_idx]])\n df_formats_each_record = pd.DataFrame(ls_formats)\n ls_df_formats.append(df_formats_each_record)\n # end of the manta-limited operation\n\n ####/FORMAT\n\n ###FILTER\n df_filters = pd.DataFrame(ls_filters)\n ###/FILTER\n \n ###INFO\n ls_df_infos = []\n for info in df_infos_meta.id:\n if len(dict_infos[info]) == 0:\n df_a_info = pd.DataFrame(columns=('id', 'value_idx', info.lower()))\n else:\n df_a_info = pd.DataFrame(dict_infos[info])\n ls_df_infos.append(df_a_info)\n odict_df_infos = OrderedDict([(k, v) for k, v in zip(df_infos_meta.id, ls_df_infos)])\n ###/INFO\n\n ###POS\n df_pos = pd.DataFrame(ls_pos)\n df_pos = df_pos[['id', 'chrom1', 'pos1', 'chrom2', 'pos2', 'strand1', 'strand2', 'ref', 'alt', 'qual', 'svtype']]\n ###/POS\n\n ###FORMAT\n df_formats = pd.concat(ls_df_formats, ignore_index=True)\n columns = ['id', 'sample', 'format', 'value_idx', 'value']\n df_formats.columns = columns\n ###/FORMAT\n \n args = [df_pos, df_filters, odict_df_infos, df_formats, odict_df_headers]\n return Vcf(*args)\n\n\ndef _read_bedpe_empty(df_bedpe):\n ls_header = list(df_bedpe.columns)\n ls_header_required = ls_header[:10]\n ls_header_option = ls_header[10:]\n df_svpos = pd.DataFrame(columns=('id', 'chrom1', 'pos1', 'chrom2', 'pos2', 'strand1', 'strand2', 'ref', 'alt', 'qual', 'svtype'))\n df_svlen = pd.DataFrame(columns=('id', 'value_idx', 'svlen'))\n df_svtype = pd.DataFrame(columns=('id', 'value_idx', 'svtype'))\n ls_df_infos = []\n for info in ls_header_option:\n df_info = pd.DataFrame(columns=('id', 'value_idx', info))\n ls_df_infos.append(df_info)\n ls_df_infos = [df_svlen, df_svtype] + ls_df_infos \n ls_infokeys = ['svlen', 'svtype'] + ls_header_option\n odict_df_infos = OrderedDict([(k, v) for k, v in zip(ls_infokeys, ls_df_infos)])\n args = [df_svpos, odict_df_infos]\n return Bedpe(*args)\n \n\ndef read_bedpe(filepath,\n header_info_path = None,\n svtype_col_name: Optional[str] = None):\n \"\"\"\n read_bedpe(filepath, header_info_path, svtype_col_name)\n Read a BEDPE file of SV and return Bedpe object.\n\n Parameters\n ---------------\n filepath: str or file-like object\n Acceptable type is equivalent to that of pandas.read_csv().\n header_info_path:\n Haven't been coded yet.\n svtype_col_name: str or None, default None\n If the bedpe file has a svtype column, please pass the column name to this argument.\n \n Returns\n ---------------\n A Bedpe object\n \"\"\"\n df_bedpe = pd.read_csv(filepath, sep='\\t')\n if df_bedpe.shape[0] == 0:\n return _read_bedpe_empty(df_bedpe)\n ls_header = list(df_bedpe.columns)\n ls_header_option = ls_header[10:]\n ls_new_header = ['chrom1', 'start1', 'end1', 'chrom2', 'start2', 'end2', 'name', 'score', 'strand1', 'strand2'] + ls_header_option\n df_bedpe.columns = ls_new_header\n df_bedpe['pos1'] = (df_bedpe['start1'] + df_bedpe['end1']) // 2 + 1\n df_bedpe['pos2'] = (df_bedpe['start2'] + df_bedpe['end2']) // 2 + 1\n df_bedpe['chrom1'] = prepend_chr(df_bedpe['chrom1'])\n df_bedpe['chrom2'] = prepend_chr(df_bedpe['chrom2'])\n\n if svtype_col_name is None:\n df_bedpe = infer_svtype_from_position(df_bedpe)\n df_svpos = df_bedpe[['name', 'chrom1', 'pos1', 'chrom2', 'pos2', 'strand1', 'strand2', 'score', 'svtype']].copy()\n else:\n df_svpos = df_bedpe[['name', 'chrom1', 'pos1', 'chrom2', 'pos2', 'strand1', 'strand2', 'score', svtype_col_name]].rename(columns={svtype_col_name: 'svtype'}).copy()\n df_bedpe['svtype'] = df_svpos['svtype']\n\n df_svpos = df_svpos.rename(columns={'name': 'id', 'score': 'qual'})\n df_svpos['ref'] = 'N'\n df_svpos = create_alt_field_from_position(df_svpos)\n\n ## below: construct INFO tables\n\n ### svlen table\n def _add_svlen(x):\n x['value_idx'] = 0\n if x.name == 'BND':\n x['svlen'] = 0\n return x\n elif x.name == 'TRA':\n x['svlen'] = 0\n return x\n elif x.name == 'DEL':\n x['svlen'] = x['pos1'] - x['pos2'] + 1\n return x\n elif x.name == 'DUP':\n x['svlen'] = x['pos2'] - x['pos1'] + 1\n return x\n elif x.name == 'INV':\n x['svlen'] = x['pos2'] - x['pos1']\n return x\n else:\n x['svlen'] = abs(x['pos2'] - x['pos1'])\n return x\n df_svlen = df_svpos.groupby('svtype').apply(_add_svlen)[['id', 'value_idx', 'svlen']]\n\n ### svtype table\n df_svtype = df_svpos[['id', 'svtype']].copy()\n df_svtype['value_idx'] = 0\n df_svtype = df_svtype[['id', 'value_idx', 'svtype']]\n\n ### cipos and ciend\n df_ci = df_bedpe.copy()\n df_ci[0] = df_ci['start1'] - df_ci['pos1']\n df_ci[1] = df_ci['end1'] - df_ci['pos1'] - 1\n df_cipos = df_ci[['name', 0, 1]].rename(columns={'name': 'id'}).set_index('id')\n df_cipos = df_cipos.stack()\n df_cipos = df_cipos.reset_index().rename(columns={'level_1': 'value_idx', 0: 'cipos'})\n \n df_ci = df_bedpe.copy()\n df_ci[0] = df_ci['start2'] - df_ci['pos2']\n df_ci[1] = df_ci['end2'] - df_ci['pos2'] - 1\n df_ciend = df_ci[['name', 0, 1]].rename(columns={'name': 'id'}).set_index('id')\n df_ciend = df_ciend.stack()\n df_ciend = df_ciend.reset_index().rename(columns={'level_1': 'value_idx', 0: 'ciend'})\n\n ls_df_infos = []\n for info in ls_header_option:\n df_info = df_bedpe[['name', info]].rename(columns={'name': 'id'}).copy()\n df_info['value_idx'] = 0\n df_info = df_info[['id', 'value_idx', info]]\n ls_df_infos.append(df_info)\n ls_df_infos = [df_svlen, df_svtype, df_cipos, df_ciend] + ls_df_infos \n ls_infokeys = ['svlen', 'svtype', 'cipos', 'ciend'] + ls_header_option\n odict_df_infos = OrderedDict([(k, v) for k, v in zip(ls_infokeys, ls_df_infos)])\n\n args = [df_svpos, odict_df_infos]\n return Bedpe(*args)\n\ndef prepend_chr(ser):\n \"\"\"\n prepend_chr(ser)\n Add \"chr\" to the beginning of every element in the Series.\n If the \"chr\" prefix has already exist, nothing will be appended but\n the type of Series elements will be changed into str.\n\n Parameters\n ----------\n ser: pd.Series\n A Series of the chromosome number.\n \n Returns\n -------\n A Series of chromosome numbers in \"chr\" notation.\n \"\"\"\n dict_regex = {\"^([0-9]+|[XY]|MT)\":r\"chr\\1\", r\"^(M)\":r\"chrMT\"}\n return ser.astype(str).replace(regex=dict_regex)\n\ndef infer_svtype_from_position(position_table):\n df = position_table.copy()\n df['svtype'] = '.'\n mask_bnd = df['chrom1'] != df['chrom2']\n mask_del = (df['chrom1'] == df['chrom2']) & \\\n (df['strand1'] == '+') & \\\n (df['strand2'] == '-')\n mask_dup = (df['chrom1'] == df['chrom2']) & \\\n (df['strand1'] == '-') & \\\n (df['strand2'] == '+')\n mask_inv = (df['chrom1'] == df['chrom2']) & \\\n (df['strand1'] != '.') & \\\n (df['strand1'] == df['strand2'])\n ls_mask = [mask_bnd, mask_del, mask_dup, mask_inv]\n ls_svtype = ['BND', 'DEL', 'DUP', 'INV']\n for mask, svtype in zip(ls_mask, ls_svtype):\n df.loc[mask, 'svtype'] = svtype\n return df\n\ndef create_alt_field_from_position(position_table):\n '''\n svtype column is required\n '''\n def _f(x):\n if x.name == '.':\n x['alt'] = '.'\n return x\n elif (x.name != 'BND') & (x.name != 'TRA'):\n x['alt'] = \"<{}>\".format(x.name)\n return x\n ls_alt = []\n for idx, row in x.iterrows():\n strand1 = row['strand1']\n strand2 = row['strand2']\n chrom2 = row['chrom2']\n pos2 = row['pos2']\n ref = row['ref']\n if (strand1 == '+') & (strand2 == '-'):\n alt = '{0}[{1}:{2}['.format(ref, chrom2, pos2)\n elif (strand1 == '+') & (strand2 == '+'):\n alt = '{0}]{1}:{2}]'.format(ref, chrom2, pos2)\n elif (strand1 == '-') & (strand2 == '+'):\n alt = ']{0}:{1}]{2}'.format(chrom2, pos2, ref)\n else:\n alt = '[{0}:{1}[{2}'.format(chrom2, pos2, ref)\n ls_alt.append(alt)\n x['alt'] = ls_alt\n return x\n df = position_table.copy()\n df = df.groupby('svtype').apply(_f)\n return df\n\ndef read_bed(filepath_or_buffer):\n \"\"\"\n read_bed(filepath_or_buffer)\n Read a BED file into Bed class.\n The input file should conform to the BED format defined by UCSC.\n https://genome.ucsc.edu/FAQ/FAQformat.html#format1\n \"\"\"\n header=None\n with open(filepath_or_buffer, 'r') as f:\n data = []\n for line in f:\n if line.startswith('track'):\n header = line\n else:\n data.append(line)\n df = pd.read_csv(\n StringIO(''.join(data)),\n sep='\\t',\n header=None\n )\n df_columns_origin = ['chrom', 'chromStart', 'chromEnd', 'name', 'score', 'strand', 'thickStart',\n 'thickEnd', 'itemRgb', 'blockCount', 'blockSize', 'blockStarts']\n df_columns = df_columns_origin[:df.shape[1]]\n df.columns = df_columns\n\n return Bed(df, header)\n\n\n ","sub_path":"src/viola/io/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":16722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"231869000","text":"from django.shortcuts import render\n\nfrom email.message import EmailMessage\nfrom email.headerregistry import Address\nfrom email.utils import make_msgid\nimport csv\nimport smtplib\nimport ssl\nimport re\nimport dns\nimport dns.resolver\nimport socket\nfrom django.template import RequestContext\n\n\n\n\n\n# Create your views here.\ndef home(request):\n\t\n\treciall=list()\n\trecicrt=list()\n\tfailed=list()\n\n\tif request.method == \"POST\":\n\t\tsender_email = request.POST['i11']\n\t\tsender_pass = request.POST['i12']\n\t\tsubject = request.POST['subject']\n\t\tbody = request.POST['body']\t\t\t\n\n\t\tf = request.FILES[\"contact_file\"]\n\t\twith open('VM_MAIL/' + f.name, 'wb+') as destination:\n\t\t\tfor chunk in f.chunks():\n\t\t\t\tdestination.write(chunk)\n\t\t\n\t\tfamily =[]\n\t\twith open('VM_MAIL/' + f.name, 'r') as file:\n\t\t\treader = csv.reader(file, delimiter=\"\\n\")\n\t\t\tfamily =[]\n\t\t\tfor rows in reader:\n\t\t\t\tfamily.append(rows[0])\n\t\tprint(family)\n\n\t\t\n\t\tfor email_address in family:\n\t\t\t#Check using Regex\n\t\t\taddressToVerify = email_address\n\t\t\taddres_cpy=email_address\n\t\t\tmatch = re.match('^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$', addressToVerify)\n\n\t\t\tif match == None:\n\t \t\t#print('Bad Syntax in ' + addressToVerify)\n\t \t\t#raise ValueError('Bad Syntax')\n\t \t\t\tfailed.append(addressToVerify)\n\t \t\t\tcontinue\n\n\t\t\t# MX record\n\t\t\t#Pull domain name \n\t\t\tdomain_name = email_address.split('@')[1]\n\t\t\t#print(domain_name)\n\n\t\t\t#get the MX record for the domain\n\t\t\t#basically using gmail.com and getting Mx records\n\t\t\trecords = dns.resolver.resolve(domain_name, 'MX')\n\t\t\tmxRecord = records[0].exchange\n\t\t\tmxRecord = str(mxRecord)\n\n\n\t\t\t# if the email address exists\n\n\t\t\t#local server hostname in which python is running\n\t\t\thost = socket.gethostname()\n\n\t\t\t# SMTP lib setup\n\t\t\tserver = smtplib.SMTP()\n\t\t\tserver.set_debuglevel(0)\n\n\t\t\t# SMTP Conversation\n\t\t\tserver.connect(mxRecord)\n\t\t\tserver.helo(host)\n\t\t\tserver.mail('me@domain.com')#keep this as it is\n\t\t\tcode, message = server.rcpt(str(addressToVerify))\n\t\t\tserver.quit()\n\n\t\t\t# Assume 250 as Success\n\t\t\tif code == 250:\n\t\t \t\t#print('Y')\n\t\t \t\trecicrt.append(addres_cpy)\n\t\t\telse:\n\t\t \t\t#print('N')\n\t\t \t\tfailed.append(addres_cpy)\n\n\n\n\t\tprint(recicrt)\n\t\tprint(failed)\n\n\t\tserver1=smtplib.SMTP('smtp.gmail.com', 587)\n\t\tserver1.starttls()\n\t\tserver1.login(sender_email, sender_pass)\n\n\t\tmymsg = EmailMessage()\n\t\tmymsg['From'] = sender_email\n\t\tmymsg['To'] = \", \".join(recicrt)\n\t\tmymsg['Subject'] = subject\n\t\tmymsg.set_content(body, subtype = 'html')\n\t\t#asparagus_cid = make_msgid()\n\t\tserver1.send_message(mymsg)\n\n\treturn render(request, 'test.html', {\"list\":failed})\n","sub_path":"VM_MAIL/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"604914287","text":"import re\n\npattern = '/\\w*/'\n\nprog = re.compile(pattern)\n\np = 0\n\nnews_str = []\n\nwith open('URLs.txt', 'r') as f:\n\n\tfor line in f:\n\n\t\tline = line.strip()\n\n\t\tif prog.match(line):\n\n\t\t\tnews_str.append(line)\n\n\t\t\tp += 1\n\nresult = []\n\ncatigories = {'politics': 0, 'world': 0, 'science': 0, 'video': 0, 'middleeast': 0, 'economics': 0, 'travel': 0, 'starlife': 0, \n\t\t\t 'health': 0, 'sport': 0, 'incidents': 0,'business': 0, 'head': 0, 'finances': 0, 'europe': 0, 'kinomusic': 0}\n\ncatigories_1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\nfor x in news_str:\n\tresult.append(str(re.findall(r'/\\w*/', x)).replace(\"/\", \"\")) \n\nfor i in result:\n\td = 0\n\tfor a,b in catigories.items():\n\t\tif a == str(i).replace(\"[\", \"\").replace(\"]\", \"\").replace(\"'\", \"\"):\n\t\t\tcatigories_1[d] += 1\n\t\td += 1\n\nd = 0\nfor a , b in catigories.items():\n\tprint(\"В категории {} находиться {} статей.\\n\".format(a, catigories_1[d]))\n\td += 1","sub_path":"dz.py","file_name":"dz.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"536922347","text":"# Algorithm 1\ndef algorithm1(alist):\n maxValue = [[],0]\n for i in range(0,len(alist)):\n for j in range(i,len(alist)):\n total = 0\n for k in range(i,j+1):\n total = total + alist[k]\n if maxValue[1] < total :\n maxValue[0] = alist[i:j+1]\n maxValue[1] = total\n return maxValue\n\ndef maxPrefix(alist):\n maxValue=[[],0]\n prior=0\n for i in range(0,len(alist)):\n current=prior+alist[i]\n if maxValue[1]= 0:\n current_total += num\n else:\n current_starting_index = idx + 1\n current_total = 0\n\n if (current_total >= highest_total):\n highest_total = current_total\n best_starting_index = current_starting_index\n best_ending_index = idx\n\n return arr[best_starting_index : best_ending_index + 1], highest_total\n\nalgos = [algorithm1, algorithm2, algorithm3, algorithm4]\n","sub_path":"all_algos.py","file_name":"all_algos.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"48275348","text":"import numpy as np\nimport math\nimport data_extraction as de\n\ndef entropy(list_l):\n if list_l[0] == -1:\n list_l = np.delete(list_l, 0)\n \n value_count = [list_l.tolist().count(i) for i in set(list_l)]\n ent = 0\n for x in value_count:\n ent = ent - x/sum(value_count)*math.log(x/sum(value_count), 2)\n return(ent)\n \ndef information_gain(list_av, S, S_ent):\n unique_values = np.array([list_av[list_av[:,0] == x] for x in set(list_av[:,0])])\n ig = S_ent\n for x in unique_values:\n x_t = x[:,1]\n ig = ig - (x_t.size/S)*entropy(x_t)\n return ig\n \ndef highest_gain(features, label):\n S = len(label)\n S_ent = entropy(label) \n gain = {}\n for i,x in enumerate(features.transpose()):\n g = information_gain(np.array([x, label]).transpose(), S, S_ent)\n gain[i] = g\n return max(gain, key = gain.get)","sub_path":"Solution/Experiment/Code/decision_tree_calculations.py","file_name":"decision_tree_calculations.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"128161919","text":"import random\n\narray = [random.randint(1, 100) for i in range(10)]\n\n\ndef bubble_sort(arr):\n for lap in range(len(arr) - 1):\n for i in range(len(arr) - 1 - lap):\n if arr[i] > arr[i + 1]:\n tmp = arr[i]\n arr[i] = arr[i + 1]\n arr[i + 1] = tmp\n return arr\n\n\nprint(array)\nprint(bubble_sort(array))\n","sub_path":"PycharmProjects/Sort/BubbleSort.py","file_name":"BubbleSort.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"5918796","text":"w=5\ndef f(x):\n w=2\n def g(y):\n w=4\n def h(z):\n global w\n return w*x+y+z\n\n return h\n return g\n\nprint(f(5)(5)(5))\n\ndef foo():\n try:\n return 5\n except :\n return 6\n finally:\n return 8\nprint(foo())\n\n\ndef func1(x,y):\n print(x/y)\n\ndef func2(x, y):\n print(x // y)\nfunc1(5,2)\nfunc1(5.0,2)\nfunc2(5,2)\nfunc1(5.0,2)\n\n\nl1=[1,2,3]\nl2=[4,5,6]\n\nl4=[]\nfor x in l1:\n for y in l2:\n l4.append(x*y)\nprint(l4)\nl3=[x*y for x,y in zip(l1,l2)]\nprint(l3)\n\nl5=[map((lambda x,y:x*y),l1,l2)]\nprint(l5)\n\nl6=[x*y for x in l1 for y in l2]\nprint(l6)","sub_path":"Interview Questions/Decorator.py","file_name":"Decorator.py","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"278711675","text":"class Product:\n id = 0\n title = ''\n category = ''\n stock = 0\n price = 0.0\n total = 0\n\n\n #contructor/method. start with double under score, the contructor will receive its own class and its own self he \"self\" is the same as the \"this\" in java\n def __init__(self, id, title, category, stock, price):\n self.id = id\n self.title = title\n self.category = category\n self.stock = stock\n self.price = price\n\n ","sub_path":"Warehouse/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"334747559","text":"import csv\nfrom collections import defaultdict\n\nimport numpy as np\nfrom scipy import stats\n\nfrom glycopeptidepy import PeptideSequence\nfrom glypy.utils import make_counter\n\ntry:\n from matplotlib import pyplot as plt\nexcept ImportError:\n pass\n\n\nfrom glycan_profiling.scoring.base import (\n ScoringFeatureBase,)\n\nfrom .structure import _get_apex_time, GlycopeptideChromatogramProxy\nfrom .linear_regression import (ransac, weighted_linear_regression_fit, prediction_interval, SMALL_ERROR)\n\n\n\nclass ElutionTimeFitter(ScoringFeatureBase):\n feature_type = 'elution_time'\n\n def __init__(self, chromatograms, scale=1):\n self.chromatograms = chromatograms\n self.neutral_mass_array = None\n self.data = None\n self.apex_time_array = None\n self.weight_matrix = None\n self.parameters = None\n self.residuals = None\n self.estimate = None\n self.scale = scale\n self._init_model_data()\n\n def _init_model_data(self):\n self.neutral_mass_array = np.array([\n x.weighted_neutral_mass for x in self.chromatograms\n ])\n self.data = self._prepare_data_matrix(self.neutral_mass_array)\n\n self.apex_time_array = np.array([\n self._get_apex_time(x) for x in self.chromatograms\n ])\n\n self.weight_matrix = self.build_weight_matrix()\n\n self.parameters = None\n self.residuals = None\n self.estimate = None\n\n def _get_apex_time(self, chromatogram):\n return _get_apex_time(chromatogram)\n\n def build_weight_matrix(self):\n return np.eye(len(self.chromatograms))\n\n def _prepare_data_vector(self, chromatogram):\n return np.array([1, chromatogram.weighted_neutral_mass,])\n\n def feature_names(self):\n return ['intercept', 'mass']\n\n def _prepare_data_matrix(self, mass_array):\n return np.vstack((\n np.ones(len(mass_array)),\n np.array(mass_array),\n )).T\n\n def _fit(self, resample=False):\n if resample:\n solution = ransac(self.data, self.apex_time_array,\n self.weight_matrix)\n alt = weighted_linear_regression_fit(\n self.data, self.apex_time_array, self.weight_matrix)\n if alt.R2 > solution.R2:\n return alt\n return solution\n else:\n solution = weighted_linear_regression_fit(\n self.data, self.apex_time_array, self.weight_matrix)\n return solution\n\n def fit(self, resample=False):\n solution = self._fit(resample=resample)\n self.estimate = solution.yhat\n self.residuals = solution.residuals\n self.parameters = solution.parameters\n self.projection_matrix = solution.projection_matrix\n self.solution = solution\n return self\n\n @property\n def rss(self):\n x = self.data\n y = self.apex_time_array\n w = self.weight_matrix\n yhat = x.dot(self.parameters)\n residuals = (y - yhat)\n rss = (np.diag(w) * residuals * residuals).sum()\n return rss\n\n @property\n def mse(self):\n return self.rss / (len(self.apex_time_array) - len(self.parameters) - 1.0)\n\n def parameter_significance(self):\n XtWX_inv = np.linalg.pinv(\n (self.data.T.dot(self.weight_matrix).dot(self.data)))\n # With unknown variance, use the mean squared error estimate\n sigma_params = np.sqrt(np.diag(self.mse * XtWX_inv))\n degrees_of_freedom = len(self.apex_time_array) - \\\n len(self.parameters) - 1.0\n # interval = stats.t.interval(1 - alpha / 2.0, degrees_of_freedom)\n t_score = np.abs(self.parameters) / sigma_params\n p_value = stats.t.sf(t_score, degrees_of_freedom) * 2\n return p_value\n\n def parameter_confidence_interval(self, alpha=0.05):\n X = self.data\n sigma_params = np.sqrt(\n np.diag((self.mse) * np.linalg.pinv(\n X.T.dot(self.weight_matrix).dot(X))))\n degrees_of_freedom = len(self.apex_time_array) - \\\n len(self.parameters) - 1\n iv = stats.t.interval((1 - alpha) / 2., degrees_of_freedom)\n iv = np.array(iv) * sigma_params.reshape((-1, 1))\n return np.array(self.parameters).reshape((-1, 1)) + iv\n\n def R2(self, adjust=True):\n x = self.data\n y = self.apex_time_array\n w = self.weight_matrix\n yhat = x.dot(self.parameters)\n residuals = (y - yhat)\n rss = (np.diag(w) * residuals * residuals).sum()\n tss = (y - y.mean())\n tss = (np.diag(w) * tss * tss).sum()\n n = len(y)\n k = len(self.parameters)\n if adjust:\n adjustment_factor = (n - 1.0) / float(n - k - 1.0)\n else:\n adjustment_factor = 1.0\n R2 = (1 - adjustment_factor * (rss / tss))\n return R2\n\n def predict(self, chromatogram):\n return self._predict(self._prepare_data_vector(chromatogram))\n\n def _predict(self, x):\n return x.dot(self.parameters)\n\n def predict_interval(self, chromatogram):\n x = self._prepare_data_vector(chromatogram)\n return self._predict_interval(x)\n\n def _predict_interval(self, x):\n y = self._predict(x)\n return prediction_interval(self.solution, x, y)\n\n def _df(self):\n return max(len(self.chromatograms) - len(self.parameters), 1)\n\n def score(self, chromatogram):\n apex = self.predict(chromatogram)\n # Use heavier tails (scale 2) to be more tolerant of larger chromatographic\n # errors.\n # The survival function's maximum value is 0.5, so double this to map the\n # range of values to be (0, 1)\n score = stats.t.sf(\n abs(apex - self._get_apex_time(chromatogram)),\n df=self._df(), scale=self.scale) * 2\n return max((score - SMALL_ERROR), SMALL_ERROR)\n\n def plot(self, ax=None):\n if ax is None:\n _fig, ax = plt.subplots(1)\n ax.scatter(self.neutral_mass_array,\n self.apex_time_array, label='Observed')\n theoretical_mass = np.linspace(\n max(self.neutral_mass_array.min() - 200, 0),\n self.neutral_mass_array.max() + 200, 400)\n X = self._prepare_data_matrix(theoretical_mass)\n Y = X.dot(self.parameters)\n ax.plot(theoretical_mass, Y, linestyle='--', label='Trend Line')\n pred_interval = self._predict_interval(X)\n ax.fill_between(\n theoretical_mass, pred_interval[0, :], pred_interval[1, :],\n alpha=0.4, label='Prediction Interval')\n return ax\n\n def clone(self):\n return self.__class__(self.chromatograms)\n\n def summary(self, join_char=' | ', justify=True):\n if justify:\n formatter = str.ljust\n else:\n def formatter(x, y):\n return x\n column_labels = ['Feature Name', \"Value\", \"p-value\", \"Conf. Int.\"]\n feature_names = list(map(str, self.feature_names()))\n parameter_values = ['%0.2f' % val for val in self.parameters]\n signif = ['%0.3f' % val for val in self.parameter_significance()]\n ci = ['%0.2f-%0.2f' % tuple(cinv)\n for cinv in self.parameter_confidence_interval()]\n sizes = list(map(len, column_labels))\n value_sizes = [max(map(len, col))\n for col in [feature_names, parameter_values, signif, ci]]\n sizes = map(max, zip(sizes, value_sizes))\n table = [[formatter(v, sizes[i]) for i, v in enumerate(column_labels)]]\n for row in zip(feature_names, parameter_values, signif, ci):\n table.append([\n formatter(v, sizes[i]) for i, v in enumerate(row)\n ])\n joiner = join_char.join\n table_str = '\\n'.join(map(joiner, table))\n return table_str\n\n def to_csv(self, fh):\n writer = csv.writer(fh)\n writer.writerow([\"name\", \"value\"])\n for fname, value in zip(self.feature_names(), self.parameters):\n writer.writerow([fname, value])\n\n\nclass AbundanceWeightedElutionTimeFitter(ElutionTimeFitter):\n def build_weight_matrix(self):\n W = np.eye(len(self.chromatograms)) * [\n np.log10(x.total_signal) for x in self.chromatograms\n ]\n W /= W.max()\n return W\n\n\nclass FactorElutionTimeFitter(ElutionTimeFitter):\n def __init__(self, chromatograms, factors=None, scale=1):\n if factors is None:\n factors = ['Hex', 'HexNAc', 'Fuc', 'Neu5Ac']\n self.factors = list(factors)\n super(FactorElutionTimeFitter, self).__init__(\n chromatograms, scale=scale)\n\n def feature_names(self):\n return ['intercept'] + self.factors\n\n def _prepare_data_matrix(self, mass_array):\n return np.vstack([np.ones(len(mass_array)), ] + [\n np.array([c.glycan_composition[f] for c in self.chromatograms])\n for f in self.factors]).T\n\n def _prepare_data_vector(self, chromatogram, no_intercept=False):\n intercept = 0 if no_intercept else 1\n return np.array(\n [intercept] + [\n chromatogram.glycan_composition[f] for f in self.factors])\n\n def predict_delta_glycan(self, chromatogram, delta_glycan):\n try:\n shifted = chromatogram.shift_glycan_composition(delta_glycan)\n except AttributeError:\n shifted = GlycopeptideChromatogramProxy.from_obj(\n chromatogram).shift_glycan_composition(delta_glycan)\n return self.predict(shifted)\n\n def prediction_plot(self, ax=None):\n if ax is None:\n _fig, ax = plt.subplots(1)\n ax.scatter(self.apex_time_array, self.estimate)\n preds = np.array(self.estimate)\n obs = np.array(self.apex_time_array)\n lo, hi = min(preds.min(), obs.min()), max(preds.max(), obs.max())\n lo -= 0.2\n hi += 0.2\n ax.set_xlim(lo, hi)\n ax.set_ylim(lo, hi)\n ax.plot([lo, hi], [lo, hi], color='black', linestyle='--', lw=0.75)\n ax.set_xlabel(\"Experimental RT (Min)\", fontsize=14)\n ax.set_ylabel(\"Predicted RT (Min)\", fontsize=14)\n ax.figure.text(0.15, 0.8, r\"$R^2:%0.2f$\" % self.R2(True))\n return ax\n\n def plot(self, ax=None, include_intervals=True):\n from glycan_profiling.plotting.colors import ColorMapper\n if ax is None:\n _fig, ax = plt.subplots(1)\n colorer = ColorMapper()\n factors = self.factors\n column_offset = 1\n distinct_combinations = set()\n partitions = defaultdict(list)\n for i, row in enumerate(self.data):\n key = tuple(row[column_offset:])\n distinct_combinations.add(key)\n partitions[key].append(\n (self.neutral_mass_array[i], self.apex_time_array[i]))\n\n theoretical_mass = np.linspace(\n max(self.neutral_mass_array.min() - 200, 0),\n self.neutral_mass_array.max() + 200, 400)\n for combination in distinct_combinations:\n members = partitions[combination]\n ox, oy = zip(*members)\n v = np.ones_like(theoretical_mass)\n factor_partition = [v * f for f in combination]\n label_part = ','.join([\"%s:%d\" % (fl, fv) for fl, fv in zip(\n factors, combination)])\n color = colorer[combination]\n ax.scatter(ox, oy, label=label_part, color=color)\n X = np.vstack([\n np.ones_like(theoretical_mass),\n # theoretical_mass,\n ] + factor_partition).T\n Y = X.dot(self.parameters)\n ax.plot(\n theoretical_mass, Y, linestyle='--', color=color)\n if include_intervals:\n pred_interval = self._predict_interval(X)\n ax.fill_between(\n theoretical_mass, pred_interval[0, :], pred_interval[1, :],\n alpha=0.4, color=color)\n\n return ax\n\n def clone(self):\n return self.__class__(self.chromatograms, factors=self.factors, scale=self.scale)\n\n def predict(self, chromatogram, no_intercept=False):\n return self._predict(self._prepare_data_vector(chromatogram, no_intercept=no_intercept))\n\n\nclass AbundanceWeightedFactorElutionTimeFitter(FactorElutionTimeFitter):\n def build_weight_matrix(self):\n W = np.eye(len(self.chromatograms)) * [\n (x.total_signal) for x in self.chromatograms\n ]\n W /= W.max()\n return W\n\n\nclass PeptideFactorElutionTimeFitter(FactorElutionTimeFitter):\n def __init__(self, chromatograms, factors=None, scale=1):\n if factors is None:\n factors = ['Hex', 'HexNAc', 'Fuc', 'Neu5Ac']\n self._peptide_to_indicator = defaultdict(make_counter(0))\n # Ensure that _peptide_to_indicator is properly initialized\n for obs in chromatograms:\n _ = self._peptide_to_indicator[self._get_peptide_key(obs)]\n super(PeptideFactorElutionTimeFitter, self).__init__(\n chromatograms, list(factors), scale)\n\n def _get_peptide_key(self, chromatogram):\n return PeptideSequence(str(chromatogram.structure)).deglycosylate()\n\n def _prepare_data_matrix(self, mass_array):\n p = len(self._peptide_to_indicator)\n n = len(self.chromatograms)\n peptides = np.zeros((p, n))\n indicator = dict(self._peptide_to_indicator)\n for i, c in enumerate(self.chromatograms):\n try:\n j = indicator[self._get_peptide_key(c)]\n peptides[j, i] = 1\n except KeyError:\n pass\n # Omit the intercept, so that all peptide levels are used without inducing linear dependence.\n return np.vstack([peptides, ] +\n [np.array([c.glycan_composition[f] for c in self.chromatograms]) for f in self.factors]).T\n\n def feature_names(self):\n names = []\n peptides = [None] * len(self._peptide_to_indicator)\n for key, value in self._peptide_to_indicator.items():\n peptides[value] = key\n names.extend(peptides)\n names.extend(self.factors)\n return names\n\n def _prepare_data_vector(self, chromatogram, no_intercept=False):\n p = len(self._peptide_to_indicator)\n peptides = [0 for _ in range(p)]\n indicator = dict(self._peptide_to_indicator)\n if not no_intercept:\n try:\n peptide_key = self._get_peptide_key(chromatogram)\n peptides[indicator[peptide_key]] = 1\n except KeyError:\n import warnings\n warnings.warn(\n \"Peptide sequence %s not part of the model.\" % (peptide_key, ))\n return np.array(\n peptides + [chromatogram.glycan_composition[f] for f in self.factors])\n\n\nclass AbundanceWeightedPeptideFactorElutionTimeFitter(PeptideFactorElutionTimeFitter):\n def build_weight_matrix(self):\n W = np.eye(len(self.chromatograms)) * [\n (x.total_signal) for x in self.chromatograms\n ]\n W /= W.max()\n return W\n\n def groupwise_R2(self, adjust=True):\n x = self.data\n y = self.apex_time_array\n w = self.weight_matrix\n yhat = x.dot(self.parameters)\n residuals = (y - yhat)\n rss_u = (np.diag(w) * residuals * residuals)\n tss = (y - y.mean())\n tss_u = (np.diag(w) * tss * tss)\n\n mapping = {}\n for key, value in self._peptide_to_indicator.items():\n mask = x[:, value] == 1\n rss = rss_u[mask].sum()\n tss = tss_u[mask].sum()\n n = len(y)\n k = len(self.parameters)\n if adjust:\n adjustment_factor = (n - 1.0) / float(n - k - 1.0)\n else:\n adjustment_factor = 1.0\n R2 = (1 - adjustment_factor * (rss / tss))\n mapping[key] = R2\n return mapping\n\n\nclass ElutionTimeModel(ScoringFeatureBase):\n feature_type = 'elution_time'\n\n def __init__(self, fit=None, factors=None):\n self.fit = fit\n self.factors = factors\n\n def configure(self, analysis_data):\n if self.fit is None:\n matches = analysis_data['matches']\n fitter = AbundanceWeightedFactorElutionTimeFitter(\n matches, self.factors)\n fitter.fit()\n self.fit = fitter\n\n def score(self, chromatogram, *args, **kwargs):\n if self.fit is not None:\n return self.fit.score(chromatogram)\n else:\n return 0.5\n","sub_path":"glycan_profiling/scoring/elution_time_grouping/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":16534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"395563015","text":"import unittest\n\nfrom api import office\nfrom logic import office_service\n\nclass OfficeServiceTest(unittest.TestCase):\n service = office_service.OfficeServiceImpl()\n\n def run_parse_test(self, text, expected_office, state_name=None):\n parse_hints = office.ParseHints(state_name=state_name) if state_name else None\n req = office.ParseOfficeRequest(\n text=text,\n parse_hints=parse_hints)\n resp = self.service.invoke('parse', req)\n self.assertEqual('SUCCESS', resp.response_code)\n self.assertIsNotNone(resp.office)\n e = expected_office\n a = resp.office\n self.assertEqual(e.type, a.type)\n self.assertEqual(e.name, a.name)\n self.assertEqual(e.line1, a.line1)\n self.assertEqual(e.line2, a.line2)\n self.assertEqual(e.city, a.city)\n self.assertEqual(e.state_code, a.state_code)\n self.assertEqual(e.zip, a.zip)\n self.assertEqual(e.phone, a.phone)\n\n def test_core_parsing(self):\n text = '''\nBIRMINGHAM\n1800 5th Avenue North\n341 Vance Federal Building\nBirmingham, AL 35203\nMain: (205) 731-1500\nFax: (205) 731-0221'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Birmingham',\n line1='1800 5th Avenue North',\n line2='341 Vance Federal Building',\n city='Birmingham',\n state_code='AL',\n zip='35203',\n phone='(205) 731-1500')\n self.run_parse_test(text, exp)\n\n text = '''\nWashington D.C.\n40B Dirksen Senate Office Building\nWashington, DC 20510\nPhone: (202) 224-3553\n'''\n exp = office.Office(\n type=office.Office.Type.DC,\n name='Washington',\n line1='40B Dirksen Senate Office Building',\n line2=None,\n city='Washington',\n state_code='DC',\n zip='20510',\n phone='(202) 224-3553')\n self.run_parse_test(text, exp)\n\n text = '''\nEAU CLAIRE\n402 Graham Street, Suite 206\nEau Claire, WI 54701-2633\nPhone: (715) 832-8424\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Eau Claire',\n line1='402 Graham Street, Suite 206',\n line2=None,\n city='Eau Claire',\n state_code='WI',\n zip='54701-2633',\n phone='(715) 832-8424')\n self.run_parse_test(text, exp)\n\n text = '''\nBowie Office\n10201 Martin Luther King Jr. Highway, Suite 210\nBowie, MD, 20720\nTel: (301) 860-0414\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Bowie',\n line1='10201 Martin Luther King Jr. Highway, Suite 210',\n line2=None,\n city='Bowie',\n state_code='MD',\n zip='20720',\n phone='(301) 860-0414')\n self.run_parse_test(text, exp)\n\n text = '''\nBangor\n202 Harlow Street, Room 20100\nBangor, ME 04401\nMain: (207) 945-0417\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Bangor',\n line1='202 Harlow Street, Room 20100',\n line2=None,\n city='Bangor',\n state_code='ME',\n zip='04401',\n phone='(207) 945-0417')\n self.run_parse_test(text, exp)\n\n text = '''\n161 High Street SE, Suite 250\nSalem, OR 97301\nPhone: (503) 362-8102\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Salem',\n line1='161 High Street SE, Suite 250',\n line2=None,\n city='Salem',\n state_code='OR',\n zip='97301',\n phone='(503) 362-8102')\n self.run_parse_test(text, exp)\n\n text = u'''\nCRANSTON\n1000 Chapel View Boulevard\nSuite 290\nCranston, RI 02920-5602\nGet Directions \\xbb\n\nT: (401) 943-3100\nF: (401) 464-6837\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Cranston',\n line1='1000 Chapel View Boulevard',\n line2='Suite 290',\n city='Cranston',\n state_code='RI',\n zip='02920-5602',\n phone='(401) 943-3100')\n self.run_parse_test(text, exp)\n\n text = u'''\nCRANSTON\nGet Directions \\xbb\n1000 Chapel View Boulevard\nSuite 290\nCranston, RI 02920-5602\n\nT: (401) 943-3100\nF: (401) 464-6837\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Cranston',\n line1='1000 Chapel View Boulevard',\n line2='Suite 290',\n city='Cranston',\n state_code='RI',\n zip='02920-5602',\n phone='(401) 943-3100')\n self.run_parse_test(text, exp)\n\n text = '''\nSMYRNA DISTRICT OFFICE\n888 Concord Road, Suite 100\nSmyrna, GA 30080\nph:\n(770) 432-5405\nfax:\n(770) 432-5813\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Smyrna',\n line1='888 Concord Road, Suite 100',\n line2=None,\n city='Smyrna',\n state_code='GA',\n zip='30080',\n phone='(770) 432-5405')\n self.run_parse_test(text, exp)\n\n\n\n def test_parsing_with_state_name(self):\n text = '''\nLouisville\n\n600 Dr. MLK Jr. Place\nRoom 1072B\nLouisville, Kentucky 40202\nPhone: 502-582-5341\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Louisville',\n line1='600 Dr. MLK Jr. Place',\n line2='Room 1072B',\n city='Louisville',\n state_code='KY',\n zip='40202',\n phone='(502) 582-5341')\n self.run_parse_test(text, exp, state_name='Kentucky')\n\n text = '''\nLouisville\n\n600 Dr. MLK Jr. Place\nRoom 1072B\nLouisville, Kentucky, 40202\nPhone: 502-582-5341\n'''\n exp = office.Office(\n type=office.Office.Type.DISTRICT,\n name='Louisville',\n line1='600 Dr. MLK Jr. Place',\n line2='Room 1072B',\n city='Louisville',\n state_code='KY',\n zip='40202',\n phone='(502) 582-5341')\n self.run_parse_test(text, exp, state_name='Kentucky')\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"logic/tests/office_service_test.py","file_name":"office_service_test.py","file_ext":"py","file_size_in_byte":6258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"164609218","text":"'''\r\nCreated on Mar 1, 2018\r\n\r\n@author: SummitWorks\r\n'''\r\nclass Employee1:\r\n empCount=0\r\n def __init__(self,sal,dept,name):\r\n self.sal=sal\r\n self.dept=dept\r\n self.name = name\r\n def printvalues(self):\r\n print(self.sal)\r\n print(self.name)\r\ne1=Employee1(232,\"Dev\",\"Raj\")\r\ne1.printvalues()\r\n","sub_path":"summitworkIT/Day3/Examples/Test_Instance_Static.py","file_name":"Test_Instance_Static.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"13893117","text":"import sqlite3,time\nimport time,hashlib\nfrom xml_parsing import *\n\n\npath = findPath('pConfig.databasePath.xml')\nconn = sqlite3.connect(path)\ncurs = conn.cursor()\n\nconn_md5 = sqlite3.connect('tempdb.tgz.md5')\ncurs_md5 = conn_md5.cursor()\n\n\ndef find_new_entries():\n curs.execute('select file_id from file_content_table');\n tmdb_lst=curs.fetchall()\n tmdb_lst=[i for i in tmdb_lst]\n curs_md5.execute('select file_id from compressed_data_table');\n md5_lst = curs_md5.fetchall()\n curs_md5.execute('select file_id from compressed_data_table where md5_hash_value is null ');\n md5_null_lst= curs_md5.fetchall()\n md5_lst=[i for i in md5_lst]\n new_fls= filter(lambda x: x not in md5_lst,tmdb_lst)\n lst = new_fls+md5_null_lst\n return lst\n\n\ndef compressData(lst):\n for i in lst:\n k=curs.execute('select * from file_content_table where file_id=? order by priority',i)\n flObj=k.fetchall()\n strn = flObj[0][-1]\n mdVal= hashlib.md5(strn).hexdigest()\n cmprs = sqlite3.Binary(strn.encode(\"zlib\"))\n curs_md5.execute('update compressed_data_table set compress_data=? where file_id = ?',(cmprs,i[0]));\n curs_md5.execute('update compressed_data_table set md5_hash_value=? where file_id = ?',(mdVal,i[0]));\n curs_md5.execute('select * from compressed_data_table');\n curs_md5.execute('insert into compressed_data_table(file_id,compress_data,md5_hash_value) select ?,?,? where (select changes()=0)',(i[0],cmprs,mdVal));\n\n conn_md5.commit()\n\ndef main():\n tm = float(find_time('tConfig.sleepDuration.xml'))\n \n while(1):\n lst = find_new_entries()\n if(lst==[]):\n time.sleep(tm)\n return main()\n else:\n compressData(lst)\n\n\nif __name__==\"__main__\":main()\n\n","sub_path":"15219_15205/compressor.py","file_name":"compressor.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"363765304","text":"# -*- coding: utf-8 -*-\nfrom jinja2 import Template\n\nfrom src.constant.constant import DEFAULT_PATH, DEFAULT_JAVA_SRC_RELATIVE_PATH\nfrom src.generator.mybatis_generator import MybatisGenerator\n\n_author_ = 'luwt'\n_date_ = '2020/4/19 23:37'\n\n\nclass SpringGenerator(MybatisGenerator):\n \"\"\"\n 对mybatis生成器做扩展,生成相应的service、serviceImpl、controller,仅作为参考框架\n 参数(此处未说明之参数,参见 MybatisGenerator 类文档)\n\n `service_tp`\n service文件的模板,存在于系统模板库中\n `service_impl_tp`\n serviceImpl文件的模板,存在于系统模板库中\n `controller_tp`\n controller文件的模板,存在于系统模板库中\n `service_package`\n service文件所在包命名空间,例如com.demo.service,该命名空间将被作为service文件头部的引包声明,若无则不声明包命名空间。\n 由包命名空间,生成器可生成service文件的命名空间,此命名空间将用于controller中作为引包声明,若无,则不声明\n `service_impl_package`\n service文件所在包命名空间,例如com.demo.service.impl,该命名空间将被作为serviceImpl文件头部的引包声明,若无则不声明。\n `controller_package`\n service文件所在包命名空间,例如com.demo.controller,该命名空间将被作为controller文件头部的引包声明,若无则不声明。\n \"\"\"\n\n def __init__(\n self,\n cursor,\n table_schema,\n table_name,\n column_name=None,\n output_path=DEFAULT_PATH,\n lombok=True,\n exec_sql=None,\n model_package=None,\n mapper_package=None,\n service_package=None,\n service_impl_package=None,\n controller_package=None,\n java_path=None,\n xml_path=None,\n consumer=None,\n file_count=None,\n count=None,\n java_src_relative=DEFAULT_JAVA_SRC_RELATIVE_PATH,\n **kwargs\n ):\n super().__init__(\n cursor,\n table_schema,\n table_name,\n column_name,\n output_path,\n lombok,\n exec_sql,\n model_package,\n mapper_package,\n java_path,\n xml_path,\n consumer,\n file_count,\n count,\n java_src_relative,\n **kwargs\n )\n self.service_tp = self.template.service_tp\n self.service_impl_tp = self.template.service_impl_tp\n self.controller_tp = self.template.controller_tp\n # service包命名空间\n self.service_package = service_package\n # serviceImpl包命名空间\n self.service_impl_package = service_impl_package\n # controller包命名空间\n self.controller_package = controller_package\n # service文件命名空间\n self.service_namespace = f'{self.service_package}.{self.class_name}Service'\n # service文件保存路径\n self.service_path = self.get_path(self.service_package) + '/' + f'{self.class_name}Service.java'\n # serviceImpl文件命名空间\n self.service_impl_namespace = f'{self.service_impl_package}.{self.class_name}ServiceImpl'\n # serviceImpl文件保存路径\n self.service_impl_path = self.get_path(self.service_impl_package) + '/' + f'{self.class_name}ServiceImpl.java'\n # controller文件命名空间\n self.controller_namespace = f'{self.controller_package}.{self.class_name}Controller'\n # controller文件保存路径\n self.controller_path = self.get_path(self.controller_package) + '/' + f'{self.class_name}Controller.java'\n\n def generate_service(self):\n content = Template(self.service_tp, trim_blocks=True, lstrip_blocks=True).render(\n cls_name=self.class_name, model_namespace=self.model_namespace,\n service_package=self.service_package, param=self.param, key=self.key\n )\n self.save(self.service_path, content)\n\n def generate_service_impl(self):\n content = Template(self.service_impl_tp, trim_blocks=True, lstrip_blocks=True).render(\n cls_name=self.class_name, model_namespace=self.model_namespace,\n mapper_namespace=self.mapper_namespace, param=self.param, key=self.key,\n service_impl_package=self.service_impl_package, hump_cls_name=self.hump_cls_name,\n service_namespace=self.service_namespace\n )\n self.save(self.service_impl_path, content)\n\n def generate_controller(self):\n content = Template(self.controller_tp, trim_blocks=True, lstrip_blocks=True).render(\n cls_name=self.class_name, model_namespace=self.model_namespace,\n service_namespace=self.service_namespace, param=self.param, key=self.key,\n controller_package=self.controller_package, hump_cls_name=self.hump_cls_name\n )\n self.save(self.controller_path, content)\n\n def main(self):\n super().main()\n self.generate_service()\n self.generate_service_impl()\n self.generate_controller()\n\n","sub_path":"src/generator/spring_generator.py","file_name":"spring_generator.py","file_ext":"py","file_size_in_byte":5262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"66359259","text":"import os\nimport unittest\nfrom appium import webdriver\nfrom time import sleep\n\n# Returns abs path relative to this file and not cwd\nimport setasdf\n\nPATH = lambda p: os.path.abspath(\n os.path.join(os.path.dirname(__file__), p)\n)\n\nclass setting_tests(unittest.TestCase):\n def setUp(self):\n desired_caps = {}\n desired_caps['platformName'] = 'Android'\n desired_caps['platformVersion'] = '6.0'\n desired_caps['deviceName'] = 'Android Emulator'\n desired_caps['app'] = PATH(\n 'apps/com.qihoo.appstore_300070142.apk'\n )\n desired_caps['appPackage'] = 'com.qihoo.appstore'\n desired_caps['appActivity'] = 'com.qihoo.appstore.home.LauncherActivity'\n #desired_caps.setCapability(\"noReset\", true)\n #把输入法关掉\n desired_caps['unicodeKeyboard'] = True\n desired_caps['noReset'] = True\n\n self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)\n\n def tearDown(self):\n self.driver.quit()\n\n def test_health(self):\n sleep(7)\n sett = self.driver.find_element_by_id('com.qihoo.appstore:id/tab_item_icon')\n sett.click()\n #health = self.driver.find_element_by_id('com.qihoo.appstore:id/clean_animation')\n #health = self.driver.find_element_by_name('立即体检')\n #health.click()\n sleep(10)\n done = self.driver.find_element_by_id('com.qihoo.appstore:id/btn_finish')\n done.click()\n sleep(2)\n quit = self.driver.find_element_by_id('com.qihoo.appstore:id/btn_left')\n quit.click()\n sleep(2)\n clean = self.driver.find_element_by_id('com.qihoo.appstore:id/bodyview')\n clean.click()\n sleep(2)\n clean_back = self.driver.find_element_by_id('com.qihoo360.mobilesafe.clean:id/common_img_back')\n clean_back.click()\n clean_back.click()\n down = self.driver.find_element_by_id('com.qihoo.appstore:id/grid_icon')\n down.click()\n sleep(2)\n\n\n\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(setting_tests)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"test_setting.py","file_name":"test_setting.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"546130781","text":"import os\nimport string\nfrom .DebugHelper import dbglog\nimport config\nimport random\n\n\ndef urlhost():\n\tdbglog(\"urlhost: start\")\n\turlhost = ''\n\tservername = ''\n\n\tif os.environ.has_key('HTTP_HOST'):\n\n\t\tservername = string.lower(os.environ['HTTP_HOST'])\t\t\t# i.e. wotc.fastrackhr.com\t\t\tmight not be there\n\t\tdbglog(\"urlhost: HTTP_HOST is there! \"+servername)\n\telse:\n\t\tdbglog(\"urlhost: NO HTTP_HOST! \")\n\n\t\tif os.environ.has_key('SERVER_NAME'):\n\t\t\tservername = string.lower(os.environ['SERVER_NAME'])\n\t\telse:\n\t\t\tdbglog(\"urlhost: NO HTTP_HOST or SERVER_NAME! \")\n\t\t\tservername = 'wotc.fastrackhr.com'\n\n\thostparts = servername.split('.')\n\tdbglog(\"hostparts =\"+repr(hostparts)+\" length=\"+str(len(hostparts)))\n\n\tif config.config[\"srv\"][\"pubsite\"] == 0:\n\t\turlhost = 'http://' + servername\n\telse:\n\t\turlhost = 'https://' + servername\n\n# for safety, only change functionality for test sites...\n\tif len(hostparts) == 3:\n\t\tif hostparts[1] == 'fastrackhr' and hostparts[2] == 'com':\n\t\t\tdbglog(\"urlhost: fastrackhr detected: returning '\"+servername+\"' \")\n\t\t\treturn (urlhost)\n\t\telif hostparts[0] == 'fthrcurrel':\n\t\t\tdbglog(\"urlhost: fthrcurrel detected: returning '\"+servername+\"' \")\n\t\t\treturn (urlhost)\n\n\telse:\n\t\tdbglog(\"urlhost: invalid/unrecognized url? '\"+servername+\"' \")\n\n\tif config.config[\"srv\"][\"pubsite\"] == 0:\n\t\turlhost = 'http://' + os.environ['HTTP_HOST']\n\n\tdbglog(\"urlhost: other http host returning '\"+urlhost+\"' \")\n\n\treturn (urlhost)\n\n\ndef random_string(length):\n\treturn ''.join(random.choice(string.lowercase) for x in range(length))\n\n\ndef safe_cast(value, to_type, default):\n\ttry:\n\t\treturn to_type(value)\n\texcept (ValueError, TypeError):\n\t\treturn default","sub_path":"cgi-bin/career/utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"227045186","text":"# coding = utf-8\n# “逆变器温度过高”故障诊断调用模块\nfrom main.src.use.listeners.CommonListener import *\nfrom main.src.application.diagnosis.General import *\nimport json\n\n# 故障名称\nfault_name = '逆变器温度过高'\n# 需要的数据,类型:返回时的字段名称\nneed_data = {'温度': 'temp'}\n\n\nclass Application:\n __data = None\n __socket = None\n __identify = None\n\n def __init__(self, identify, socket):\n self.__socket = socket\n self.__identify = identify\n socket.send_json({'type': 'request', 'token': identify, 'device': need_data})\n\n def main(self, data):\n self.__data = data\n print(fault_name + \" Received request: %s\" % data)\n try:\n execute = Execute()\n execute.set_data(float(data['temp']))\n execute.set_execute_listener(CommonListener(self.__identify, self.__socket))\n algorithm = ValueIsHigh()\n algorithm.set_threshold(50)\n execute.set_algorithm(algorithm)\n execute.execute()\n except json.JSONDecodeError:\n self.__socket.send_json({'token': self.__identify, 'data': {'error': 'json解析错误'}})\n","sub_path":"main/src/use/diagnosis/InverterTempIsHigh.py","file_name":"InverterTempIsHigh.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"222980291","text":"import gzip\nimport http.cookiejar\nimport time\nimport matplotlib.pyplot as plt\nfrom io import BytesIO\nfrom urllib import request\nfrom wordcloud import WordCloud\nimport jieba\nimport numpy\nimport pandas\nfrom PIL import Image\nfrom bs4 import BeautifulSoup\nimport matplotlib\nmatplotlib.rcParams['figure.figsize'] = (10.0, 5.0)\n\nurl = \"https://movie.douban.com/subject/25779217/comments?start={}&limit=20\"\nheaders = {\n \"User-Agent\": \" Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36\",\n 'Accept-encoding': 'gzip'\n}\nuser_agent_list = [\n \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/61.0\",\n \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36\",\n \"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)\",\n \"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10.5; en-US; rv:1.9.2.15) Gecko/20110303 Firefox/3.6.15\",\n]\n\n\ndef main(index=0, content=\"\"):\n cookies = http.cookiejar.CookieJar()\n handler = request.HTTPCookieProcessor(cookies)\n opener = request.build_opener(handler)\n\n ht = jixHtml(opener, url.format(index))\n\n tasks = []\n index = 0\n for t in ht.findAll(class_='comment-content'):\n content += str(ht.findAll(class_='comment-content')[0].text).strip().replace(\" \",\"\")\n return content\n\n\ndef jixHtml(opener, URL):\n # headers['User-Agent'] = random.choice(user_agent_list)\n req = request.Request(URL, headers=headers)\n resp = openurl(opener, req)\n acceptEncoding = resp.info().get('Content-Encoding')\n htmls = ''\n if acceptEncoding == 'gzip':\n htmls = resp.read()\n buff = BytesIO(htmls)\n f = gzip.GzipFile(fileobj=buff)\n htmls = f.read().decode('utf-8')\n else:\n htmls = resp.read().decode('utf-8')\n # print(htmls)\n ht = BeautifulSoup(htmls, \"lxml\")\n return ht\n\n\ndef openurl(opener, req):\n resp = None\n jx = False\n try:\n resp = opener.open(req)\n except Exception as e:\n print(e)\n jx = True\n finally:\n print('最后执行')\n if jx:\n time.sleep(1)\n resp = openurl(opener, req)\n\n return resp\n\n\n\nif __name__ == '__main__':\n content = \"\"\n for i in range(10):\n time.sleep(1)\n content = main(i*20, content)\n cs = jieba._lcut(content)\n words_df = pandas.DataFrame({\"segment\": cs})\n stopwords = pandas.read_csv('stopwords.txt', index_col=False, quoting=3, sep='\\t', names=['stopword'],\n encoding='gbk') # quoting=3全部引用\n words_df = words_df[~words_df.segment.isin(stopwords.stopword)]\n words_stat = words_df.groupby('segment').agg(计数=pandas.NamedAgg(column='segment', aggfunc='size')).reset_index().sort_values(\n by='计数', ascending=False)\n print(words_stat.head())\n img=numpy.array(Image.open(\"11.png\"))\n wordcloud=WordCloud(font_path=\"SimHei.ttf\",mask=img,background_color=\"white\",max_font_size=80,min_font_size=6,scale=10)\n word_frequence = {x[0]:x[1] for x in words_stat.head(1000).values}\n\n word_frequence_list = []\n for key in word_frequence:\n temp = (key,word_frequence[key])\n word_frequence_list.append(temp)\n\n wordcloud=wordcloud.fit_words( dict(word_frequence_list))\n plt.figure()\n plt.imshow(wordcloud)\n plt.axis(\"off\")\n plt.show()\n\n\n","sub_path":"study/dhz.py","file_name":"dhz.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"439794119","text":"import reversion\nfrom django.shortcuts import render\nfrom django.db import transaction\nfrom django.utils.translation import ugettext as _, ungettext\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import (\n login_required, permission_required, user_passes_test\n)\nfrom django.views.decorators.csrf import ensure_csrf_cookie\nfrom modoboa.lib import parameters, events\nfrom modoboa.lib.exceptions import (\n PermDeniedException, BadRequest\n)\nfrom modoboa.lib.webutils import (\n _render_to_string, render_to_json_response\n)\nfrom modoboa.lib.formutils import CreationWizard\nfrom modoboa.lib.templatetags.lib_tags import pagination_bar\nfrom modoboa.core.models import User\nfrom modoboa.extensions.admin.models import Mailbox, Domain\nfrom modoboa.extensions.admin.lib import (\n get_sort_order, get_listing_page, get_identities\n)\nfrom modoboa.extensions.admin.forms import (\n AccountForm, AccountFormGeneral, AccountFormMail\n)\n\n\n@login_required\n@user_passes_test(\n lambda u: u.has_perm(\"core.add_user\") or u.has_perm(\"admin.add_alias\")\n)\ndef _identities(request):\n filters = dict((fname, request.GET.get(fname, None))\n for fname in ['searchquery', 'idtfilter', 'grpfilter'])\n request.session['identities_filters'] = filters\n idents_list = get_identities(request.user, **filters)\n sort_order, sort_dir = get_sort_order(request.GET, \"identity\",\n [\"identity\", \"name_or_rcpt\", \"tags\"])\n if sort_order in [\"identity\", \"name_or_rcpt\"]:\n objects = sorted(idents_list, key=lambda o: getattr(o, sort_order),\n reverse=sort_dir == '-')\n else:\n objects = sorted(idents_list, key=lambda o: o.tags[0],\n reverse=sort_dir == '-')\n page = get_listing_page(objects, request.GET.get(\"page\", 1))\n return render_to_json_response({\n \"table\": _render_to_string(request, \"admin/identities_table.html\", {\n \"identities\": page.object_list,\n \"tableid\": \"objects_table\"\n }),\n \"handle_mailboxes\": parameters.get_admin(\"HANDLE_MAILBOXES\",\n raise_error=False),\n \"page\": page.number,\n \"paginbar\": pagination_bar(page)\n })\n\n\n@login_required\n@user_passes_test(\n lambda u: u.has_perm(\"admin.add_user\") or u.has_perm(\"admin.add_alias\")\n)\n@ensure_csrf_cookie\ndef identities(request, tplname=\"admin/identities.html\"):\n return render(request, tplname, {\n \"selection\": \"identities\",\n \"deflocation\": \"list/\"\n })\n\n\n@login_required\n@permission_required(\"core.add_user\")\ndef accounts_list(request):\n accs = User.objects.filter(is_superuser=False) \\\n .exclude(groups__name='SimpleUsers')\n res = [a.username for a in accs.all()]\n return render_to_json_response(res)\n\n\n@login_required\n@permission_required(\"admin.add_mailbox\")\ndef list_quotas(request, tplname=\"admin/quotas.html\"):\n from modoboa.lib.dbutils import db_type\n\n sort_order, sort_dir = get_sort_order(request.GET, \"address\")\n mboxes = Mailbox.objects.get_for_admin(\n request.user, request.GET.get(\"searchquery\", None)\n )\n mboxes = mboxes.exclude(quota=0)\n if sort_order in [\"address\", \"quota\", \"quota_value__bytes\"]:\n mboxes = mboxes.order_by(\"%s%s\" % (sort_dir, sort_order))\n elif sort_order == \"quota_usage\":\n if db_type() == \"postgres\":\n select = '(admin_quota.bytes::float / (CAST(admin_mailbox.quota AS BIGINT) * 1048576)) * 100'\n else:\n select = 'admin_quota.bytes / (admin_mailbox.quota * 1048576) * 100'\n mboxes = mboxes.extra(\n select={'quota_usage': select},\n where=[\"admin_quota.mbox_id=admin_mailbox.id\"],\n tables=[\"admin_quota\"],\n order_by=[\"%s%s\" % (sort_dir, sort_order)]\n )\n else:\n raise BadRequest(_(\"Invalid request\"))\n page = get_listing_page(mboxes, request.GET.get(\"page\", 1))\n return render_to_json_response({\n \"page\": page.number,\n \"paginbar\": pagination_bar(page),\n \"table\": _render_to_string(request, tplname, {\n \"mboxes\": page\n })\n })\n\n\n@login_required\n@permission_required(\"core.add_user\")\n@transaction.commit_on_success\n@reversion.create_revision()\ndef newaccount(request, tplname='common/wizard_forms.html'):\n \"\"\"Create a new account.\n\n .. note:: An issue still remains int this code: if all validation\n steps are successful but an error occurs after we call 'save',\n the account will be created. It happens transaction management\n doesn't work very well with nested functions. Need to wait for\n django 1.6 and atomicity.\n \"\"\"\n cwizard = CreationWizard()\n cwizard.add_step(AccountFormGeneral, _(\"General\"),\n [dict(classes=\"btn-inverse next\", label=_(\"Next\"))],\n new_args=[request.user])\n cwizard.add_step(AccountFormMail, _(\"Mail\"),\n [dict(classes=\"btn-primary submit\", label=_(\"Create\")),\n dict(classes=\"btn-inverse prev\", label=_(\"Previous\"))],\n formtpl=\"admin/mailform.html\")\n\n if request.method == \"POST\":\n retcode, data = cwizard.validate_step(request)\n if retcode == -1:\n raise BadRequest(data)\n if retcode == 1:\n return render_to_json_response(\n {'title': cwizard.get_title(data + 1), 'stepid': data}\n )\n if retcode == 2:\n genform = cwizard.steps[0][\"form\"]\n account = genform.save()\n account.post_create(request.user)\n mailform = cwizard.steps[1][\"form\"]\n mailform.save(request.user, account)\n return render_to_json_response(_(\"Account created\"))\n return render_to_json_response({\n 'stepid': data, 'form_errors': cwizard.errors\n }, status=400)\n\n ctx = {\n 'title': _(\"New account\"),\n 'action': reverse(newaccount),\n 'formid': 'newaccount_form',\n 'submit_label': _(\"Create\")\n }\n cwizard.create_forms()\n ctx.update(steps=cwizard.steps)\n ctx.update(subtitle=\"1. %s\" % cwizard.steps[0]['title'])\n return render(request, tplname, ctx)\n\n\n@login_required\n@permission_required(\"core.change_user\")\n@transaction.commit_on_success\n@reversion.create_revision()\ndef editaccount(request, accountid, tplname=\"common/tabforms.html\"):\n account = User.objects.get(pk=accountid)\n if not request.user.can_access(account):\n raise PermDeniedException\n mb = None\n if account.mailbox_set.count():\n mb = account.mailbox_set.all()[0]\n\n instances = dict(general=account, mail=mb, perms=account)\n events.raiseEvent(\"FillAccountInstances\", request.user, account, instances)\n\n if request.method == \"POST\":\n classes = {}\n form = AccountForm(request.user, request.POST,\n instances=instances, classes=classes)\n account.oldgroup = account.group\n if form.is_valid(mandatory_only=True):\n form.save_general_form()\n if form.is_valid(optional_only=True):\n events.raiseEvent(\"AccountModified\", account, form.account)\n form.save()\n return render_to_json_response(_(\"Account updated\"))\n return render_to_json_response({'form_errors': form.errors}, status=400)\n\n ctx = {\n 'title': account.username,\n 'formid': 'accountform',\n 'action': reverse(editaccount, args=[accountid]),\n 'action_label': _('Update'),\n 'action_classes': 'submit',\n 'tabs': AccountForm(request.user, instances=instances)\n }\n active_tab_id = request.GET.get(\"active_tab\", \"default\")\n if active_tab_id != \"default\":\n ctx[\"tabs\"].active_id = active_tab_id\n return render(request, tplname, ctx)\n\n\n@login_required\n@permission_required(\"core.delete_user\")\n@transaction.commit_on_success\ndef delaccount(request, accountid):\n keepdir = True if request.POST.get(\"keepdir\", \"false\") == \"true\" else False\n User.objects.get(pk=accountid).delete(request.user, keep_mb_dir=keepdir)\n return render_to_json_response(\n ungettext(\"Account deleted\", \"Accounts deleted\", 1)\n )\n\n\n@login_required\n@permission_required(\"admin.add_domain\")\ndef remove_permission(request):\n domid = request.GET.get(\"domid\", None)\n daid = request.GET.get(\"daid\", None)\n if domid is None or daid is None:\n raise BadRequest(_(\"Invalid request\"))\n try:\n account = User.objects.get(pk=daid)\n domain = Domain.objects.get(pk=domid)\n except (User.DoesNotExist, Domain.DoesNotExist):\n raise BadRequest(_(\"Invalid request\"))\n if not request.user.can_access(account) or not request.user.can_access(domain):\n raise PermDeniedException\n domain.remove_admin(account)\n return render_to_json_response({})\n","sub_path":"modoboa/extensions/admin/views/identity.py","file_name":"identity.py","file_ext":"py","file_size_in_byte":8909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"40633362","text":"import typing as T\nimport operator\nimport collections\n'''--- Day 8: I Heard You Like Registers ---\n\nYou receive a signal directly from the CPU. Because of your recent assistance with jump instructions, it would like you to compute the result of a series of unusual register instructions.\n\nEach instruction consists of several parts: the register to modify, whether to increase or decrease that register's value, the amount by which to increase or decrease it, and a condition. If the condition fails, skip the instruction without modifying the register. The registers all start at 0. The instructions look like this:\n\nb inc 5 if a > 1\na inc 1 if b < 5\nc dec -10 if a >= 1\nc inc -20 if c == 10\nThese instructions would be processed as follows:\n\nBecause a starts at 0, it is not greater than 1, and so b is not modified.\na is increased by 1 (to 1) because b is less than 5 (it is 0).\nc is decreased by -10 (to 10) because a is now greater than or equal to 1 (it is 1).\nc is increased by -20 (to -10) because c is equal to 10.\nAfter this process, the largest value in any register is 1.\n\nYou might also encounter <= (less than or equal to) or != (not equal to). However, the CPU doesn't have the bandwidth to tell you what all the registers are named, and leaves that to you to determine.\n\nWhat is the largest value in any register after completing the instructions in your puzzle input?\n'''\n\nBINOP = T.Callable[[int, int], int]\nRegisters = T.DefaultDict[str, int]\n\n\n_op_lookup = { \n \"<=\": operator.le, \n \"<\": operator.lt,\n \"==\": operator.eq, \n \"!=\": operator.ne,\n \">\": operator.gt,\n \">=\": operator.ge,\n \"inc\": operator.add,\n \"dec\": operator.sub,\n }\n\ndef op(sym: str) -> BINOP:\n return _op_lookup[sym]\n\npath = \"advent_008_input.txt\"\n\n\nclass ThreeOp():\n def __init__(self, register: str, opcode: str, literal: str) -> None:\n self.op = op(opcode)\n self.register = register\n self.right = int(literal)\n\n\n def __call__(self, registers: Registers) -> int:\n left = registers[self.register]\n return self.op(left, self.right)\n\nclass Instruction():\n def __init__(self, incrementer: ThreeOp, comparer: ThreeOp) -> None:\n self.inc = incrementer\n self.cmp = comparer\n @property\n def reg(self) -> str:\n return self.inc.register\n def __call__(self, registers: Registers) -> int:\n if self.cmp(registers):\n result = self.inc(registers)\n registers[self.reg] = result\n return result\n return 0\n\ndef get_instructions(path: str) -> T.Iterable[Instruction]:\n with open(path) as fp:\n for line in fp:\n yield parse_instruction(line)\n\n\ndef parse_instruction(raw: str) -> Instruction:\n parts = raw.split()\n if len(parts) != 7:\n raise ValueError(\"could not parse code\")\n return Instruction(ThreeOp(*parts[:3]), ThreeOp(*parts[4:]))\n \ndef max_register_ever(instructions: T.Iterable[Instruction]) -> int:\n registers: Registers = collections.defaultdict(int)\n largest = 0\n for op in instructions:\n largest = max(largest, op(registers))\n return largest\n\n\ntest_instructions = ['b inc 5 if a > 1',\n'a inc 1 if b < 5',\n'c dec -10 if a >= 1',\n'c inc -20 if c == 10']\n\nif __name__ == '__main__':\n print(max_register_ever(get_instructions(path)))\n","sub_path":"2017/008/advent_008_b.py","file_name":"advent_008_b.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"380981137","text":"\"\"\"\nImagine you want to log stuff in multiple files of a Python project. You'd\nprobably write some code that looks like this:\n\n logging.debug(\"Hello, World!\")\n\nPretty simple. Unfortunately, some packages like gym seem to clobber the\ndefault logger that is used by logging.debug. No big deal, just use a different\nlogger:\n\n logging.getLogger(\"mylogger\").debug(\"Hello, World!\")\n\nTwo problems stick out though. First, \"mylogger\" is a bit of a magic constant.\nSecond, that's a lot of typing for a print statement! This file makes it a\ntinier bit more convenient to log stuff. In one file, run this:\n\n import log\n log.init(verbose=True)\n\nAnd then from any other file, run something this:\n\n from log import debug\n debug(\"Iteration {} of {}\", 1, num_iters)\n\"\"\"\n\nimport inspect\nimport logging\nimport os\nfrom datetime import datetime\n\nfrom absl import flags\n\nflags.DEFINE_boolean(\"verbose\", True, \"whether to activate logging\")\n\n\nclass _StackCrawlingFormatter(logging.Formatter):\n \"\"\"\n If we configure a python logger with the format string\n \"%(pathname):%(lineno): %(message)\", messages logged via `log.debug` will\n be prefixed with the path name and line number of the code that called\n `log.debug`. Unfortunately, when a `log.debug` call is wrapped in a helper\n function (e.g. debug below), the path name and line number is always that\n of the helper function, not the function which called the helper function.\n\n A _StackCrawlingFormatter is a hack to log a different pathname and line\n number. Simply set the `pathname` and `lineno` attributes of the formatter\n before you call `log.debug`. See `debug` below for an example.\n \"\"\"\n\n def __init__(self, format_str):\n super().__init__(format_str)\n self.pathname = None\n self.lineno = None\n\n def format(self, record):\n s = super().format(record)\n if self.pathname is not None:\n s = s.replace(\"{pathname}\", self.pathname)\n if self.lineno is not None:\n s = s.replace(\"{lineno}\", str(self.lineno))\n if \"{fmttime}\" in s:\n tztime = datetime.now().astimezone()\n fmttime = tztime.strftime(\"%Y-%m-%d %H:%M:%S %Z\")\n s = s.replace(\"{fmttime}\", fmttime)\n return s\n\n\n_LOGGER = logging.getLogger(__package__)\n_FORMAT_STRING = \"[{fmttime} {pathname}:{lineno}] %(message)s\"\n_FORMATTER = _StackCrawlingFormatter(_FORMAT_STRING)\n\n\ndef init():\n \"\"\"Initialize the logger.\"\"\"\n handler = logging.StreamHandler()\n handler.setFormatter(_FORMATTER)\n _LOGGER.propagate = False\n _LOGGER.addHandler(handler)\n if flags.FLAGS.verbose:\n _LOGGER.setLevel(logging.DEBUG)\n else:\n _LOGGER.setLevel(logging.INFO)\n\ndef _prep_formatter():\n # Get the path name and line number of the function which called us.\n previous_frame = inspect.currentframe().f_back\n try:\n pathname, lineno, _, _, _ = inspect.getframeinfo(previous_frame)\n except Exception: # pylint: disable=broad-except\n pathname = \".py\"\n lineno = 0\n _FORMATTER.pathname = _clean_path(pathname)\n _FORMATTER.lineno = lineno\n\ndef debug(s, *args):\n \"\"\"debug(s, x1, ..., xn) logs s.format(x1, ..., xn).\"\"\"\n _prep_formatter()\n _LOGGER.debug(s.format(*args))\n\ndef info(s, *args):\n \"\"\"info(s, x1, ..., xn) logs s.format(x1, ..., xn).\"\"\"\n _prep_formatter()\n _LOGGER.info(s.format(*args))\n\ndef _clean_path(path):\n \"\"\"\n Simplifies the path for readability.\n \"\"\"\n path = os.path.abspath(path)\n home = os.path.expanduser(\"~\")\n if os.path.commonpath([path, home]) == home:\n home_path = os.path.join(\"~\", os.path.relpath(path, home))\n home_path = os.path.normpath(home_path)\n else:\n home_path = path\n cwd = os.getcwd()\n if os.path.commonpath([cwd, path]):\n cwd_path = os.path.join(\".\", os.path.relpath(path, cwd))\n cwd_path = os.path.normpath(cwd_path)\n else:\n cwd_path = path\n return min(home_path, cwd_path, path, key=len)\n","sub_path":"fdd/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"406184024","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nimport datetime\n\ndef home(httpRequest):\n home = \"welcome My New Home, powered by Django\"\n return HttpResponse(home)\n\n\ndef hello(httpRequest):\n current_time = datetime.datetime.now()\n return HttpResponse(f\"Hello, Now is {current_time}\")\n\ndef current_time(httpRequest):\n current_time = datetime.datetime.now()\n return render(httpRequest, 'test.html', {'current_time': current_time, 'is_first': True})\n\ndef template_test(httpRequest):\n current_time = datetime.datetime.now()\n return render(httpRequest, 'content.html', {'current_time': current_time, 'name': 'UnyongChoi'})\n\ndef cal_extra_work_time(httpRequest) :\n worktimes = \"\"\" \n 9:00, 7:00, 8:20, 7:50,\n 8:50, 8:30, 8:00, 8:00, 8:00,\n 8:00, 8:00, 8:00, \n 8:00, 8:00, 8:00, 8:00\n \"\"\"\n days, calculated_time, expected_time = parsing_and_calculate_extra_or_overtime(worktimes)\n\n return render(httpRequest, 'extra_time_calculator.html', {'worktimes': worktimes, 'work_days': days, \"calculated_time\": calculated_time, \"expected_time\":expected_time})\n\ndef parsing_and_calculate_extra_or_overtime(worktimes):\n times = [x.strip() for x in worktimes.split(',')]\n workdays = len(times)\n\n totalMyTime = MyTimeClass(\"0:0\")\n for time in times:\n totalMyTime = totalMyTime + MyTimeClass(time)\n\n expected_hour = 8 * workdays\n expected_work_time = MyTimeClass(f\"{expected_hour}:0\")\n\n return workdays, totalMyTime, expected_work_time\n\nclass MyTimeClass:\n def __str__(self):\n return f\"{self.hour}:{self.minutes}\"\n\n def __init__(self, timestring):\n self.hour = int(timestring.split(':')[0])\n self.minutes = int(timestring.split(':')[1])\n \n def __add__ (self, other):\n sumTime = MyTimeClass('0:0')\n\n sumTime.hour = self.hour + other.hour\n sumTime.minutes = self.minutes + other.minutes\n\n offset_hour, remainder_minute = divmod(sumTime.minutes, 60)\n sumTime.hour = sumTime.hour + offset_hour\n\n if offset_hour > 0:\n sumTime.minutes = remainder_minute\n\n return sumTime\n","sub_path":"mysite/mysite/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"511319223","text":"from __future__ import print_function\n\"\"\"\nFunctions needed to calculate the Jones polynomial of K. Still needs work ...\n\"\"\"\nfrom sage.symbolic.ring import var\nimport sage.graphs.graph as graph\n\ndef cut(G,T,e):\n \"\"\"\n Input:\n --A graph G.\n --A spanning tree T for G\n --And edge e of T\n \n Cutting T along e separates T into two components.\n Returns: The list of edges in G - e connecting the two different components of T-e.\"\"\"\n if not e in T.edges():\n raise Exception(\"e must be an edge of T.\")\n H = G.copy()\n S = T.copy()\n S.delete_edge(e)\n (C1, C2) = S.connected_components()\n answer = list()\n for f in G.edges():\n if (f[0] in C1 and f[1] in C2) or (f[0] in C2 and f[1] in C1):\n if f != e:\n answer.append(f)\n return answer \n\ndef is_internally_active(G, T, e):\n \"\"\"\n Input:\n --A graph G.\n --A spanning tree T for G\n --And edge e of G\n\n Returns: True is e is in T and e is internally active for T, False otherwise. Uses the ordering on G.edges().\"\"\"\n if not e in T.edges():\n return False\n edges = G.edges()\n for f in cut(G,T,e):\n if edges.index(f) 1/A in negative case.\n s = _edge_sign(K,e)\n if is_internally_active(G,T,e):\n return -A**(-3*s)\n if (e in T.edges()) and (not is_internally_active(G,T,e)):\n return A**s\n if is_externally_active(G,T,e):\n return -A**(3*s)\n if (not e in T.edges()) and (not is_externally_active(G,T,e)):\n return A**(-1*s)\n \ndef _Jones_contrib(K, G, T, A):\n \"Returns the contribution to the Jones polynomial of the tree T. G should be self.black_graph().\"\n answer = 1\n # 2 loops, edges in T and edges not in T\n for e in G.edges():\n answer = answer*_Jones_contrib_edge(K,G,T,e,A)\n return answer\n\ndef Jones_poly(K,variable=None):\n if not variable:\n variable = var('q')\n answer = 0\n A = var('A')\n G = K.black_graph()\n for T in G.spanning_trees():\n answer = answer + _Jones_contrib(K,G,T,A)\n answer = answer * (-A)**(3*K.writhe())\n answer = answer.expand()\n #Python doesn't deal well with rational powers, so renormalizing (divide exponents by 4) is a pain. (Sage would do this fine.)\n ans = 0\n for [coeff, exp] in answer.coefficients():\n ans = ans + coeff*(variable**(exp/4))\n return ans\n","sub_path":"venv/Lib/site-packages/spherogram-1.4.1-py2.7-win32.egg/spherogram/links/jones.py","file_name":"jones.py","file_ext":"py","file_size_in_byte":4572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"110476147","text":"'''\ntest cases:\n[] & [] return true\n[] & [!] return false\n[1] & [] return true\n\n'''\n\nclass Solution(object):\n def validate(self, pushed, popped):\n ''' \n to check two list with same numbers of elements\n :type pushed: List[int] cannot be empty\n :type popped: List[int] cannot be empty\n :rtype: bool\n '''\n stack = []\n pushidx = 0\n popidx = 0\n count = 0\n while pushidx 0\n for model_id, fold_number in model_info.items():\n if TTA:\n for TTA_round in range(TTA_rounds):\n print(f\"TTA round {TTA_round + 1}/{TTA_rounds}\")\n print(f\"Inference for model {model_id} on fold {fold_number} -- {counter}/{len(model_info)}\")\n counter += 1\n run_single(model_id, fold_number, gpu_number, TTA, TTA_round)\n else:\n print(f\"Inference for model {model_id} on fold {fold_number} -- {counter}/{len(model_info)}\")\n counter += 1\n run_single(model_id, fold_number, gpu_number, TTA)\n","sub_path":"inference/covid_inference_batch.py","file_name":"covid_inference_batch.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"484971871","text":"import numpy as np\nfrom numpy.testing import assert_allclose\n\nfrom rating_models import OrdinalLogisticRatings\nfrom optimize_model import train_valid_test_split\nfrom utils.data import get_data\nfrom utils.model import goals2class\n\n\n*_, seasons_all = train_valid_test_split(\"TEST\", True)\nmatches = get_data(seasons_all)\n\n\ndef numerical_grad(model, params, args, h=1e-6):\n grad = np.zeros_like(params)\n for i in range(len(params)):\n params1 = np.copy(params)\n params2 = np.copy(params)\n params1[i] += h\n params2[i] -= h\n grad[i] = (model._negative_loglik(params1, *args) - model._negative_loglik(params2, *args)) / (2 * h)\n return grad\n\n\ndef test_ordinal_logistic_ratings():\n model_olr = OrdinalLogisticRatings(lambda_reg=1.0, penalty='l1')\n X = model_olr.get_features(matches[['HomeTeam', 'AwayTeam']])\n y = matches[['FTHG', 'FTAG']].apply(goals2class, axis=1).values\n random_weight = np.random.uniform(0.5, 2., len(y))\n for sample_weight in (random_weight, None):\n args = (X, y, sample_weight, 3, 1e-8)\n params = np.concatenate((np.random.randn(X.shape[1]), (-0.5, 1.0)))\n grad_exact = model_olr._grad_negative_loglik(params, *args)\n grad_approx = numerical_grad(model_olr, params, args)\n assert_allclose(grad_exact, grad_approx, rtol=1e-6)\n","sub_path":"tests/test_gradients.py","file_name":"test_gradients.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"464415055","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 14 12:45:45 2019\r\n\r\n@author: yeves\r\n\"\"\"\r\n\r\nimport time\r\nimport pyvisa\r\nimport serial\r\n\r\n\"\"\"\r\n:brief Converts list data from scope to voltage values \r\n:param list data type raw_rata contains the values recorded\r\n:from scope in ASCII format\r\n:param resourceManager object scope: access point of the oscilloscope\r\n:return list data type voltage: recorded voltage values\r\n\"\"\"\r\ndef convert_raw_voltage_data(raw_data, scope):\r\n #Query returns the y-axis scale on oscilloscope graph\r\n ymult = float(scope.query('WFMOutpre:YMULT?'))\r\n #Query returns the y-zero value of the oscilloscope graph\r\n yzero = float(scope.query('WFMOutpre:YZERO?'))\r\n #Query returns the offset value for the y-axis on the oscilloscope graph\r\n yoff = float(scope.query('WFMOutpre:YOFF?'))\r\n npoint=len(raw_data)\r\n voltage=['?']*npoint\r\n #Convert raw data values and fill into voltage list\r\n #Non-recorded data appears as '?' in voltage list\r\n for i in range(npoint):\r\n voltage[i]=ymult*(raw_data[i]-yoff)+yzero\r\n return voltage\r\n\"\"\"\r\n:brief sets the channel of the scope\r\n:param resourceManager object scope: access point of the oscilloscope\r\n:param int data type channel: channel scope is to be set\r\n\"\"\"\r\ndef set_channel(scope, channel):\r\n scope.write(\":DATa:SOUrce CH\"+str(channel))\r\n\"\"\"\r\n:brief obtains raw data from oscilloscope and converts it into voltage list\r\n:param resourceManager object scope: access point of the oscilloscope\r\n:return list data type voltage: recorded voltage values\r\n\"\"\"\r\ndef get_data(scope):\r\n scope.write(\"WFMOutpre:ENCdg ASCii\")\r\n data = scope.query_ascii_values(\"CURVE?\")\r\n voltage=convert_raw_voltage_data(data, scope)\r\n return voltage\r\n\r\n\"\"\"\r\n:brief prints recorded data into datasheet docuement with corresponding\r\n voltage and time recorded from each of the channels\r\n:param resourceManager object scope: access point of the oscilloscope\r\n:param int data type numchan is number of channels\r\n:param list data type voltage contains recorded voltage values\r\n:param list data type times contains recorded time values corresponding\r\n:with recorded voltage\r\n:param float data type dt records the sampling time interval\r\n:param file data type outfile: datasheet into which data would be stored \r\n:param stime data type String:Locale’s appropriate date and time representation\r\n param float data type timeins: time as a floating point number expressed in seconds since the epoch, in UTC.\r\n\"\"\" \r\n\"\"\"\r\n:brief obtains the times for which sampling data was recorded\r\n:param resourceManager object scope: access point of the oscilloscope\r\n:param int data type record_length: number of sample data recorded\r\n:return list data type times: the times at which sampling data was recorded\r\n\"\"\" \r\ndef get_time(scope, record_length):\r\n times=['?']*record_length\r\n xincr = float(scope.query('WFMOutpre:XINCR?'))\r\n print('xincr= '+str(xincr))\r\n for i in range(record_length):\r\n times[i]=float(i)*xincr\r\n return times \r\n\r\n\"\"\"\r\n:brief obtains the recording time interval\r\n:param resourceManager object scope: access point of the oscilloscope\r\n:return float data type xincr: the sampling time interval\r\n\"\"\" \r\ndef get_dt(scope):\r\n xincr = float(scope.query('WFMOutpre:XINCR?'))\r\n return xincr\r\n\"\"\"\r\n:brief obtains the total time for which data was recorded from oscillopscope\r\n:param resourceManager object scope: access point of the oscilloscope\r\n:return float data type wait_time: total time taken for data sample collection\r\n\"\"\"\r\ndef calc_wait_time(scope):\r\n record_length=float(scope.query(':HORIZONTAL:RECORDLENGTH?'))\r\n dt=get_dt(scope)\r\n wait_time=record_length*dt\r\n return wait_time\r\n\r\n\"\"\"\r\n:brief sets the scale for the graph of the data\r\n:param resourceManager object scope: the access point of the oscilloscope\r\n:param int data type numchan: number of channels \r\n:param int data type short_record_length: unexplained\r\n:param int data type long_record_length: unexplained\r\n\"\"\"\r\ndef checkscale(scope, numchan, short_record_length, long_record_length):\r\n base_record_length=int(scope.query(':HORIZONTAL:RECORDLENGTH?')) \r\n if short_record_length != base_record_length:\r\n scope.write(':Horizontal:Recordlength '+str(short_record_length)) #Why?\r\n hscale = 0.000000001*short_record_length*0.1 #Why?\r\n scope.write(\":Horizontal:Scale \"+str(hscale))\r\n #Sets the \"from\" part of the waveform to be captured. In this case from data point 1\r\n scope.write('DATA:START 1')\r\n #Sets the \"to\" part of the waveform to be captured. In this case to the last recordrd data point\r\n scope.write('DATA:STOP '+str(short_record_length))\r\n scope.write('ACQUIRE:STOPAFTER RUnsTOP')\r\n for i in range(numchan):\r\n okayscale = 0\r\n while okayscale == 0:\r\n set_channel(scope, i+1)\r\n scope.write(\"WFMOutpre:ENCdg ASCii\")\r\n data = scope.query_ascii_values(\"CURVE?\")\r\n highcount = 0\r\n lowcount = 0\r\n for j in range(short_record_length):\r\n if data[j] > 32760: #Why 32760?\r\n highcount += 1\r\n elif data[j] < 32760/5:\r\n lowcount += 1\r\n if highcount/short_record_length > 0.0001:\r\n chscale = float(scope.query(\"CH\"+str(i+1)+\":SCALE?\"))\r\n \"\"\"\r\n Oscilloscope has scales of 1mV, 2mV, 5mV, 0.1V, 0.2V, 0.5V up\r\n to 10V in a pattern of 1,2,5.\r\n To increase scale when it is a unit value of 1 or 5, multiply by 2\r\n else multiply by 2.5.\r\n If scale is at 10V, then that is the max.\r\n \"\"\"\r\n if chscale in [0.001, 0.01, 0.1, 1.0, 0.005, 0.05, 0.5, 5.0]:\r\n newchscale = chscale*2\r\n if chscale in [0.002, 0.02, 0.2, 2.0]:\r\n newchscale = chscale*2.5\r\n if chscale == 10:\r\n okayscale = 1\r\n print('CH'+str(i+1)+': already at max scale')\r\n break \r\n scope.write(\"CH\"+str(i+1)+\":SCALE \"+str(newchscale))\r\n print('CH'+str(i+1)+': changing scale from '+str(chscale)+' to '+str(newchscale))\r\n if lowcount/short_record_length > 0.9999 and highcount/short_record_length < 0.0001:\r\n chscale = float(scope.query(\"CH\"+str(i+1)+\":SCALE?\"))\r\n if chscale in [0.01, 0.1, 1.0, 10.0, 0.002, 0.02, 0.2, 2.0]:\r\n newchscale = chscale/2\r\n if chscale in [ 0.005, 0.05, 0.5, 5.0]:\r\n newchscale = chscale/2.5\r\n if chscale == 0.001:\r\n okayscale = 1\r\n print('CH'+str(i+1)+': already at min scale')\r\n break \r\n scope.write(\"CH\"+str(i+1)+\":SCALE \"+str(newchscale))\r\n print('CH'+str(i+1)+': changing scale from '+str(chscale)+' to '+str(newchscale))\r\n if highcount/short_record_length < 0.0001 and lowcount/short_record_length < 0.9999:\r\n okayscale = 1\r\n scope.write(\":Horizontal:recordlength \"+str(long_record_length))\r\n hscale = 0.000000001*long_record_length*0.1\r\n scope.write(\":Horizontal:Scale \"+str(hscale))\r\n\r\n\"\"\"\r\n:brief reads data from oscilloscope and returns recorded voltage\r\n:param resourceManager object scope: the access point of the oscilloscope \r\n:param int data type numchan: number of channels \r\n:param int data type nstart: unexplained\r\n:param String data type descriptor: describes the experiment undertaken\r\n:param int data type short_record_length: unexplained\r\n:param int data type long_record_length: unexplained\r\n\"\"\"\r\ndef read_and_write_data_from_Nch(scope, numchan, nstart, short_record_length, long_record_length):\r\n checkscale(scope, numchan, short_record_length, long_record_length) \r\n wait_time = calc_wait_time(scope)\r\n record_length=int(scope.query(':HORIZONTAL:RECORDLENGTH?'))\r\n scope.write('DATA:START 1')\r\n scope.write('DATA:STOP '+str(record_length))\r\n scope.write('acquire:stopafter sequence')\r\n voltage = [['?']*(record_length)]*numchan\r\n for i in range(numchan):\r\n set_channel(scope, i+1)\r\n voltage[i]=get_data(scope) \r\n time.sleep(wait_time)\r\n set_channel(scope, 1)\r\n times=get_time(scope, record_length)\r\n scope.write('FPAnel:PRESS runstop')\r\n \r\n output = [times]\r\n for i in range(numchan):\r\n output+=[voltage[i]]\r\n scope.close()\r\n return output\r\n\r\n\"\"\"\r\n:brief plots the data received from oscilloscope\r\n:param resourceManager object scope: the access point of the oscilloscope \r\n:param int data type nstart: unexplained\r\n:param int data type i: channel from which data is read\r\n:param list data type times: the times at which sampling data was recorded\r\n:param list data type voltage: recorded voltage values\r\n:param String data type figoutfile: adress where graphs plotted are stored\r\n:param String data type descriptor: describes the experiment undertaken\r\n:return\r\n\"\"\"\r\n\"\"\"\r\n:brief\r\n:param\r\n:param\r\n:return\r\n\"\"\"\r\ndef mainforAmbrell(numchan, nstart, j, short_record_length, long_record_length):\r\n \r\n #Initialize system for data-taking\r\n rm = pyvisa.highlevel.ResourceManager()\r\n #Visa address for Tektronik Osciloscope\r\n visa_address = 'TCPIP::169.254.3.117::INSTR'\r\n\r\n scope = rm.open_resource(visa_address)\r\n #Open channels\r\n scope.write(\":SELECT:CH1 on\")\r\n scope.write(\":SELECT:CH2 on\")\r\n scope.write(\":SELECT:CH3 on\")\r\n #Encodes oscilloscope data into ASCII format\r\n scope.write(\":DATA:ENCDG ASCII\")\r\n \r\n scope.write('Data:width 2')\r\n \r\n return read_and_write_data_from_Nch(scope, numchan, nstart, short_record_length, long_record_length)\r\n\r\ndef scopeRead(shortRecordLength, longRecordLength, numCollects, numChan):\r\n short_record_length = shortRecordLength\r\n long_record_length = longRecordLength\r\n #descriptor = 'CH1-Hcoil-CH2-Mcoil-empty-test'\r\n numcollects = numCollects\r\n numchan= numChan\r\n \r\n \"\"\"\r\n note time between data collections is about 16 seconds already because of various oscilloscope data transfer wait times\r\n (which are probably overly conservative)\r\n so any nonzero pause value makes that wait time longer than 16 seconds\r\n \"\"\"\r\n pause = 0\r\n nstart = 0\r\n output = []\r\n \r\n for j in range(numcollects):\r\n output += [mainforAmbrell(numchan, nstart, j, short_record_length, long_record_length)]\r\n time.sleep(pause)\r\n \r\n return output\r\n\r\ndef opsensRead(numTimes):\r\n delay = 0.02;\r\n ntimes = numTimes;\r\n\r\n ser = serial.Serial(\"COM3\",9600, timeout=((ntimes*delay)+2))\r\n unicodestring = \"measure:start \"+str(ntimes)+\"\\n\"\r\n\r\n ser.write(unicodestring.encode(\"ascii\"))\r\n rawData0 = ser.read(ntimes*10)\r\n rawData0 = rawData0.decode(\"ascii\")\r\n data0 = rawData0.split('\\n')\r\n\r\n removeMisc = ['\\4','CH1','']\r\n errors = ['Err -170','Err -201', 'Err -140','Err -160']\r\n data1 = []\r\n\r\n for y in range(len(removeMisc)):\r\n while removeMisc[y] in data0:\r\n data0.remove(removeMisc[y])\r\n \r\n for x in range(len(data0)):\r\n time = x*float(delay)\r\n temp = \"?\"\r\n if data0[x] not in errors:\r\n temp=float(data0[x])\r\n data1.append([time,temp])\r\n ser.close()\r\n return data1","sub_path":"legacyCode/tempsAndScopeLabview.py","file_name":"tempsAndScopeLabview.py","file_ext":"py","file_size_in_byte":11451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"621909430","text":"import matplotlib.pyplot as plt\nimport cv2 as cv\nimport numpy as np\n\ndef otsu_threshold (img):\n hist = cv.calcHist([img],[0],None,[256],[0,256]) \n hist_norm = np.divide(hist.ravel(),hist.sum()) \n q = hist_norm.cumsum()\n\n bins = np.arange(256)\n\n fn_min = np.inf\n threshold = -1\n\n for i in range(1,256):\n p1,p2 = np.hsplit(hist_norm,[i])\n\n q1 , q2 = q[i] , q[255]-q[i]\n \n if q1 < 1.e-6 or q2 < 1.e-6:\n continue\n\n b1 , b2 = np.hsplit(bins,[i])\n\n m1 = np.sum(p1 * b1)/q1 \n m2 = np.sum(p2 * b2)/q2\n\n v1 = np.sum( ((b1 - m1)**2) * p1)/q1\n v2 = np.sum( ((b2 - m2)**2) * p2)/q2\n\n fn = v1*q1 + v2*q2\n\n if fn < fn_min:\n fn_min = fn\n threshold = i\n\n return threshold\n\n\n\nimg = cv.imread(\"input.jpg\",0) \n\nthreshold = otsu_threshold(img)\n\na, img_my = cv.threshold(img,threshold,255,cv.THRESH_BINARY)\ncv.imshow(\"My\",img_my)\n\nret , img_os = cv.threshold(img,0,255,cv.THRESH_BINARY + cv.THRESH_OTSU)\ncv.imshow(\"OS\",img_os)\n\n#cv.imwrite(\"output.jpg\",img_my)\n\ncv.waitKey(0)\n\n","sub_path":"LaTeX Document/Real Deal/python scripts/otsu_thresholding.py","file_name":"otsu_thresholding.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"92526166","text":"from django.views.generic.detail import DetailView\nfrom project_user.models import JoinTeam, Project, Team\n\nclass TeamDetailView(DetailView):\n model = Team\n template_name = 'project_user/detail_team.html'\n \n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['admin'] = JoinTeam.objects.get(team=self.object, status=\"Admin\")\n context['projects'] = Project.objects.filter(team=self.object)\n return context","sub_path":"project_user/TeamDetailView.py","file_name":"TeamDetailView.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"104087863","text":"from cs50 import get_int\n\n#prompt user for appropraite height\nwhile True:\n h = get_int(\"Height: \")\n if h >= 0 and h < 24:\n break\n\n#for every row\nfor i in range(h):\n #print spaces\n print(\" \" * (h-i-1), end=\"\")\n #print hashes & new line\n print(\"#\" * (i+2))\n","sub_path":"pset6/mario/mario.py","file_name":"mario.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"69455107","text":"import threading\nimport tempfile\nimport os\nimport pkg_resources\nimport sys\n\nclass Event(threading.Event):\n def __init__(self):\n self.__stopped = False\n super().__init__()\n def wait(self):\n while True:\n if super().wait(0.5) or self.__stopped:\n break\n def is_set(self):\n if self.__stopped:\n return True\n return super().is_set()\n isSet = is_set\n def stop(self):\n self.__stopped = True\n \ndef uncensor(text):\n censored = {\n 'f******': 'fucking',\n 'f***': 'fuck',\n 's***': 'shit',\n 'b****': 'bitch',\n 'a**': 'ass'\n }\n for key,val in censored.items():\n text = text.replace(key,val)\n return text\n\ndef tempfile_name(dir=None,suffix=None):\n with tempfile.NamedTemporaryFile(dir=dir,suffix=suffix) as tmpfile:\n path = tmpfile.name\n return (path, os.path.basename(path))\n\ndef str_to_number(x):\n if x == '' or x == '-':\n return 0\n try:\n return float(x)\n except ValueError:\n return None\n\ndef resource_filename(path):\n try:\n return os.path.join(sys._MEIPASS,path)\n except Exception:\n return pkg_resources.resource_filename('voice_robotifier',path)\n","sub_path":"voice_robotifier/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"542276746","text":"import cgi\nimport json\nimport re\nimport threading\nimport sys\n#raise Exception(\" path \"+','.join(sys.path))\nfrom cgi import parse_header\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom socketserver import ThreadingMixIn\n\nfrom openalpr import Alpr\n\nHTTP_CODE_BAD_REQUEST = 400\n\nalpr = Alpr(country=\"gb\", config_file=\"/etc/openalpr/openalpr.conf\", runtime_dir=\"/usr/share/openalpr/runtime_data\")\n\n\nclass HTTPRequestHandler(BaseHTTPRequestHandler):\n def do_POST(self):\n jsontxt = \"{}\"\n if None != re.search('/api/v1/identify', self.path):\n ctype, pdict = parse_header(self.headers['content-type'])\n pdict['boundary'] = bytes(pdict['boundary'], \"utf-8\")\n pdict['CONTENT-LENGTH'] = self.headers.get_content_type()\n if ctype == 'multipart/form-data':\n postvars = cgi.parse_multipart(self.rfile, pdict)\n\n image_ = postvars['image'][0]\n\n data = alpr.recognize_array(image_)\n jsontxt = json.dumps(data)\n self.send_response(200)\n self.send_header('Content-Type', 'application/json')\n self.end_headers()\n self.wfile.write(jsontxt.encode(encoding='utf_8'))\n else:\n self.send_response(403)\n self.send_header('Content-Type', 'application/json')\n self.end_headers()\n return\n\n\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n allow_reuse_address = True\n\n def shutdown(self):\n self.socket.close()\n HTTPServer.shutdown(self)\n\n\nclass SimpleHttpServer:\n def __init__(self, ip, port):\n self.server = ThreadedHTTPServer((ip, port), HTTPRequestHandler)\n self.server_thread = threading.Thread(target=self.server.serve_forever)\n\n def start(self):\n self.server_thread.daemon = True\n self.server_thread.start()\n\n def waitForThread(self):\n self.server_thread.join()\n\n def stop(self):\n self.server.shutdown()\n self.waitForThread()\n\n\nif __name__ == \"__main__\":\n server = SimpleHttpServer(\"0.0.0.0\", 8080)\n print('HTTP Server Running...........')\n server.start()\n server.waitForThread()\n","sub_path":"daemon/src/webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"592456570","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n# Theano variables are replaced by placeholders\n# but shape and name are optional\nA = tf.placeholder(tf.float32, shape=(5, 5), name='A')\nv = tf.placeholder(tf.float32)\nv2 = tf.matmul(A, v)\n\n# similar to Theano, you need to \"feed\" the variables values.\n# In TensorFlow you do the \"actual work\" in a \"session\".\n\nwith tf.Session() as session:\n # the values are fed in via the appropriately named argument \"feed_dict\"\n # v needs to be of shape=(5, 1) not just shape=(5,)\n # it's more like \"real\" matrix multiplication\n output = session.run(v2, feed_dict={A: np.random.randn(5, 5), v: np.random.randn(5, 1)})\n # what's this output that is returned by the session? let's print it\n print(output, type(output))\n # luckily, the output type is just a numpy array. back to safety!\n\n# TensorFlow variables are like Theano shared variables.\n# But Theano variables are like TensorFlow placeholders.\n\n# A tf variable can be initialized with a numpy array or a tf array\n# or more correctly, anything that can be turned into a tf tensor\nshape = (2, 2)\ntheta = tf.Variable(tf.random_normal(shape))\n# or: theta= tf.Variable(np.random.randn(2, 2))\nc = tf.Variable(0) # a scalar\n\n# you need to \"initialize\" the variables first\ninit = tf.global_variables_initializer()\n\nwith tf.Session() as session:\n out = session.run(init) # and then \"run\" the init operation\n print(out) # it's just None\n\n # eval() in tf is like get_value() in Theano\n print(theta.eval()) # the initial value of theta\n print(c.eval())\n\ntheta = tf.Variable(20.0)\ncost = theta*theta + theta + 1.0\n\n# One difference between Theano and TensorFlow is that you don't write the updates\n# yourself in TensorFlow. You choose an optimizer that implements the algorithm you want.\n# 0.3 is the learning rate. Documentation lists the params.\ntrain_op = tf.train.GradientDescentOptimizer(0.3).minimize(cost)\n\n# let's run a session again\ninit = tf.global_variables_initializer()\nwith tf.Session() as session:\n session.run(init)\n\n # Strangely, while the weight update is automated, the loop itself is not.\n # So we'll just call train_op until convergence.\n # This is useful anyway, to track the cost function.\n for epoch in range(12):\n session.run(train_op)\n print(\"epoch = %d, cost = %.3f, u = %.3f\" % (epoch, cost.eval(), theta.eval()))\n\n","sub_path":"Modern practical Deep Networks/Deep Feedforward Networks/tensorflow_basics.py","file_name":"tensorflow_basics.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"165443249","text":"import json\nimport traceback\nimport sys\nimport pandas as pd\nfrom pathlib import Path\nimport csv\nimport time\nimport requests\nimport os\nfrom typing import Callable, Any, Union, Iterable\nimport parsedatetime\nimport datetime\nimport re\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\nclass AuthenticationError(ValueError):\n pass\n\nclass WebDriver:\n # most credits go here\n # https://jpmelos.com/articles/how-use-chrome-selenium-inside-docker-container-running-python/\n def __init__(self, headless=True, download_dir='/tmp/xero_custom_reports'):\n try:\n print(\"making tmp directory for saving excels\", download_dir)\n os.makedirs(download_dir)\n except FileExistsError:\n pass\n\n self.download_dir = download_dir\n self.options = webdriver.ChromeOptions()\n\n self.options.add_argument('--disable-extensions')\n\n if headless:\n self.options.add_argument('--headless')\n self.options.add_argument('--disable-gpu')\n self.options.add_argument('--no-sandbox')\n\n # to make the button clickable\n self.options.add_argument('--window-size=1920,1080')\n user_agent = (\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5)\"\n \"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36\")\n self.options.add_argument('--user-agent={}'.format(user_agent))\n\n self.options.add_experimental_option(\n 'prefs', {\n 'download.default_directory': self.download_dir,\n 'download.prompt_for_download': False,\n 'download.directory_upgrade': True,\n 'intl.accept_languages': 'en,en_US',\n 'safebrowsing.enabled': True\n }\n )\n\n def __enter__(self):\n self.open()\n return self\n\n def __exit__(self, *args, **kwargs):\n self.close()\n\n def open(self):\n self.driver = webdriver.Chrome(chrome_options=self.options)\n self.driver.implicitly_wait(10)\n\n def close(self):\n self.driver.quit()\n\n def enable_download_in_headless_chrome(self):\n # downloading files in headless mode doesn't work!\n # file isn't downloaded and no error is thrown\n #add missing support for chrome \"send_command\" to selenium webdriver\n # https://bugs.chromium.org/p/chromium/issues/detail?id=696481#c39\n self.driver.command_executor._commands[\"send_command\"] = (\"POST\", '/session/{}/chromium/send_command'.format(self.driver.session_id))\n params = {\n 'cmd': 'Page.setDownloadBehavior',\n 'params': {'behavior': 'allow', 'downloadPath': self.download_dir}\n }\n self.driver.execute(\"send_command\", params)\n\n def login(self, username, password, url=\"https://login.xero.com\"):\n self.driver.get(url)\n\n email_field = self.driver.find_element_by_id(\"email\")\n email_field.clear()\n email_field.send_keys(username)\n\n pass_field = self.driver.find_element_by_id(\"password\")\n pass_field.clear()\n pass_field.send_keys(password)\n pass_field.send_keys(Keys.RETURN)\n time.sleep(2)\n\n title = self.driver.title\n if \"Xero | Dashboard\" not in title:\n raise AuthenticationError(\n (\"Probably didn't authenticate sucesfully. \"\n \"The title says '{}'. Check your credentials and account_id!\").format(title))\n\n def list_reports(self, account_id):\n self.driver.get(\n \"https://reporting.xero.com/{}/v2/ReportList/CustomReports?\".format(\n account_id))\n # it's a json returned in html\n js = json.loads(self.driver.find_element_by_tag_name('pre').text)\n return {r[\"id\"]: r[\"name\"] for r in js['reports']}\n # print report ids and names here?\n\n @staticmethod\n def account_id_from_url(url):\n try:\n return re.search(r\"(?!=.com/)!\\w+\", url).group()\n except AttributeError:\n raise ValueError(\"Couldn't find account_id in {}\".format(url))\n\n def download_report(\n self,\n report_id,\n account_id,\n from_date=None,\n to_date=None,\n delay_seconds=15):\n \"\"\"\n \"\"\"\n \n # the first string after xero.com/ is the account id\n report_download_template = (\n \"https://reporting.xero.com/\"\n \"{account_id}/v1/Run/\"\n \"{report_id}?isCustom=True\").format(account_id=account_id, report_id=report_id)\n\n print(\"getting report from \", report_download_template,\n \"from_date\", from_date,\n \"to_date\", to_date)\n self.driver.get(report_download_template)\n self.enable_download_in_headless_chrome()\n print(\"Waiting for page to load\")\n time.sleep(3)\n self.update_date_range(from_date, to_date, delay_seconds)\n\n # click export btn so that excel btn is rendered\n export_btn = self._locate_export_button()\n export_btn.click()\n time.sleep(1)\n\n excel_btn = self._locate_export_to_excel_button()\n excel_btn.click()\n # the sleeps are experimental and it might happen that the file won't be downloaded\n time.sleep(3)\n while True:\n report_path = glob_excels(self.download_dir)\n if not report_path:\n print(\"Waiting for the report to be downloaded\")\n time.sleep(3)\n else:\n print(\"Report downloaded to \", report_path)\n time.sleep(3)\n break\n \n \n def direct_url(self,\n account_id,\n url = None):\n \n if url == None:\n raise ValueError(\"No URL provided.\")\n else:\n explicit_company_url = (\n \"https://reporting.xero.com/\"\n \"{account_id}/summary\").format(account_id=account_id)\n print(\"Localise company \", explicit_company_url)\n self.driver.get(explicit_company_url)\n print(\"Waiting for page to load\")\n time.sleep(3)\n print(\"Getting report from \", url,\n \" for company: \", account_id)\n self.driver.get(url)\n print(\"Waiting for page to load\")\n time.sleep(3)\n self.enable_download_in_headless_chrome()\n self.driver.get(url.replace(\"Report.aspx?\", \"ExcelReport.aspx?\", 1))\n time.sleep(3)\n count = 0 #for debug\n while True:\n report_path = glob_excels(self.download_dir)\n if count > 10: #for debug\n raise ValueError(\"Looping too many times\") #for debug\n elif not report_path:\n print(\"Waiting for the report to be downloaded\")\n time.sleep(3)\n count += 1\n else:\n print(\"Report downloaded to \", report_path)\n time.sleep(3)\n break\n\n def _locate_export_button(self):\n print(\"Looking for export button\")\n for btn in self.driver.find_elements_by_tag_name('button'):\n if btn.get_attribute('data-automationid') == 'report-toolbar-export-button':\n print(\"Found\")\n return btn\n raise KeyError(\"Couldn't find export menu. \"\n \"The underlying html/css probably changed and the code needs to be adjusted\")\n def _locate_export_to_excel_button(self):\n print(\"Looking for excel button\")\n for btn in self.driver.find_elements_by_tag_name('button'):\n if btn.get_attribute('data-automationid') == 'report-toolbar-export-excel-menuitem--body':\n print(\"Found\")\n return btn\n\n raise KeyError(\"Couldn't find export button. \"\n \"The underlying html/css probably changed and the code needs to be adjusted\")\n\n def update_date_range(self,\n from_time: Union[str, None],\n until_time: Union[str, None],\n delay_seconds: int=15):\n # update From field\n if from_time:\n print(\"Updating from time\")\n from_input_field = self.driver.find_element_by_id(\"dateFieldFrom-inputEl\")\n print(\"Found input field\", from_input_field)\n time.sleep(2.5)\n from_input_field.send_keys(\n Keys.BACKSPACE * len(from_input_field.get_attribute(\"value\")))\n time.sleep(2.5)\n\n from_input_field.send_keys(from_time)\n # press the update button\n print(\"Field updated\")\n\n if until_time:\n # update To field\n print(\"Updating until time\")\n until_input_field = self.driver.find_element_by_id(\"dateFieldTo-inputEl\")\n time.sleep(2.5)\n # clear the input field\n until_input_field.send_keys(\n Keys.BACKSPACE * len(until_input_field.get_attribute(\"value\")))\n\n time.sleep(2.5)\n # input the datetime\n until_input_field.send_keys(until_time)\n print(\"field updated\")\n time.sleep(2.5)\n # take the first div that satisfies the condition\n print(\"Looking for update button\")\n update_btn = next(filter(\n lambda div: div.get_attribute(\"data-automationid\") == \"date-toolbar-update-button\",\n self.driver.find_elements_by_tag_name(\"div\")))\n print(\"Found\", update_btn)\n print(\"Clicking\")\n update_btn.click()\n # wait 15 seconds to the report is, hopefully, updated we can't really\n # use explicit waits baked into selenium because the buttons do not\n # have unique ids\n print(\"Waiting for {} seconds after updating the date range\".format(delay_seconds))\n time.sleep(delay_seconds)\n\ndef glob_excels(excel_dir):\n return list(Path(excel_dir).glob(\"*.xls*\"))\n\ndef clean_newlines(value):\n if isinstance(value, str):\n return value.replace(u\"\\n\", \" \")\n else:\n return value\n\n\ndef convert_excel(excel_dir, path_out):\n excels = glob_excels(excel_dir)\n if len(excels) != 1:\n raise ValueError(\n \"Expected only one excel to \"\n \"be in tmp folder!, there are {}\".format(excels))\n for excel in excels:\n print(\"converting {} into {}\".format(excel, path_out))\n # saving to csc doesn't escape newlines correctly\n # soo we clean them manually\n report = (pd.read_excel(excel)\n .applymap(clean_newlines)\n )\n report.index.name = 'row_number'\n report.to_csv(path_out)\n\n # clean up!\n excel.unlink()\n\n\ndef main(params, datadir='/data/'):\n download_dir = '/tmp/xero_custom_reports_foo/'\n outdir = Path(datadir) / 'out/tables/'\n \n \n wd = WebDriver(headless=True, download_dir=download_dir)\n account_id = params['account_id']\n action = params['action']\n if action == 'list_reports':\n print(\"Listing available reports\")\n with wd:\n wd.login(params['username'], params['#password'])\n reports = wd.list_reports(account_id)\n print(json.dumps(reports, indent=2))\n elif action == 'download_reports':\n print(\"downloading reports\")\n with wd:\n wd.login(params['username'], params['#password'])\n for report in params['reports']:\n print(\"Downloading report\", report)\n from_date = robotize_date(report.get(\"from_date\", None))\n to_date = robotize_date(report.get(\"to_date\", None))\n delay_seconds = report.get(\"delay_seconds\", 15)\n try:\n wd.download_report(report_id = report['report_id'],\n account_id=account_id,\n from_date=from_date,\n to_date=to_date,\n delay_seconds=delay_seconds)\n except Exception:\n sc_path = '/tmp/xero_custom_reports_latest_exception.png'\n print(\"Saved screenshot to\", sc_path)\n wd.driver.save_screenshot(sc_path)\n raise\n outname = str(Path(report['filename']).stem) + '.csv'\n convert_excel(download_dir, outdir / outname)\n elif action == 'direct_url':\n print(\"direct_url\")\n with wd:\n wd.login(params['username'], params['#password'])\n try:\n wd.direct_url(account_id=account_id,\n url = params['direct_url'])\n except Exception:\n sc_path = '/tmp/xero_custom_reports_latest_exception.png'\n print(\"Saved screenshot to\", sc_path)\n wd.driver.save_screenshot(sc_path)\n raise\n outname = 'report.csv'\n convert_excel(download_dir, outdir / outname)\n else:\n raise ValueError(\"unknown action, '{}'\".format(action))\n\n\ndef robotize_date(dt_str):\n if dt_str is None:\n return\n cal = parsedatetime.Calendar()\n t_struct, status = cal.parse(dt_str)\n if status != 1:\n raise ValueError(\"Couldn't convert '{}' to a datetime\".format(dt_str))\n converted = datetime.datetime(*t_struct[:6]).strftime(\"%-d %b %Y\")\n print(\"converted\", dt_str, \"to\", converted)\n return converted\n\nif __name__ == \"__main__\":\n with open(\"/data/config.json\") as f:\n cfg = json.load(f)\n try:\n main(cfg[\"parameters\"])\n except Exception as err:\n print(err)\n traceback.print_exc()\n sys.exit(1)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"510389969","text":"class Kunde:\n\n def __init__(self, tlf, innholdsstoffer):\n self._tlf = tlf\n self._innholdsstoffer = innholdsstoffer\n\n def velgRetter(self, meny):\n redusertMeny = meny.hentRedusertMeny(self._innholdsstoffer)\n bestilling = []\n # Mangler hentemetoder, skriver ut hele kategorien\n for kat in redusertMeny.values():\n print(kat)\n print(redusertMeny[kat])\n rett = input(\"Oppgi rett\")\n if rett != \"\":\n bestilling.append(rett)\n return bestilling\n","sub_path":"Uke 13/eksamen_h18/Kunde.py","file_name":"Kunde.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"487377759","text":"from django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom djlime.utils import get_file_path\nfrom django.db import models\nfrom imagekit.models.fields import ImageSpecField\nfrom imagekit.processors.resize import ResizeToFill\n\n\nclass Portfolio(models.Model):\n\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n show = models.BooleanField(_(\"show\"), default=True)\n title = models.CharField(max_length=200)\n description = models.TextField(_(\"description\"), blank=True)\n author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)\n main_image = models.ImageField(\n _(\"main image\"),\n upload_to=get_file_path,\n null=True,\n blank=True,\n )\n large = ImageSpecField([ResizeToFill(930, 310)], source=\"main_image\")\n thumbnail = ImageSpecField([ResizeToFill(360, 320)], source=\"main_image\")\n\n @property\n def upload_dir(self):\n return 'portfolio/'\n\n def image_url(self):\n return self.thumbnail.url\n\n\n class Meta:\n ordering = (\"created_at\",)\n verbose_name = _(\"Portfolio\")\n\n def __str__(self):\n return self.author.username\n\n\nclass Image(models.Model):\n\n created_at = models.DateTimeField(auto_now_add=True)\n enabled = models.BooleanField(_(\"enabled\"), default=True)\n title = models.CharField(_(\"name\"), max_length=100)\n portfolio = models.ForeignKey(\n Portfolio, null=True, on_delete=models.SET_NULL, verbose_name=_(\"portfolio\")\n )\n image = models.ImageField(\n _(\"image\"),\n upload_to=get_file_path,\n help_text=_(\"recommended size 1000x665\"),\n null=True,\n blank=True,\n )\n\n large = ImageSpecField([ResizeToFill(930, 310)], source=\"image\")\n thumbnail = ImageSpecField([ResizeToFill(360, 320)], source=\"image\")\n\n @property\n def upload_dir(self):\n return 'images/'\n\n def __str__(self):\n return self.title\n","sub_path":"projects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"250276171","text":"from .db_cmd import get_most_votes, get_username_from_id, check_player_ban\nfrom telegram.ext.dispatcher import run_async\nfrom telegram.utils.helpers import mention_html\nfrom . import BotStats, check_channel_join\n\n\n@check_channel_join\n@check_player_ban\n@run_async\ndef most_votes(update, context):\n reply = update.message.reply_to_message\n args = context.args\n chat_id = update.message.chat.id\n texts = update.chat_lang.Mostvotes\n days = 7\n for arg in args:\n if arg.isdigit() and 15 > len(arg) > 5:\n player = int(arg)\n try:\n mention = mention_html(player, context.bot.get_chat(player).first_name)\n except:\n mention = get_username_from_id(player)\n break\n elif arg.isdigit():\n arg = int(arg)\n if 1 <= arg <= 31:\n days = int(arg)\n elif '@' == arg[0] and 5 < len(args) < 32:\n try:\n player_info = context.bot.get_chat(args[0])\n player = player_info.id\n mention = mention_html(player, player_info.first_name)\n break\n except:\n player = update.message.from_user.id\n mention = update.message.from_user.mention_html()\n break\n else:\n if reply:\n player = reply.from_user.id\n mention = reply.from_user.mention_html()\n else:\n player = update.message.from_user.id\n mention = update.message.from_user.mention_html()\n if chat_id == -1001461432821:\n chat_id = player\n votes, voted = get_most_votes(player, chat_id if chat_id != player else None, days=days)\n text = ''\n where = texts.in_the + f\"{update.message.chat.title}\" if chat_id != player else ''\n if votes:\n text += texts.voted\n for _, voted_player, count in votes:\n try:\n text += '‎ {}: {}\\n'.format(\n mention_html(voted_player, rf\"{context.bot.get_chat(voted_player).first_name}\"), count)\n except:\n text += '‎ {}: {}\\n'.format(get_username_from_id(voted_player), count)\n text += '\\n'\n else:\n text += texts.no_vote\n if voted:\n text += texts.votes\n for voter_player, _, count in voted:\n try:\n text += '‎ {}: {}\\n'.format(\n mention_html(voter_player, rf\"{context.bot.get_chat(voter_player).first_name}\"), count)\n except:\n text += '‎ {}: {}\\n'.format(get_username_from_id(voter_player), count)\n text += '\\n'\n else:\n text += texts.no_votes\n update.message.reply_text(text.format(mention=mention, where=where, days=days), parse_mode='html')\n BotStats.most_votes += 1\n","sub_path":"src/rolesaver/most_votes.py","file_name":"most_votes.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"244127547","text":"\n# helper functions\n\ndef create_permission(codename,name,content_type_model,user):\n \"\"\"\n Creates and assigns a User permission\n\n Args:\n codename: codename arg in Permission object\n name: name arg in Permission object\n content_type_model: model to get ContentType\n user: User object to grant Permission\n \n Returns:\n None\n \"\"\" \n from django.contrib.auth.models import Permission\n from django.contrib.contenttypes.models import ContentType\n\n content_type = ContentType.objects.get_for_model(content_type_model)\n\n permission = Permission.objects.create(\n codename = codename,\n name = name,\n content_type = content_type,\n )\n\n user.user_permissions.add(permission)\n \n return user\n","sub_path":"wei_showroom/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"206125874","text":"# Under MIT License, see LICENSE.txt\nimport logging\nimport os\nimport cProfile\n\nfrom multiprocessing import Process\nfrom queue import Full\nfrom time import time, sleep\n\nfrom Util.timing import create_fps_timer\n\nfrom ai.executors.debug_executor import DebugExecutor\nfrom ai.executors.play_executor import PlayExecutor\nfrom ai.states.game_state import GameState\nfrom ai.states.play_state import PlayState\n\nfrom config.config import Config\nconfig = Config()\n\nclass Coach(Process):\n\n MAX_EXCESS_TIME = 0.05\n\n def __init__(self, framework):\n\n super().__init__(name=__name__)\n\n self.framework = framework\n self.logger = logging.getLogger(self.__class__.__name__)\n\n # Managers for shared memory between process\n self.engine_game_state = self.framework.game_state\n self.field = self.framework.field\n\n # Queues for process communication\n self.ai_queue = self.framework.ai_queue\n self.referee_queue = self.framework.referee_queue\n self.ui_send_queue = self.framework.ui_send_queue\n self.ui_recv_queue = self.framework.ui_recv_queue\n\n # States\n self.game_state = GameState()\n self.play_state = PlayState()\n\n # Executors\n self.play_executor = PlayExecutor(self.play_state,\n self.ui_send_queue,\n self.referee_queue)\n self.debug_executor = DebugExecutor(self.play_state,\n self.play_executor,\n self.ui_send_queue,\n self.ui_recv_queue)\n\n # fps and limitation\n self.fps = config['GAME']['fps']\n self.frame_count = 0\n self.last_frame_count = 0\n self.dt = 0.0\n self.last_time = 0.0\n\n def callback(excess_time):\n if excess_time > Coach.MAX_EXCESS_TIME:\n self.logger.debug('Overloaded (%.1f ms behind schedule)', 1000*excess_time)\n\n self.fps_sleep = create_fps_timer(self.fps, on_miss_callback=callback)\n\n # profiling\n self.profiler = None\n\n def wait_for_geometry(self):\n self.logger.debug('Waiting for field\\'s geometry from the Engine.')\n start = time()\n while not self.field:\n self.fps_sleep()\n self.game_state.const = self.field\n self.logger.debug('Geometry received from the Engine in {:0.2f} seconds.'.format(time() - start))\n\n def wait_for_referee(self):\n if Config()['GAME']['competition_mode']:\n self.logger.debug('Waiting for commands from the referee')\n while self.referee_queue.qsize() == 0:\n self.logger.debug('Referee is not active or port is set incorrectly, current port is {})'.format(\n Config()['COMMUNICATION']['referee_port']))\n sleep(1)\n self.logger.debug('Referee command detected')\n\n def run(self):\n\n try:\n\n self.logger.debug('Running with process ID {} at {} fps.'.format(os.getpid(), self.fps))\n\n # profiling\n self.profiler = cProfile.Profile()\n if self.framework.profiling:\n self.profiler.enable()\n\n self.wait_for_geometry()\n self.wait_for_referee()\n while True:\n self.frame_count += 1\n self.update_time()\n self.main_loop()\n self.fps_sleep()\n self.framework.coach_watchdog.value = time()\n\n except KeyboardInterrupt:\n self.logger.debug('Interrupted.')\n except BrokenPipeError:\n self.logger.exception('A connection was broken.')\n except:\n self.logger.exception('An error occurred.')\n finally:\n self.stop()\n\n def main_loop(self):\n self.game_state.update(self.engine_game_state)\n self.debug_executor.exec()\n engine_commands = self.play_executor.exec()\n try:\n self.ai_queue.put_nowait(engine_commands)\n except Full:\n self.logger.critical('The Engine queue is full.')\n\n def update_time(self):\n current_time = time()\n self.dt = current_time - self.last_time\n self.last_time = current_time\n\n def dump_profiling_stats(self):\n if self.framework.profiling:\n self.profiler.dump_stats(config['GAME']['profiling_filename'])\n self.logger.debug('Profiling data written to {}.'.format(config['GAME']['profiling_filename']))\n\n def is_alive(self):\n if config['GAME']['competition_mode']:\n if time() - self.framework.coach_watchdog.value > self.framework.MAX_HANGING_TIME:\n self.logger.critical('Process is hanging. Shutting down.')\n return False\n return super().is_alive()\n\n def stop(self):\n self.dump_profiling_stats()\n self.logger.info('Stopped.')\n","sub_path":"ai/coach.py","file_name":"coach.py","file_ext":"py","file_size_in_byte":4948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"601688739","text":"\"\"\"\r\n\r\nThis is tutorial of tensorflow DIY example of ANN\r\n\r\n\tX = samples x features , Real \r\n\ty in O [Category] \r\n\t\r\n\tbuild artificial neural network ANN : f(weight,data)\r\n\r\n\r\n\"\"\"\r\nimport tensorflow as tf\r\nimport random \r\n\r\n\r\n\"\"\"\r\ngenerate _list of matrix or tensors\r\n\r\n\"\"\"\r\ndef RandomGenerator(nrols,ncols=0,_boolPrint=False):\r\n\t_list = []\r\n\tif ncols > 0:\r\n\t\tfor i in range(nrols):\r\n\t\t\t_list2 = []\r\n\t\t\tfor j in range(ncols):\r\n\t\t\t\t_list2.append(random.uniform(1,10))\r\n\t\t\t_list.append(_list2)\t\t\r\n\telse:\r\n\t\tfor i in range(nrols):\r\n\t\t\t_list.append(float(random.randint(1,5)))\r\n\t\r\n\tif _boolPrint == True:\r\n\t\tfor i in range(len(_list)):\r\n\t\t\tprint(_list[i])\r\n\r\n\r\n\treturn _list\r\n\r\n\r\ndef Batch_Data(_list,batchsize=1):\r\n\tm = int(float(len(_list))/float(batchsize))\r\n\t_listOutput = []\r\n\tfor k in range(m-1):\r\n\t\t_listOutput.append(_list[k*batchsize:(k+1)*batchsize])\r\n\t_listOutput.append(_list[(m-1)*batchsize:])\r\n\t\r\n\t# reshape \r\n\tfor b in range(len(_listOutput)):\r\n\t\tfor i in range(len(_listOutput[b])):\r\n\t\t\tfor j in range(len(_listOutput[b][i])):\r\n\t\t\t\t_listOutput[b][i][j] = [_listOutput[b][i][j]]\r\n\t\t\t\r\n\t\t\t\r\n\treturn _listOutput\r\n\r\n#print(Batch_Data([[1,2],[3,4],[5,6],[7,8]],2))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# [samples x 1] ----- > [samples x kinds]\r\ndef OneHotEncoding(_listInput,_boolPrint=False):\r\n\tcount = 0 \r\n\t_dict = {}\r\n\t# calculate different kinds !!\r\n\tfor i in range(len(_listInput)):\r\n\t\tif _listInput[i] not in _dict:\r\n\t\t\t_dict[_listInput[i]] = count\r\n\t\t\tcount+=1\r\n\t_listOutput = []\r\n\t# put vectors !!\r\n\tfor i in range(len(_listInput)):\r\n\t\t_listTemp = [0.0] * len(_dict)\r\n\t\t_listTemp[_dict[_listInput[i]]] = 1.0\r\n\t\t_listOutput.append(_listTemp)\r\n\t# print\r\n\tif _boolPrint == True:\r\n\t\tfor key in _dict:\r\n\t\t\tprint(\"Label \" + str(key) + \" Pos = \" + str(_dict[key]))\r\n\t\tprint(\"=======================================\")\r\n\t\tfor i in range(len(_listInput)):\r\n\t\t\tprint(\"[\"+str(i+1)+\"] \",end=\" Label = \")\r\n\t\t\tprint(_listInput[i],end=\" , OneHot = \")\r\n\t\t\tprint(_listOutput[i])\r\n\t\tprint(\"=======================================\")\r\n\t\t\r\n\r\n\treturn (_listOutput,_dict) \r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\"\"\"\r\n X = samples x features , _list \r\n y = samples x One-Hot-Encoding \r\n\"\"\"\r\n\r\n# All_Reals to One_Hot \r\nclass ANNClassifier:\r\n\tdef __init__(self,X,y):\r\n\t\tself.nsamples = len(X)\r\n\t\tself.sizeI = len(X[0])\r\n\t\tY,_dictY = OneHotEncoding(y,True)\r\n\t\tself.sizeO = len(_dictY)\r\n\t\tself.input_data = X\r\n\t\tself.true_labels = Y\r\n\t\r\n\tdef build_batch_model(self,batchsize=1,sizeH=5):\r\n\t\tself.sizeH = sizeH\r\n\t\tself.batchsize = batchsize\r\n\t\tself.niter = int(self.nsamples/self.batchsize) \r\n\t\t# build_Input/Output_Layers \r\n\t\tself.I = tf.placeholder(shape=[self.batchsize,self.sizeI,1],dtype=tf.float32)\r\n\t\tself.O = tf.placeholder(shape=[self.batchsize,self.sizeO,1],dtype=tf.float32)\r\n\t\t# init Hidden Layers\r\n\t\tself.H = []\r\n\t\tself.Z = []\r\n\t\tself.Ot = []\r\n\t\tself.Zt = []\r\n\t\t# initialize weights \r\n\t\tself.W_hi = tf.Variable(tf.random_normal(shape=[self.sizeH,self.sizeI],mean=0.0,stddev=0.01))\r\n\t\t#self.B_h = tf.Variable(tf.random_normal(shape=[self.sizeH,1],mean=0.0,stddev=0.01))\r\n\t\tself.W_zh = tf.Variable(tf.random_normal(shape=[self.sizeO,self.sizeH],stddev=0.01))\r\n\t\t# build network + objectives \r\n\t\tself.loss_sample = []\r\n\t\tfor b in range(self.batchsize):\r\n\t\t\tself.H.append(tf.sigmoid(tf.matmul(self.W_hi,self.I[b])))\r\n\t\t\tself.Z.append(tf.sigmoid(tf.matmul(self.W_zh,self.H[b])))\r\n\t\t\t# transpose \r\n\t\t\tself.Zt.append(tf.transpose(self.Z[b]))\r\n\t\t\tself.Ot.append(tf.transpose(self.O[b]))\r\n\t\t\t# need row vector \r\n\t\t\tself.loss_sample.append(tf.nn.softmax_cross_entropy_with_logits(logits=self.Zt[b],labels=self.Ot[b]))\r\n\t\t# sum over_all_batch\r\n\t\tself.loss_batch = tf.reduce_sum(self.loss_sample)\r\n\t\r\n\tdef training(self,nepochs=50,learning_rate=0.001,modelname='testModel'):\r\n\t\tprint(\"===========================================\")\r\n\t\tprint(\"modelname = \" + str(modelname))\r\n\t\tprint(\"num_samples = \" + str(self.nsamples))\r\n\t\tprint(\"num_features = \" + str(self.sizeI))\r\n\t\tprint(\"num_category = \" + str(self.sizeO))\r\n\t\tprint(\"num_batchsize = \"+ str(self.batchsize))\r\n\t\tprint(\"num_iterations = \" + str(self.niter))\r\n\t\tprint(\"num_epochs = \" + str(nepochs))\r\n\t\tprint()\r\n\t\tprint(\"===========================================\")\r\n\t\t_str = input(\"Press To Continue !!\")\r\n\t\t# split data into batch_list\r\n\t\tself.learning_rate = learning_rate\r\n\t\tself.batch_listI = Batch_Data(self.input_data,self.batchsize)\r\n\t\tself.batch_listO = Batch_Data(self.true_labels,self.batchsize)\r\n\r\n\t\t# create optimizer \r\n\t\tself.train_epoch = tf.train.GradientDescentOptimizer(self.learning_rate).minimize(self.loss_batch)\r\n\t\tself.saver = tf.train.Saver()\r\n\t\twith tf.Session() as sess:\r\n\t\t\tsess.run(tf.global_variables_initializer())\r\n\t\t\t# Loops : epoch - iteration \r\n\t\t\tfor e in range(nepochs):\r\n\t\t\t\tloss_val = 0.0\r\n\t\t\t\tfor i in range(self.niter):\r\n\t\t\t\t\t_,loss_batch_val,loss_sample_vec = sess.run([self.train_epoch,self.loss_batch,self.loss_sample],feed_dict={self.I:self.batch_listI[i],self.O:self.batch_listO[i]})\r\n\t\t\t\t\t\r\n\t\t\t\t\tloss_val += loss_batch_val\r\n\t\t\t\t\t\"\"\"\r\n\t\t\t\t\t#___________ try to print loss_sample ____________#\r\n\t\t\t\t\tfor b in range(self.batchsize):\r\n\t\t\t\t\t\tprint(loss_sample_vec[b],end=\",\")\r\n\t\t\t\t\tprint()\r\n\t\t\t\t\t\"\"\"\r\n\r\n\t\t\t\tloss_val /= float(self.nsamples)\r\n\t\t\t\t\r\n\r\n\t\t\t\t# \r\n\t\t\t\tif (e+1) % 10 == 0:\r\n\t\t\t\t\tprint(\"=================================================\") \r\n\t\t\t\t\tprint(\"epoch [\"+ str(e+1) +\"] loss = \" + str(loss_val))\t\r\n\t\t\t\t\tself.saver.save(sess,\"./\"+modelname)\t\r\n\r\n\t\r\n\r\n\r\n#___________________________________________________________________________________#\r\ndef main():\t\r\n\r\n\tX = RandomGenerator(20,7,True)\r\n\ty = RandomGenerator(20,0,True)\t\r\n\tmodel = ANNClassifier(X,y)\r\n\tmodel.build_batch_model(10)\r\n\tmodel.training(10000)\r\n\r\nmain()\r\n","sub_path":"tutorial_tensorflow.py","file_name":"tutorial_tensorflow.py","file_ext":"py","file_size_in_byte":5668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"472999104","text":"clean_car_red = True\nclean_car_blue = True\nclean_car_green = True\nnum_of_car = 0\nbusy = False\n\nprint(\"Welcome to the car wash\")\n\nredCheck = input(\"Is the Red car Dirty? (Yes or No)\")\nif redCheck == \"Yes\":\n\tclean_car_red = False\n\nblueCheck = input(\"Is the Blue car Dirty? (Yes or No)\")\nif blueCheck == \"Yes\":\n\tclean_car_blue = False\n\ngreenCheck = input(\"Is the Green car Dirty? (Yes or No)\")\nif greenCheck == \"Yes\":\n\tclean_car_green = False\t\n\n\nif clean_car_red == False:\n\tprint(\"Red car really needs a cleaning\")\n\tnum_of_car +=1\n\nif clean_car_blue == False:\n\tprint(\"Blue car really needs a cleaning\")\n\tnum_of_car +=1\n\n\nif clean_car_green == False:\n\tprint(\"Green car really needs a cleaning\")\n\tnum_of_car +=1\n\tprint(num_of_car)\n\nif num_of_car == 3:\n\tbusy = True\n\nif busy == True:\n\tprint(\"The car wash was was packed today\")\n\n\n\n","sub_path":"Task 8/boolean example programs/boolean_example.py","file_name":"boolean_example.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"237972847","text":"# 双指针\nclass Solution:\n def removeElement(self, nums: list, val: int) -> int:\n if len(nums) == 0:\n return 0\n j = 0\n for i in range(0, len(nums)):\n if nums[i] != val:\n nums[j] = nums[i]\n j += 1\n return j\n\n\ns = Solution()\nprint(s.removeElement([0, 1, 2, 2, 3, 0, 4, 2], 2))\n","sub_path":"leetcode/shuzu/双指针/02_移除元素.py","file_name":"02_移除元素.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"645314960","text":"from twisted.web.server import NOT_DONE_YET\nfrom txoauth2 import GrantTypes\n\nfrom tests import MockRequest\nfrom tests.unit.testOAuth2Resource import AbstractSharedGrantTest\n\n\nclass TestAuthorizationCodeGrant(AbstractSharedGrantTest):\n \"\"\"\n Test the authorization resource part of the Authorization Code Grant flow.\n See https://tools.ietf.org/html/rfc6749#section-4.1\n \"\"\"\n _RESPONSE_TYPE = 'code'\n\n def assertValidCodeResponse(self, request, result, data, msg, expectedCodeDataLifetime=120,\n expectedAdditionalData=None, expectedScope=None):\n \"\"\"\n Validate the parameters of the uri that the authorization endpoint redirected to.\n\n :param request: The request.\n :param result: The result of the grantAccess call.\n :param data: The data that was stored in the persistent storage.\n :param msg: The assertion message.\n :param expectedCodeDataLifetime: The expected life time of the\n code stored in the persistent storage.\n :param expectedAdditionalData: Expected additional data stored alongside the code.\n :param expectedScope: The expected scope of the code.\n \"\"\"\n if msg.endswith('.'):\n msg = msg[:-1]\n self.assertEquals(result, NOT_DONE_YET, msg=msg + ': Expected the authorization resource '\n 'to redirect the resource owner.')\n self.assertTrue(request.finished,\n msg=msg + ': Expected the authorization resource to close the request.')\n redirectUrl = self.assertRedirectsTo(request, data['redirect_uri'], msg)\n redirectParameter = self.getParameterFromRedirectUrl(redirectUrl, False)\n self.assertIn(\n 'code', redirectParameter,\n msg=msg + ': Expected the authorization resource to send a code to the redirect uri.')\n if data['state'] is None:\n self.assertNotIn(\n 'state', redirectParameter,\n msg=msg + ': Expected the authorization resource not to send a state '\n 'to the redirect uri if it did not receive one.')\n else:\n self.assertIn('state', redirectParameter,\n msg=msg + ': Expected the authorization resource to '\n 'send a state to the redirect uri.')\n self.assertEquals(\n redirectParameter['state'], data['state'] if isinstance(data['state'], str)\n else data['state'].decode('utf-8', errors='replace'),\n msg=msg + ': Expected the authorization resource to send '\n 'the exact same state back to the redirect uri.')\n code = 'code' + redirectParameter['code']\n try:\n self.assertApproximates(\n expectedCodeDataLifetime, self._PERSISTENT_STORAGE.getExpireTime(code), 1,\n msg=msg + ': The stored code did not have the expected lifetime.')\n codeData = self._PERSISTENT_STORAGE.pop(code)\n except KeyError:\n self.fail(msg + ': Expected the authorization resource to store a data '\n 'entry with the given code in the persistent storage.')\n if expectedScope is None:\n expectedScope = data['scope']\n self.assertIn('scope', codeData, msg=msg + ': Expected the authorization resource to '\n 'store the scope in the code date.')\n self.assertListEqual(expectedScope, codeData['scope'],\n msg=msg + ': Expected the authorization resource to store the '\n 'expected scope in the code date.')\n self.assertIn('additional_data', codeData,\n msg=msg + ': Expected the authorization resource to store the '\n 'additional data in the code date.')\n self.assertEquals(expectedAdditionalData, codeData['additional_data'],\n msg=msg + ': Expected the authorization resource to store the '\n 'expected additional data in the code date.')\n for key in ['client_id', 'redirect_uri']:\n self.assertIn(\n key, codeData, msg=msg + ': Expected the authorization resource to store the '\n '{name} in the code date.'.format(name=key))\n self.assertEquals(data[key], codeData[key],\n msg=msg + ': Expected the authorization resource to store the '\n 'expected {name} in the code date.'.format(name=key))\n\n def testGrantAccessCodeLifetime(self):\n \"\"\" Ensure that the code lifetime is controlled by the codeDataLifetime parameter. \"\"\"\n dataKey = 'authorizationCodeGrantDataKeyLifetime'\n redirectUri = self._VALID_CLIENT.redirectUris[0]\n lifeTime = 60\n request = MockRequest('GET', 'some/path')\n data = {\n 'response_type': GrantTypes.AuthorizationCode.value,\n 'redirect_uri': redirectUri,\n 'client_id': self._VALID_CLIENT.id,\n 'scope': ['All'],\n 'state': b'state\\xFF\\xFF'\n }\n self._PERSISTENT_STORAGE.put(dataKey, data)\n result = self._AUTH_RESOURCE.grantAccess(request, dataKey, codeLifeTime=lifeTime)\n self.assertValidCodeResponse(\n request, result, data, expectedCodeDataLifetime=lifeTime,\n msg='Expected the auth resource to correctly handle a valid accepted code grant '\n 'and store the code data with the given lifetime.')\n\n def testGrantAccessAdditionalData(self):\n \"\"\" Ensure that additional data given to grantAccess is stored with the code. \"\"\"\n dataKey = 'authorizationCodeGrantDataKeyAdditionalData'\n redirectUri = self._VALID_CLIENT.redirectUris[0]\n request = MockRequest('GET', 'some/path')\n additionalData = 'someData'\n data = {\n 'response_type': GrantTypes.AuthorizationCode.value,\n 'redirect_uri': redirectUri,\n 'client_id': self._VALID_CLIENT.id,\n 'scope': ['All'],\n 'state': b'state\\xFF\\xFF'\n }\n self._PERSISTENT_STORAGE.put(dataKey, data)\n result = self._AUTH_RESOURCE.grantAccess(request, dataKey, additionalData=additionalData)\n self.assertValidCodeResponse(\n request, result, data, expectedAdditionalData=additionalData,\n msg='Expected the auth resource to correctly handle a valid accepted code grant '\n 'and store the code data with the given additional data.')\n","sub_path":"tests/unit/testOAuth2AuthorizationCodeGrant.py","file_name":"testOAuth2AuthorizationCodeGrant.py","file_ext":"py","file_size_in_byte":6755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"231839063","text":"\"\"\"\n 学生管理系统\n 项目计划:\n 1.完成数据模型类StudentModel\n 2.创建逻辑控制类StudentManagerController\n 3.完成数据:学生列表__stu_list\n 4.行为:获取列表 stu_list\n 5.添加学生方法 add_student\n 6.根据编号删除学生remove_student\n\"\"\"\n\n\nclass StudentModel:\n \"\"\"\n 学生模型\n \"\"\"\n\n def __init__(self, name=\"\", age=0, score=0, id=0):\n \"\"\"\n 创建学生对象\n :param id: 编号(该学生对象的唯一标识)\n :param name: 姓名,str类型\n :param age: 年龄,int类型\n :param score: 成绩,float类型\n \"\"\"\n self.id = id\n self.name = name\n self.age = age\n self.score = score\n\n @property\n def age(self):\n return self.__age\n\n @age.setter\n def age(self, value):\n self.__age = value\n\n\nclass StudentManagerController:\n \"\"\"\n 学生管理控制器,负责业务逻辑处理\n \"\"\"\n # 类变量,表示初始编号\n __init_id = 1000\n\n def __init__(self):\n self.__stu_list = [] # 只读\n\n @property\n def stu_list(self):\n \"\"\"\n 学生列表\n :return: 存储学生对象的列表\n \"\"\"\n return self.__stu_list\n\n def add_student(self, stu_info):\n \"\"\"\n 添加一个新学生\n :param stu_info: 没有编号的学生信息\n \"\"\"\n stu_info.id = self.__generate_id()\n self.__stu_list.append(stu_info)\n\n def __generate_id(self):\n StudentManagerController.__init_id += 1\n return StudentManagerController.__init_id\n\n def remove_student(self, id):\n \"\"\"\n 移除学生信息\n :param id: 待删除的学生编号\n \"\"\"\n for item in self.__stu_list:\n if item.id == id:\n self.__stu_list.remove(item)\n return True # 表示移除成功\n return False # 表示移除失败\n\n def update_student(self, stu_info):\n \"\"\"\n 修改学生信息\n \"\"\"\n for item in self.__stu_list:\n if item.id == stu_info.id:\n item.name = stu_info.name\n item.age = stu_info.age\n item.score = stu_info.score\n return True\n return False\n\n def order_by_score(self):\n \"\"\"\n 根据成绩对学生成绩进行升序排序\n \"\"\"\n for i in range(len(self.stu_list) - 1):\n for j in range(i + 1, len(self.stu_list)):\n if self.stu_list[i].score > self.stu_list[j].score:\n self.stu_list[i], self.stu_list[j] = self.stu_list[j], \\\n self.stu_list[i]\n return True\n return False\n\n\n'''\n# -------------测试代码---------------\nmanager = StudentManagerController()\ns01 = StudnetModel(\"zs\", 24, 100)\nmanager.add_student(s01)\nmanager.add_student(StudnetModel(\"ls\", 24, 100))\nfor item in manager.stu_list:\n print(item.id)\n\nprint(manager.remove_student(1002))\nfor item in manager.stu_list:\n print(item.id)\n'''\n\n\nclass StudentManagerView:\n \"\"\"\n 学生管理器视图\n \"\"\"\n\n def __init__(self):\n self.__manager = StudentManagerController()\n\n def __display_menu(self):\n print(\"1)添加学生\")\n print(\"2)显示学生\")\n print(\"3)删除学生\")\n print(\"4)修改学生\")\n print(\"5)按照成绩升序显示学生\")\n\n def __select_menu(self):\n item = input(\"请输入:\")\n if item == \"1\":\n self.__input_student()\n elif item == \"2\":\n self.__output_student(self.__manager.stu_list)\n elif item == \"3\":\n self.__delete_student()\n elif item == \"4\":\n self.__modify_student()\n else:\n self.__output_student_by_score()\n\n def __input_student(self):\n name = input(\"请输入姓名:\")\n age = int(input(\"请输入年龄:\"))\n score = int(input(\"请输入成绩:\"))\n stu = StudentModel(name, age, score)\n self.__manager.add_student(stu)\n\n def __output_student(self, list_output):\n for item in list_output:\n print(item.id, item.name, item.age, item.score)\n\n def __delete_student(self):\n id = int(input(\"请输入待删除的学生编号:\"))\n if self.__manager.remove_student(id):\n print(\"删除成功\")\n else:\n print(\"删除失败\")\n\n def __modify_student(self):\n stu = StudentModel()\n stu.id = int(input(\"请输入待修改学生编号:\"))\n stu.name = input(\"请输入姓名:\")\n stu.age = int(input(\"请输入年龄:\"))\n stu.score = int(input(\"请输入成绩:\"))\n if self.__manager.update_student(stu):\n print(\"修改成功\")\n else:\n print(\"修改失败\")\n\n def __output_student_by_score(self):\n self.__manager.order_by_score()\n self.__output_student(self.__manager.stu_list)\n\n def main(self):\n while True:\n self.__display_menu()\n self.__select_menu()\n\n\nview = StudentManagerView()\nview.main()\n","sub_path":"first_step/student_manage_system/student_manage_system.py","file_name":"student_manage_system.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"57061479","text":"#!/usr/bin/env python3\n\n# To import glob library, read all the pathnames matching with a specified pattern\nimport glob\n# To import the pandas library\nimport pandas as pd\n# To import the module 'mathplotlib.pyplot(plotting framework)'\nimport matplotlib.pyplot as plt\n# To import numpy library as fundamental package to compute function\nimport numpy as np\n# To import system specific parameters and functions\nimport sys\n\n#Make function to count the kmers\n#Define count kmers as c_kmers based on sequence and specific k\n#For every i which is in range of formula (sequence length - the k value + 1),\n#Define what is kmers and formula then if that kmers are not in counts then give it 0\n#Otherwise, if kmers are in script, add 1 incrementally depend the number of Kmer\n#Then return value from the function and pass back the counts expression\n\ndef c_kmers(seq, k):\n counts = {}\n for i in range(len(seq) - k + 1):\n kmers = seq[i:i+k]\n if kmers not in counts:\n counts[kmers] = 0\n else:\n counts[kmers] += 1\n return counts\n\n#Define function to find other DNAs except ACGT (find the wrong DNA)\n#If i is not A,C,G, or T, it is wrong DNA and add it incrementally each one\n#And if the condition becomes true, output this value from this function\ndef others_dna(seq):\n wrong_dna = {}\n for i in seq:\n if i not in 'ACGT':\n if i in wrong_dna: wrong_dna[ i ] += 1\n else: wrong_dna[ i ] = 1\n if wrong_dna != {}: return wrong_dna\n\n#Define function to create a table(kmers, observe, possible) in .csv\n#Define data field consisting 3 columns and convert into csv\n#Use index=False as default\ndef table_kmers(filename, data, sequename):\n tableofkmers = pd.DataFrame([[i[0], i[1], i[2]] for i in data], columns=['kmers', 'observed', 'possible'])\n tableofkmers.to_csv('result/table/'+ filename + '_' + sequename+'.csv', index=False)\n\n#Define function to create linguistic complexity of the graph of each species name\n#Name plot, x, and y label then use blue circle markers in the graph\n#Give the name of plot and label then save the graph into result folder and pic name\ndef graph_lingcomplex(filename, sequename_l, lingcomplex):\n plt.plot(sequename_l, lingcomplex, 'bo')\n plt.xlabel('Sequence_name')\n plt.ylabel('Linguistic_Complexity')\n graph_name = filename + '_lingcomplexity.png'\n plt.savefig('result/pic/'+graph_name)\n\n#Define function to compare between observe and possible kmers\n#Make two figures (fig1 and fig2) in one graph to compare observe and possible\n#Define function of graph visualization (barwidth, opacity, color, label, legend, ect)\n#Save the graph into result folder and pic name\ndef graph_kmers(filename, sequenames, observed_kmers, possible_kmers):\n figure, axis = plt.subplots()\n index = np.arange(len(sequenames))\n barwidth = 0.2\n opacity = 0.4\n fig1 = plt.bar(index + barwidth, observed_kmers, barwidth,\n alpha=opacity,\n color='b',\n label='The number of Observed Kmers')\n fig2 = plt.bar(index, possible_kmers, barwidth,\n alpha=opacity,\n color='r',\n label='The number of Possible Kmers')\n plt.xlabel('Sequence')\n plt.ylabel('Kmers')\n plt.xticks(index + barwidth, sequenames)\n plt.legend()\n graph_file = filename + '_obs_poss_kmers.png'\n plt.savefig('result/pic/'+graph_file)\n\n#Define function to create graph of wrong DNA\n#Define the position and values of the graph and labels for x axis\n#Make the name of the graph (.png) then save it\ndef wrong_dna_graph(filename, data, seq_name):\n plt.clf()\n plt.bar(range(len(data)), list(data.values()), align='center')\n plt.xticks(range(len(data)), list(data.keys()))\n graph_name = 'wrong_dna_'+ filename + '_' + seq_name + '.png'\n plt.savefig('result/pic/'+graph_name)\n\n#Primary function\n#Make the _name_ is set to the module'name\n#We already import the sys module, then we need to put the filename into the script\n#To work with command line arguments\n#The pathnames will match the name containing *.fasta file\n#Change/delete > symbol in front of sequence name\n#Read Append/add the argument (sequename, total kmer etc) to the end of the list\nif __name__ == \"__main__\":\n filename=sys.argv[1]\n if filename in glob.glob('*.fasta'):\n f = open(filename,'r')\n seq = f.readlines()\n filename = filename.replace('.', '_')\n sequenames = []\n observed_kmers = []\n possible_kmers = []\n lingcomplex = []\n for line_num, line in enumerate(seq[0:len(seq)]):\n if len(line) > 1 :\n if '>' in line :\n line = line.replace(\">\", \"\")\n sequename = line.rstrip()\n sequenames.append(sequename)\n else:\n seq = line.rstrip()\n #check per each sequence name, the sequence format\n seque_format = others_dna(seq)\n klist = []\n possibles = []\n observes = []\n for k in range(1,len(seq)+1):\n #check the possible kmers\n if 4**k < len(seq):\n possible = 4**k\n else:\n possible = len(seq) - k + 1\n #get the kmers\n counts = c_kmers(seq, k)\n #print(counts)\n #get the observed kmers\n observed = len(counts)\n klist.append(k)\n possibles.append(possible)\n observes.append(observed)\n #get the total possible kmers\n possible_total = sum(possibles)\n possibles.append(possible_total)\n possible_kmers.append(possible_total)\n #get the total observed kmers\n observed_total = sum(observes)\n observes.append(observed_total)\n observed_kmers.append(observed_total)\n klist.append('Total Kmers');\n #Combine data of klist, observes and possible\n data = list(zip(klist, observes, possibles))\n #Create table consisting the data and sequence name of the filename\n det = table_kmers(filename, data, sequename)\n #Define function the linguistic complexity then append the argument\n linguistic_complexity = observed_total/possible_total\n lingcomplex.append(linguistic_complexity)\n #Print all linguistic complexity\n #Make the language of execution\n all_lingcomplex = graph_lingcomplex(filename, sequenames, lingcomplex)\n if seque_format != None:\n wrong_graph = wrong_dna_graph(filename, seque_format, sequename)\n print('Wrong dna exist in', sequename, ' detail:', seque_format)\n summary_kmers = graph_kmers(filename, sequenames, observed_kmers, possible_kmers)\n print('Success')\n\n else:\n print('Not success')\n","sub_path":"hevahy.py","file_name":"hevahy.py","file_ext":"py","file_size_in_byte":7237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"569403084","text":"class Node:\r\n def __init__(self,data):\r\n self.data=data\r\n self.left=None\r\n self.right=None\r\n\r\nclass BinarySearchTree:\r\n def __init__(self):\r\n self.root=None\r\n\r\n def insert(self,data):\r\n n=Node(data)\r\n if self.root is None:\r\n self.root=n\r\n else:\r\n curr=self.root\r\n while True:\r\n if datacurr.data:\r\n if curr.right is None:\r\n curr.right=n\r\n break\r\n else:\r\n curr=curr.right\r\n else:\r\n break\r\n\r\ndef inorder(root):\r\n if root is None:\r\n return None\r\n inorder(root.left)\r\n print(root.data,end=' ')\r\n inorder(root.right)\r\n\r\ndef levelorder(root):\r\n q=[]\r\n q.append(root)\r\n while len(q)>0:\r\n x=q.pop(0)\r\n print(x.data,end=' ')\r\n if x.left is not None:\r\n q.append(x.left)\r\n if x.right is not None:\r\n q.append(x.right)\r\n\r\ndef levelorder_printline(root):\r\n if root is None:\r\n return None\r\n q=[]\r\n ans=[]\r\n q.append(root)\r\n while len(q):\r\n x=len(q)\r\n t=[]\r\n while x>0:\r\n root=q.pop(0)\r\n t.append(root.data)\r\n if root.left is not None:\r\n q.append(root.left)\r\n if root.right is not None:\r\n q.append(root.right)\r\n x=x-1\r\n ans.append(t)\r\n print(ans)\r\n\r\n#########################################################\r\n'''ob=BinarySearchTree()\r\nl=list(map(int,input().split()))\r\nfor i in l:\r\n ob.insert(i)\r\nprint('Inorder : ',end=' ')\r\ninorder(ob.root)\r\nprint()\r\n\r\nprint('Level Order:',end=' ')\r\nlevelorder(ob.root)\r\nprint()'''\r\n\r\nprint('Level Order Line by Line:')\r\nroot = Node(3);\r\nroot.left = Node(9);\r\nroot.right = Node(20);\r\nroot.right.left = Node(15);\r\nroot.right.right = Node(17);\r\nlevelorder_printline(root)\r\n","sub_path":"Trees/Level_order_traversal.py","file_name":"Level_order_traversal.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"463496219","text":"def sort_priority(values, group):\n def helper(x):\n if x in group:\n return 0, x\n return 1, x\n\n values.sort(key=helper)\n\n\nnumbers = [8, 3, 1, 2, 5, 4, 7, 6]\ngroup = {2, 3, 5, 7}\nsort_priority(numbers, group)\nprint(numbers)\n\n\ndef sort_priority2(values, group):\n found = False\n\n def helper(x):\n if x in group:\n nonlocal found\n found = True\n return 0, x\n return 1, x\n\n values.sort(key=helper)\n return found\n\nfound = sort_priority2(numbers, group)\nprint(\"found\", found)\nprint(numbers)\n","sub_path":"03_functions/21_know_closure/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"225217513","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\nimport scipy\nimport os\nimport time\nimport copy\n\nimport seaborn as sns\n\nimport plot_court\nimport sklearn.model_selection\nfrom sklearn.decomposition import NMF\n\n\n# Load data and keep desired columns\nfull_DatFrame = pd.read_csv('../dat/joined_shots_2013.csv')\ndf = pd.DataFrame(full_DatFrame, \n columns = ['PLAYER_ID.1', 'PLAYER_NAME', \n 'MATCHUP', 'LOCATION', 'TEAM_ID', \n 'SHOT_DISTANCE', \n 'PTS_TYPE', 'LOC_X', 'LOC_Y', \n 'ACTION_TYPE', 'SHOT_TYPE',\n 'SHOT_ATTEMPTED_FLAG', 'SHOT_MADE_FLAG'])\n\n# Add shooter's team column\nteamID_dict = plot_court.out_teamsDict()\ndef out_teamAbbrev(teamID):\n teamID_dict = plot_court.out_teamsDict()\n return teamID_dict[teamID]['abbreviation']\ndf['TEAM_ABBREV'] = pd.Series(map(out_teamAbbrev, df.TEAM_ID), index=df.index)\n\n\n################################################################\n#%%###############################################################\n\n\n# Number of bins and range in each direction used to make the grid for analysis\nii = 1\nif (ii == 0):\n bins, binRange = ([20,14], [[-250,250], [-47.5,302.5]])\n sigma2 = 3.5\nelif (ii == 1):\n bins, binRange = ([25,18], [[-250,250], [-47.5,312.5]])\n sigma2 = 12.5\n sigma2 = 20\n sigma2 = 40\n #sigma2 = 60\n #sigma2 = 3.35e3\n sigma2 = 1e3\n #\n #sigma2 = 7e4\nelif (ii == 2):\n bins, binRange = ([30,21], [[-250,250], [-47.5,302.5]])\n sigma2 = 49.\nelif (ii == 3):\n bins, binRange = ([40,28], [[-250,250], [-47.5,302.5]])\n sigma2 = 5e3\n sigma2 = 1.\n #sigma2 = 4.09e8\nelif (ii == 4):\n bins, binRange = ([50,35], [[-250,250], [-47.5,302.5]])\n sigma2 = 25.\n\nhist2d, xedges, yedges, binnumber = scipy.stats.binned_statistic_2d(df.LOC_X, df.LOC_Y, \n df.SHOT_MADE_FLAG,\n statistic='count',\n bins=bins, \n range=binRange)\n# Creating the grid we will use for analysis\nXX, YY = np.meshgrid(xedges, yedges)\nbinX_flat = XX.T[:-1,:-1].flatten()\nbinY_flat = YY.T[:-1,:-1].flatten()\nbinXY = np.column_stack((binX_flat.T, binY_flat.T))\ndist_matrix = scipy.spatial.distance_matrix(binXY, binXY)\n\n\ndef cov_func(dist_matrix, sigma2, phi2):\n return sigma2 * np.exp( -(dist_matrix**2) / (2 * phi2) )\n\nphi2 = 40.**2\n#phi2 = 25.**2\n# sigma2 = 1./np.sqrt(2 * np.pi * phi2)\n\ncov_K = cov_func(dist_matrix, sigma2, phi2)\n# np.linalg.det under/overflows for very small/large values of det, so slogdet is more robust\nsign, logdet_cov_K = np.linalg.slogdet(cov_K)\ndet_cov_K = sign * np.exp(logdet_cov_K)\ninv_cov_K = np.linalg.inv(cov_K)\nnbins = np.prod(bins)\n\nprint(sign, logdet_cov_K, det_cov_K)\n\n\n################################################################\n#%%###############################################################\n\n\nnum_players = 300\ntop_players_shotNum = df.PLAYER_NAME.value_counts()[:num_players]\ntop_players_nameList = top_players_shotNum.index.tolist()\n\n\n################################################################\n################################################################\n\n\ntrain_df = {}\ntest_df = {}\nrandSeed = 546682\nfor i, player in enumerate(set(top_players_nameList)): \n temp = df[df.PLAYER_NAME == player]\n train_df[player], test_df[player] = sklearn.model_selection.train_test_split(temp, test_size=0.2, random_state=randSeed)\n\n \nplayer_shotHist_train = {}\nfor i, player in enumerate(set(top_players_nameList)): \n temp = train_df[player]\n hist2d, xedges, yedges, binnumber = scipy.stats.binned_statistic_2d(temp.LOC_X, temp.LOC_Y, \n temp.SHOT_MADE_FLAG,\n statistic='count',\n bins=bins, \n range=binRange)\n player_shotHist_train[player] = hist2d.flatten()\n \n \nplayer_shotMadeHist_train = {}\nfor i, player in enumerate(set(top_players_nameList)): \n temp = train_df[player][train_df[player].SHOT_MADE_FLAG == 1.0]\n hist2d, xedges, yedges, binnumber = scipy.stats.binned_statistic_2d(temp.LOC_X, temp.LOC_Y, \n temp.SHOT_MADE_FLAG,\n statistic='count',\n bins=bins, \n range=binRange)\n player_shotMadeHist_train[player] = hist2d.flatten()\n\n\n################################################################\n# Likelihood-max for shot count distribution (Log Gaussian Cox Process)\n################################################################\n\n\ndef ln_prior(nbins, zn_v, logdet_cov_K, inv_cov_K):\n part1 = - (nbins/2.) * np.log(2 * np.pi) - (0.5 * logdet_cov_K)\n part2 = -0.5 * np.dot(zn_v, np.dot(inv_cov_K, zn_v))\n return part1 + part2\n\ndef lambdaN_func(z0, zn_v):\n return np.exp(z0 + zn_v)\n\ndef ln_lambdaN_func(z0, zn_v):\n return z0 + zn_v\n\ndef ln_factorial(n):\n temp = scipy.misc.factorial(n)\n return np.log(temp)\n\ndef ln_likelihood(z0, zn_v, Xn_v):\n part1 = -lambdaN_func(z0, zn_v)\n part2 = Xn_v * ln_lambdaN_func(z0, zn_v)\n part3 = -ln_factorial(Xn_v)\n #print(np.sum(part1), np.sum(part2), np.sum(part3))\n #print(part3)\n return np.sum(part1 + part2 + part3)\n\ndef ln_postprob(z, Xn_v, logdet_cov_K, inv_cov_K, nbins):\n z0 = z[0]\n zn_v = z[1:]\n return ln_prior(nbins, zn_v, logdet_cov_K, inv_cov_K) + ln_likelihood(z0, zn_v, Xn_v)\n\n\n################################################################\n#%%#############################################################\ndef plot_player_rawHist(player):\n Xn_v = player_shotHist_train[player]\n temp = np.array(Xn_v, dtype='float')/np.sum(Xn_v)\n rawHist_v = np.reshape(temp, bins)\n ##########\n extent = np.min(xedges), np.max(xedges), np.max(yedges), np.min(yedges)\n \n# plt.imshow(LAMBDA_v.T, cmap=plt.cm.gist_heat_r, alpha=.9,\n# extent=extent)\n plt.imshow(rawHist_v.T, cmap=plt.cm.RdYlBu_r, alpha=.5, vmax=0.02,\n extent=extent)\n plot_court.draw_court(outer_lines=True, lw=1.5)\n \n plt.xlim(-300,300)\n plt.ylim(-100,500)\n plt.grid('off')\n plt.axis('off')\n plt.title('%s: raw histogram'%(player), fontsize=15)\n# plt.axis('off')\n plt.tight_layout()\n plt.show()\n#%%#############################################################\ndef plot_player_normLambda_old(player):\n seed = 348098\n norm_lambdaN_v = np.loadtxt('player2013_lambda_seed%d/norm_lambda_%s.txt'%(seed, player))\n LAMBDA_v = np.reshape(norm_lambdaN_v, bins)\n ##########\n extent = np.min(xedges), np.max(xedges), np.max(yedges), np.min(yedges)\n \n# plt.imshow(LAMBDA_v.T, cmap=plt.cm.gist_heat_r, alpha=.9,\n# extent=extent)\n plt.imshow(LAMBDA_v.T, cmap=plt.cm.RdYlBu_r, alpha=.5, vmax=0.02,\n extent=extent)\n plot_court.draw_court(outer_lines=True, lw=1.5)\n \n plt.xlim(-300,300)\n plt.ylim(-100,500)\n plt.grid('off')\n plt.axis('off')\n plt.title('%s: LGCP'%(player), fontsize=15)\n# plt.axis('off')\n plt.tight_layout()\n plt.show()\n#%%###############################################################\n \ndef plot_player_normLambda(player, seed):\n norm_lambdaN_v = np.loadtxt('player2013_lambda_new_seed%d/norm_lambda_%s.txt'%(seed, player))\n LAMBDA_v = np.reshape(norm_lambdaN_v, bins)\n print(np.sum(LAMBDA_v))\n ##########\n extent = np.min(xedges), np.max(xedges), np.max(yedges), np.min(yedges)\n \n# plt.imshow(LAMBDA_v.T, cmap=plt.cm.gist_heat_r, alpha=.9,\n# extent=extent)\n plt.imshow(LAMBDA_v.T, cmap=plt.cm.RdYlBu_r, alpha=.5, vmax=0.02,\n extent=extent)\n plot_court.draw_court(outer_lines=True, lw=1.5)\n \n plt.xlim(-300,300)\n plt.ylim(-100,500)\n plt.grid('off')\n plt.axis('off')\n plt.title('%s: LGCP'%(player), fontsize=15)\n# plt.axis('off')\n plt.tight_layout()\n plt.show()\n\n#%%\n#start_time = time.time()\n#\n#player = 'LeBron James'\n#Xn_v = player_shotHist_train[player]\n#print(Xn_v)\n#z0_guess = np.log(np.mean(Xn_v))\n##temp = copy.deepcopy(Xn_v)\n##np.place(temp, temp==0., 1e-10)\n##zn_v_guess = np.log(temp) - z0\n#zn_v_guess = 0. * Xn_v\n#z_guess = np.append(z0_guess, zn_v_guess)\n##ln_prior(nbins, zn_v_guess, logdet_cov_K, inv_cov_K)\n##ln_likelihood(z0_guess, zn_v_guess, Xn_v)\n#neg_logLike = lambda *args: -ln_postprob(*args)\n#result = scipy.optimize.minimize(neg_logLike, z_guess, \n# args=(Xn_v, logdet_cov_K, inv_cov_K, nbins))\n#z_MaxLike = result[\"x\"]\n#z0_MaxLike = z_MaxLike[0]\n#zn_MaxLike = z_MaxLike[1:]\n#lambdaN_v = np.exp(z0_MaxLike + zn_MaxLike)\n#norm_lambdaN_v = lambdaN_v / np.sum(lambdaN_v)\n#np.savetxt('player2013_lambda_new_seed%d/norm_lambda_%s.txt'%(randSeed, player), norm_lambdaN_v)\n#\n#print(\"------ %s seconds ------\" %(time.time() - start_time))\n#plot_player_normLambda(player, randSeed)\n#%%###############################################################\n################################################################\n\nyear = 2014\ndirectory = 'player%d_lambda_new_seed%d'%(year,randSeed)\nif not os.path.exists(directory):\n os.makedirs(directory)\nLL = np.zeros((num_players,np.prod(bins)))\n\nprint('Computing LL, normalized Lambda for each player')\nprint('================================================')\nprint('================================================')\nfor i, player in enumerate(top_players_nameList):\n try:\n norm_lambdaN_v = np.loadtxt('player%d_lambda_new_seed%d/norm_lambda_%s.txt'%(year, randSeed, player))\n if np.all(norm_lambdaN_v == norm_lambdaN_v[0]):\n print(player, 'BAD')\n except:\n print('================================================')\n start_time = time.time()\n \n Xn_v = player_shotHist_train[player]\n z0_guess = np.log(np.mean(Xn_v))\n zn_v_guess = np.zeros(len(Xn_v))\n z_guess = np.append(z0_guess, zn_v_guess)\n \n neg_logLike = lambda *args: -ln_postprob(*args)\n result = scipy.optimize.minimize(neg_logLike, z_guess, \n args=(Xn_v, logdet_cov_K, inv_cov_K, nbins))\n z_MaxLike = result[\"x\"]\n z0_MaxLike = z_MaxLike[0]\n zn_MaxLike = z_MaxLike[1:]\n lambdaN_v = np.exp(z0_MaxLike + zn_MaxLike)\n norm_lambdaN_v = lambdaN_v / np.sum(lambdaN_v)\n \n print(\"------ %s seconds ------\" %(time.time() - start_time))\n if np.all(norm_lambdaN_v == norm_lambdaN_v[0]):\n print(player, 'BAD')\n np.savetxt('player%d_lambda_new_seed%d/norm_lambda_%s.txt'%(year, randSeed, player), norm_lambdaN_v)\n print(player)\n LL[i,:] = norm_lambdaN_v[:]\n\n \n\n################################################################\n#%%###############################################################\n\n\nn_comp = 16\nmodel = NMF(n_components=n_comp, init='nndsvda', max_iter=6000, tol=1e-7,\n solver='mu', beta_loss='kullback-leibler')\nW = model.fit_transform(LL)\nH = model.components_ \n\ndef normalize_W_and_H(W, H, n_comp):\n W_norm = np.copy(W)\n H_norm = np.copy(H)\n for i in range(n_comp):\n temp = np.sum(H[i,:])\n W_norm[:,i] *= temp\n H_norm[i,:] *= 1./temp\n return W_norm, H_norm\n\nW_norm, H_norm = normalize_W_and_H(W, H, n_comp)\n\n\nplt.figure(figsize=(16,5))\nfor i in range(n_comp):\n plt.subplot(2, n_comp/2, i+1)\n\n extent = np.max(xedges), np.min(xedges), np.max(yedges), np.min(yedges)\n\n# plt.imshow(H[i,:].reshape(bins[0],bins[1]).T, cmap=plt.cm.gist_heat_r, alpha=.9,\n# extent=extent)\n plt.imshow(H_norm[i,:].reshape(bins[0],bins[1]).T, cmap=plt.cm.RdYlBu_r, alpha=.5,\n extent=extent)\n plot_court.draw_court(outer_lines=True, lw=1.)\n\n plt.xlim(-300,300)\n plt.ylim(-100,500)\n plt.title('Basis vector %d'%(i), fontsize=12)\n plt.axis('off')\nplt.show()\n\n\n#%%###############################################################\n# Likelihood-max for FG% distribution (Inhomogeneous Binomial Process)\n################################################################\n\n# When compared to LGCP, still use a spatially vary field variable zn\n# local success probability (or field goal %, i.e. FG%) is the logistic function of zn\n\n\ndef ln_prior_binomial(zn_v, det_cov_K, inv_cov_K):\n part1 = -np.log(2 * np.pi * (det_cov_K**0.5))\n part2 = -0.5 * np.dot(zn_v, np.dot(inv_cov_K, zn_v))\n return part1 + part2\n\ndef binomialP_func(z0, zn_v):\n # Input: field variables\n # Output: Bernouli success prob (from logistic function)\n return 1./(1. + np.exp(-(z0 + zn_v)))\n\ndef ln_factorial(n):\n # an improvement of the Sterling Approximation of log(n!)\n # given by Srinivasa Ramanujan (Ramanujan 1988)\n # scipy.misc.factorial stops worknig at large values of n\n sterling = n * np.log(n) - n\n correct = (1./6) * np.log(n * (1 + 4*n*(1 + 2*n))) + np.log(np.pi)/2\n return sterling + correct\n\ndef ln_binomialCoeff(n, k):\n return ln_factorial(n) - ln_factorial(k) - ln_factorial(n-k)\n\ndef ln_likelihood_binomial(z0, zn_v, Xn_made_v, Xn_v):\n part1 = ln_binomialCoeff(Xn_v, Xn_made_v)\n part2 = Xn_made_v * np.log(binomialP_func(z0, zn_v))\n part3 = (Xn_v - Xn_made_v) * np.log(1 - binomialP_func(z0, zn_v))\n #print(np.sum(part1), np.sum(part2), np.sum(part3))\n #print(part3)\n return np.sum(part1 + part2 + part3)\n\ndef ln_postprob_binomial(z, Xn_made_v, Xn_v, det_cov_K, inv_cov_K):\n z0 = z[0]\n zn_v = z[1:]\n return ln_prior_binomial(zn_v, det_cov_K, inv_cov_K) + ln_likelihood(z0, zn_v, Xn_v)\n\n\n################################################################\n################################################################\n \ndef plot_player_fgPercent(player):\n fgPercent_v = np.loadtxt('player_FGp/FGpercent_%s.txt'%(player))\n FGper_v = np.reshape(fgPercent_v, bins)\n ##########\n extent = np.min(xedges), np.max(xedges), np.max(yedges), np.min(yedges)\n \n plt.imshow(FGper_v.T, cmap=plt.cm.RdYlBu_r, alpha=.5, vmax=1.,\n extent=extent)\n plot_court.draw_court(outer_lines=True, lw=1.5)\n \n plt.xlim(-300,300)\n plt.ylim(-100,500)\n plt.title('%s: est FG percent'%(player), fontsize=15)\n# plt.axis('off')\n plt.tight_layout()\n plt.show()\n\n\n################################################################\n################################################################\n\nphi2 = 25.**2\nsigma2 = 5.\n\ncov_K = cov_func(dist_matrix, sigma2, phi2)\ndet_cov_K = np.linalg.det(cov_K)\ninv_cov_K = np.linalg.inv(cov_K)\n\n################################################################\n################################################################\n\nplayer = 'Kevin Durant'\n\nXn_v = player_shotHist_train[player]\nXn_made_v = player_shotMadeHist_train[player]\nz0_guess = -np.log((float(np.sum(Xn_v)) / np.sum(Xn_made_v)) - 1)\nzn_v_guess = np.zeros(len(Xn_v))\nz_guess = np.append(z0_guess, zn_v_guess)\n\nneg_logLike = lambda *args: -ln_postprob_binomial(*args)\nresult = scipy.optimize.minimize(neg_logLike, z_guess, \n args=(Xn_made_v, Xn_v, det_cov_K, inv_cov_K))\nz_MaxLike = result[\"x\"]\nz0_MaxLike = z_MaxLike[0]\nzn_MaxLike = z_MaxLike[1:]\nfgPercent_v = binomialP_func(z0_MaxLike, zn_MaxLike)\nnp.savetxt('player_FGp/FGpercent_%s.txt'%(player), fgPercent_v)\n\nplot_player_fgPercent(player)\nplot_player_normLambda(player)\n\n#FGper = np.zeros((num_players,np.prod(bins)))\n#for i, player in enumerate(top_players_nameList):\n# try:\n# fgPercent_v = np.loadtxt('player_FGp/FGpercent_%s.txt'%(player))\n# except:\n# Xn_v = player_shotHist_train[player]\n# Xn_made_v = player_shotMadeHist_train[player]\n# z0_guess = -np.log((float(len(Xn_v)) / len(Xn_made_v)) - 1)\n# zn_v_guess = np.zeros(len(Xn_v))\n# z_guess = np.append(z0_guess, zn_v_guess)\n# \n# neg_logLike = lambda *args: -ln_postprob_binomial(*args)\n# result = scipy.optimize.minimize(neg_logLike, z_guess, \n# args=(Xn_made_v, Xn_v, det_cov_K, inv_cov_K))\n# z_MaxLike = result[\"x\"]\n# z0_MaxLike = z_MaxLike[0]\n# zn_MaxLike = z_MaxLike[1:]\n# fgPercent_v = binomialP_func(z0_MaxLike, zn_MaxLike)\n# \n# np.savetxt('player_FGp/FGpercent_%s.txt'%(player), fgPercent_v)\n# print(player)\n# FGper[i,:] = fgPercent_v[:]\n \n \n################################################################\n################################################################\n\n\n#n_comp = 10\n#model = NMF(n_components=n_comp, init='nndsvd', max_iter=2000, solver='cd')\n#W = model.fit_transform(LL)\n#H = model.components_ \n#\n#\n#plt.figure(figsize=(20,14))\n#for i in range(n_comp):\n# plt.subplot(2, n_comp/2 + 1, i+1)\n#\n# extent = np.max(xedges), np.min(xedges), np.max(yedges), np.min(yedges)\n#\n# plt.imshow(H[i,:].reshape(bins[0],bins[1]).T, cmap=plt.cm.gist_heat_r, alpha=.9,\n# extent=extent)\n# plot_court.draw_court(outer_lines=True, lw=1.)\n#\n# plt.xlim(-300,300)\n# plt.ylim(-100,500)\n# plt.title('Basis vector %d'%(i), fontsize=15)\n# plt.axis('off')\n#plt.show()\n","sub_path":"scripts/nbaPlayer_shotRate_lgcp_new.py","file_name":"nbaPlayer_shotRate_lgcp_new.py","file_ext":"py","file_size_in_byte":17689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"523351133","text":"seat_count = 9\nvip_seat_array = [4, 7]\n\n# 이 문제에서는 Fibo(1) = 1, Fibo(2) = 2 로 시작합니다!\nmemo = {\n 1: 1,\n 2: 2\n}\n\n\ndef fibo_dynamic_programming(n, fibo_memo):\n if n in fibo_memo:\n return fibo_memo[n]\n\n nth_fibo = fibo_dynamic_programming(n - 1, fibo_memo) + fibo_dynamic_programming(n - 2, fibo_memo)\n fibo_memo[n] = nth_fibo\n return nth_fibo\n\n\ndef get_all_ways_of_theater_seat(total_count, fixed_seat_array):\n way_count = 1\n cur_index = 0\n for fixed_seat in fixed_seat_array:\n fixed_seat_index = fixed_seat - 1\n way_count = way_count * fibo_dynamic_programming(fixed_seat_index - cur_index, memo)\n print(\"way_count :\", way_count)\n cur_index = fixed_seat\n\n print(\"cur_index :\", cur_index)\n last_way_count = fibo_dynamic_programming(total_count - cur_index, memo)\n result = way_count * last_way_count\n return result\n\n\n# 12가 출력되어야 합니다!\nprint(get_all_ways_of_theater_seat(seat_count, vip_seat_array))","sub_path":"week_4/homework/03_get_all_ways_of_theater_seat.py","file_name":"03_get_all_ways_of_theater_seat.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"600531100","text":"from flask_wtf import Form\nfrom wtforms import StringField\nfrom wtforms.validators import DataRequired\n\nclass MyForm(Form):\n name = StringField('Firstname')\n lastname = StringField('Lastname')\n login = StringField('login')\n desc = StringField('desc')\n email = StringField('Email')\n gender = StringField('Gender')\n address = StringField('Address')\n city = StringField('City')\n phone = StringField('Phone')\n specialty = StringField('Speciality')\n global_search = StringField('Global')","sub_path":"src/MyForm.py","file_name":"MyForm.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"455681606","text":"import cv2\r\nimport datetime\r\n\r\n\r\ncap=cv2.VideoCapture(0)\r\n\r\n#every property is associated with a no\r\n#print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n#print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n\r\n\r\n#setting the width\r\n#cap.set(3,1208)\r\n#setting the height\r\n#cap.set(4,720)\r\n\r\nprint(cap.get(3))\r\nprint(cap.get(4))\r\n\r\nwhile(cap.isOpened()):\r\n ret, frame = cap.read()\r\n\r\n if ret == True:\r\n \r\n\r\n font=cv2.FONT_HERSHEY_SIMPLEX\r\n text=\"Width: \"+str(cap.get(3)) +\" Height: \"+str(cap.get(4))\r\n\r\n datet=str(datetime.datetime.now())\r\n\r\n frame=cv2.putText(frame,text+' '+datet,(10,50),font,1,(0,255,255),2,cv2.LINE_AA)\r\n\r\n \r\n cv2.imshow(\"Frame\",frame)\r\n #gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\r\n #cv2.imshow(\"Frame\",gray)\r\n\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n else:\r\n break\r\ncap.release()\r\ncv2.destroyAllWindows()","sub_path":"add_text_to_videos.py","file_name":"add_text_to_videos.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"49327148","text":"from django.urls import path\n\nfrom .views import ContactList, PersonView, AddPersonAddress, ModifyPersonAddress, AddPersonEmail, \\\n ModifyPersonEmail, AddPersonPhone, ModifyPersonPhone, GroupsView, AddGroupView, ModifyGroupView, AddToGroupView, \\\n RemoveFromGroupView, GroupView, SearchGroupView, DeleteContactView\n\n\napp_name = 'contacts'\n\nurlpatterns = [\n path('', ContactList.as_view(), name='contact_list'),\n path('contact//', PersonView.as_view(), name='contact'),\n path('contact/remove//', DeleteContactView.as_view(), name='delete-contact'),\n path('contact//new-address/', AddPersonAddress.as_view(), name='add-address'),\n path('contact//modify-address//', ModifyPersonAddress.as_view(),\n name='modify-address'),\n path('contact//new-email/', AddPersonEmail.as_view(), name='add-email'),\n path('contact//modify-email//', ModifyPersonEmail.as_view(),\n name='modify-email'),\n path('contact//new-phone/', AddPersonPhone.as_view(), name='add-phone'),\n path('contact//modify-phone//', ModifyPersonPhone.as_view(),\n name='modify-phone'),\n\n path('groups/', GroupsView.as_view(), name='groups'),\n path('groups/add-group/', AddGroupView.as_view(), name='add-group'),\n path('groups/add-to-group//', AddToGroupView.as_view(), name='add-to-group'),\n path('groups/remove-from-group/', RemoveFromGroupView.as_view(), name='remove-from-group'),\n path('groups/modify-group//', ModifyGroupView.as_view(), name='modify-group'),\n path('groups/group//', GroupView.as_view(), name='group'),\n path('groups/group//search/', SearchGroupView.as_view(), name='search'),\n\n ]\n","sub_path":"app/contacts/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":"15"} +{"seq_id":"491500356","text":"\"\"\"\nModule to handle communication with the Gotify server\n\"\"\"\nimport http.client\nimport json\nimport logging\nimport socket\n\n\nclass Gotify:\n \"\"\"\n Class to handle Gotify communications\n \"\"\"\n\n def __init__(self, server, port, app_key, client_key=None):\n self.api = http.client.HTTPConnection(server, port)\n self.app_key = app_key\n self.client_key = client_key\n self.base_headers = {\n 'Content-type': 'application/json',\n 'Accept': 'application/json',\n }\n\n def _call(self, method, url, body=None):\n \"\"\"\n Method to call Gotify with an app or client key as appropriate\n \"\"\"\n headers = self.base_headers.copy()\n if method in ['GET', 'DELETE']:\n headers['X-Gotify-Key'] = self.client_key\n else:\n headers['X-Gotify-Key'] = self.app_key\n\n logging.debug('Sending to Gotify:\\n%s', body)\n\n try:\n self.api.request(method, url, body=body, headers=headers)\n response = self.api.getresponse()\n except (ConnectionRefusedError, socket.gaierror) as error:\n logging.error('Connection error: %s', error)\n return {\n 'status': error.errno,\n 'reason': error.strerror,\n }\n\n resp_obj = {\n 'status': response.status,\n 'reason': response.reason,\n 'json': None,\n }\n rawbody = response.read()\n if len(rawbody) > 0:\n try:\n resp_obj['json'] = json.loads(rawbody.decode())\n except json.decoder.JSONDecodeError as error:\n logging.error('Could not parse JSON: %s', error)\n\n logging.debug('Returned from Gotify:\\n%s', json.dumps(resp_obj, indent=2))\n logging.debug('Status: %s, Reason: %s', resp_obj['status'], resp_obj['reason'])\n\n return resp_obj\n\n def delete(self, msg_id):\n \"\"\"\n Method to delete a message from the Gotify server\n \"\"\"\n logging.debug('Deleting message ID: %s', msg_id)\n return self._call('DELETE', f'/message/{msg_id}')\n\n def find_byfingerprint(self, message):\n \"\"\"\n Method to return the ID of a matching message\n \"\"\"\n try:\n new_fingerprint = message['fingerprint']\n except KeyError:\n logging.debug('No fingerprint found in new message')\n return None\n\n msg_list = []\n for old_message in self.messages():\n try:\n old_fingerprint = old_message['extras']['alertify']['fingerprint']\n if old_fingerprint == new_fingerprint:\n msg_list.append(old_message['id'])\n except KeyError:\n logging.warning(\n 'No fingerprint found in message ID: %s',\n old_message['id'],\n )\n\n return msg_list\n\n def messages(self):\n \"\"\"\n Method to return a list of messages from the Gotify server\n \"\"\"\n if not self.client_key:\n logging.warning(\n 'No client key is configured. No messages could be retrieved.'\n )\n return []\n logging.debug('Fetching existing messages from Gotify')\n return self._call('GET', '/message')['json'].get('messages', [])\n\n def send_alert(self, payload):\n \"\"\"\n Method to send a message payload to a Gotify server\n \"\"\"\n logging.debug('Sending message to Gotify')\n return self._call('POST', '/message', body=json.dumps(payload, indent=2))\n\n def healthcheck(self):\n \"\"\"\n Method to perform a healthcheck against Gotify\n \"\"\"\n return self._call('GET', '/health')\n","sub_path":"src/alertify/gotify.py","file_name":"gotify.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"148590082","text":"# DJANGO IMPORTS #\nfrom django.conf import settings\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.core.mail import send_mail\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom django.template.loader import render_to_string\nfrom django.shortcuts import render\nfrom django.urls import reverse, reverse_lazy\nfrom django.utils.encoding import force_bytes\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.views.generic import TemplateView, ListView, CreateView, UpdateView, DeleteView\n\n# MODULE IMPORTS #\nfrom accounts_module import forms, models, tokens\nfrom homework_module.models import FkHomeworkUser\nfrom quiz_module.models import History\n\n\n'''\n =======================\n ********PROFILE********\n =======================\n'''\n\n\nclass ProfileView(TemplateView, LoginRequiredMixin):\n template_name = 'accounts/profile.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n user = self.request.user\n user_profile = models.UserProfile.objects.get(user=user)\n hm_length = 0\n hs_length = 0\n\n try:\n homework = FkHomeworkUser.objects.filter(user=user_profile)\n hm_length = homework.count()\n except FkHomeworkUser.DoesNotExist:\n homework = None\n try:\n history = History.objects.filter(user=user_profile)\n hs_length = history.count()\n except History.DoesNotExist:\n history = None\n\n q = models.UserProfile.objects.all().order_by('-passed_flag', '-mark', '-points')\n position = 0\n for i in q:\n position += 1\n if i.user.username == user.username:\n break\n\n context['rank'] = position\n if hm_length == 0:\n context['homework'] = None\n else:\n context['homework'] = homework\n if hs_length == 0:\n context['history'] = None\n else:\n context['history'] = history\n context['user_profile'] = user_profile\n\n return context\n\n\n'''\n ==========================================\n ********USER PROFILE FOR MODERATOR********\n ==========================================\n'''\n\n\nclass UserProfileView(TemplateView, LoginRequiredMixin):\n template_name = 'accounts/profile.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n user = models.User.objects.get(pk=context['pk'])\n user_profile = models.UserProfile.objects.get(user=user)\n hm_length = 0\n hs_length = 0\n\n try:\n homework = FkHomeworkUser.objects.filter(user=user_profile)\n hm_length = homework.count()\n except FkHomeworkUser.DoesNotExist:\n homework = None\n try:\n history = History.objects.filter(user=user_profile)\n hs_length = history.count()\n except History.DoesNotExist:\n history = None\n\n q = models.UserProfile.objects.all().order_by('-passed_flag', '-mark', '-points')\n position = 0\n for i in q:\n position += 1\n if i.user.username == user.username:\n break\n\n context['rank'] = position\n if hm_length == 0:\n context['homework'] = None\n else:\n context['homework'] = homework\n if hs_length == 0:\n context['history'] = None\n else:\n context['history'] = history\n context['user_profile'] = user_profile\n\n return context\n\n\n'''\n ===========================\n ********LEADERBOARD********\n ===========================\n'''\n\n\nclass LeaderboardListView(ListView, LoginRequiredMixin):\n template_name = 'accounts/leaderboard.html'\n context_object_name = 'entries'\n paginate_by = 10\n queryset = models.UserProfile.objects.all().order_by('-passed_flag', '-mark', '-points')\n\n def get_context_data(self, **kwargs):\n context = super(LeaderboardListView, self).get_context_data(**kwargs)\n user = self.request.user\n position = 0\n for i in self.queryset:\n position += 1\n if i.user.username == user.username:\n break\n if position % 10 == 0:\n user_page = position // 10\n else:\n user_page = position // 10 + 1\n context['user_page'] = user_page\n context['username'] = self.request.user.username\n context['total'] = self.queryset.count()\n return context\n\n\n'''\n ========================\n ********REGISTER********\n ========================\n'''\n\n\nclass RegisterConfirm(TemplateView):\n template_name = 'accounts/complete_register.html'\n\n\ndef register(request, option):\n tab = 0\n if request.user.is_authenticated:\n if option == 0:\n return HttpResponseRedirect(reverse(settings.LOGIN_REDIRECT_URL))\n else:\n return HttpResponseRedirect(reverse(settings.M_LOGIN_REDIRECT_URL))\n else:\n if request.method == \"POST\":\n user_form = forms.UserForm(data=request.POST)\n\n if option == 0:\n profile_form = forms.UserProfileForm(data=request.POST)\n else:\n profile_form = forms.ModeratorProfileForm(data=request.POST)\n\n if user_form.is_valid() and profile_form.is_valid():\n\n user = user_form.save()\n user.set_password(user.password)\n user.is_active = False\n if option != 0:\n user.is_staff = True\n user.save()\n\n profile = profile_form.save(commit=False)\n profile.user = user\n profile.save()\n\n # Adaptat dupa https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef\n\n current_site = get_current_site(request)\n uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()\n token = tokens.account_activation_token.make_token(user)\n\n if option == 0:\n email_subject_template = 'accounts/acc_user_email.html'\n email = user_form.cleaned_data['email']\n else:\n email_subject_template = 'accounts/acc_moderator_email.html'\n email = settings.ADMIN_EMAIL\n\n moderator_request = models.PendingModerator(\n first_name=user_form.cleaned_data['first_name'],\n last_name=user_form.cleaned_data['last_name'],\n username=user_form.cleaned_data['username'],\n rank=profile_form.cleaned_data['rank'],\n )\n moderator_request.save()\n\n message = render_to_string(email_subject_template, {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': uid,\n 'token': token,\n })\n\n send_mail(\n 'Activate the account',\n message,\n settings.EMAIL_HOST_USER,\n [email]\n )\n\n if option == 0:\n user_flag = 0\n else:\n user_flag = 1\n return render(request, 'accounts/complete_register.html', {'flag': user_flag})\n else:\n print(user_form.errors, profile_form.errors)\n else:\n user_form = forms.UserForm\n\n if option == 0:\n profile_form = forms.UserProfileForm\n else:\n profile_form = forms.ModeratorProfileForm\n tab = 1\n\n context = {\n 'user_form': user_form,\n 'profile_form': profile_form,\n 'tab': tab,\n }\n return render(request, 'accounts/register.html', context=context)\n\n\n'''\n =====================\n ********LOGIN********\n =====================\n'''\n\n\ndef user_login(request):\n if request.user.is_authenticated:\n\n if request.user.is_superuser:\n return HttpResponseRedirect(reverse('admin:index'))\n else:\n if request.user.is_staff:\n return HttpResponseRedirect(reverse(settings.M_LOGIN_REDIRECT_URL))\n else:\n return HttpResponseRedirect(reverse(settings.LOGIN_REDIRECT_URL))\n else:\n if request.method == \"POST\":\n username = request.POST.get('username')\n password = request.POST.get('password')\n try:\n my_user = models.User.objects.get(username=username)\n except models.User.DoesNotExist:\n my_user = None\n\n if my_user is not None:\n if my_user.is_active:\n user = authenticate(username=username, password=password)\n if user:\n login(request, user)\n\n if request.user.is_superuser:\n return HttpResponseRedirect(reverse('admin:index'))\n else:\n if request.user.is_staff:\n return HttpResponseRedirect(reverse(settings.M_LOGIN_REDIRECT_URL))\n else:\n return HttpResponseRedirect(reverse(settings.LOGIN_REDIRECT_URL))\n else:\n return render(request, 'accounts/index.html', {'login_err': 1})\n else:\n return HttpResponseRedirect(reverse('accounts:regConfirm'))\n else:\n return render(request, 'accounts/index.html', {'login_err': 1})\n else:\n return render(request, 'accounts/index.html')\n\n\n@login_required\ndef user_logout(request):\n logout(request)\n return HttpResponseRedirect(reverse('accounts:index'))\n\n\ndef get_chart_data(request):\n user = request.user\n user_profile = models.UserProfile.objects.get(user=user)\n history = History.objects.filter(user=user_profile).order_by('-date')[:10]\n chart_data = dict()\n counter = 1\n for entry in reversed(history):\n label = 'Q' + str(counter)\n chart_data[label] = entry.score\n counter += 1\n context = {\n 'chart_data': chart_data\n }\n return JsonResponse(context)\n\n\ndef get_chart_data_moderator(request, pk):\n user = models.User.objects.get(pk=pk)\n user_profile = models.UserProfile.objects.get(user=user)\n history = History.objects.filter(user=user_profile).order_by('-date')[:10]\n chart_data = dict()\n counter = 1\n for entry in reversed(history):\n label = 'Q' + str(counter)\n chart_data[label] = entry.score\n counter += 1\n context = {\n 'chart_data': chart_data\n }\n return JsonResponse(context)\n\n\n'''\n ==================================\n ********ACCOUNT ACTIVATION********\n ==================================\n'''\n\n# Adaptat dupa https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef\n\n\ndef activate(request, uid, token):\n try:\n decoded_uid = urlsafe_base64_decode(uid).decode()\n user = models.User.objects.get(pk=decoded_uid)\n except(TypeError, ValueError, OverflowError, models.User.DoesNotExist):\n user = None\n if user is not None and tokens.account_activation_token.check_token(user, token):\n user.is_active = True\n user.save()\n login(request, user)\n return render(request, 'accounts/activation_response.html', {'success': 1})\n else:\n return render(request, 'accounts/activation_response.html', {'success': 0})\n\n\n# Adaptat dupa https://medium.com/@frfahim/django-registration-with-confirmation-email-bb5da011e4ef\ndef send_activation_link(request):\n flag = 0\n option = 0\n email = request.GET.get('email')\n try:\n user = models.User.objects.get(email=email)\n except models.User.DoesNotExist:\n user = None\n if user:\n if not user.is_active:\n current_site = get_current_site(request)\n uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()\n token = tokens.account_activation_token.make_token(user)\n\n try:\n user_profile = models.ModeratorProfile.objects.get(user=user)\n except models.ModeratorProfile.DoesNotExist:\n option = 1\n\n if option == 1:\n email_subject_template = 'accounts/acc_user_email.html'\n email = user.email\n else:\n email_subject_template = 'accounts/acc_moderator_email.html'\n email = settings.ADMIN_EMAIL\n\n message = render_to_string(email_subject_template, {\n 'user': user,\n 'domain': current_site.domain,\n 'uid': uid,\n 'token': token,\n })\n\n send_mail(\n 'Activate the account',\n message,\n settings.EMAIL_HOST_USER,\n [email]\n )\n flag = 1\n else:\n flag = -1\n context = {\n 'flag': flag,\n }\n return JsonResponse(context)\n\n\n'''\n ==========================\n ********GROUP CRUD********\n ==========================\n'''\n\n\nclass GroupListViewCRUD(UserPassesTestMixin, LoginRequiredMixin, ListView):\n model = models.Group\n template_name = 'accounts/CRUD/group_control_panel.html'\n context_object_name = 'entries'\n paginate_by = 5\n queryset = models.Group.objects.all().order_by('group')\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(GroupListViewCRUD, self).get_context_data(**kwargs)\n user = self.request.user\n context['tableRows'] = 'Group'\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'Group'\n return context\n\n\nclass GroupCreateView(UserPassesTestMixin, LoginRequiredMixin, CreateView):\n model = models.Group\n fields = ['group']\n success_url = reverse_lazy('accounts:CRUD_group')\n template_name = 'accounts/CRUD/generic_create_update_form.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(GroupCreateView, self).get_context_data(**kwargs)\n user = self.request.user\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'Group'\n context['method'] = 'Creation'\n return context\n\n\nclass GroupUpdateView(UserPassesTestMixin, LoginRequiredMixin, UpdateView):\n model = models.Group\n fields = ['group']\n success_url = reverse_lazy('accounts:CRUD_group')\n template_name = 'accounts/CRUD/generic_create_update_form.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(GroupUpdateView, self).get_context_data(**kwargs)\n user = self.request.user\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'Group'\n context['method'] = 'Editing'\n return context\n\n\nclass GroupDeleteView(UserPassesTestMixin, LoginRequiredMixin, DeleteView):\n model = models.Group\n success_url = reverse_lazy('accounts:CRUD_group')\n template_name = 'accounts/CRUD/generic_confirm_delete.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(GroupDeleteView, self).get_context_data(**kwargs)\n delete_flag = False\n user = self.request.user\n group = models.Group.objects.get(pk=self.kwargs.get('pk'))\n try:\n q = models.UserProfile.objects.filter(group=group).count()\n except models.UserProfile.DoesNotExist:\n q = 0\n if q == 0:\n delete_flag = True\n context['delete_flag'] = delete_flag\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'group'\n return context\n\n\n'''\n ===========================\n *******YEAR CRUD*******\n ===========================\n'''\n\n\nclass YearListViewCRUD(UserPassesTestMixin, LoginRequiredMixin, ListView):\n model = models.Year\n template_name = 'accounts/CRUD/year_control_panel.html'\n context_object_name = 'entries'\n paginate_by = 5\n queryset = models.Year.objects.all().order_by('year')\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(YearListViewCRUD, self).get_context_data(**kwargs)\n\n user = self.request.user\n context['tableRows'] = 'Year'\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'Year'\n return context\n\n\nclass YearCreateView(UserPassesTestMixin, LoginRequiredMixin, CreateView):\n model = models.Year\n fields = ['year']\n success_url = reverse_lazy('accounts:CRUD_year')\n template_name = 'accounts/CRUD/generic_create_update_form.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(YearCreateView, self).get_context_data(**kwargs)\n user = self.request.user\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'Year'\n context['method'] = 'Creation'\n return context\n\n\nclass YearUpdateView(UserPassesTestMixin, LoginRequiredMixin, UpdateView):\n model = models.Year\n fields = ['year']\n success_url = reverse_lazy('accounts:CRUD_year')\n template_name = 'accounts/CRUD/generic_create_update_form.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(YearUpdateView, self).get_context_data(**kwargs)\n user = self.request.user\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'Year'\n context['method'] = 'Editing'\n return context\n\n\nclass YearDeleteView(UserPassesTestMixin, LoginRequiredMixin, DeleteView):\n model = models.Year\n success_url = reverse_lazy('accounts:CRUD_year')\n template_name = 'accounts/CRUD/generic_confirm_delete.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(YearDeleteView, self).get_context_data(**kwargs)\n delete_flag = False\n user = self.request.user\n year = models.Year.objects.get(pk=self.kwargs.get('pk'))\n try:\n q = models.UserProfile.objects.filter(year=year).count()\n except models.UserProfile.DoesNotExist:\n q = 0\n if q == 0:\n delete_flag = True\n context['delete_flag'] = delete_flag\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'year'\n return context\n\n\n'''\n ===========================\n *******ACADEMIC CRUD*******\n ===========================\n'''\n\n\nclass AcademicRankListViewCRUD(UserPassesTestMixin, LoginRequiredMixin, ListView):\n model = models.AcademicRank\n template_name = 'accounts/CRUD/academicRank_control_panel.html'\n context_object_name = 'entries'\n paginate_by = 5\n queryset = models.AcademicRank.objects.all().order_by('rank')\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(AcademicRankListViewCRUD, self).get_context_data(**kwargs)\n\n user = self.request.user\n context['tableRows'] = 'Rank Priority-Number'\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'AcademicRank'\n return context\n\n\nclass AcademicRankCreateView(UserPassesTestMixin, LoginRequiredMixin, CreateView):\n model = models.AcademicRank\n fields = ['rank', 'number']\n success_url = reverse_lazy('accounts:CRUD_academicRank')\n template_name = 'accounts/CRUD/generic_create_update_form.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(AcademicRankCreateView, self).get_context_data(**kwargs)\n user = self.request.user\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'AcademicRank'\n context['method'] = 'Creation'\n return context\n\n\nclass AcademicRankUpdateView(UserPassesTestMixin, LoginRequiredMixin, UpdateView):\n model = models.AcademicRank\n fields = ['rank', 'number']\n success_url = reverse_lazy('accounts:CRUD_academicRank')\n template_name = 'accounts/CRUD/generic_create_update_form.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(AcademicRankUpdateView, self).get_context_data(**kwargs)\n user = self.request.user\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'AcademicRank'\n context['method'] = 'Editing'\n return context\n\n\nclass AcademicRankDeleteView(UserPassesTestMixin, LoginRequiredMixin, DeleteView):\n model = models.AcademicRank\n success_url = reverse_lazy('accounts:CRUD_academicRank')\n template_name = 'accounts/CRUD/generic_confirm_delete.html'\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(AcademicRankDeleteView, self).get_context_data(**kwargs)\n delete_flag = False\n user = self.request.user\n rank = models.AcademicRank.objects.get(pk=self.kwargs.get('pk'))\n try:\n q = models.ModeratorProfile.objects.filter(rank=rank).count()\n except models.ModeratorProfile.DoesNotExist:\n q = 0\n if q == 0:\n delete_flag = True\n context['delete_flag'] = delete_flag\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'academic'\n return context\n\n\n'''\n ===========================\n *******USERS CRUD*******\n ===========================\n'''\n\n\nclass UsersListViewCRUD(UserPassesTestMixin, LoginRequiredMixin, ListView):\n model = models.UserProfile\n template_name = 'accounts/CRUD/users_control_panel.html'\n context_object_name = 'entries'\n paginate_by = 9\n queryset = models.UserProfile.objects.all().order_by('-year', 'group')\n\n def test_func(self):\n user = self.request.user\n return user.is_staff\n\n def get_context_data(self, **kwargs):\n context = super(UsersListViewCRUD, self).get_context_data(**kwargs)\n\n user = self.request.user\n context['tableRows'] = 'Username Registration-No Year Group Mark Points Status'\n context['UserProfile'] = models.ModeratorProfile.objects.get(user=user)\n context['table'] = 'Users'\n return context\n","sub_path":"accounts_module/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":23669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"151871614","text":"import json\nimport os.path\nimport csv\nimport jwt\nimport base64\nimport math\nimport hashlib\nfrom flask import Flask\nfrom flask import request, make_response, jsonify\nfrom flask_mysqldb import MySQL\nimport jwt\napp = Flask(__name__)\napp.config['MYSQL_USER'] = 'root'\napp.config['MYSQL_PASSWORD'] = 'Stupid@55655'\napp.config['MYSQL_DB'] = 'region'\napp.config['MYSQL_CURSORCLASS'] = 'DictCursor'\nmysql = MySQL(app)\n \n\n\n# function to get all distinct countries\n@app.route(\"/getCountries\")\ndef getCountries():\n token = request.headers.get(\"Authorization\")\n ans = loggedPerson(token)\n if ans:\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"SELECT distinct(name) from countries \"\"\"\n )\n countries = cursor.fetchall()\n print(countries)\n cursor.close()\n return jsonify(countries)\n else:\n return ({\"message\": \"No Country\"})\n\n\n# function to delete a country\n@app.route(\"/deleteCountry//\")\ndef deleteCountry(idx, stat_id):\n print(\"here\")\n token = request.headers.get(\"Authorization\")\n ans = loggedPerson(token)\n if ans:\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"DELETE FROM info where id=%s\"\"\", (stat_id,)\n )\n cursor.connection.commit()\n cursor.close()\n print(\"query exceuted\")\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"DELETE FROM place where id=%s\"\"\", (idx,)\n )\n cursor.connection.commit()\n cursor.close()\n return ({\"message\": \"Deleted\"})\n else:\n return ({\"message\": \"Not authorized\"})\n\n\n\n# function to get city details\n@app.route(\"/getStatDetails//\")\ndef getStatDetails(idx, stat_id):\n token = request.headers.get(\"Authorization\")\n ans = loggedPerson(token)\n if ans:\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\" SELECT * from info where id=%s and place_id=%s\"\"\", (\n stat_id, idx)\n )\n detail = cursor.fetchall()\n print(detail)\n cursor.connection.commit()\n cursor.close()\n return jsonify(detail)\n else:\n return ({\"message\": \"Bus not available\"})\n\n\n\n\n\n# function to update/edit city details\n@app.route(\"/updateStatDetails//\", methods=[\"POST\"])\ndef updateCityDetails(idx, stat_id):\n token = request.headers.get(\"Authorization\")\n ans = loggedPerson(token)\n if request.method == \"POST\":\n if ans:\n cursor = mysql.connection.cursor()\n print(request.json[\"population\"], request.json[\"income\"])\n cursor.execute(\n \"\"\" Update info set population=%s, income=%s where id=%s and place_id=%s\"\"\", (\n request.json[\"population\"], request.json[\"income\"], stat_id, idx)\n )\n cursor.connection.commit()\n cursor.close()\n return ({\"message\": \"Updated Successfully\"})\n else:\n return ({\"message\": \"No Cities\"})\n\n\n\n\n\n\n# function to add a country\n@app.route(\"/addCountry\", methods=[\"POST\"])\ndef addCountry():\n token = request.headers.get(\"Authorization\")\n ans = loggedPerson(token)\n if request.method == \"POST\":\n if ans:\n print(request.json[\"country\"])\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"INSERT INTO countries(id,name)values(NULL,%s)\"\"\", (\n request.json[\"country\"],)\n )\n cursor.connection.commit()\n cursor.close()\n return {\"message\": \"Added country\"}\n else:\n return ({\"message\": \"No Country\"})\n\n\n\n\n\n\n\n\n\n# function to check for availability of the city and aadding based on result\n@app.route(\"/addCity\", methods=[\"POST\"])\ndef addCity():\n token = request.headers.get(\"Authorization\")\n ans = loggedPerson(token)\n if request.method == \"POST\":\n if ans:\n cursor = mysql.connection.cursor()\n print(request.json[\"country\"], request.json[\"city\"])\n cursor.execute(\n \"\"\"SELECT * from place where country=%s and city=%s\"\"\", (\n request.json[\"country\"], request.json[\"city\"])\n )\n available = cursor.fetchall()\n cursor.connection.commit()\n cursor.close()\n print(available)\n if(not available):\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"INSERT INTO place(id,country,city) values(NULL,%s,%s)\"\"\", (\n request.json[\"country\"], request.json[\"city\"])\n )\n cursor.connection.commit()\n cursor.close()\n\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"SELECT id from place where country=%s and city=%s\"\"\", (\n request.json[\"country\"], request.json[\"city\"])\n )\n idx = cursor.fetchall()\n cursor.connection.commit()\n cursor.close()\n print(idx[0][\"id\"])\n\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"INSERT INTO info(id,place_id,population,income)values(NULL,%s,%s,%s)\"\"\", (int(\n idx[0][\"id\"]), request.json[\"population\"], request.json[\"income\"])\n )\n cursor.connection.commit()\n cursor.close()\n\n else:\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"SELECT id from place where country=%s and city=%s\"\"\", (\n request.json[\"place\"], request.json[\"city\"])\n )\n idx = cursor.fetchall()\n cursor.connection.commit()\n cursor.close()\n print(idx)\n\n cursor = mysql.connection.cursor()\n cursor.execute(\n \"\"\"INSERT INTO info(id,place_id,population,income)values(NULL,%s,%s,%s)\"\"\", (int(\n idx[0][\"id\"]), request.json[\"population\"], request.json[\"income\"])\n )\n cursor.connection.commit()\n cursor.close()\n return({\"message\": \"checked\"})\n\n\n\n# function to check pagination\n@app.route(\"/pagination\",methods=[\"POST\"])\ndef pagination():\n print(\"coming\")\n if request.method==\"POST\":\n\n token = request.headers.get(\"Authorization\")\n ans = loggedPerson(token)\n if ans:\n total_items = []\n cursor = mysql.connection.cursor()\n cursor.execute(\n # \"\"\" select terminal.id,bus.id as bus_id, source,destination,bus_no,schedule from terminal join bus on bus.terminal_id=terminal.id order by destination desc\"\"\"\n \"\"\" select place.id,info.id as stat_id, country,city,population,income from place join info on info.place_id=place.id order by country asc\"\"\"\n )\n\n total_items = cursor.fetchall()\n # count_pages=math.floor(total_items/request.json[\"dataPerPage\"])\n cursor.connection.commit()\n cursor.close() \n \n total_pages = math.ceil(len(total_items)/request.json[\"dataPerPage\"])\n prev_page_end = (request.json[\"activePage\"]-1) * request.json[\"dataPerPage\"]\n curr_page_end =request.json[\"activePage\"] *request.json[\"dataPerPage\"]\n curr_page_items = total_items[prev_page_end:curr_page_end]\n print(curr_page_items)\n return {\"total_pages\":total_pages,\"curr_page_items\":curr_page_items}\n else:\n return({\"message\":\"trying pagination\"})\n \n\n\nfrom user import user\nfrom registration import auth\nfrom registration import loggedPerson\napp.register_blueprint(auth, url_prefix=\"/auth\")\napp.register_blueprint(user, url_prefix=\"/user\")\n","sub_path":"submissions/sm_021_piyush-jain/week_23/evaluation/backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"612803397","text":"from django_filters import rest_framework as filters\nfrom django.db import models\nfrom showcase.models import Storyboard, Storyboarder, Tag\n\nclass StoryboardFilter(filters.FilterSet):\n\n storyboarder = filters.ModelMultipleChoiceFilter(\n name='storyboarder__username',\n to_field_name='username',\n queryset=Storyboarder.objects.all(),\n conjoined=True,\n )\n\n tags = filters.ModelMultipleChoiceFilter(\n name='tags__internal_id',\n to_field_name='internal_id',\n queryset=Tag.objects.all(),\n conjoined=True,\n )\n\n class Meta:\n model = Storyboard\n\n fields = ['song', 'artist', 'set_id',\n 'storyboarder', 'mapper',\n 'date_added', 'date_created',\n 'medium', 'tags']\n\n filter_overrides = {\n models.CharField: {\n 'filter_class': filters.CharFilter,\n 'extra': lambda f: {\n 'lookup_expr': 'icontains',\n }\n }\n }\n","sub_path":"osb_api/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"627032226","text":"from __future__ import absolute_import\nfrom __future__ import division\n## system\nfrom future import standard_library\nstandard_library.install_aliases()\nimport mpi4py\nfrom mpi4py import MPI\nimport os\nimport numpy as np\nimport time\nimport io\nimport traceback\nimport copy\nimport collections\nimport logging\n\n## this package\nfrom . import CommSystemUtil\nfrom . import PsanaUtil\nfrom .MessageBuffers import SM_MsgBuffer, MVW_MsgBuffer\nfrom . import Timing\nfrom .XCorrBase import XCorrBase\nfrom . import Counter120hz\n\nMPI4PY_200 = mpi4py.__version__.startswith('2')\n\n########## for Timing.timecall\nVIEWEREVT = 'update'\nCSPADEVT = 'cspadevt'\ntimingorder =[] # list of names in order inserted\ntimingdict = {}\n###########\n\ndef roundRobin(n, dictData):\n '''returns list from dict by round robin over keys\n \n Args:\n n (int): length of list to return\n dictData (dict): values are lists to select return items from\n\n Returns:\n list: n items from values of dictData\n\n Examples:\n >>> roundRobin(5, {'keyA':[1,2,3], 'keyB':[10,20,30]})\n [1,10,2,20,3]\n '''\n if n==0:\n return []\n keys = list(dictData.keys())\n keys.sort()\n assert len(keys)>0, \"rounRobin will fail to find n=%d items from empty dict\" % n\n nextVal = dict([(ky,0) for ky in keys])\n results = []\n keyIndex = 0\n keysWithAllValuesUsed = set()\n while len(results)= numServers+int(excludeRank0), \\\n \"To many servers requested for MPI World. numServers=%d. MPI World Size=%d. excludeRank0=%d\" % \\\n (numServers, comm.Get_size(), excludeRank0)\n\n if serverHosts is None:\n serverHosts = []\n\n ## identify host -> rank map through collective MPI communication\n localHostName = MPI.Get_processor_name()\n allHostNames = []\n if MPI4PY_200:\n allHostNames = comm.allgather(localHostName)\n else:\n allHostNames = comm.allgather(localHostName, None)\n assert len(allHostNames) == comm.Get_size(), 'allgather failed - did not get one host per rank'\n serverHost2ranks = collections.defaultdict(list)\n for ii, hostName in enumerate(allHostNames):\n if excludeRank0 and ii==0:\n continue\n serverHost2ranks[hostName].append(ii)\n\n hostsNotFound = [host for host in serverHosts if host not in serverHost2ranks.keys()]\n for host in hostsNotFound:\n if MPI.Get_rank()==0:\n if host == allHostNames[0] and excludeRank0:\n sys.write(\"WARNING specified server host: %s only had rank 0 on it. rank 0 is reserved. Host will not be used for a server.\")\n else:\n sys.write(\"WARNING specified host: %s was not found in MPI World.\" % host)\n\n if len(serverHosts) == 0:\n ranksForRoundRobin = serverHost2ranks\n else:\n ranksForRoundRobin = dict()\n for host in serverHosts:\n if host in hostsNotFound:\n continue\n ranksForRoundRobin[host]=serverHost2ranks[host]\n\n serverRanks = roundRobin(numServers, ranksForRoundRobin)\n\n hostmsg = 'server host assignment:'\n rank2host=collections.defaultdict(list)\n for host,rankList in serverHost2ranks.items():\n for rank in rankList:\n rank2host[rank].append(host)\n\n hostmsg += \", \".join([\"rnk=%d->host=%s\" % (rank, rank2host[rank]) for rank in serverRanks \\\n if rank in serverRanks])\n return serverRanks, hostmsg\n\nclass MPI_Communicators(object):\n '''Keeps track of the different communicators for collective\n communications. Includes many parameters that identify the ranks\n and the communicators they are in.\n\n Call identifyCommSubsystems to return a initialized instance or\n getTestingMPIObject()\n\n Then call the method setMask.\n '''\n def __init__(self):\n pass\n\n def setLogger(self, verbosity):\n self.logger = CommSystemUtil.makeLogger(self.testMode, self.isMaster, \\\n self.isViewer, self.isServer, self.rank, verbosity)\n\n def notWorker2toN(self):\n if self.isWorker and not self.isFirstWorker:\n return False\n return True\n\n # these functions make it simpler to exclude logging from all the workers.\n # all workers generally do the same thing. If they all logged it gets noisy.\n def logInfo(self, msg, allWorkers=False):\n '''By default logs a message only from worker one\n '''\n if allWorkers or self.notWorker2toN():\n self.logger.info(msg)\n\n def logWarning(self, msg, allWorkers=False):\n '''By default logs a message only from worker one\n '''\n if allWorkers or self.notWorker2toN():\n self.logger.warning(msg)\n\n def logDebug(self, msg, allWorkers=False):\n '''By default logs a message only from worker one\n '''\n if allWorkers or self.notWorker2toN():\n self.logger.debug(msg)\n\n def logError(self, msg, allWorkers=False):\n '''By default logs a message only from worker one\n '''\n if allWorkers or self.notWorker2toN():\n self.logger.error(msg)\n\n\n def setMask(self, maskNdarrayCoords):\n '''sets scatterv parameters and stores mask\n\n Args:\n maskNdarrayCoords (numpy.ndarray): integer array, 1 for elements that should be processed. \n It must have the same shape as the NDArray for the detector.\n\n Notes:\n sets the following attributes\n\n * totalElements: number of pixels that are 1 in the mask\n * workerWorldRankToCount[rank]: number of element that worker processes\n * workerWorldRankToOffset[rank]: offset of where those elements start in \n a flattened version of the ndarray\n * maskNdarrayCoords: the mask as a logical True/False array\n shape has not been changed\n\n '''\n mask_flat = maskNdarrayCoords.flatten()\n maskValues = set(mask_flat)\n assert maskValues.union(set([0,1])) == set([0,1]), \"mask contains values other than 0 and 1.\" + \\\n (\" mask contains %d distinct values\" % len(maskValues))\n assert 1 in maskValues, \"The mask does not have the value 1, it is all 0. Elements marked with 1 are processed\"\n self.totalElements = np.sum(mask_flat)\n self.maskNdarrayCoords = maskNdarrayCoords == 1 # is is important to convert mask to array of bool, np.bool\n\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logDebug(\"MPIParams.setMask: loaded and stored mask with shape=%s elements included=%d excluded=%s\" % \\\n (self.maskNdarrayCoords.shape, np.sum(self.maskNdarrayCoords),\n np.sum(0==self.maskNdarrayCoords)))\n\n workerOffsets, workerCounts = CommSystemUtil.divideAmongWorkers(self.totalElements, \n self.numWorkers)\n assert self.numWorkers == len(self.workerRanks)\n assert len(workerCounts)==self.numWorkers\n\n self.workerWorldRankToCount = {}\n self.workerWorldRankToOffset = {}\n\n for workerRank, workerOffset, workerCount in zip(self.workerRanks,\n workerOffsets,\n workerCounts):\n self.workerWorldRankToCount[workerRank] = workerCount\n self.workerWorldRankToOffset[workerRank] = workerOffset\n\n for serverRank in self.serverRanks:\n serverCommDict = self.serverWorkers[serverRank]\n serverRankInComm = serverCommDict['serverRankInComm']\n scatterCounts = copy.copy(workerCounts)\n serverCount = 0\n scatterCounts.insert(serverRankInComm, serverCount)\n scatterOffsets = copy.copy(workerOffsets)\n # the value we use for the server offset is not important, but checkCountsOffsets\n # which we call below checks for offset[i+1]=offset[i]+count[i]\n if serverRankInComm == 0:\n serverOffset = 0\n else:\n serverOffset = workerOffsets[serverRankInComm-1]+workerCounts[serverRankInComm-1]\n scatterOffsets.insert(serverRankInComm, serverOffset)\n self.serverWorkers[serverRank]['groupScattervCounts'] = tuple(scatterCounts)\n self.serverWorkers[serverRank]['groupScattervOffsets'] = tuple(scatterOffsets)\n CommSystemUtil.checkCountsOffsets(scatterCounts, scatterOffsets, self.totalElements)\n\ndef getTestingMPIObject():\n '''mock up MPI_Communicators object for test_alt mode.\n \n Simulate an MPI_Communicators which looks like a single server/worker/viewer as being the\n same rank.\n '''\n mp = MPI_Communicators()\n mp.isServer = True\n mp.isWorker = True\n mp.isFirstWorker = True\n mp.isFirstServer = True\n mp.isViewer = True\n mp.isMaster = False\n mp.testMode = True\n mp.rank = MPI.COMM_WORLD.rank\n assert mp.rank == 0, \"test MPI object is for non-MPI environment, but MPI world rank != 0\"\n mp.workerRanks = [mp.rank]\n mp.numWorkers = 1\n mp.serverRanks = [0]\n mp.serverWorkers = {}\n mp.serverWorkers[0]={'serverRankInComm':0}\n mp.viewerRankInViewerWorkersComm = 0\n return mp\n\ndef identifyCommSubsystems(serverRanks, worldComm=None):\n '''Return a fully initialized instance of a MPI_Communicators object\n The object will contain the following attributes::\n\n serverRanks - ranks that are servers in worldComm\n comm - duplicate of the worldComm\n rank - rank in worldComm\n worldNumProcs - size of worldComm\n masterRank - master rank in worldComm\n viewerRank - viewer rank in worldComm\n workerRanks - list of worker ranks in worldComm\n firstWorkerRank - first worker rank in worldComm\n numWorkers - number of workers\n\n # these parameters identify which group this rank is\n isMaster\n isViewer\n isServer\n isFirstWorker\n isWorker\n\n isTestMode = False\n\n masterWorkersComm - intra communicator for master/workers collective communication\n viewerWorkersComm - intra communicator for viewer/workers collective communication\n viewerRankInViewerWorkersComm - viewer rank in the above intra-communicator\n firstWorkerRankInViewerWorkersComm - first worker rank in the above intra-communicator\n\n # the following is a dict with one key for each server rank\n serverWorkers[serverRank]['comm'] - intra communicator, this server and all workers\n serverWorkers[serverRank]['serverRankInComm'] - this server rank in the comm\n serverWorkers[serverRank]['workerRanksInCommDict'] - a key for this dict is a\n worker rank in the world space. The value is the rank in the 'comm' value\n '''\n assert len(serverRanks) > 0, \"need at least one server\"\n assert min(serverRanks) >= 0, \"cannot have negative server ranks\"\n if worldComm is None:\n worldComm = MPI.COMM_WORLD\n\n mc = MPI_Communicators()\n mc.testMode = False\n mc.serverRanks = serverRanks\n mc.comm = worldComm.Dup()\n mc.rank = mc.comm.Get_rank()\n mc.worldNumProcs = mc.comm.Get_size()\n assert mc.worldNumProcs >= 4, \"need at least 4 ranks for comm system (server/master/viewer/workers)\"\n assert mc.worldNumProcs - len(mc.serverRanks) >= 3, \"With %d servers but only %d ranks in world, not enough ranks for worker/viewer/master\" % \\\n (len(mc.serverRanks), mc.worldNumProcs)\n availRanks = [rank for rank in range(mc.worldNumProcs) \\\n if rank not in mc.serverRanks]\n assert len(availRanks)>=3, \"To many servers for world size. \" + \\\n (\"Only %d ranks left for master/viewer/workers\" % len(availRanks))\n mc.viewerRank = min(availRanks)\n availRanks.remove(mc.viewerRank)\n mc.masterRank = min(availRanks)\n availRanks.remove(mc.masterRank)\n mc.workerRanks = availRanks\n mc.firstWorkerRank = min(mc.workerRanks)\n mc.firstServerRank = min(mc.serverRanks)\n\n mc.isMaster = mc.rank == mc.masterRank\n mc.isViewer = mc.rank == mc.viewerRank\n mc.isServer = mc.rank in mc.serverRanks\n mc.isFirstWorker = mc.rank == mc.firstWorkerRank\n mc.isFirstServer = mc.rank == mc.firstServerRank\n mc.isWorker = mc.rank not in ([mc.masterRank, mc.viewerRank] + mc.serverRanks)\n mc.numWorkers = len(mc.workerRanks)\n \n worldGroup = mc.comm.Get_group()\n masterWorkersGroup = worldGroup.Excl([mc.viewerRank] + mc.serverRanks)\n viewerWorkersGroup = worldGroup.Excl([mc.masterRank] + mc.serverRanks)\n\n mc.masterWorkersComm = mc.comm.Create(masterWorkersGroup) # will be an invalid group on proc with viewer\n mc.viewerWorkersComm = mc.comm.Create(viewerWorkersGroup) # will be an invalid group on proc with master\n\n mc.serverWorkers = dict()\n for serverRank in mc.serverRanks:\n otherServers = [rank for rank in mc.serverRanks if rank != serverRank]\n serverWorkersGroup = worldGroup.Excl([mc.viewerRank, mc.masterRank]+otherServers)\n serverRankInComm = MPI.Group.Translate_ranks(worldGroup, [serverRank],\n serverWorkersGroup)[0]\n workerRanksInComm = MPI.Group.Translate_ranks(worldGroup, mc.workerRanks,\n serverWorkersGroup)\n workerRanksInCommDict = dict(zip(mc.workerRanks,workerRanksInComm))\n serverWorkersComm = mc.comm.Create(serverWorkersGroup)\n \n mc.serverWorkers[serverRank]={'comm':serverWorkersComm,\n 'serverRankInComm':serverRankInComm,\n 'workerRanksInCommDict':workerRanksInCommDict,\n }\n \n tmp1,tmp2 = MPI.Group.Translate_ranks(worldGroup, [mc.firstWorkerRank, mc.viewerRank], \n viewerWorkersGroup)\n mc.firstWorkerRankInViewerWorkersComm,mc.viewerRankInViewerWorkersComm = tmp1,tmp2\n tmp1,tmp2 = MPI.Group.Translate_ranks(worldGroup, [mc.firstWorkerRank, mc.masterRank], \n masterWorkersGroup)\n mc.firstWorkerRankInMasterWorkersComm, mc.masterRankInMasterWorkersComm = tmp1,tmp2\n\n return mc\n\nclass ScatterDataQueue(object):\n '''queue of event data to scatter. Helper for servers.\n\n After a server gets data and tells the master its timestamp, it will work on adding\n a new array to the queue.\n '''\n def __init__(self, maskToCopyOutData, dtypeForScatter, logger):\n assert maskToCopyOutData.dtype == np.bool\n self.maskToCopyOutData = maskToCopyOutData\n self.numElements = np.sum(maskToCopyOutData)\n self.dtypeForScatter = dtypeForScatter\n self.iterDataQueue = []\n self.scatterDataQueue = []\n self.logger = logger\n\n def empty(self):\n assert len(self.iterDataQueue)==len(self.scatterDataQueue), \"ScatterDataQueue: internal lists are not the same length\"\n return len(self.iterDataQueue) == 0\n\n def nextEventId(self):\n assert not self.empty(), \"ScatterDataQueue: nextEventId called on non-empty data\"\n return self.iterDataQueue[0].eventId()\n\n def popHead(self):\n assert not self.empty(), \"ScatterDataQueue: popHead called on non-empty data\"\n assert len(self.iterDataQueue)==len(self.scatterDataQueue), \"ScatterDataQueue: internal lists are not the same length\"\n datum = self.iterDataQueue.pop(0)\n scatter1Darray = self.scatterDataQueue.pop(0)\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"ScatterDataQueue: popHead %s\" % datum)\n return scatter1Darray\n\n def addFrom(self, dataGen, num):\n assert len(self.iterDataQueue)==len(self.scatterDataQueue), \"ScatterDataQueue: internal lists are not the same length\"\n while num > 0:\n try:\n datum = next(dataGen)\n except StopIteration:\n self.logger.debug(\"ScatterDataQueue: addFrom: dataGen is empty\")\n return\n scatterData = np.zeros(self.numElements, dtype=self.dtypeForScatter)\n scatterData[:] = datum.dataArray[self.maskToCopyOutData]\n self.iterDataQueue.append(datum)\n self.scatterDataQueue.append(scatterData)\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"ScatterDataQueue: addFrom %s\" % datum)\n num -= 1\n \nclass RunServer(object):\n '''runs server rank\n\n This function carries out the server side communication in the package.\n It does the following\n\n ::\n \n * iteratates through data in Python generator argument\n * for each datum from generator:\n ** sends sec/nsec to master\n ** gets OkForWorkers or Abort from master\n ** upon OkForWorkers calls .sendToWorkers(datum) method in dataIterator\n The dataIterator handles details such as scattering detector data to workers\n\n Args:\n dataIter: instance of a callback class. Must provide these methods:\n .dataGenerator() a Python generator. Each returned object\n must have a time() returning sec,nsec\n .sendToWorkers(datum) receives a datum returned by dataGenerator.\n user can now send data to workers\n workers will know the upcoming time already\n comm: MPI intra-communicator for server ranks and master rank.\n rank: rank of this server\n masterRank: rank of master\n logger: Python logging logger\n '''\n def __init__(self, dataIter, xCorrBase, comm, rank, masterRank, logger):\n self.dataIter = dataIter\n self.xCorrBase = xCorrBase\n self.comm = comm\n self.rank = rank\n self.masterRank = masterRank\n self.logger = logger\n self.dataGen = None\n self.scatterDataQueue = None\n\n @Timing.timecall(timingDict=timingdict)\n def addDataToScatterQueue(self):\n self.scatterDataQueue.addFrom(self.dataGen, 1)\n \n @Timing.timecall(timingDict=timingdict)\n def sendEventReadyToMaster(self, sendEventReadyBuffer):\n sec, nsec, fiducials = self.scatterDataQueue.nextEventId()\n sendEventReadyBuffer.setEventId(sec, nsec, fiducials)\n if self.logger.isEnabledFor(logging.DEBUG):\n debugMsg = \"RunServer: data to scatter,\"\n debugMsg += \" Event Id: sec=0x%8.8X nsec=0x%8.8X fid=0x%5.5X.\" % (sec, nsec, fiducials)\n debugMsg += \" Before Send EVT\"\n self.logger.debug(debugMsg)\n self.comm.Send([sendEventReadyBuffer.getNumpyBuffer(),\n sendEventReadyBuffer.getMPIType()],\n dest=self.masterRank)\n self.logger.debug(\"RunServer: After Send, before Recv, first adding to Queue\")\n \n @Timing.timecall(timingDict=timingdict)\n def receiveMessageFromMaster(self, receiveOkForWorkersBuffer):\n self.comm.Recv([receiveOkForWorkersBuffer.getNumpyBuffer(), \n receiveOkForWorkersBuffer.getMPIType()],\n source=self.masterRank)\n\n @Timing.timecall(timingDict=timingdict)\n def scatterToWorkers(self):\n self.logger.debug(\"RunServer: about to scatter to workers\")\n toScatter1DArray = self.scatterDataQueue.popHead()\n self.xCorrBase.serverWorkersScatter(detectorData1Darray=toScatter1DArray, \n serverWorldRank=None)\n\n def run(self):\n sendEventReadyBuffer = SM_MsgBuffer(rank=self.rank)\n sendEventReadyBuffer.setEvt()\n receiveOkForWorkersBuffer = SM_MsgBuffer(rank=self.rank)\n abortFromMaster = False\n self.dataGen = self.dataIter.dataGenerator()\n self.scatterDataQueue=ScatterDataQueue(self.xCorrBase.mp.maskNdarrayCoords, np.float32, self.logger)\n initialQueueSize = 1\n\n while initialQueueSize > 0:\n initialQueueSize -= 1\n self.addDataToScatterQueue()\n\n while not self.scatterDataQueue.empty():\n self.sendEventReadyToMaster(sendEventReadyBuffer)\n # master is most likely telling one of the other servers to scatter right now.\n # read new data before waiting to be told to scatter\n self.addDataToScatterQueue()\n self.receiveMessageFromMaster(receiveOkForWorkersBuffer)\n if receiveOkForWorkersBuffer.isSendToWorkers():\n self.scatterToWorkers()\n elif receiveOkForWorkersBuffer.isAbort():\n self.logger.debug(\"RunServer: After Recv. Abort\")\n abortFromMaster = True\n break\n else:\n raise Exception(\"unknown msgtag from master. buffer=%r\" % receiveOkForWorkersBuffer)\n\n if abortFromMaster:\n self.dataIter.abortFromMaster()\n else:\n sendEventReadyBuffer.setEnd()\n self.logger.debug(\"CommSystem.run: Before Send END\")\n self.comm.Send([sendEventReadyBuffer.getNumpyBuffer(), \n sendEventReadyBuffer.getMPIType()],\n dest=self.masterRank)\n self.logger.debug(\"CommSystem.run: After Send END. Finished\")\n\nclass RunMaster(object):\n '''runs master message passing.\n '''\n def __init__(self, worldComm, masterRank, viewerRank, serverRanks, serversRoundRobin,\n masterWorkersComm, masterRankInMasterWorkersComm,\n updateIntervalEvents, hostmsg, logger):\n\n self.worldComm = worldComm\n self.masterRank = masterRank\n self.serverRanks = serverRanks\n self.serversRoundRobin = serversRoundRobin\n self.masterWorkersComm = masterWorkersComm\n self.masterRankInMasterWorkersComm = masterRankInMasterWorkersComm\n self.updateIntervalEvents = updateIntervalEvents\n self.worldComm = worldComm\n self.viewerRank = viewerRank\n self.logger = logger\n self.logger.info(hostmsg)\n\n # initially all servers are not ready\n self.notReadyServers = [r for r in serverRanks] # MPI Test on request is false\n self.readyServers = [] # MPI Test on request is True\n self.finishedServers = [] # rank has returend end\n\n self.sendOkForWorkersBuffer = SM_MsgBuffer()\n self.bcastWorkersBuffer = MVW_MsgBuffer()\n self.viewerBuffer = MVW_MsgBuffer()\n self.lastUpdate = 0\n self.numEvents = 0\n \n self.eventIdToCounter = None\n\n def getNextServerData(self, serverDataList, lastServerRank):\n '''Takes a list of server data buffers. identifies next server. \n\n Ordinarily, does a round robin on the servers, based on the lastServerRank.\n However if serversRoundRobin is False, or lastServerRank is None, picks the\n server with the earliest timestamp.\n\n ARGS:\n serverDataList: each element is a SeversMasterMessaging buffer\n lastServerRank: rank of last server used.\n RET:\n the buffer with the earliest time\n '''\n if self.serversRoundRobin and lastServerRank is not None:\n ranksAndPos = [(serverData.getRank(),ii) for ii,serverData in enumerate(serverDataList)]\n ranksAndPos.sort()\n ranks = [pair[0] for pair in ranksAndPos]\n positions = [pair[1] for pair in ranksAndPos]\n try:\n ranks.index(lastServerRank)\n except ValueError:\n return serverDataList[positions[0]]\n nextServerPositionInRoundRobin = ((1 + ranks.index(lastServerRank)) % len(serverDataList))\n nextServerData = serverDataList[positions[nextServerPositionInRoundRobin]]\n return nextServerData\n \n earliestIdx = 0\n sec, nsec, fiducials = serverDataList[earliestIdx].getEventId()\n for candIdx in range(1,len(serverDataList)):\n curSec, curNsec, curFiducials = serverDataList[candIdx].getEventId()\n earlierByTime = False\n if (curSec < sec) or ((curSec == sec) and (curNsec < nsec)):\n earlierByTime = True\n # TODO: should also check if earlier by fiducial\n if earlierByTime:\n sec = curSec\n nsec = curNsec\n fiducials = curFiducials\n earliestIdx = candIdx\n return serverDataList[earliestIdx]\n \n def initRecvRequestsFromServers(self):\n # create buffers for receiving, and the requests\n serverReceiveData = dict()\n serverRequests = dict()\n self.logger.debug(\"CommSystem: before first Irecv from servers\")\n for serverRank in self.serverRanks:\n serverReceiveBuffer = SM_MsgBuffer(rank=serverRank)\n firstServerRequest = self.worldComm.Irecv([serverReceiveBuffer.getNumpyBuffer(), \n serverReceiveBuffer.getMPIType()],\n source=serverRank)\n serverReceiveData[serverRank] = serverReceiveBuffer\n serverRequests[serverRank] = firstServerRequest\n self.logger.debug(\"CommSystem: after first Irecv from servers\")\n return serverReceiveData, serverRequests\n\n @Timing.timecall(timingDict=timingdict)\n def informWorkersOfNewData(self, selectedServerRank, sec, nsec, fiducials, counter):\n self.bcastWorkersBuffer.setEvt()\n self.bcastWorkersBuffer.setRank(selectedServerRank)\n self.bcastWorkersBuffer.setSeconds(sec)\n self.bcastWorkersBuffer.setNanoSeconds(nsec)\n self.bcastWorkersBuffer.setFiducials(fiducials)\n self.bcastWorkersBuffer.setCounter(counter)\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"CommSystem: before Bcast -> workers EVT sec=0x%8.8d nsec=0x%8.8X fid=0x%5.5X counter=%d\" % \\\n (self.bcastWorkersBuffer.getSeconds(), self.bcastWorkersBuffer.getNanoSeconds(), \n self.bcastWorkersBuffer.getFiducials(), self.bcastWorkersBuffer.getCounter()))\n self.masterWorkersComm.Bcast([self.bcastWorkersBuffer.getNumpyBuffer(),\n self.bcastWorkersBuffer.getMPIType()],\n root=self.masterRankInMasterWorkersComm)\n# self.masterWorkersComm.Barrier()\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"CommSystem: after Bcast/Barrier -> workers EVT counter=%d\" % counter)\n\n @Timing.timecall(timingDict=timingdict)\n def informViewerOfUpdate(self, latestEventId):\n self.viewerBuffer.setUpdate()\n self.viewerBuffer.setSeconds(latestEventId['sec'])\n self.viewerBuffer.setNanoSeconds(latestEventId['nsec'])\n self.viewerBuffer.setFiducials(latestEventId['fiducials'])\n self.viewerBuffer.setCounter(latestEventId['counter'])\n self.worldComm.Send([self.viewerBuffer.getNumpyBuffer(),\n self.viewerBuffer.getMPIType()],\n dest=self.viewerRank)\n\n def sendEndToViewer(self):\n self.viewerBuffer.setEnd()\n self.worldComm.Send([self.viewerBuffer.getNumpyBuffer(),\n self.viewerBuffer.getMPIType()],\n dest=self.viewerRank)\n\n @Timing.timecall(timingDict=timingdict)\n def informWorkersToUpdateViewer(self):\n self.logger.debug(\"CommSystem: before Bcast -> workers UPDATE\")\n self.bcastWorkersBuffer.setUpdate()\n self.masterWorkersComm.Bcast([self.bcastWorkersBuffer.getNumpyBuffer(),\n self.bcastWorkersBuffer.getMPIType()],\n root=self.masterRankInMasterWorkersComm)\n# self.masterWorkersComm.Barrier()\n self.logger.debug(\"CommSystem: after Bcast/Barrier -> workers UPDATE\")\n\n def sendEndToWorkers(self):\n self.bcastWorkersBuffer.setEnd()\n self.logger.debug(\"CommSystem: before Bcast -> workers END\")\n self.masterWorkersComm.Bcast([self.bcastWorkersBuffer.getNumpyBuffer(),\n self.bcastWorkersBuffer.getMPIType()],\n root=self.masterRankInMasterWorkersComm)\n # self.masterWorkersComm.Barrier()\n self.logger.debug(\"CommSystem: after Bcast/Barrier -> workers END\")\n\n @Timing.timecall(timingDict=timingdict)\n def waitOnServers(self, serverRequests, serverReceiveData):\n '''called during communication loop. \n Called when not all servers are ready, or at end.\n The master wants all servers to have data available, or to be done with their\n data before it picks the next server to scatter.\n\n identifies a done server through waitany\n tests all done servers\n idenfies finisned servers among done servers\n\n at the end of this function,\n\n self.notReadyServers + self.finishedServers + self.readyServers \n\n will be the same as it was on entry, and self.notReadyServers will be 0. There will be\n at least one server in the finishedServers or readyServers\n '''\n assert len(self.notReadyServers)>0, \"waitOnServers called, but no not-ready servers\"\n\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"CommSystem: before waitany. notReadyServers=%s\" % self.notReadyServers)\n requestList = [serverRequests[rnk] for rnk in self.notReadyServers]\n MPI.Request.Waitall(requestList)\n\n newReadyServers = [s for s in self.notReadyServers]\n self.notReadyServers = []\n\n newFinishedServers = [server for server in newReadyServers \\\n if serverReceiveData[server].isEnd()]\n self.finishedServers.extend(newFinishedServers)\n for server in newFinishedServers:\n # take finished servers out of pool to get next event from\n newReadyServers.remove(server)\n\n self.readyServers.extend(newReadyServers)\n\n @Timing.timecall(timingDict=timingdict)\n def tellServerToScatterToWorkers(self, selectedServerRank):\n self.sendOkForWorkersBuffer.setSendToWorkers()\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"CommSystem: before SendOkForWorkers to server %d\" % selectedServerRank)\n self.worldComm.Send([self.sendOkForWorkersBuffer.getNumpyBuffer(), \n self.sendOkForWorkersBuffer.getMPIType()], \n dest=selectedServerRank)\n def run(self):\n ####### helper functions ##########\n def initializeCounterFunctionWithFirstTime(sec, nsec, fiducials):\n self.eventIdToCounter = Counter120hz.Counter120hz(sec, nsec, fiducials)\n\n def updateLatestEventId(latestEventId, counter, sec, nsec, fiducials):\n if (latestEventId['counter'] is None) or (counter > latestEventId['counter']):\n latestEventId['counter']=counter\n latestEventId['sec']=sec\n latestEventId['nsec']=nsec\n latestEventId['fiducials']=fiducials\n ##################################\n\n serverReceiveData, serverRequests = self.initRecvRequestsFromServers()\n numEventsAtLastDataRateMsg = 0\n timeAtLastDataRateMsg = time.time()\n startTime = time.time()\n noData = True\n selectedServerRank = None\n latestEventId = {'sec':None, 'nsec':None, 'fiducials':None, 'counter':None}\n\n while True:\n # a server must be in one of: ready, noReady or finished\n serversAccountedFor = len(self.readyServers) + len(self.finishedServers) + \\\n len(self.notReadyServers)\n assert serversAccountedFor == len(self.serverRanks), \\\n \"loop invariant broken? #servers=%d != #accountedfor=%d\" % \\\n (len(self.serverRanks), len(serversAccountedFor))\n\n assert len(set(self.readyServers))==len(self.readyServers), \"readyServers=%r contains dups\" % self.readyServers\n assert len(set(self.finishedServers))==len(self.finishedServers), \"readyServers=%r contains dups\" % self.readyServers\n assert len(set(self.notReadyServers))==len(self.notReadyServers), \"notReadyServers=%r contains dups\" % self.notReadyServers\n\n if len(self.finishedServers)==len(self.serverRanks): \n break\n\n if len(self.notReadyServers)!=0:\n self.waitOnServers(serverRequests, serverReceiveData)\n if len(self.readyServers)==0:\n # the servers we waited on are finished. \n continue\n serverDataList = [serverReceiveData[server] for server in self.readyServers]\n nextServerData = self.getNextServerData(serverDataList, selectedServerRank)\n selectedServerRank = nextServerData.getRank()\n sec, nsec, fiducials = nextServerData.getEventId()\n noData = False\n if self.eventIdToCounter is None:\n initializeCounterFunctionWithFirstTime(sec, nsec, fiducials)\n counter = self.eventIdToCounter.getCounter(sec, fiducials)\n updateLatestEventId(latestEventId, counter, sec, nsec, fiducials)\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"CommSystem: next server rank=%d sec=0x%8.8X nsec=0x%8.8X fiducials=0x%5.5X counter=%5d\" % \\\n (selectedServerRank, sec, nsec, fiducials, counter))\n self.informWorkersOfNewData(selectedServerRank, sec, nsec, fiducials, counter)\n self.tellServerToScatterToWorkers(selectedServerRank)\n\n self.readyServers.remove(selectedServerRank)\n self.notReadyServers.append(selectedServerRank)\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"CommSystem: after sendOk, before replacing request with Irecv from rank %d\" % selectedServerRank)\n serverReceiveBuffer = serverReceiveData[selectedServerRank]\n serverRequests[selectedServerRank] = self.worldComm.Irecv([serverReceiveBuffer.getNumpyBuffer(), \n serverReceiveBuffer.getMPIType()], \\\n source = selectedServerRank)\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"CommSystem: after Irecv from rank %d\" % selectedServerRank)\n\n # check to see if there should be an update for the viewer\n self.numEvents += 1\n if (self.updateIntervalEvents > 0) and (self.numEvents - self.lastUpdate > self.updateIntervalEvents):\n self.lastUpdate = self.numEvents\n self.logger.debug(\"CommSystem: Informing viewers and workers to update\" )\n self.informViewerOfUpdate(latestEventId)\n self.informWorkersToUpdateViewer()\n\n # check to display message\n eventsSinceLastDataRateMsg = self.numEvents - numEventsAtLastDataRateMsg\n if eventsSinceLastDataRateMsg > 1200: # 10 seconds of data at 120hz\n curTime = time.time()\n dataRateHz = eventsSinceLastDataRateMsg/(curTime-timeAtLastDataRateMsg)\n self.logger.info(\"Current data rate is %.2f Hz. %d events processed\" % (dataRateHz, self.numEvents))\n timeAtLastDataRateMsg = curTime\n numEventsAtLastDataRateMsg = self.numEvents\n\n assert noData == False, \"There was no data in master loop\"\n\n # one last datarate msg\n dataRateHz = self.numEvents/(time.time()-startTime)\n self.logger.info(\"Overall data rate is %.2f Hz. Number of events is %d\" % (dataRateHz, self.numEvents))\n\n # send one last update at the end\n self.logger.debug(\"CommSystem: servers finished. sending one last update\")\n self.informViewerOfUpdate(latestEventId)\n self.informWorkersToUpdateViewer()\n\n self.sendEndToWorkers()\n self.sendEndToViewer()\n\nclass RunWorker(object):\n def __init__(self, masterWorkersComm, masterRankInMasterWorkersComm, \n xCorrBase, logger, isFirstWorker):\n self.masterWorkersComm = masterWorkersComm\n self.masterRankInMasterWorkersComm = masterRankInMasterWorkersComm\n self.xCorrBase = xCorrBase\n self.logger = logger\n self.isFirstWorker = isFirstWorker\n self.msgBuffer = MVW_MsgBuffer()\n self.evtNumber = 0\n\n @Timing.timecall(timingDict=timingdict)\n def workerWaitForMasterBcast(self):\n self.masterWorkersComm.Bcast([self.msgBuffer.getNumpyBuffer(),\n self.msgBuffer.getMPIType()],\n root=self.masterRankInMasterWorkersComm)\n# self.masterWorkersComm.Barrier()\n\n @Timing.timecall(timingDict=timingdict)\n def serverWorkersScatter(self, serverWorldRank):\n self.xCorrBase.serverWorkersScatter(detectorData1Darray=None,\n serverWorldRank = serverWorldRank)\n\n @Timing.timecall(timingDict=timingdict)\n def storeNewWorkerData(self, counter):\n self.xCorrBase.storeNewWorkerData(counter = counter)\n\n @Timing.timecall(timingDict=timingdict)\n def viewerWorkersUpdate(self, lastTime):\n self.xCorrBase.viewerWorkersUpdate(lastTime = lastTime)\n\n def run(self):\n lastTime = {'sec':0, 'nsec':0, 'fiducials':0, 'counter':0}\n numEvents = 0\n while True:\n numEvents += 1\n self.logger.debug(\"CommSystem.run: before Bcast from master\")\n self.workerWaitForMasterBcast()\n\n if self.msgBuffer.isEvt():\n serverWithData = self.msgBuffer.getRank()\n lastTime = self.msgBuffer.getTime()\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug(\"CommSystem.run: after Bcast from master. EVT server=%2d counter=%d\" % \\\n (serverWithData, lastTime['counter']))\n self.serverWorkersScatter(serverWorldRank = serverWithData)\n self.storeNewWorkerData(counter = lastTime['counter'])\n\n elif self.msgBuffer.isUpdate():\n self.logger.debug(\"CommSystem.run: after Bcast from master - UPDATE\")\n self.viewerWorkersUpdate(lastTime = lastTime)\n self.logger.debug(\"CommSystem.run: returned from viewer workers update\")\n elif self.msgBuffer.isEnd():\n self.logger.debug(\"CommSystem.run: after Bcast from master - END. quiting\")\n break\n else:\n raise Exception(\"unknown msgtag\")\n self.evtNumber += 1\n\nclass RunViewer(object):\n def __init__(self, worldComm, masterRank, xCorrBase, logger):\n self.worldComm = worldComm\n self.masterRank = masterRank\n self.logger = logger\n self.xCorrBase = xCorrBase\n self.msgbuffer = MVW_MsgBuffer()\n\n @Timing.timecall(timingDict=timingdict)\n def waitForMasterMessage(self):\n self.worldComm.Recv([self.msgbuffer.getNumpyBuffer(),\n self.msgbuffer.getMPIType()],\n source=self.masterRank)\n\n @Timing.timecall(timingDict=timingdict)\n def viewerWorkersUpdate(self, lastTime):\n self.xCorrBase.viewerWorkersUpdate(lastTime)\n\n def run(self):\n while True:\n self.logger.debug('CommSystem.run: before Recv from master')\n self.waitForMasterMessage()\n\n if self.msgbuffer.isUpdate():\n lastTime = self.msgbuffer.getTime()\n if self.logger.isEnabledFor(logging.DEBUG):\n self.logger.debug('CommSystem.run: after Recv from master. get UPDATE: counter=%d' % lastTime['counter'])\n self.viewerWorkersUpdate(lastTime = lastTime)\n elif self.msgbuffer.isEnd():\n self.logger.debug('CommSystem.run: after Recv from master. get END. quiting.')\n break\n else:\n raise Exception(\"unknown msgtag\")\n self.xCorrBase.shutdown_viewer()\n\ndef runTestAlt(mp, xCorrBase):\n xCorrBase.serverInit()\n xCorrBase.workerInit()\n xCorrBase.viewerInit()\n eventIter = xCorrBase.makeEventIter()\n eventIds = []\n allData = []\n mp.logInfo(\"Starting to read through data for test_alt\")\n for datum in eventIter.dataGenerator():\n maskedData = datum.dataArray[mp.maskNdarrayCoords]\n maskedData = maskedData.flatten().copy()\n xCorrBase.userObj.workerAdjustData(maskedData)\n\n eventIds.append((datum.sec, datum.nsec, datum.fiducials))\n allData.append(maskedData)\n\n mp.logInfo(\"read through data for test_alt\")\n sortedCounters, newDataOrder = PsanaUtil.getSortedCountersBasedOnSecNsecAtHertz(eventIds, 120)\n \n if not np.all(newDataOrder==np.sort(newDataOrder)):\n mp.logWarning(\"DAQ data did not come in sorted order.\")\n \n eventIdNumpyDtype = np.dtype([('sec',np.int32),\n ('nsec',np.int32),\n ('fiducials',np.int32),\n ('counter',np.int64)])\n sortedData = np.zeros((len(allData),len(allData[0])), dtype=allData[0].dtype)\n sortedEventIds = np.zeros(len(allData), dtype=eventIdNumpyDtype)\n for idx,sortedPos in enumerate(newDataOrder):\n sortedData[idx,:]=allData[sortedPos][:]\n sortedEventIds[idx]['counter'] = sortedCounters[idx]\n eventIdInSortOrder = eventIds[sortedPos]\n sortedEventIds[idx]['sec'] = eventIdInSortOrder[0]\n sortedEventIds[idx]['nsec'] = eventIdInSortOrder[1]\n sortedEventIds[idx]['fiducials'] = eventIdInSortOrder[2]\n if xCorrBase.h5file is not None:\n testGroup = xCorrBase.h5file.create_group('test')\n testGroup['detectorEventIds'] = sortedEventIds\n testGroup['detectorData'] = sortedData\n \n xCorrBase.userObj.calcAndPublishForTestAlt(sortedEventIds, sortedData, xCorrBase.h5GroupUser)\n xCorrBase.shutdown_viewer()\n return 0\n\ndef runCommSystem(mp, updateInterval, xCorrBase, hostmsg, serversRoundRobin, test_alt):\n '''main driver for the system. \n\n ARGS:\n mp - instance of MPI_Communicators\n updateInterval (int): \n xCorrBase:\n hostmsg: \n test_alt (bool): True if this is testing mode\n '''\n if test_alt:\n return runTestAlt(mp, xCorrBase)\n\n logger = mp.logger\n reportTiming = False\n timingNode = ''\n try:\n if mp.isServer: \n xCorrBase.serverInit()\n eventIter = xCorrBase.makeEventIter()\n runServer = RunServer(eventIter, xCorrBase,\n mp.comm, mp.rank, mp.masterRank, xCorrBase.logger)\n runServer.run()\n if mp.isFirstServer:\n reportTiming = True\n timingNode = 'FIRST SERVER'\n\n elif mp.isMaster:\n runMaster = RunMaster(mp.comm, mp.masterRank, mp.viewerRank, mp.serverRanks, serversRoundRobin,\n mp.masterWorkersComm, mp.masterRankInMasterWorkersComm,\n updateInterval, hostmsg, logger)\n runMaster.run()\n reportTiming = True\n timingNode = 'MASTER'\n\n elif mp.isViewer:\n xCorrBase.viewerInit()\n runViewer = RunViewer(mp.comm, mp.masterRank, xCorrBase, logger)\n runViewer.run()\n reportTiming = True\n timingNode = 'VIEWER'\n\n elif mp.isWorker:\n xCorrBase.workerInit()\n runWorker = RunWorker(mp.masterWorkersComm, mp.masterRankInMasterWorkersComm,\n xCorrBase, logger, mp.isFirstWorker)\n runWorker.run()\n if mp.isFirstWorker:\n reportTiming = True\n timingNode = 'FIRST WORKER'\n \n else:\n raise Exception(\"rank is neither server/master/viewer or worker - internal error\")\n\n except Exception:\n exceptBuffer = io.StringIO()\n traceback.print_exc(file=exceptBuffer)\n logger.error('encountered exception: %s' % exceptBuffer.getvalue())\n MPI.COMM_WORLD.Abort(1)\n return -1\n\n if reportTiming:\n hdr = '--BEGIN %s TIMING--' % timingNode\n footer = '--END %s TIMING--' % timingNode\n Timing.reportOnTimingDict(logger,hdr, footer,\n timingDict=timingdict)\n return 0\n\ndef isNoneOrListOfStrings(arg):\n def isListOfStrings(arg):\n if not isinstance(arg, list):\n return False\n def isStr(x): return isinstance(x,str)\n return all(map(isStr,arg))\n if arg is None:\n return True\n return isListOfStrings(arg)\n\nclass CommSystemFramework(object):\n def __init__(self, system_params, user_params, test_alt=False):\n CommSystemUtil.checkParams(system_params, user_params)\n numServers = int(system_params['numServers'])\n dataset = system_params['dataset']\n serverHosts = system_params['serverHosts']\n self.serversRoundRobin = system_params['serversRoundRobin']\n assert isNoneOrListOfStrings(serverHosts), \"system_params['serverHosts'] is neither None or a list of str\"\n\n self.test_alt = test_alt\n\n if test_alt:\n assert MPI.COMM_WORLD.size == 1, \"In test_alt mode, do not run in MPI mode\"\n hostmsg = \"test mode - no host assignent\"\n mp = getTestingMPIObject()\n else:\n serverRanks, hostmsg = identifyServerRanks(MPI.COMM_WORLD,\n numServers,\n serverHosts,\n excludeRank0=True)\n # set mpi paramemeters for framework\n mp = identifyCommSubsystems(serverRanks=serverRanks, worldComm=MPI.COMM_WORLD)\n\n self.hostmsg = hostmsg\n verbosity = system_params['verbosity']\n mp.setLogger(verbosity)\n maskNdarrayCoords_Filename = system_params['maskNdarrayCoords']\n assert os.path.exists(maskNdarrayCoords_Filename), \"mask file %s not found\" % maskNdarrayCoords_Filename\n maskNdarrayCoords = np.load(maskNdarrayCoords_Filename).astype(np.int8)\n mp.setMask(maskNdarrayCoords)\n srcString = system_params['src']\n numEvents = system_params['numEvents']\n maxTimes = system_params['times']\n assert isinstance(srcString,str), \"system parameters src is not a string\"\n assert isinstance(numEvents,int), \"system parameters numevents is not an int\"\n assert isinstance(maxTimes,int), \"system parameters maxTimes is not an int\"\n\n xcorrBase = XCorrBase(mp, \n dataset, \n srcString, \n numEvents, \n maxTimes, \n system_params, \n user_params,\n test_alt)\n self.mp = mp\n self.xcorrBase = xcorrBase\n self.maxTimes = maxTimes\n self.updateInterval = system_params['update']\n \n def run(self):\n return runCommSystem(self.mp, self.updateInterval, self.xcorrBase, self.hostmsg, self.serversRoundRobin, self.test_alt)\n\n","sub_path":"src/CommSystem.py","file_name":"CommSystem.py","file_ext":"py","file_size_in_byte":49453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"283973504","text":"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.\n# Copyright (c) 2018, NVIDIA CORPORATION. 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\"\"\"Code adapted from the examples in pytorch-pretrained-bert library\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport argparse\nimport logging\nimport os\nimport pickle\nfrom io import open\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\nmlm_cvg_hack = 10\n\nimport numpy as np\nimport torch\nfrom torch.nn import CrossEntropyLoss\nfrom torch.utils.data import DataLoader, Dataset, RandomSampler\nfrom torch.utils.data.distributed import DistributedSampler\nfrom tqdm import tqdm, trange\n\nfrom pytorch_pretrained_bert.modeling import BertPreTrainedModel, BertModel, BertOnlyMLMHead, BertConfig, WEIGHTS_NAME, CONFIG_NAME\nfrom pytorch_pretrained_bert.tokenization import BertTokenizer\nfrom pytorch_pretrained_bert.optimization import BertAdam, warmup_linear\n\nfrom torch.utils.data import Dataset\nimport random\nimport os\n\n# os.environ['CUDA_VISIBLE_DEVICES']='6'\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO)\nlogger = logging.getLogger(__name__)\n\n\nclass MyBertForMaskedLM(BertPreTrainedModel):\n \"\"\"BERT model with the masked language modeling head.\n This module comprises the BERT model followed by the masked language modeling head.\n Params:\n config: a BertConfig class instance with the configuration to build a new model.\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `masked_lm_labels`: masked language modeling labels: torch.LongTensor of shape [batch_size, sequence_length]\n with indices selected in [-1, 0, ..., vocab_size]. All labels set to -1 are ignored (masked), the loss\n is only computed for the labels set in [0, ..., vocab_size]\n Outputs:\n if `masked_lm_labels` is not `None`:\n Outputs the masked language modeling loss.\n if `masked_lm_labels` is `None`:\n Outputs the masked language modeling logits of shape [batch_size, sequence_length, vocab_size].\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n model = BertForMaskedLM(config)\n masked_lm_logits_scores = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config):\n super(MyBertForMaskedLM, self).__init__(config)\n self.bert = BertModel(config)\n self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, masked_lm_labels=None):\n sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask,\n output_all_encoded_layers=False)\n prediction_scores = self.cls(sequence_output)\n\n if masked_lm_labels is not None:\n loss_fct = CrossEntropyLoss(ignore_index=-1)\n masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))\n return masked_lm_loss\n else:\n return prediction_scores\n\n\nclass DataProcessor(object):\n \"\"\"Processor for the MRPC data set (GLUE version).\"\"\"\n\n def get_conll_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_pkl(os.path.join(data_dir, \"conll_train.pkl\")), \"conll_train\")\n\n def get_conll_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_pkl(os.path.join(data_dir, \"conll_test.pkl\")), \"conll_dev\")\n \n def get_sep_scitech_train_examples(self, data_dir):\n \"\"\" See base class\"\"\"\n return self._create_exmaples(\n self._read_pkl(os.path.join(dat_dir, \"sep_scitech_train.pkl\")), \"twitter_train\")\n\n\n def get_sep_scitech_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_pkl(os.path.join(data_dir, \"sep_scitech_test.pkl\")), \"twitter_test\")\n\n def get_scitech_general_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples_without_replacement(\n self._read_pkl(os.path.join(data_dir, \"scitech_train.pkl\")), \"twitter_general\")\n\n def get_labels(self, data_dir):\n \"\"\"See base class.\"\"\"\n return ['B', 'I', 'O']\n\n def _create_examples(self, data, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, elem) in enumerate(data):\n guid = \"%s-%s\" % (set_type, i)\n text = elem[0]\n # label = elem[1] # not necessary for cloze-style LM fine-tuning\n for j in range(mlm_cvg_hack):\n examples.append(InputExample(guid=guid, text=text))\n return examples\n\n def _create_examples_without_replacement(self, data, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, elem) in enumerate(data):\n guid = \"%s-%s\" % (set_type, i)\n text = elem[0]\n # label = elem[1] # not necessary for cloze-style LM fine-tuning\n examples.append(InputExample(guid=guid, text=text))\n return examples\n\n def _read_pkl(self, input_file):\n \"\"\"Reads a tab separated value file.\"\"\"\n data = pickle.load(open(input_file, 'rb'))\n return data\n\n\nclass BERTDataset(Dataset):\n def __init__(self, data_dir, tokenizer, seq_len):\n self.vocab = tokenizer.vocab\n self.tokenizer = tokenizer\n self.seq_len = seq_len\n self.sample_counter = 0\n\n processor = DataProcessor()\n # self.examples = processor.get_sep_twitter_train_examples(data_dir) # change here for switching between train/test or whole PPCEME mode\n\n # use test examples in unsupervised domain tuning\n self.examples = processor.get_sep_scitech_test_examples(data_dir)\n # self.examples.extend(test_examples)\n\n # hybrid domain tuning\n orig_domain_examples = random.sample(processor.get_conll_train_examples(data_dir), len(self.examples))\n # orig_domain_examples = processor.get_conll_train_examples(data_dir)\n self.examples.extend(orig_domain_examples)\n\n general_examples = processor.get_scitech_general_examples(data_dir)\n self.examples.extend(general_examples)\n\n def __len__(self):\n # last line of doc won't be used, because there's no \"nextSentence\". Additionally, we start counting at 0.\n return len(self.examples)\n\n def __getitem__(self, item):\n cur_id = self.sample_counter\n self.sample_counter += 1\n\n # combine to one sample\n cur_example = self.examples[item]\n\n # transform sample to features\n cur_features = convert_example_to_features(cur_example, self.seq_len, self.tokenizer)\n\n cur_tensors = (torch.tensor(cur_features.input_ids),\n torch.tensor(cur_features.input_mask),\n torch.tensor(cur_features.segment_ids),\n torch.tensor(cur_features.lm_label_ids))\n\n return cur_tensors\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text):\n \"\"\"Constructs a InputExample.\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text = text # list of tokens\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, lm_label_ids):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.lm_label_ids = lm_label_ids\n\n\ndef random_word(tokens, tokenizer):\n \"\"\"\n Masking some random tokens for Language Model task with probabilities as in the original BERT paper.\n :param tokens: list of str, tokenized sentence.\n :param tokenizer: Tokenizer, object used for tokenization (we need it's vocab here)\n :return: (list of str, list of int), masked tokens and related labels for LM prediction\n \"\"\"\n output_label = []\n\n for i, token in enumerate(tokens):\n prob = random.random()\n # mask token with 15% probability\n if prob < 0.15:\n prob /= 0.15\n\n # 80% randomly change token to mask token\n if prob < 0.8:\n tokens[i] = \"[MASK]\"\n\n # 10% randomly change token to random token\n elif prob < 0.9:\n tokens[i] = random.choice(list(tokenizer.vocab.items()))[0]\n\n # -> rest 10% randomly keep current token\n\n # append current token to output (we will predict these later)\n try:\n output_label.append(tokenizer.vocab[token])\n except KeyError:\n # For unknown words (should not occur with BPE vocab)\n output_label.append(tokenizer.vocab[\"[UNK]\"])\n logger.warning(\"Cannot find token '{}' in vocab. Using [UNK] insetad\".format(token))\n else:\n # no masking token (will be ignored by loss function later)\n output_label.append(-1)\n\n return tokens, output_label\n\n\ndef convert_example_to_features(example, max_seq_length, tokenizer):\n \"\"\"\n Convert a raw sample (pair of sentences as tokenized strings) into a proper training sample with\n IDs, LM labels, input_mask, CLS and SEP tokens etc.\n :param example: InputExample, containing sentence input as strings and is_next label\n :param max_seq_length: int, maximum length of sequence.\n :param tokenizer: Tokenizer\n :return: InputFeatures, containing all inputs and labels of one sample as IDs (as used for model training)\n \"\"\"\n tokens = example.text\n\n# # Account for [CLS] and [SEP] with \"- 2\"\n# if len(tokens) > max_seq_length - 2:\n# tokens = tokens[:(max_seq_length - 2)]\n\n bert_tokens = []\n for token in tokens:\n new_tokens = tokenizer.tokenize(token)\n if len(bert_tokens) + len(new_tokens) > max_seq_length - 2:\n # print(\"You shouldn't see this since the test set is already pre-separated.\")\n break\n else:\n bert_tokens.extend(new_tokens)\n\n masked_tokens, masked_tokens_label = random_word(bert_tokens, tokenizer)\n # concatenate lm labels and account for CLS, SEP, SEP\n lm_label_ids = ([-1] + masked_tokens_label + [-1])\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambigiously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in masked_tokens:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n lm_label_ids.append(-1)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n assert len(lm_label_ids) == max_seq_length\n\n features = InputFeatures(input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n lm_label_ids=lm_label_ids)\n return features\n\n\ndef main():\n parser = argparse.ArgumentParser()\n\n ## Required parameters\n parser.add_argument(\"--data_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The input data dir. Should contain the .tsv files (or other data files) for the task.\")\n parser.add_argument(\"--bert_tokenizer\", default=None, type=str, required=True,\n help=\"Bert pre-trained tokenizer selected in the list: bert-base-uncased, \"\n \"bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.\")\n parser.add_argument(\"--bert_model\", default=None, type=str, required=True,\n help=\"Bert pre-trained model selected in the list: bert-base-uncased, \"\n \"bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.\")\n parser.add_argument(\"--output_dir\",\n default=None,\n type=str,\n required=True,\n help=\"The output directory where the model checkpoints will be written.\")\n\n ## Other parameters\n parser.add_argument(\"--trained_model_dir\",\n default=\"\",\n type=str,\n help=\"Where is the fine-tuned BERT model?\")\n parser.add_argument(\"--max_seq_length\",\n default=128,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--do_train\",\n action='store_true',\n help=\"Whether to run training.\")\n parser.add_argument(\"--train_batch_size\",\n default=32,\n type=int,\n help=\"Total batch size for training.\")\n parser.add_argument(\"--learning_rate\",\n default=3e-5,\n type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--num_train_epochs\",\n default=3.0,\n type=float,\n help=\"Total number of training epochs to perform.\")\n parser.add_argument(\"--warmup_proportion\",\n default=0.1,\n type=float,\n help=\"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10%% of training.\")\n parser.add_argument(\"--no_cuda\",\n action='store_true',\n help=\"Whether not to use CUDA when available\")\n parser.add_argument(\"--do_lower_case\",\n action='store_true',\n help=\"Whether to lower case the input text. True for uncased models, False for cased models.\")\n parser.add_argument(\"--local_rank\",\n type=int,\n default=-1,\n help=\"local_rank for distributed training on gpus\")\n parser.add_argument('--seed',\n type=int,\n default=42,\n help=\"random seed for initialization\")\n parser.add_argument('--gradient_accumulation_steps',\n type=int,\n default=1,\n help=\"Number of updates steps to accumualte before performing a backward/update pass.\")\n parser.add_argument('--fp16',\n action='store_true',\n help=\"Whether to use 16-bit float precision instead of 32-bit\")\n parser.add_argument('--loss_scale',\n type = float, default = 0,\n help = \"Loss scaling to improve fp16 numeric stability. Only used when fp16 set to True.\\n\"\n \"0 (default value): dynamic loss scaling.\\n\"\n \"Positive power of 2: static loss scaling value.\\n\")\n\n args = parser.parse_args()\n\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n n_gpu = torch.cuda.device_count()\n else:\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n n_gpu = 1\n # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.distributed.init_process_group(backend='nccl')\n logger.info(\"device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}\".format(\n device, n_gpu, bool(args.local_rank != -1), args.fp16))\n\n if args.gradient_accumulation_steps < 1:\n raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format(\n args.gradient_accumulation_steps))\n\n args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps\n\n random.seed(args.seed)\n np.random.seed(args.seed)\n torch.manual_seed(args.seed)\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n if not args.do_train:\n raise ValueError(\"Training is currently the only implemented execution option. Please set `do_train`.\")\n\n if os.path.exists(args.output_dir) and os.listdir(args.output_dir):\n #raise ValueError(\"Output directory ({}) already exists and is not empty.\".format(args.output_dir))\n print(\"WARNING: Output directory already exists and is not empty.\")\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n tokenizer = BertTokenizer.from_pretrained(args.bert_tokenizer, do_lower_case=args.do_lower_case)\n\n #train_examples = None\n num_train_optimization_steps = None\n if args.do_train:\n train_dataset = BERTDataset(args.data_dir, tokenizer, seq_len=args.max_seq_length)\n num_train_optimization_steps = int(\n len(train_dataset) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs\n if args.local_rank != -1:\n num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()\n\n # Prepare model\n if args.trained_model_dir:\n if os.path.exists(os.path.join(args.output_dir, WEIGHTS_NAME)):\n previous_state_dict = torch.load(os.path.join(args.output_dir, WEIGHTS_NAME))\n else:\n from collections import OrderedDict\n previous_state_dict = OrderedDict()\n distant_state_dict = torch.load(os.path.join(args.trained_model_dir, WEIGHTS_NAME))\n previous_state_dict.update(distant_state_dict) # note that the final layers of previous model and distant model must have different attribute names!\n model = MyBertForMaskedLM.from_pretrained(args.trained_model_dir, state_dict=previous_state_dict)\n else:\n model = MyBertForMaskedLM.from_pretrained(args.bert_model)\n if args.fp16:\n model.half()\n model.to(device)\n #if args.local_rank != -1:\n # try:\n # from apex.parallel import DistributedDataParallel as DDP\n # except ImportError:\n # raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n # model = DDP(model)\n #elif n_gpu > 1:\n # model = torch.nn.DataParallel(model)\n\n # Prepare optimizer\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n optimizer_grouped_parameters = [\n {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},\n {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\n ]\n\n if args.fp16:\n try:\n from apex.optimizers import FP16_Optimizer\n from apex.optimizers import FusedAdam\n except ImportError:\n raise ImportError(\"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n\n optimizer = FusedAdam(optimizer_grouped_parameters,\n lr=args.learning_rate,\n bias_correction=False,\n max_grad_norm=1.0)\n if args.loss_scale == 0:\n optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)\n else:\n optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)\n\n else:\n optimizer = BertAdam(optimizer_grouped_parameters,\n lr=args.learning_rate,\n warmup=args.warmup_proportion,\n t_total=num_train_optimization_steps)\n\n global_step = 0\n if args.do_train:\n logger.info(\"***** Running training *****\")\n logger.info(\" Num examples = %d\", len(train_dataset))\n logger.info(\" Batch size = %d\", args.train_batch_size)\n logger.info(\" Num steps = %d\", num_train_optimization_steps)\n\n if args.local_rank == -1:\n train_sampler = RandomSampler(train_dataset)\n else:\n #TODO: check if this works with current data generator from disk that relies on next(file)\n # (it doesn't return item back by index)\n train_sampler = DistributedSampler(train_dataset)\n train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)\n\n model.train()\n for _ in trange(int(args.num_train_epochs), desc=\"Epoch\"):\n tr_loss = 0\n nb_tr_examples, nb_tr_steps = 0, 0\n for step, batch in enumerate(tqdm(train_dataloader, desc=\"Iteration\")):\n batch = tuple(t.to(device) for t in batch)\n input_ids, input_mask, segment_ids, lm_label_ids = batch\n loss = model(input_ids, segment_ids, input_mask, lm_label_ids)\n if n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu.\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n if args.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n tr_loss += loss.item()\n nb_tr_examples += input_ids.size(0)\n nb_tr_steps += 1\n if (step + 1) % args.gradient_accumulation_steps == 0:\n if args.fp16:\n # modify learning rate with special warm up BERT uses\n # if args.fp16 is False, BertAdam is used that handles this automatically\n lr_this_step = args.learning_rate * warmup_linear(global_step / num_train_optimization_steps, args.warmup_proportion)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr_this_step\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n # Save a trained model\n logger.info(\"** ** * Saving fine - tuned model ** ** * \")\n model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self\n output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)\n torch.save(model_to_save.state_dict(), output_model_file)\n output_config_file = os.path.join(args.output_dir, CONFIG_NAME)\n with open(output_config_file, 'w') as f:\n f.write(model_to_save.config.to_json_string())\n\n\ndef accuracy(out, labels):\n outputs = np.argmax(out, axis=1)\n return np.sum(outputs == labels)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"code/cross-domain/domain-tuning.py","file_name":"domain-tuning.py","file_ext":"py","file_size_in_byte":26861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"370721342","text":"#!/usr/bin/env python\n\"\"\"\nTest file conversion using samples\n\"\"\"\n\nimport hashlib\n\n\ndef test_conversion():\n \" execute single test \"\n\n from asrtoolkit.data_structures.time_aligned_text import time_aligned_text\n input_file = time_aligned_text(\"../samples/BillGatesTEDTalk.stm\")\n input_file.write(\"file_conversion_test.txt\")\n reference_sha = hashlib.sha1(open(\"../samples/BillGatesTEDTalk.txt\", 'r',\n encoding='utf8').read().encode()).hexdigest()\n new_sha = hashlib.sha1(open(\"file_conversion_test.txt\", 'r', encoding='utf8').read().encode()).hexdigest()\n assert reference_sha == new_sha\n\n\nif __name__ == '__main__':\n import sys\n import pytest\n pytest.main(sys.argv)\n","sub_path":"tests/test_conversion.py","file_name":"test_conversion.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"177306871","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/3/12 13:13\n# @Department of Aeronautics and Astronautics, Fudan University\n# @Author : XuanjieXiao\n# @Email:xuanjiexiao@163.com\n# @File : chp2-4\n# @Project : pythonlearning\n\ni=0\nj=0\nwhile j <= 100:\n if((j%2)==0):\n i = i + j\n j += 1\nprint(i)\n\n\nfor item in 'python':\n print(item)\n\nfor _ in range(10):\n print('人生苦短,我要吃肉')","sub_path":"chp2/chp2-4.py","file_name":"chp2-4.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"418780923","text":"import os\n#import cv2\nimport glob\nimport gzip\nimport itertools\nimport numpy as np\nimport pylab as plt\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\n#from PIL import Image\n#from tqdm import tqdm\nfrom six.moves import xrange\nfrom urllib.request import urlretrieve\n#from scipy.misc import imsave, imread, imresize\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# comment below two lines to implement this code with GPU\n#os.environ['CUDA_DEVICE_ORDER'] = \"PCI_BUS_ID\"\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = '-1'\n\nDIR_PATH = os.path.dirname(os.path.realpath(__file__))\nDATA_DIR = os.path.join(DIR_PATH, \"data\") # path for your result\n\nNUM_IMAGES = 60000\nDATABASE_NAME = 'mnist'\nOUTPUT_NAME = 'out_vanilla'\nOUTPUT_PATH = os.path.join(DATA_DIR, OUTPUT_NAME)\n\n\n# This section is to implement vanilla GAN. You need to complete TODO by yourself according to vanilla GAN theory.\nclass VanillaGAN():\n def __init__(self, sess, img_size, z_dim, hidden_dim, batch_size, epoch):\n self.sess = sess\n self.epoch = epoch\n self.z_dim = z_dim\n self.img_size = img_size\n self.img_dim = img_size * img_size\n self.img_shape = [img_size, img_size, 1]\n self.hidden_dim = hidden_dim\n self.batch_size = batch_size\n\n self.build_model()\n self.model_name = \"vanilla_GAN.model\"\n\n def build_model(self):\n self.is_training = tf.placeholder(tf.bool, name=\"is_training\")\n self.img = tf.placeholder(tf.float32, [None, self.img_dim], name='real_images')\n\n self.z = tf.placeholder(tf.float32, [None, self.z_dim], name='z')\n self.z_sum = tf.summary.histogram('z', self.z)\n\n initializer = tf.contrib.layers.xavier_initializer()\n\n # parameters for generator\n # input layer parameters ()\n self.G_W1 = tf.Variable(initializer([self.z_dim, self.hidden_dim]))\n self.G_b1 = tf.Variable(tf.zeros(shape=[self.hidden_dim]))\n\n # output layer parameters\n self.G_W2 = tf.Variable(initializer([self.hidden_dim, self.img_dim]))\n self.G_b2 = tf.Variable(tf.zeros(shape=[self.img_dim]))\n\n # parameters for discriminator\n # input layer parameters\n self.D_W1 = tf.Variable(initializer([self.img_dim, self.hidden_dim]))\n self.D_b1 = tf.Variable(tf.zeros(shape=[self.hidden_dim]))\n\n # output layer parameters\n self.D_W2 = tf.Variable(initializer([self.hidden_dim, 1]))\n self.D_b2 = tf.Variable(tf.zeros(shape=[1]))\n\n # self.img_fake is produced by generator with a random input z\n self.img_fake = self.generator(self.z, self.G_W1, self.G_b1, self.G_W2, self.G_b2)\n\n # self.D presents\n # self.D_fake presents\n self.D, self.D_logits_real = self.discriminator(self.img, self.D_W1, self.D_b1, self.D_W2, self.D_b2)\n self.D_fake, self.D_logits_fake = self.discriminator(self.img_fake, self.D_W1, self.D_b1, self.D_W2, self.D_b2)\n\n self.d_sum = tf.summary.histogram(\"d\", self.D)\n self.d__sum = tf.summary.histogram(\"d_\", self.D_fake)\n self.img_fake_sum = tf.summary.histogram(\"G\", self.img_fake)\n\n self.D_loss_real = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=self.D_logits_real, labels=tf.ones_like(self.D_logits_real)))\n self.D_loss_fake = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=self.D_logits_fake,\n labels=tf.zeros_like(self.D_logits_fake)))\n self.D_loss = self.D_loss_real + self.D_loss_fake\n self.G_loss = tf.reduce_mean(\n tf.nn.sigmoid_cross_entropy_with_logits(logits=self.D_logits_fake, labels=tf.ones_like(self.D_logits_fake)))\n\n self.D_vars = [self.D_W1, self.D_b1, self.D_W2, self.D_b2]\n self.G_vars = [self.G_W1, self.G_b1, self.G_W2, self.G_b2]\n\n def generator(self, z, W1, b1, W2, b2):\n # TODO: generate fake image with W1, b1, W2, b2\n # Hints: using tf.nn.relu(), tf.matmul(), tf.nn.sigmoid() to implement functions as:\n\n # The first function is: h1 = relu(z*W1 + b1), \n h1 = tf.nn.relu(tf.matmul(z, W1) + b1)\n\n # The seconde one is: prob = h1*W2 + b2\n prob = tf.matmul(h1, W2) + b2\n\n # The last one is to use activation fuction sigmoid(prob) \n output = tf.nn.sigmoid(prob)\n\n return output\n\n def discriminator(self, img, W1, b1, W2, b2):\n # TODO: discriminator is used to discriminate whether an input image is real or not.\n\n # The first function is: h1 = relu(img*W1 + b1)\n h1 = tf.nn.relu(tf.matmul(img, W1) + b1)\n\n # The second one is: logit = h1*W2 + b2\n logit = tf.matmul(h1, W2) + b2\n\n # The third one is to generate the probability of an input image to be a real one with sigmoid.\n prob = tf.nn.sigmoid(logit)\n\n return prob, logit\n\n def plot(self, samples):\n fig = plt.figure(figsize=(4, 4))\n gs = gridspec.GridSpec(4, 4)\n gs.update(wspace=0.05, hspace=0.05)\n\n for i, sample in enumerate(samples):\n ax = plt.subplot(gs[i])\n plt.axis('off')\n ax.set_xticklabels([])\n ax.set_yticklabels([])\n ax.set_aspect('equal')\n plt.imshow(sample.reshape(self.img_size, self.img_size), cmap=\"Greys_r\")\n\n return fig\n\n def train(self, output_path):\n d_optim = tf.train.AdamOptimizer().minimize(self.D_loss, var_list=self.D_vars)\n g_optim = tf.train.AdamOptimizer().minimize(self.G_loss, var_list=self.G_vars)\n\n try:\n tf.global_variables_initializer().run()\n except:\n tf.initialize_all_variables().run()\n\n i = 0\n counter = 1\n mnist = input_data.read_data_sets('./MNIST_data', one_hot=True)\n\n for epoch in xrange(self.epoch):\n input_z = np.random.uniform(-1, 1, [self.batch_size, self.z_dim]).astype(np.float32)\n input_imgs, _ = mnist.train.next_batch(self.batch_size)\n\n # Update D network\n _, D_loss_curr = self.sess.run([d_optim, self.D_loss], feed_dict={self.img: input_imgs, self.z: input_z})\n _, G_loss_curr = self.sess.run([g_optim, self.G_loss], feed_dict={self.z: input_z})\n\n counter += 1\n if counter % 1000 == 0:\n print(\"Epoch: [{:2d}] D_loss: {:.8f}, G_loss {:.8f}\".format(\n epoch, D_loss_curr, G_loss_curr))\n\n samples = self.sess.run(self.img_fake, feed_dict={self.z: input_z})\n # import pdb; pdb.set_trace()\n fig = self.plot(samples)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n plt.savefig(os.path.join(output_path, '{}.png'.format(str(i).zfill(3))), bbox_inches='tight')\n i += 1\n plt.close(fig)\n\n\ndef run():\n flags = tf.app.flags\n flags.DEFINE_integer(\"img_size\", 28, \"Image size.\")\n flags.DEFINE_integer(\"z_dim\", 100, \"The dimension of random input z.\")\n flags.DEFINE_integer(\"hidden_dim\", 128, \"The dimension of hidden \")\n flags.DEFINE_integer(\"batch_size\", 16, \"The size of batch images [32]\")\n flags.DEFINE_integer(\"epoch\", 100000, \"Epoch to train!\")\n FLAGS = flags.FLAGS\n\n config = tf.ConfigProto(\n device_count={'GPU': 1}) # if you wanna implement this code with GPU, change 0 to 1 or 2.\n with tf.Session(config=config) as sess:\n vanilla_gan = VanillaGAN(sess, img_size=FLAGS.img_size, z_dim=FLAGS.z_dim,\n hidden_dim=FLAGS.hidden_dim, batch_size=FLAGS.batch_size,\n epoch=FLAGS.epoch)\n vanilla_gan.train(OUTPUT_PATH)\n\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"vanilla_gan.py","file_name":"vanilla_gan.py","file_ext":"py","file_size_in_byte":7795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"80135070","text":"'''Задача: Пользователь вводит с клавиатуры список слов (и чисел).\nСлова вывести в возрастающем порядке, числа — в убывающем.\n\nПример ввода:\nВишня\n1\nБоб\n3\nЯблоко\n2\n0\nАрбуз\n\nПример вывода:\nАрбуз\n3\nБоб\n2\nВишня\n1\n0\nЯблоко\n\n\nТребования:\n1. Программа должна считывать данные с клавиатуры.\n2. Программа должна выводить данные на экран.\n3. Выведенные слова должны быть упорядочены по возрастанию.\n4. Выведенные числа должны быть упорядочены по убыванию.\n'''\ninput = [\n 'Вишня',\n 1,\n 'Боб',\n 3,\n 'Яблоко',\n 2,\n 0,\n 'Арбуз']\n\nprint(input)\n\nints = [] # список чисел\nstrs = [] # список строк\nfor r in input:\n if isinstance(r, int):\n ints.append(r)\n else:\n strs.append(r)\n\nstrs.sort() # сортировка списка строк\nints.sort(reverse=True) # сортировка списка чисел\n\noutput = []\nfor r in input:\n if isinstance(r, int):\n output.append(ints.pop(0))\n else:\n output.append(strs.pop(0))\n\nprint(output)\n","sub_path":"Efremov/Efremov3_sort.py","file_name":"Efremov3_sort.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"118633864","text":"# реализовать бинарное дерево поиска \n# с заданным интерфейсом, описание которого потеряно)\n\nfrom collections import deque\n\n\nclass Node:\n def __init__(self, value, left=None, right=None):\n self.value = value\n self.left = left\n self.right = right\n\n\nclass BinarySearchTree:\n\n def __init__(self, value=None):\n if value is None:\n self.root = None\n self.size = 0\n else:\n self.root = Node(value)\n self.size = 1\n self.counter = 0\n\n def append(self, value):\n if self.root is None:\n self.root = Node(value)\n else:\n self.__put(value, self.root)\n self.size += 1\n\n def __put(self, value, current_node):\n if value < current_node.value:\n if current_node.left is None:\n current_node.left = Node(value)\n else:\n self.__put(value, current_node.left)\n else:\n if current_node.right is None:\n current_node.right = Node(value)\n else:\n self.__put(value, current_node.right)\n self.queue = self.__queue()\n\n def __contains__(self, item):\n return item in self.__queue()\n\n def __iter__(self):\n self.counter = 0\n self.queue = self.__queue()\n return self\n\n def __next__(self):\n if self.counter < self.size:\n self.counter += 1\n return next(self.queue)\n else:\n raise StopIteration()\n\n def __queue(self):\n queue = deque()\n queue.append(self.root)\n for _ in range(self.size):\n current_node = queue.popleft()\n yield current_node.value\n if current_node.left is not None:\n queue.append(current_node.left)\n if current_node.right is not None:\n queue.append(current_node.right)\n\n\nif __name__ == '__main__':\n tree = BinarySearchTree(9)\n for v in [5, 0, 6, 2, 1, 3]:\n tree.append(v)\n\n for v in [6, 12]:\n print(v in tree)\n\n print(next(tree))\n print(next(tree))\n print(next(tree))\n print(next(tree))\n print(next(tree))\n\n print(*tree)\n","sub_path":"8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"531710680","text":"print('所有三位数的素数如下:', end=' ')\nfor i in range(100, 1000):\n j = 2\n flag = 1\n while j < i:\n if i % j == 0:\n flag = 0\n break\n j += 1\n if flag == 1:\n print(i, end=' ')","sub_path":"Test_CourseEg/com/bin23/chapter3/eg3_15.py","file_name":"eg3_15.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"647227806","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport contractor.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Site',\n fields=[\n ('name', models.CharField(max_length=40, primary_key=True, serialize=False)),\n ('description', models.CharField(max_length=200)),\n ('config_values', contractor.fields.MapField(default={}, blank=True)),\n ('updated', models.DateTimeField(auto_now=True)),\n ('created', models.DateTimeField(auto_now_add=True)),\n ('parent', models.ForeignKey(blank=True, null=True, to='Site.Site')),\n ],\n ),\n ]\n","sub_path":"contractor/Site/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"409627601","text":"\"\"\"\nThe functions in this file relate to filling in cumulative data in which \nthere is \"NO DATA\".\n\"\"\"\n\nfrom datetime import date, timedelta\n\nimport flask\nimport pandas as pd\n\nfrom app.api import utils\n\n_NO_DATA = {'NO DATA', 'Not Reported', 'Data Pending', 'Closed'}\n\ndef replace_no_data(df):\n cume_cols = [x for x in df.columns if x.startswith('Cume_')]\n no_data = df[df[cume_cols].isin(_NO_DATA).any(1)]\n\n for index, row in no_data.iterrows():\n facility = df.loc[\n (df.Facility == row.Facility) &\n (df.County == row.County) &\n (df.City == row.City)]\n\n prev_dates = [x for x in set(facility.Date) if x < row.Date]\n if len(prev_dates) == 0:\n flask.current_app.logger.info('First outbreak date for %s contains a \"no data\" string, carrying it forward...' % row.Facility)\n continue\n\n most_recent_date = max(prev_dates)\n\n prev_row = df.loc[\n (df.Date == most_recent_date) &\n (df.Facility == row.Facility) &\n (df.County == row.County) &\n (df.City == row.City)].iloc[0]\n\n for col in cume_cols:\n if row[col] in _NO_DATA:\n df.loc[index, col] = prev_row[col]\n\n return df\n","sub_path":"app/api/replace_no_data.py","file_name":"replace_no_data.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"16403908","text":"import TIS\r\n\r\n# This sample shows, how to control the focus and, if availabe the zoom\r\n# of a motorized lens\r\n# needed packages:\r\n# pyhton-gst-1.0\r\n# tiscamera\r\n\r\n\r\n# Open camera, set video format, framerate and determine, whether the sink is color or bw\r\n# Parameters: Serialnumber, width, height, framerate (numerator only) , color, videowindow\r\n# If color is False, then monochrome / bw format is in memory. If color is True, then RGB32\r\n# colorformat is in memory\r\n\r\nTis = TIS.TIS(\"00001234\", 640, 480, 30, True, True)\r\n# the camera with serial number 10710286 uses a 640x480 video format at 30 fps and the image is converted to\r\n# RGBx, which is similar to RGB32.\r\n\r\nTis.Start_pipeline() # Start the pipeline so the camera streams\r\n\r\n# Tis.List_Properties() # List available properties\r\n\r\n\r\nwhile True:\r\n key = raw_input(\"f : Auto Focus\\nf+ : increase focus\\nf- : decrease focus\\nz+ : increase zoom\\n\"\r\n \"z- : decrease zoom\\nq : quit\\nPlease enter:\")\r\n if key == \"f\":\r\n Tis.Set_Property(\"Focus Auto\", True)\r\n\r\n if key == \"f+\":\r\n focus = Tis.Get_Property(\"Focus\").value\r\n focus = 10\r\n Tis.Set_Property(\"Focus\", focus)\r\n\r\n if key == \"f-\":\r\n focus = Tis.Get_Property(\"Focus\").value\r\n focus -= 10\r\n Tis.Set_Property(\"Focus\", focus)\r\n\r\n if key == \"z+\":\r\n zoom = Tis.Get_Property(\"Zoom\").value\r\n zoom += 1\r\n Tis.Set_Property(\"Zoom\", zoom)\r\n\r\n if key == \"z-\":\r\n zoom = Tis.Get_Property(\"Zoom\").value\r\n zoom -= 1\r\n Tis.Set_Property(\"Zoom\", zoom)\r\n\r\n if key == \"q\":\r\n break\r\n\r\nTis.Stop_pipeline()\r\nprint('Program ends')\r\n\r\n\r\n","sub_path":"Auto Focus On Push in Python/Program.py","file_name":"Program.py","file_ext":"py","file_size_in_byte":1805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"121263488","text":"# coding: utf8\nimport unittest\nimport json\nimport os\nfrom backend.api import app, get_images\n\n\nclass ImageTestCase(unittest.TestCase):\n def setUp(self):\n self.app = app\n self.client = app.test_client()\n\n def test_can_get(self):\n response = self.client.get('/api/images/')\n self.assertEqual(response.status_code, 200)\n payload = json.loads(response.data)\n self.assertIn('items', payload)\n self.assertEqual(len(payload['items']), len(os.listdir(app.config['UPLOAD_DIR'])))\n\n def test_can_post(self):\n response = self.client.post('/api/images/',\n data={'file': ('uploads/1.jpeg', 'test.jpeg')},\n content_type='multipart/form-data')\n self.assertEqual(response.status_code, 200)\n payload = json.loads(response.data)\n self.assertEqual(payload['url'], \"http://localhost:5000/uploads/test.jpeg\")\n\n def test_bad_request_on_no_file(self):\n response = self.client.post('/api/images/',\n content_type='multipart/form-data')\n self.assertEqual(response.status_code, 400)\n\n def tearDown(self):\n test_file = os.path.abspath(os.path.join(app.config['UPLOAD_DIR'], 'test.jpeg'))\n if os.path.exists(test_file):\n os.system('rm %s' % test_file)\n","sub_path":"testsuite/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"145512243","text":"\nimport acquire as acq\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler\n\n\ndef drop_blank_charge(df):\n df2 = df.copy()\n df2 = df2[df2['total_charges'] != ' ']\n df2['total_charges'] = df2.total_charges.astype(float)\n return df2\n\ndef encode_churn(df):\n encoder = LabelEncoder()\n encoder.fit(df.churn)\n return df.assign(churn_encode = encoder.transform(df.churn))\n\ndef tenure_yearly(df):\n df[['tenure_yearly']] = df[['tenure']]//12\n return df\n\ndef multiple_lines_encode(df):\n tdf = df.copy()\n tdf['multiple_lines'].replace('No phone service', '0', inplace = True)\n tdf['multiple_lines'].replace('No', '1', inplace = True)\n tdf['multiple_lines'].replace('Yes','2', inplace=True)\n df['phone_id'] = tdf.multiple_lines.astype('int')\n return df\n\ndef streaming_movies_encode(df):\n tdf = df.copy()\n tdf['streaming_movies'].replace('No internet service', '0', inplace = True)\n tdf['streaming_movies'].replace('No', '0', inplace = True)\n tdf['streaming_movies'].replace('Yes','1', inplace=True)\n df['movies_encode'] = tdf.streaming_movies.astype('int')\n return df\n\ndef streaming_tv_encode(df):\n tdf = df.copy()\n tdf['streaming_tv'].replace('No internet service', '0', inplace = True)\n tdf['streaming_tv'].replace('No', '0', inplace = True)\n tdf['streaming_tv'].replace('Yes','2', inplace=True)\n df['tv_encode'] = tdf.streaming_tv.astype('int')\n return df\n\ndef streaming_combine(df):\n df['streaming_services'] = df.tv_encode + df.movies_encode\n return df\n\ndef online_security_encode(df):\n tdf = df.copy()\n tdf['online_security'].replace('No internet service', '0', inplace = True)\n tdf['online_security'].replace('No', '0', inplace = True)\n tdf['online_security'].replace('Yes', '1', inplace = True)\n df['online_security_encode'] = tdf.online_security.astype('int')\n return df\n\ndef online_backup_encode(df):\n tdf = df.copy()\n tdf['online_backup'].replace('No internet service', '0', inplace = True)\n tdf['online_backup'].replace('No', '0', inplace = True)\n tdf['online_backup'].replace('Yes', '2', inplace = True)\n df['online_backup_encode'] = tdf.online_backup.astype('int')\n return df\n\ndef online_svc_combine(df):\n df['online_security_backup'] = df.online_security_encode + df.online_backup_encode\n return df\n\ndef household_combine(df):\n tdf = df.copy()\n tdf.dependents.replace('No','0', inplace=True)\n tdf.dependents.replace('Yes','2', inplace=True)\n tdf.partner.replace('Yes','1', inplace=True)\n tdf.partner.replace('No','0', inplace=True)\n df['household_type_id'] = tdf.partner.astype('int') + tdf.dependents.astype('int')\n return df\n\ndef internet_type_id_encode(df):\n tdf = df.copy()\n tdf.internet_service_type_id.replace(3,0, inplace = True)\n df.internet_service_type_id = tdf.internet_service_type_id\n return df\n\ndef gender_encode(df):\n tdf = df.copy()\n tdf.gender.replace('Female', '0',inplace = True)\n tdf.gender.replace('Male', '1',inplace = True)\n df['gender_encode'] = tdf.gender.astype('int')\n return df\n\ndef paperless_billing_encode(df):\n tdf = df.copy()\n tdf.paperless_billing.replace('No', '0',inplace = True)\n tdf.paperless_billing.replace('Yes', '1',inplace = True)\n df['paperless_billing_encode'] = tdf.paperless_billing.astype('int')\n return df\n\ndef tech_support_encode(df):\n tdf = df.copy()\n tdf['tech_support'].replace('No internet service', '0', inplace = True)\n tdf['tech_support'].replace('No', '1', inplace = True)\n tdf['tech_support'].replace('Yes','2', inplace=True)\n df['tech_support_encode'] = tdf.tech_support.astype('int')\n return df\n\ndef device_protection_encode(df):\n tdf = df.copy()\n tdf['device_protection'].replace('No internet service', '0', inplace = True)\n tdf['device_protection'].replace('No', '1', inplace = True)\n tdf['device_protection'].replace('Yes','2', inplace=True)\n df['device_protection_encode'] = tdf.device_protection.astype('int')\n return df\n\ndef df_value_counts(df):\n for c in df.columns:\n return df[c].value_counts()\n\ndef scale_total_charges(df1,df2):\n\n a = df1.copy()\n b = df2.copy()\n scaler = MinMaxScaler()\n scaler.fit(a[['total_charges']])\n a['total_charges_scaled'] = scaler.transform(a[['total_charges']])\n b['total_charges_scaled'] = scaler.transform(b[['total_charges']])\n\n return [a,b]\n\ndef scale_monthly_charges(df1,df2):\n a = df1.copy()\n b = df2.copy()\n scaler = MinMaxScaler()\n scaler.fit(a[['monthly_charges']])\n a['monthly_charges_scaled'] = scaler.transform(a[['monthly_charges']])\n b['monthly_charges_scaled'] = scaler.transform(b[['monthly_charges']])\n\n return [a,b]\n\ndef scale_split_data(df1,df2):\n a = df1.copy()\n b = df2.copy()\n a,b = scale_monthly_charges(a,b)\n a,b = scale_total_charges(a,b)\n return [a,b]\n\ndef prep_telco(df):\n return df.pipe(drop_blank_charge)\\\n .pipe(tenure_yearly)\\\n .pipe(encode_churn)\\\n .pipe(multiple_lines_encode)\\\n .pipe(streaming_movies_encode)\\\n .pipe(streaming_tv_encode)\\\n .pipe(streaming_combine)\\\n .pipe(online_security_encode)\\\n .pipe(online_backup_encode)\\\n .pipe(online_svc_combine)\\\n .pipe(household_combine)\\\n .pipe(internet_type_id_encode)\\\n .pipe(gender_encode)\\\n .pipe(paperless_billing_encode)\\\n .pipe(tech_support_encode)\\\n .pipe(device_protection_encode)\n","sub_path":"prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":5471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"5451252","text":"\"\"\"Unit and regression tests for the Airviro system module.\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom pyAirviro import system\nimport pyAirviro.tests\n\n\nclass AirviroVersionTests(pyAirviro.tests.TestCase):\n\n \"\"\"Unit and regression tests for the Airviro version handling.\"\"\"\n\n def test_version(self):\n if system.is_airviro():\n self.assertGreater(len(system.version), 0)\n self.assertTrue(\n all(c in '.0123456789' for c in system.version),\n msg=\"system.version = '%s'\" % system.version,\n )\n else:\n self.assertEqual(system.version, system.DEFAULT_VERSION)\n\n def test_version_override(self):\n original_version = system.version\n with system.airviro_version('3.0test'):\n self.assertEqual(system.version, '3.0test')\n self.assertEqual(system.version, original_version)\n","sub_path":"pyAirviro/tests/test_system.py","file_name":"test_system.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"544974731","text":"import urllib.parse\nimport urllib.request\nimport time\nimport hmac\nimport base64\nimport configparser\n\ndef GetSASToken(baseURI,KeyName,KeyValue):\n\texpiry = int(time.time()) + 3600\n\tStringToSign = urllib.parse.quote_plus(baseURI) + '\\n' + str(expiry)\n\th = hmac.new(bytes(SharedAccessKey,\"utf-8\"),\n bytes(StringToSign,\"utf-8\"),\n \"sha256\")\n\t\n\tsignature = base64.b64encode(h.digest())\n\tsasTokenFrame = \"SharedAccessSignature {0}&{1}&se={2}&skn={3}\"\n\tsasToken = sasTokenFrame.format(urllib.parse.urlencode({'sr':baseURI}),\n\t\t\t\turllib.parse.urlencode({'sig':signature}), \n\t\t\t\texpiry, \n\t\t\t\tSharedAccessKeyName)\n\treturn sasToken\n\nconfig = configparser.ConfigParser()\nconfig.read('config')\n\nnamespace = config['AzureServiceBus']['namespace']\nqueueName = config['AzureServiceBus']['queueName']\nbaseURI = 'https://' + namespace + '.servicebus.windows.net/'\n\nSharedAccessKeyName = config['AzureServiceBus']['SharedAccessKeyName']\nSharedAccessKey = config['AzureServiceBus']['SharedAccessKey']\n\nsasToken = GetSASToken(baseURI,SharedAccessKeyName,SharedAccessKey)\n#print(\"StringToSign: \" + StringToSign)\n\nGetQueueRequest = urllib.request.Request(baseURI + queueName)\nGetQueueRequest.add_header('Authorization',sasToken)\n\n#print(ListQueuesRequest.get_full_url())\n#print(ListQueuesRequest.header_items())\n#print(sasToken)\nprint(GetQueueRequest.get_method() + \" \" + GetQueueRequest.get_full_url())\nResponse = urllib.request.urlopen(GetQueueRequest)\n\nprint(\"Response Code: \" + str(Response.getcode()))\nprint(\"Response Body\")\nprint(\"--------------------------------------------------------------\")\nprint(Response.read())\nprint(\"--------------------------------------------------------------\")\n","sub_path":"AzureServiceBus/GetQueueREST.py","file_name":"GetQueueREST.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"504190888","text":"import torch\nimport torchvision\nimport numpy as np\nimport numpy.linalg as LA\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torchvision.utils import save_image\nfrom torchvision import datasets\nimport torchvision.transforms as transforms\nimport time\nimport pandas as pd\nimport torch.utils.data as data_utils\nfrom torch.utils.data import Dataset, DataLoader\n####hyper paramters\nlearning_rate=0.001\ndownload_fraction=1.\nupload_fraction=0.1\nbatch_size=100\nEpoch=500\ndata_num=32560 \nn=10 #num of users\n####accuracy\ndef accuracy(label,output):\n\t_,prediction=torch.max(output.data,1)\n\treturn (prediction==label).sum()\n####load data\ndataset= pd.read_csv('../data_from_chong_xiang_mlaas/dp_data/pudf/hospital_training_ori.csv')\nnumber=len(dataset)\ndata_num=number\nfeatures=dataset.ix[:,1:].as_matrix()\ntargets=dataset.ix[:,0].as_matrix().astype(np.int64)\nfeatures=torch.FloatTensor(features)\ntargets=torch.LongTensor(targets)\nadult_dataset = data_utils.TensorDataset(features, targets)\ntrainloader = DataLoader(adult_dataset, batch_size=batch_size,shuffle=True, num_workers=4)\t\t\ntestloader = DataLoader(adult_dataset, batch_size=batch_size,shuffle=True, num_workers=4)\t\ndef get_all_training_data():\n\tAll_train_data=torch.Tensor([])\n\tAll_train_label=torch.LongTensor([])\n\tj=0\n\tfor i,data in enumerate(trainloader,0):\n\t\timage,label=data\n\t\tAll_train_label=torch.cat((All_train_label,label),0)\n\t\tAll_train_data=torch.cat((All_train_data,image),0)\n\t\tj=j+1\n\t\tif j==data_num/batch_size:\n\t\t\tbreak\n\treturn All_train_data,All_train_label\n####model definitions\nclass Net(nn.Module):\n\tdef __init__(self):\n\t\tsuper(Net,self).__init__()\n\t\tself.fully=nn.Linear(776,10)\n\tdef forward(self,x):\n\t\tx=self.fully(x)\n\t\treturn x\n\nserver=Net()\ncriterion=nn.CrossEntropyLoss()\noptimizer_server=optim.Adam(server.parameters(), lr=learning_rate, betas=(0.5, 0.999))\n\nlocal_model=[]\nlocal_optimizer=[]\nfor i in range(n):\n\tlocal_model.append(Net())\n\tlocal_optimizer.append(optim.Adam(local_model[i].parameters(), lr=learning_rate, betas=(0.5, 0.999)))\n\ndef get_data(index,step,data,label):\n\tsize=data_num/n\n\tleftsize=index*size+step*batch_size\n\trightsize=min(leftsize+batch_size,data_num)\n\treturn data[leftsize:rightsize],label[leftsize:rightsize]\n####training_protocol\ndef get_dimension(shape):\n\tnum=1\n\tfor i in shape:\n\t\tnum*=i\n\treturn num,shape\ndef download_parameters():\n\treturn server.state_dict()\ndef upload_parameters(prev_params,cur_params):\n\tfor k in cur_params:\n\t\tcur_params[k]=cur_params[k]-prev_params[k]\n\tall_parameters=[]\n\tfor k in cur_params:\n\t\tval=cur_params[k]\n\t\tshape=val.size()\n\t\tnum,result=get_dimension(shape)\n\t\tval=val.view([1,num])\n\t\tfor j in range(num):\n\t\t\tall_parameters.append(abs(val[0][j]))\n\tall_parameters=sorted(all_parameters,reverse=True)\n\tflag=all_parameters[int(len(all_parameters)*upload_fraction)]\n\tfor j in cur_params:\n\t\tval=cur_params[j]\n\t\tshape=val.size()\n\t\tnum,result=get_dimension(shape)\n\t\tval=val.view([-1,num])\n\t\tfor k in range(num):\n\t\t\tif abs(val[0][k]))\n# See LICENSE file for full copyright and licensing details.\n# \"License URL : \"\n#\n##########################################################################\n\nfrom odoo import api, fields, models, _\n\nclass ResConfigSettings(models.TransientModel):\n _inherit = 'res.config.settings'\n\n group_order_global_discount_so = fields.Boolean(\"A global discount on sale order\",\n implied_group='discount_sale_order.group_order_global_discount_so',\n help=\"\"\"Allows to give a global discount on sale order. \"\"\")\n global_discount_tax_so = fields.Selection([\n ('untax', 'Untaxed amount'),\n ('taxed', 'Tax added amount'),\n ], \"Global Discount Calculation\",\n help=\"Global disount calculation will be ( \\\n 'untax' : Global discount will be applied before applying tax, \\\n 'taxed' : Global disount will be applied after applying tax)\")\n group_discount_sale_line = fields.Boolean(\"Apply discount on sale order line\",\n implied_group='discount_sale_order.group_discount_sale_line',\n help=\"\"\"Allows to give discount on sale order line. \"\"\")\n discount_account_so = fields.Many2one(\n 'account.account',\n string=\"Discount Account\",\n help=\"\"\"Account for Global discount on sale order.\"\"\")\n\n\n @api.multi\n def set_values(self):\n super(ResConfigSettings, self).set_values()\n IrConfigPrmtr = self.env['ir.config_parameter'].sudo()\n IrConfigPrmtr.set_param(\n \"sale.global_discount_tax_so\", self.global_discount_tax_so\n )\n IrConfigPrmtr.set_param(\n \"sale.discount_account_so\", self.discount_account_so.id\n )\n\n @api.model\n def get_values(self):\n res = super(ResConfigSettings, self).get_values()\n IrConfigPrmtr = self.env['ir.config_parameter'].sudo()\n globalDiscountTax = IrConfigPrmtr.get_param('sale.global_discount_tax_so')\n discount_account_so = int(IrConfigPrmtr.get_param('sale.discount_account_so'))\n res.update({\n 'global_discount_tax_so' : globalDiscountTax,\n 'discount_account_so' : discount_account_so,\n })\n return res\n","sub_path":"discount_sale_order/models/res_config.py","file_name":"res_config.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"494014349","text":"budget = float(input('Enter your budget for this month: '))\n\nanswer = True\ncounter = 1\nexpenses = 0\n\nwhile answer:\n answer = input('Enter the quantity for expense %d (Enter to finish): ' % counter)\n if answer:\n expenses += int(answer)\n counter += 1\n\nfinal = budget - expenses\nprint(\"The user's final amount is\", final)","sub_path":"ch4_ex/3_budget_analysis.py","file_name":"3_budget_analysis.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"344482596","text":"bl_info = {\r\n \"name\": \"EasyRend\",\r\n \"author\": \"Crafto 1337\",\r\n \"version\": (0, 1, 1),\r\n \"blender\": (2, 80, 0),\r\n \"description\": \"Easily change the render settings of your project\",\r\n \"warning\": \"\",\r\n \"wiki_url\": \"\",\r\n \"category\": \"Render\",\r\n}\r\n\r\nimport bpy\r\nfrom bpy.types import PropertyGroup\r\n\r\n#def LoadPreset(context):\r\n \r\n \r\n \r\ndef overwrite(context):\r\n scene = context.scene\r\n propies = scene.properties\r\n \r\n if propies.engine == 'OP1':\r\n bpy.context.scene.render.engine = 'BLENDER_EEVEE'\r\n bpy.context.scene.eevee.taa_render_samples = propies.samples\r\n elif propies.engine == 'OP2':\r\n bpy.context.scene.render.engine = 'BLENDER_WORKBENCH'\r\n else:\r\n bpy.context.scene.render.engine = 'CYCLES'\r\n bpy.context.scene.cycles.samples = propies.samples\r\n bpy.context.scene.cycles.max_bounces = propies.bounces\r\n bpy.context.scene.render.tile_x = propies.tileSize\r\n bpy.context.scene.render.tile_y = propies.tileSize\r\n \r\n if propies.device == 'OP1':\r\n bpy.context.scene.cycles.device = 'CPU'\r\n else:\r\n bpy.context.scene.cycles.device = 'GPU'\r\n\r\n bpy.context.scene.render.resolution_x = propies.resX\r\n bpy.context.scene.render.resolution_y = propies.resY\r\n bpy.context.scene.render.resolution_percentage = propies.resPercent\r\n\r\n if propies.output == 'OP1':\r\n bpy.context.scene.render.image_settings.file_format = 'PNG'\r\n if propies.transparent == True:\r\n bpy.context.scene.render.film_transparent = True\r\n bpy.context.scene.render.image_settings.color_mode = 'RGBA'\r\n else:\r\n bpy.context.scene.render.film_transparent = False\r\n bpy.context.scene.render.image_settings.color_mode = 'RGB'\r\n else:\r\n bpy.context.scene.render.image_settings.file_format = 'FFMPEG'\r\n bpy.context.scene.render.ffmpeg.format = \"MPEG4\"\r\n bpy.context.scene.render.ffmpeg.codec = \"H264\"\r\n bpy.context.scene.render.ffmpeg.gopsize = 1\r\n bpy.context.scene.render.ffmpeg.video_bitrate = propies.bitrate\r\n bpy.context.scene.render.ffmpeg.minrate = propies.min_bitrate\r\n bpy.context.scene.render.ffmpeg.maxrate = propies.max_bitrate\r\n \r\n\r\n bpy.context.scene.render.fps = propies.fps\r\n bpy.context.scene.frame_step = propies.step\r\n \r\n if propies.quality == 'OP1':\r\n bpy.context.scene.render.ffmpeg.constant_rate_factor = 'LOWEST'\r\n elif propies.quality == 'OP2':\r\n bpy.context.scene.render.ffmpeg.constant_rate_factor = 'VERYLOW'\r\n elif propies.quality == 'OP3':\r\n bpy.context.scene.render.ffmpeg.constant_rate_factor = 'LOW'\r\n elif propies.quality == 'OP4':\r\n bpy.context.scene.render.ffmpeg.constant_rate_factor = 'MEDIUM'\r\n elif propies.quality == 'OP5':\r\n bpy.context.scene.render.ffmpeg.constant_rate_factor = 'HIGH'\r\n elif propies.quality == 'OP6':\r\n bpy.context.scene.render.ffmpeg.constant_rate_factor = 'PERC_LOSSLESS'\r\n elif propies.quality == 'OP7':\r\n bpy.context.scene.render.ffmpeg.constant_rate_factor = 'LOSSLESS'\r\n else:\r\n bpy.context.scene.render.ffmpeg.constant_rate_factor = 'NONE'\r\n \r\n bpy.context.scene.render.filepath = propies.path\r\n\r\nclass LoadPresetButton(bpy.types.Operator):\r\n bl_idname = \"object.load_preset\"\r\n bl_label = \"Load Preset Button\"\r\n\r\n @classmethod\r\n def poll(cls, context):\r\n return context.active_object is not None\r\n\r\n def execute(self, context):\r\n LoadPreset(context)\r\n return {'FINISHED'}\r\n\r\nclass OverwriteButton(bpy.types.Operator):\r\n bl_idname = \"object.overwrite\"\r\n bl_label = \"Overwrite Button\"\r\n\r\n @classmethod\r\n def poll(cls, context):\r\n return context.active_object is not None\r\n\r\n def execute(self, context):\r\n overwrite(context)\r\n return {'FINISHED'}\r\n\r\nclass Properties(bpy.types.PropertyGroup):\r\n \r\n preset : bpy.props.EnumProperty(\r\n name = \"Presets\",\r\n description = \"\",\r\n items = [\r\n ('OP1', \"Fastest\", \"Fastest, but with the worst quality\"),\r\n ('OP2', \"Fast\", \"Fast, but with a low quality\"),\r\n ('OP3', \"Blanced\", \"A balance out of speed and quality\"),\r\n ('OP4', \"Good\", \"Slow, but with a good quality\"),\r\n ('OP4', \"Best\", \"Slowest, but with the best quality\"),\r\n ]\r\n )\r\n \r\n engine : bpy.props.EnumProperty(\r\n name = \"Render Engine\",\r\n description = \"\",\r\n items = [\r\n ('OP1', \"EEVEE\", \"Use the EEVEE render engine\"),\r\n ('OP2', \"Workbench\", \"Use the Workbench render engine\"),\r\n ('OP3', \"Cycles\", \"Use the Cycles render engine\")\r\n ]\r\n )\r\n \r\n device : bpy.props.EnumProperty(\r\n name = \"Render Device\",\r\n description = \"\",\r\n items = [\r\n ('OP1', \"CPU\", \"Use CPU for rendering\"),\r\n ('OP2', \"GPU\", \"Use GPU for rendering\")\r\n ]\r\n )\r\n \r\n samples : bpy.props.IntProperty(\r\n name = \"Samples\",\r\n #description = \"\",\r\n soft_min = 1,\r\n default = 64\r\n )\r\n \r\n bounces : bpy.props.IntProperty(\r\n name = \"Light Bounces\",\r\n #description = \"\"\r\n soft_min = 1,\r\n default = 12\r\n )\r\n\r\n resX : bpy.props.IntProperty(\r\n name = \"Resolution X\",\r\n #description = \"\",\r\n soft_min = 4,\r\n soft_max = 65536,\r\n default = 1920\r\n )\r\n \r\n resY : bpy.props.IntProperty(\r\n name = \"Resolution Y\",\r\n #description = \"\",\r\n soft_min = 4,\r\n soft_max = 65536,\r\n default = 1080\r\n )\r\n \r\n resPercent : bpy.props.IntProperty(\r\n name = \"Resolution %\",\r\n #description = \"\",\r\n soft_min = 1,\r\n soft_max = 100,\r\n default = 100\r\n )\r\n \r\n tileSize : bpy.props.IntProperty(\r\n name = \"Tile Size\",\r\n #description = \"\",\r\n soft_min = 8,\r\n soft_max = 512,\r\n default = 32\r\n )\r\n\r\n output : bpy.props.EnumProperty(\r\n name = \"Output Type\",\r\n description = \"\",\r\n items = [\r\n ('OP1', \"Image\", \"Give an still image as output\"),\r\n ('OP2', \"Video\", \"Give an video as output\")\r\n ]\r\n )\r\n \r\n transparent : bpy.props.BoolProperty(\r\n name = \"Transparent\"\r\n )\r\n \r\n animation : bpy.props.BoolProperty(\r\n name = \"Animation\"\r\n )\r\n \r\n fps : bpy.props.IntProperty(\r\n name = \"Frame Rate\",\r\n #description = \"\",\r\n soft_min = 1,\r\n soft_max = 120,\r\n default = 24\r\n )\r\n \r\n step : bpy.props.IntProperty(\r\n name = \"Frame Step\",\r\n #description = \"\",\r\n soft_min = 1,\r\n soft_max = 100,\r\n default = 1\r\n )\r\n\r\n quality : bpy.props.EnumProperty(\r\n name = \"Output Quality\",\r\n description = \"\",\r\n items = [\r\n ('OP1', \"Lowest quality\", \"worst quality\"),\r\n ('OP2', \"Very low quality\", \"better, but still bad\"),\r\n ('OP3', \"Low quality\", \"low quality\"),\r\n ('OP4', \"medium quality\", \"normal quality\"),\r\n ('OP5', \"High quality\", \"high quality\"),\r\n ('OP6', \"Perceptually lossless\", \"nearly lossless quality\"),\r\n ('OP7', \"Lossless\", \"lossless quality\"),\r\n ('OP8', \"Constant Bitrate\", \"the best quality\")\r\n ],\r\n default = 'OP4'\r\n )\r\n \r\n bitrate : bpy.props.IntProperty(\r\n name = \"Bitrate\",\r\n #description = \"\",\r\n soft_min = 1,\r\n soft_max = 10000,\r\n default = 6000\r\n )\r\n \r\n min_bitrate : bpy.props.IntProperty(\r\n name = \"Minumum\",\r\n #description = \"\",\r\n soft_min = 1,\r\n soft_max = 10000,\r\n default = 1\r\n )\r\n \r\n max_bitrate : bpy.props.IntProperty(\r\n name = \"Maximum\",\r\n #description = \"\",\r\n soft_min = 1,\r\n soft_max = 10000,\r\n default = 9000\r\n )\r\n \r\n speed : bpy.props.EnumProperty(\r\n name = \"Encoding Speed\",\r\n description = \"\",\r\n items = [\r\n ('OP1', \"Slowest\", \"Very slow, but highest Quality\"),\r\n ('OP2', \"Good\", \"Average speed. Not too slow and no big quality lossage\"),\r\n ('OP3', \"Realtime\", \"If you need it really fast, then this is your option, but the quality isn´t the best\")\r\n ],\r\n default = 'OP2'\r\n )\r\n \r\n path : bpy.props.StringProperty(\r\n name = \"Output Path\",\r\n #description = \"My description\",\r\n\tsubtype='FILE_PATH'\r\n )\r\n\r\nclass UI(bpy.types.Panel):\r\n bl_space_type = 'VIEW_3D'\r\n bl_region_type = 'UI'\r\n bl_category = \"EasyRend\"\r\n bl_label = 'EasyRend'\r\n \r\n def draw(self, context):\r\n layout = self.layout\r\n col = layout.column(align=True)\r\n scene = context.scene\r\n propies = scene.properties\r\n \r\n row = col.row()\r\n \r\n col.separator()\r\n col.prop(propies, \"engine\")\r\n \r\n \r\n \r\n if propies.engine == 'OP3':\r\n col.separator()\r\n col.prop(propies, \"device\")\r\n col.separator()\r\n col.prop(propies, \"tileSize\")\r\n col.separator()\r\n else:\r\n col.separator()\r\n \r\n col.prop(propies, \"samples\")\r\n \r\n if propies.engine == 'OP3':\r\n col.separator()\r\n col.prop(propies, \"bounces\")\r\n col.separator()\r\n else:\r\n col.separator()\r\n \r\n col.prop(propies, \"resX\")\r\n col.prop(propies, \"resY\")\r\n col.prop(propies, \"resPercent\", slider=True)\r\n \r\n col.separator()\r\n col.prop(propies, \"output\")\r\n \r\n if propies.output == 'OP1':\r\n col.separator()\r\n col.prop(propies, \"transparent\")\r\n col.separator()\r\n col.prop(propies, \"animation\")\r\n col.separator()\r\n else:\r\n col.separator()\r\n \r\n if propies.animation == True:\r\n col.prop(propies, \"fps\")\r\n \r\n col.separator()\r\n col.prop(propies, \"step\")\r\n col.separator()\r\n else:\r\n col.separator()\r\n \r\n if propies.output == 'OP2':\r\n col.prop(propies, \"quality\")\r\n \r\n if propies.quality == 'OP8':\r\n col.separator()\r\n col.prop(propies, \"bitrate\")\r\n col.prop(propies, \"min_bitrate\")\r\n col.prop(propies, \"max_bitrate\")\r\n col.separator()\r\n else:\r\n col.separator()\r\n \r\n col.prop(propies, \"speed\")\r\n col.separator()\r\n else:\r\n col.separator()\r\n \r\n col.prop(propies, \"path\")\r\n\r\n col.separator()\r\n row = col.row()\r\n row.operator(\"object.overwrite\", text=\"Overwrite\")\r\n \r\n col.separator()\r\n row = col.row()\r\n if propies.animation == True or propies.output == 'OP2':\r\n row.operator(\"render.render\", text=\"Render\", icon='RENDER_ANIMATION').animation = True\r\n else:\r\n row.operator(\"render.render\", text=\"Render\", icon='RENDER_STILL')\r\n\r\ndef register():\r\n bpy.utils.register_class(LoadPresetButton)\r\n bpy.utils.register_class(OverwriteButton)\r\n bpy.utils.register_class(Properties)\r\n \r\n bpy.types.Scene.properties = bpy.props.PointerProperty(type= Properties)\r\n\r\n bpy.utils.register_class(UI)\r\n\r\ndef unregister():\r\n bpy.utils.unregister_class(LoadPresetButton)\r\n bpy.utils.unregister_class(OverwriteButton)\r\n bpy.utils.unregister_class(Properties)\r\n \r\n del bpy.types.Scene.properties\r\n\r\n bpy.utils.register_class(UI)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n register()","sub_path":"Archive/EasyRend 0.1.1.py","file_name":"EasyRend 0.1.1.py","file_ext":"py","file_size_in_byte":11837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"175154967","text":"import chem_lex.ChemlabLexer as Lexer\nimport chem_parse.ChemlabParser as Parser\nimport sys\n\n\ndef main():\n # If no file name passed when running we open the ChemLAB command line, if not we try to parse the file passed\n try:\n # Check if something was passed. If not, we open command line theme\n trace = False\n lexer = Lexer.ChemLABLexer()\n lexer.build()\n parser = Parser.ChemlabParser()\n parser.build(trace=trace)\n if len(sys.argv) <= 1:\n while True:\n try:\n buff = input(\"ChemLAB >>\")\n if not buff:\n continue\n if trace:\n print(\"Buffer Content: \")\n print(buff)\n print(\"Tokenized buffer: \")\n lexer.test(buff)\n print(\"Parsing File...\")\n parser.parseContent(buff, lexer.lexer)\n except KeyboardInterrupt:\n exit()\n except Exception as e:\n print(\"Error on line `\"+ buff +\"`\\nPlease try again\")\n print(\"Error was: \"+str(e))\n continue\n else:\n filename = sys.argv[1]\n if trace:\n print(\"Prepping to parse file \"+filename)\n file = open(filename, 'r')\n s = file.read()\n if trace:\n print(\"File Content: \")\n print(s)\n print(\"Tokenized file: \")\n lexer.test(s)\n print(\"Parsing File...\")\n parser.parseContent(s, lexer.lexer)\n except (FileNotFoundError, EOFError) as e:\n print(\"Error reading file. Could not open or read.\\n\")\n except Exception as e2:\n print(\"Error parsing content. Could not parse file.\\n\")\n print(\"Error found: \"+str(e2))\n finally:\n try:\n file.close()\n except NameError:\n pass\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"545718797","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom subprocess import check_output\nfrom keras.models import Model\nfrom keras.layers import Dense, Embedding, Input , Activation\nfrom keras.layers import LSTM, Bidirectional, GlobalMaxPool1D, Dropout, GRU\nfrom keras.preprocessing import text, sequence\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers import Flatten , Conv1D , GlobalMaxPooling1D , GlobalAveragePooling1D, MaxPooling1D\nfrom keras.models import Sequential\nimport re , os \nimport logging, gensim , random\nfrom gensim.models import word2vec\nfrom keras.layers.merge import concatenate\nimport nltk \nfrom collections import OrderedDict\nimport sys\nfrom nltk.tokenize import word_tokenize\n\nif sys.version_info < (3,):\n maketrans = string.maketrans\nelse:\n maketrans = str.maketrans\n\ndef text_to_word_sequence(text,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True, split=\" \"):\n \"\"\"Converts a text to a sequence of words (or tokens).\n # Arguments\n text: Input text (string).\n filters: Sequence of characters to filter out.\n lower: Whether to convert the input to lowercase.\n split: Sentence split marker (string).\n # Returns\n A list of words (or tokens).\n \"\"\"\n if lower:\n text = text.lower()\n\n if sys.version_info < (3,) and isinstance(text, unicode):\n translate_map = dict((ord(c), unicode(split)) for c in filters)\n else:\n translate_map = maketrans(filters, split * len(filters))\n\n text = text.translate(translate_map)\n #seq = text.split(split)\n seq = text.split()\n \n #seq = word_tokenize(text)\n #print(\"text:\",seq)\n \n #pos_seq = nltk.pos_tag(text)\n #return [i for i in seq if i]\n return nltk.pos_tag(seq)\n\nclass TokenizerPOS(text.Tokenizer):\n \"\"\"Text tokenization utility class.\n This class allows to vectorize a text corpus, by turning each\n text into either a sequence of integers (each integer being the index\n of a token in a dictionary) or into a vector where the coefficient\n for each token could be binary, based on word count, based on tf-idf...\n # Arguments\n num_words: the maximum number of words to keep, based\n on word frequency. Only the most common `num_words` words will\n be kept.\n filters: a string where each element is a character that will be\n filtered from the texts. The default is all punctuation, plus\n tabs and line breaks, minus the `'` character.\n lower: boolean. Whether to convert the texts to lowercase.\n split: character or string to use for token splitting.\n char_level: if True, every character will be treated as a token.\n oov_token: if given, it will be added to word_index and used to\n replace out-of-vocabulary words during text_to_sequence calls\n By default, all punctuation is removed, turning the texts into\n space-separated sequences of words\n (words maybe include the `'` character). These sequences are then\n split into lists of tokens. They will then be indexed or vectorized.\n `0` is a reserved index that won't be assigned to any word.\n \"\"\"\n\n def __init__(self, num_words=None,\n filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n lower=True,\n split=' ',\n char_level=False,\n oov_token=None,\n **kwargs):\n # Legacy support\n if 'nb_words' in kwargs:\n warnings.warn('The `nb_words` argument in `Tokenizer` '\n 'has been renamed `num_words`.')\n num_words = kwargs.pop('nb_words')\n if kwargs:\n raise TypeError('Unrecognized keyword arguments: ' + str(kwargs))\n\n self.word_counts = OrderedDict()\n self.word_docs = {}\n self.pos_counts = OrderedDict()\n self.pos_docs = {}\n \n self.filters = filters\n self.split = split\n self.lower = lower\n \n self.num_words = num_words\n \n self.document_count = 0\n self.char_level = char_level\n self.oov_token = oov_token\n \n def texts_to_sequences(self, texts):\n \"\"\"Transforms each text in texts in a sequence of integers.\n Only top \"num_words\" most frequent words will be taken into account.\n Only words known by the tokenizer will be taken into account.\n # Arguments\n texts: A list of texts (strings).\n # Returns\n A list of sequences.\n \"\"\"\n res = []\n res_pos = [] \n for vect,vect_pos in self.texts_to_sequences_generator(texts):\n res.append(vect)\n res_pos.append(vect_pos)\n return res , res_pos\n\n def texts_to_sequences_generator(self, texts):\n \"\"\"Transforms each text in texts in a sequence of integers.\n Only top \"num_words\" most frequent words will be taken into account.\n Only words known by the tokenizer will be taken into account.\n # Arguments\n texts: A list of texts (strings).\n # Yields\n Yields individual sequences.\n \"\"\"\n num_words = self.num_words\n for text in texts:\n seq = text_to_word_sequence(text,self.filters,self.lower,self.split)\n vect = []\n res_pos = [] \n for w,p in seq:\n i = self.word_index.get(w)\n j = self.word_index_pos.get(p)\n if i is not None:\n if num_words and i >= num_words:\n continue\n else:\n vect.append(i)\n res_pos.append(j)\n elif self.oov_token is not None:\n i = self.word_index.get(self.oov_token)\n j = self.word_index_pos.get(self.oov_token)\n if i is not None:\n vect.append(i)\n res_pos.append(j)\n yield vect , res_pos\n \n def fit_on_texts(self, texts):\n \"\"\"Updates internal vocabulary based on a list of texts.\n Required before using `texts_to_sequences` or `texts_to_matrix`.\n # Arguments\n texts: can be a list of strings,\n or a generator of strings (for memory-efficiency)\n \"\"\"\n self.document_count = 0\n print(len(texts))\n for text in texts:\n self.document_count += 1\n seq = text_to_word_sequence(text,self.filters,self.lower,self.split)\n #print(str(seq))\n for w,pos in seq:\n if w in self.word_counts:\n self.word_counts[w] += 1\n else:\n self.word_counts[w] = 1\n \n if pos in self.pos_counts:\n self.pos_counts[pos] += 1\n else:\n self.pos_counts[pos] = 1\n \n \n for w in set([w for w,pos in seq]):\n if w in self.word_docs:\n self.word_docs[w] += 1\n else:\n self.word_docs[w] = 1\n \n for pos in set([pos for w,pos in seq]):\n if pos in self.pos_docs:\n self.pos_docs[pos] += 1\n else:\n self.pos_docs[pos] = 1\n\n wcounts = list(self.word_counts.items())\n wcounts.sort(key=lambda x: x[1], reverse=True)\n sorted_voc = [wc[0] for wc in wcounts]\n # note that index 0 is reserved, never assigned to an existing word\n self.word_index = dict(list(zip(sorted_voc, list(range(1, len(sorted_voc) + 1)))))\n \n pcounts = list(self.pos_counts.items())\n pcounts.sort(key=lambda x: x[1], reverse=True)\n sorted_voc_pos = [wc[0] for wc in pcounts]\n # note that index 0 is reserved, never assigned to an existing word\n self.word_index_pos = dict(list(zip(sorted_voc_pos, list(range(1, len(sorted_voc_pos) + 1)))))\n\n if self.oov_token is not None:\n i = self.word_index.get(self.oov_token)\n if i is None:\n self.word_index[self.oov_token] = len(self.word_index) + 1\n i = self.word_index_pos.get(self.oov_token)\n if i is None:\n self.word_index_pos[self.oov_token] = len(self.word_index_pos) + 1\n\n self.index_docs = {}\n for w, c in list(self.word_docs.items()):\n self.index_docs[self.word_index[w]] = c\n \n self.index_docs_pos = {}\n for w, c in list(self.pos_docs.items()):\n self.index_docs_pos[self.word_index_pos[w]] = c\n\n\n\n\n### --------------------> conf \nlist_classes = [\"toxic\", \"severe_toxic\", \"obscene\", \"threat\", \"insult\", \"identity_hate\"]\nmax_features = 20000\n\n\n######## ARMONY #####################################\n# maxlen 200 (2x)\n# EMBEDDING_DIM 100 (x) <--- \n# GRU 100 (layers = 1) (x) \n# num_dense 100 (x) \n#####################################################\n\n\nmaxlen = 600\n \nEMBEDDING_DIM_1 = 300\nwe_fn_1='glove.840B.300d.txt'\n\nEMBEDDING_DIM_2 = 100\n\nrate_drop_dense = 0.2\nnum_dense = EMBEDDING_DIM_1 + EMBEDDING_DIM_2\n\nbatch_size = 32\nepochs = 10\n\n### --------------------------> load data \ntrain = pd.read_csv(\"data/train.csv\")\n#train = train[:2000]\ntest = pd.read_csv(\"data/test.csv\")\n#test = test[:2000]\ntrain = train.sample(frac=1)\n\n\n# pre-processing \ndef pre_process_pre_trained_embed(train,test):\n\tprint('>> Indexing word vectors ...')\n\tembeddings_index_1 = {}\n\tf = open(os.path.join('data', we_fn_1))\n\tfor line in f:\n\t values = line.split(' ')\n\t word = values[0] #print(\"values:\",values)\n\t coefs = np.asarray(values[1:], dtype='float32')\n\t embeddings_index_1[word] = coefs\n\tf.close()\n\tprint('Found %s word vectors. [1]' % len(embeddings_index_1))\n\n\tprint(\">> pre-processing ... \")\n\tlist_sentences_train = train[\"comment_text\"].fillna(\"__NA__\").values\n\ty = train[list_classes].values\n\tlist_sentences_test = test[\"comment_text\"].fillna(\"__NA__\").values\n\n\n # TokenizerPOS\n\ttokenizer = TokenizerPOS(num_words=max_features)\n\ttokenizer.fit_on_texts(list(list_sentences_train) + list(list_sentences_test))\n\tlist_tokenized_train = tokenizer.texts_to_sequences(list(list_sentences_train))\n\tlist_tokenized_test = tokenizer.texts_to_sequences(list(list_sentences_test))\n\n ### ------------ word \n\tword_index = tokenizer.word_index\n\tX_t = sequence.pad_sequences(list_tokenized_train[0], maxlen=maxlen)\n\tX_te = sequence.pad_sequences(list_tokenized_test[0], maxlen=maxlen)\n\n\t# prepare embedding matrix\n\tprint('>> Preparing embedding matrix 1...')\n\tnum_words = min(max_features, len(word_index))\n\tembedding_matrix_1 = np.zeros((num_words, EMBEDDING_DIM_1))\n\tfor word, i in word_index.items():\n\t if i >= max_features:\n\t continue\n\t embedding_vector = embeddings_index_1.get(word)\n\t if embedding_vector is not None:\n\t # words not found in embedding index will be all-zeros.\n\t embedding_matrix_1[i] = embedding_vector\n\n\t### ------------ POS \n\tX_t_POS = sequence.pad_sequences(list_tokenized_train[1], maxlen=maxlen)\n\tX_te_POS = sequence.pad_sequences(list_tokenized_test[1], maxlen=maxlen)\n\n\treturn X_t, X_te, y , embedding_matrix_1 , X_t_POS , X_te_POS\n\n\n\ndef get_bidirectional(embed_size_1 = 200 , embedding_matrix_1 = None, embed_size_2 = 200 , \n #num_lstm = 50 , \n rate_drop_dense = 0.1,\n num_dense = 50):\n \n print(\">> get_model_bidirectional_avg [pre-trained word embeddings]<<\")\n #embedding_layer = Embedding(max_features,embed_size,weights=[embedding_matrix],input_length=maxlen,trainable=True)\n embedding_layer_1 = Embedding(max_features,embed_size_1,weights=[embedding_matrix_1],input_length=maxlen)\n embedding_layer_2 = Embedding(max_features,embed_size_2,input_length=maxlen)\n\n\n inp1 = Input(shape=(maxlen, ) , dtype='int32')\n inp2 = Input(shape=(maxlen, ) , dtype='int32')\n\n x1 = embedding_layer_1(inp1)\n x2 = embedding_layer_2(inp2)\n \n x = concatenate([x1, x2],axis=2)\n\n x = Bidirectional(GRU(num_dense, return_sequences=True, dropout=rate_drop_dense, recurrent_dropout=rate_drop_dense,trainable=True))(x)\n x = GlobalMaxPool1D()(x)\n x = Dense(num_dense, activation=\"relu\")(x)\n x = Dropout(rate_drop_dense)(x)\n x = Dense(6, activation=\"sigmoid\")(x)\n\n model = Model(inputs=[inp1,inp2], outputs=x)\n model.compile(loss='binary_crossentropy',\n optimizer='adam',\n #optimizer='nadam',\n metrics=['accuracy'])\n\n return model\n\n# train \nX_t, X_te, y , embedding_matrix_1 , X_t_POS , X_te_POS = pre_process_pre_trained_embed(train=train,test=test)\n\nmodel = get_bidirectional(embed_size_1 = EMBEDDING_DIM_1 , embedding_matrix_1 = embedding_matrix_1, embed_size_2 = EMBEDDING_DIM_2 , rate_drop_dense = rate_drop_dense,num_dense = num_dense)\nprint(model.summary())\nfile_path=\"weights_base.best.hdf5\"\ncheckpoint = ModelCheckpoint(file_path, monitor='val_loss', verbose=1, save_best_only=True, mode='min')\nearly = EarlyStopping(monitor=\"val_loss\", mode=\"min\", patience=0)\ncallbacks_list = [checkpoint, early] #early\nmodel.fit([X_t,X_t_POS], y, batch_size=batch_size, epochs=epochs, validation_split=0.1, callbacks=callbacks_list, shuffle=True)\n\n# predict\nprint(\">>> predicting on test set ... \")\nmodel.load_weights(file_path)\ny_test = model.predict([X_te,X_te_POS])\n\n#sub\nsample_submission = pd.read_csv(\"data/sample_submission.csv\")\nsample_submission[list_classes] = y_test\nsample_submission.to_csv(\"sub_gru11_Embed_POS_dropout02_2.csv.gz\", index=False , compression='gzip')\n","sub_path":"competitions/jigsaw-toxic-comment-classification-challenge/gru11.py","file_name":"gru11.py","file_ext":"py","file_size_in_byte":13905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"503622805","text":"from sys import argv\nfrom random import randint\n\n\ndef _random_pair(size):\n return randint(0, size - 1), randint(0, size - 1)\n\n\ndef _min_rich(size, constr):\n return constr * (size * (size - 1) // 2)\n\n\ndef _randomize_matrix(arr):\n l = len(arr)\n for i in range(_min_rich(l)):\n x, y = randint(0, l - 1), randint(0, l - 1)\n arr[x][y] = 0\n arr[y][x] = 0\n\n return arr\n\n\nclass FriendList:\n def __init__(self, lista):\n self.lista = lista\n\n def friends_of(self, vertex):\n pos = self.lista.index(vertex)\n return [\n vertex,\n self.lista[pos - 1],\n self.lista[pos + 1]\n ]\n\n\ndef _rich(graph):\n tab = []\n for i in range(len(graph)):\n tab += graph[i]\n # print(tab)\n return len(tab)\n\n\ndef gen_list(size, constr):\n lista = [i + 1 for i in range(size - 1)]\n for i in range(size):\n a, b = _random_pair(size - 1)\n lista[a], lista[b] = lista[b], lista[a]\n lista = [*lista, 0]\n way = {}\n way[0] = [lista[0]]\n # print(lista)\n\n for i in range(size - 1):\n way[lista[i]] = [lista[i + 1]]\n\n #\n lista = FriendList(lista)\n\n while _rich(way) < _min_rich(size, constr):\n i = randint(1, size - 2)\n a, b = i, i\n forbiden = lista.friends_of(i)\n while a in forbiden or a in way[i] or b in way[i] or b in forbiden:\n a, b = _random_pair(size)\n way[i].append(a)\n way[i].append(b)\n\n for i in range(size):\n way[i] = sorted(list(set(way[i])))\n # a, b = _random_pair(len(way[i]))\n # way[i][a], way[i][b] = way[i][b], way[i][a]\n\n return(way)\n\n\nclass Generator:\n def __init__(self, size, density, hamiltonian=True):\n self.size = size\n self.list = gen_list(size, density)\n if not hamiltonian:\n self.list[size - 1] = []\n used = _rich(self.list)\n poss = _min_rich(size, 1)\n print(\n f\"Used {used} edges of {poss} edges possible ({(used/poss) *10000 // 10 / 10}%)\"\n )\n\n def matrix(self):\n n = len(self.list)\n matrix = [[0 for _ in range(n)] for _ in range(n)]\n for i in range(n):\n for el in self.list[i]:\n matrix[i][el] = matrix[el][i] = 1\n return matrix\n\n def lista(self):\n return self.list\n\n def print_list(self):\n for i in range(self.size):\n print(f\"{i:3} :\", \" \".join(\n [f\"→ {v}\" for v in self.list[i]]))\n\n return self\n\n\nif __name__ == '__main__':\n # _cli()\n print(\n gen_list(20, 0.5)\n )\n","sub_path":"backer/ggen.py","file_name":"ggen.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"50170120","text":"import socket\r\n\r\nstart=input('Start? ')\r\n\r\nsections=\"\"\r\n\r\nsock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nsock.bind((socket.gethostname(), 1234))\r\n\r\nn=0\r\n\r\nwhile True:\r\n sock.listen()\r\n try:\r\n client, address=sock.accept()\r\n except:\r\n pass\r\n client.send(\"Capture\".encode())\r\n image=client.recv(40960000)\r\n sock.settimeout(0.01)\r\n sections+=str(image)\r\n n+=1\r\n if n==4:\r\n break\r\n \r\nrewrite=open('Retrieved.png', 'wb')\r\nrewrite.write(eval(sections))\r\nrewrite.close()\r\n","sub_path":"Host Image Capture.py","file_name":"Host Image Capture.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"438635455","text":"class Employee:\n \n # Specifying the class variables below:\n\n num_of_emps = 0 # this one will remain constant across all instances \n raise_amount = 1.04 # a const amt used by all instances \n\n def __init__(self, first, last, pay):\n self.first = first\n self.last = last\n self.pay = pay\n self.email = first + '.' + last + '@company.com'\n\n Employee.num_of_emps += 1 # amt inc when a new instance in created \n\n def fullname(self):\n return '{} {}'.format(self.first, self.last)\n\n def apply_raise(self):\n self.pay = int(self.pay * self.raise_amount) \n\n ''' in above line we are using self.raise_amount , meaning \n first the variable is checked in the scope of instance \n if it exists , then its value is used ,IF NOT exist then\n it find the class from which it is inheriting the variable\n from '''\n\n\n# To get the list of the attribute and the methods names of a instance or a class\n#print(Employee.__dict__)\n\n\n# Below code to cross-check the above concept\n\nprint(\"before creating two emp's\", Employee.num_of_emps)\n\nemp_1 = Employee('Dinesh', 'Singh', 5000000)\nemp_2 = Employee('Aarush', 'lola', 5000000)\n\nprint(\"After creating two employees\",Employee.num_of_emps)\n\n\n","sub_path":"python_practice/vars_class_n_instance.py","file_name":"vars_class_n_instance.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"614374405","text":"from prac6.programming_language import ProgrammingLanguage\n\nruby = ProgrammingLanguage(\"Ruby\", \"Dynamic\", True, 1995)\npython = ProgrammingLanguage (\"Python\", \"Dynamic\", True, 1991)\nvisual_basic = ProgrammingLanguage (\"Visual Basic\", \"Static\", False, 1991)\n\nprint(python)\n\nlanguage = [ruby, python, visual_basic]\n\nfor language in languages:\n if language.is_dynamic():\n print(language.name)","sub_path":"languages.py","file_name":"languages.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"645911805","text":"from autograd.numpy import dot\nfrom autograd.numpy import exp\nfrom autograd.numpy import expand_dims\nfrom autograd.numpy import eye\nfrom autograd.numpy.linalg import solve\nimport autograd.numpy.random as npr\nfrom contextlib import contextmanager\nfrom collections import namedtuple\nfrom collections.abc import Iterable\nfrom fnmatch import fnmatch\nfrom math import dist\nfrom math import ceil\nfrom os import getcwd\nfrom os.path import dirname\nfrom os.path import abspath\nfrom os.path import join\nfrom os.path import realpath\nfrom os import scandir\nfrom fnmatch import fnmatch\nfrom threading import Lock\n\nPYTHON_DIR = abspath(dirname(realpath(__file__)))\nOAK_MODULE_DIR = abspath(dirname(PYTHON_DIR))\nPROJECT_DIR = abspath(dirname(OAK_MODULE_DIR))\nRESOURCES_DIR = join(PROJECT_DIR, 'resources')\n\ndef load_file(filename, keep_comments=True):\n text = ''\n\n with open(filename, 'r') as handler:\n text = handler.read()\n\n def replacement(match):\n expr = match.group(0)\n if expr.startswith('/'):\n return ''\n else:\n return expr\n\n pattern = compile(\n r'//.*?$|/\\*.*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"',\n re.DOTALL | re.MULTILINE\n )\n\n if keep_comments is not True:\n return text\n \n return sub(pattern, replacement, text)\n\ndef search_for_file(base_path, file_name):\n directories = []\n discovered_files = []\n \n directories.append(base_path)\n\n while len(directories) > 0:\n directory = directories.pop()\n with scandir(directory) as entries:\n for entry in entries:\n if entry.is_dir():\n directories.append(entry.path)\n else:\n # Entry must be a file\n if fnmatch(entry.name, file_name):\n discovered_files.append(entry.path)\n \n return discovered_files\n\nclass LocalFileRead:\n def __init__(self, path, mode='rt'):\n self._path = join(RESOURCES_DIR, path)\n self._mode = mode\n def open(self):\n return open(self._path, self._mode)\n \nclass LocalFileWrite:\n def __init__(self, path, mode='xt'):\n self._path = join(RESOURCES_DIR, path)\n self._mode=mode\n def open(self):\n return open(self._path, self._mode) \n\ndef is_iterable_but_not_string_like(an_object):\n if isinstance(an_object, Iterable) and not isinstance(an_object, str):\n return True\n else:\n return False \n\ndef near(value, expectation, tolerance_interval=0):\n \"\"\" Returns True if a value falls within an expectation\n :tolerance_interval: takes a numeric value or a two-dimensional tuple or list representing the pair (left_tolerance_amount, right_tolerance_amount).\n \"\"\"\n if value == expectation:\n return True \n elif is_iterable_but_not_string_like(tolerance_interval) and len(tolerance_interval) == 2: \n if value >= expectation + tolerance_interval[0] and value <= expectation + tolerance_interval[1]:\n return True\n else:\n return False\n elif tolerance_interval and value <= expectation + tolerance_interval:\n return True\n else:\n return False\n\ndef near_or_greater(value, expectation, tolerance_interval=0):\n if near(value, expectation, tolerance_interval):\n return True\n elif value > expectation:\n return True\n else:\n return False\n\ndef near_or_less(value, expectation, tolerance_interval=0):\n if near(value, expectation, tolerance_interval):\n return True\n elif value < expectation:\n return True\n else:\n return False\n\ndef interval_measure(ordered_sequence, degree=1, step=1, distance_metric=lambda x_i, x_j: dist([x_i], [x_j])):\n \"\"\" Measures the intervals between elements of an ordered sequence.\n The :step: dictates the number of index places between elements to consider.\n Supplied the sequence [1,2,3,4,5] and a :step:=1, this method will take the intervals:\n 1,2 , 2,3 , 3,4 , and 4,5. Supplied the same sequence and a :step:=2. this method\n will take the intervals: 1,2 , 2,3 , 3,4 , 4,5 and also 1,3 and 3,5.\n The :degree: indicates the number of times to successively take the\n interval between elements in a sequence. Supplied the sequence\n [2,3,4,5] and a :degree:=2, the result of [2,3,4,5] :degree:=1, [1,1,1],\n will also be measured for the same steps.\n\n measure([2,3,4,5], degree=2, step=2) returns:\n\n [[2,3,4,5] , [2,4] , [2,5]\n [] , [1,1,1] , [2]\n [] , [] , [0,0]]\n\n The trace supplies the interval of the supplied sequence.\n \"\"\"\n count = len(ordered_sequence)\n\n if step < 1:\n return -1\n\n if count < 2:\n return [ordered_sequence]\n\n intervals = []\n\n for d in range(degree+1):\n intervals.append([])\n for s in range(step+1):\n if d == 0:\n intervals[d].append(ordered_sequence[::s+1])\n else:\n intervals[d].append([])\n for d in range(1, degree+1):\n for s in range(1, step + 1):\n for index_i in range(1, len(intervals[d-1][s-1])):\n x_i = intervals[d-1][s-1][index_i-1]\n for index_j in range(index_i, len(intervals[d-1][s-1]), len(intervals[d-1][s-1])):\n x_j = intervals[d-1][s-1][index_j]\n distance = dist([x_j], [x_i])\n intervals[d][s].append(x_j - x_i)\n return intervals\n\ndef variadic_dot_product(*stru):\n dot_product = eye(str[0])\n for structure in stru:\n dot_product = dot(dot_product, structure)\n return dot_product\n \n","sub_path":"python/oak/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"366186080","text":"import re\nimport zipfile\n\nz = zipfile.ZipFile(\"/Users/user/zhangqi/pychallenge/channel.zip\")\nnum = \"90052\"\npat = re.compile(r\"nothing is (\\d+)\")\nres = []\nwhile True:\n filename = \"/Users/user/zhangqi/pychallenge/channel/\" + num + \".txt\"\n filename_suffix = filename.split('/')[-1]\n print(filename)\n with open(filename, \"r\") as f:\n text = f.read()\n res.append(z.getinfo(filename_suffix).comment)\n m = pat.search(text)\n if m:\n num = m.group(1)\n else:\n print(text)\n break\n\n# Collect the comments.\nprint(\"\".join(map(bytes.decode, res)))\n\n# ****************************************************************\n# ****************************************************************\n# ** **\n# ** OO OO XX YYYY GG GG EEEEEE NN NN **\n# ** OO OO XXXXXX YYYYYY GG GG EEEEEE NN NN **\n# ** OO OO XXX XXX YYY YY GG GG EE NN NN **\n# ** OOOOOOOO XX XX YY GGG EEEEE NNNN **\n# ** OOOOOOOO XX XX YY GGG EEEEE NN **\n# ** OO OO XXX XXX YYY YY GG GG EE NN **\n# ** OO OO XXXXXX YYYYYY GG GG EEEEEE NN **\n# ** OO OO XX YYYY GG GG EEEEEE NN **\n# ** **\n# ****************************************************************\n# **************************************************************\n\n# It's in the air, look at the letters\n# http://www.pythonchallenge.com/pc/def/oxygen.html","sub_path":"level_6.py","file_name":"level_6.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"292546615","text":"#!/usr/bin/env python3\n# pylint: disable=invalid-name\n\"\"\"\nGet ECE cross correlation contour plots\n\"\"\"\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy.signal import correlate, butter, filtfilt\nimport _data, _misc\n# plt.switch_backend('Agg')\nplt.rcParams.update({'axes.formatter.use_mathtext': True,\n 'axes.formatter.limits': [-3, 4]})\nsns.set(style='ticks', palette='Set2')\n\n\n# %%\ndef get_ece_h(shot):\n '''get ece data'''\n ece = np.array([])\n ece_h = np.array([])\n chs = []\n fs = 5e3\n b, a = butter(4, [10/fs, 100/fs], btype='bandpass')\n for ch in range(1, 33):\n pname = f'ece{ch}'\n chs.append(pname)\n y, t = _data.get_mds(pname, shot)\n y_h = filtfilt(b, a, y)\n if ece.size == 0:\n ece, ece_h = y, y_h\n else:\n ece = np.vstack((ece, y))\n ece_h = np.vstack((ece_h, y_h))\n return ece, ece_h, t, chs\n\n\ndef calc_ccf(ece, t):\n '''Calculate CCF of ECE signals'''\n fn = _misc.slcfun(t1, t2)\n tind = fn(t)\n im = ece[:, tind]\n dn, tlen = im.shape\n xcorr = np.empty((dn, tlen*2-1))\n iref = 25\n for ir in range(dn):\n corr = correlate(im[iref, :], im[ir, :],\n mode='full', method='auto')\n corr /= (np.std(im[iref, :]) * np.std(im[ir, :]) * tlen)\n xcorr[ir, :] = corr\n dt = np.mean(np.diff(t))\n tlag = np.arange(-tlen+1, tlen) * dt\n return xcorr, tlag\n\n\ndef plot_ccf(corr, tlag):\n chan = np.arange(1, 33)\n plt.figure()\n plt.pcolormesh(tlag, chan, corr, vmin=-1, vmax=1, cmap='coolwarm')\n plt.colorbar()\n plt.xlabel(r'$\\Delta t$ (ms)')\n plt.ylabel('channels')\n plt.title(f'#{shot}')\n plt.tight_layout()\n plt.savefig(f'../fig/ECE_CCF.png', dpi=300, transparent=True)\n plt.show()\n\n\nif __name__ == \"__main__\":\n shot = 150136\n t1, t2 = 2.3e3, 2.6e3\n ece, eceh, t, chs = get_ece_h(shot)\n corr, tlag = calc_ccf(eceh, t)\n plot_ccf(corr, tlag)\n","sub_path":"ece_corr.py","file_name":"ece_corr.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"75705647","text":"class TrieNode:\n def __init__(self):\n self.children = {}\n self.isWord = False\n\nclass Trie(object):\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.root = TrieNode()\n\n def insert(self, word):\n \"\"\"\n Inserts a word into the trie.\n :type word: str\n :rtype: void\n \"\"\"\n node = self.root\n for char in word:\n if char not in node.children:\n node.children[char] = TrieNode()\n node = node.children[char]\n \n node.isWord = True\n \n\n def search(self, word):\n \"\"\"\n Returns if the word is in the trie.\n :type word: str\n :rtype: bool\n \"\"\"\n node = self.root\n\n for char in word:\n if char not in node.children:\n return False\n node = node.children[char]\n\n return node.isWord\n\n \n def startsWith(self, prefix):\n \"\"\"\n Returns if there is any word in the trie that starts with the given prefix.\n :type prefix: str\n :rtype: bool\n \"\"\"\n node = self.root\n for pre in prefix:\n if pre not in node.children:\n return False\n node = node.children[pre]\n\n return True\ns = Solution()\na = s.longestValidParentheses(')()())')\nprint(a)\n","sub_path":"medium/208.Implement Trie.py","file_name":"208.Implement Trie.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"375277870","text":"# -*- coding:utf-8 -*-\nimport MySQLdb\nimport re\n\nclass HtmlOutputer(object):\n\t\"\"\"docstring for HtmlOutputer\"\"\"\n\tdef __init__(self):\n\t\tsuper(HtmlOutputer, self).__init__()\n\t\tself.datas = []\n\n\tdef collect_data(self, data):\n\t\tif data is None:\n\t\t\treturn None\n\t\tself.datas.append(data)\n\n\tdef output_html(self):\n\t\tfout = open('output.html', 'w')\n\n\t\tfout.write(\"\")\n\t\tfout.write('')\n\t\tfout.write(\"\")\n\t\tfout.write(\"\")\n\t\tfout.write(\"\")\n\t\t\n\t\t# ascii \n\t\tcount = 1\n\t\tfor data in self.datas:\n\t\t\tfout.write(\"\")\n\t\t\tfout.write(\"\" % count)\n\t\t\tcount += 1\n\t\t\tfout.write(\"\" % data['url'])\n\t\t\tfout.write(\"\" % data['title'].encode('utf-8'))\n\t\t\tfout.write(\"\" % data['description'].encode('utf-8'))\n\t\t\tfout.write(\"\" % data['input'].encode('utf-8'))\n\t\t\tfout.write(\"\" % data['output'].encode('utf-8'))\n\t\t\tfout.write(\"\" % data['prosampleinput'].encode('utf-8'))\n\t\t\tfout.write(\"\" % data['prosampleoutput'].encode('utf-8'))\n\t\t\tfout.write(\"\")\n\n\t\tfout.write(\"
    Nourltitledescriptioninputoutputprosampleinputprosampleoutput
    %s%s%s%s%s%s%s%s
    \")\n\t\tfout.write(\"\")\n\t\tfout.write(\"\")\n\n\t\tfout.close()\n\n\tdef output_mysql(self):\n\t\tconn = MySQLdb.Connect(\n\t\t\t host='localhost',\n\t\t\t port = 3306,\n\t\t\t user='root',\n\t\t\t passwd='1234',\n\t\t\t db ='MNNUOJ',\n\t\t\t charset='utf8'\n )\n\t\tcur = conn.cursor()\n\t\tsqli_insert = \"insert into question(No,url,title,description,input,output,prosampleinput,prosampleoutput) values(%s,%s,%s,%s,%s,%s,%s,%s)\"\n\t\tfor data in self.datas:\n\t\t\tno = re.findall(r\"http://acm.mnnu.edu.cn/Problem/show/id/(.+?)\\.htm\",data['url'])\n\t\t\ttitle = re.findall(r\".\\:(.*)\",data['title'])\n\t\t\ttry:\n\t\t\t\tcur.execute(sqli_insert,(no,data['url'],title,data['description'],data['input'],data['output'],data['prosampleinput'],data['prosampleoutput']))\n\t\t\texcept Exception as e:\n\t\t\t\tsqli_updata = \"update question SET url=%s,title=%s,description=%s,input=%s,output=%s,prosampleinput=%s,prosampleoutput=%s where No=%s\"\n\t\t\t\tcur.execute(sqli_updata,(data['url'],title,data['description'],data['input'],data['output'],data['prosampleinput'],data['prosampleoutput'],no))\n\n\t\tcur.close();\n\t\tconn.commit();\n\t\tconn.close();","sub_path":"spider/html_outputer.py","file_name":"html_outputer.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"584866330","text":"# TURN WATER PUMP ON\n# by Lourdes Morales\n#\n# Reference: https://www.raspberrypi.org/learning/python-quick-reaction-game/worksheet/\n#\n# First, import module / library needed to control \n# the GPIO pins on the Raspberry Pi\n\nimport RPi.GPIO as GPIO\n\n# Make sure the GPIO pins are ready\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setwarnings(False)\n\n# Set up the pin that the water pump connects to on the Raspberry Pi \n# as an output. \n\nwater_pump_1 = 21 #--------PIN NUMBER FOR WATER PUMP------------------\nwater_pump_2 = 20\n\nGPIO.setup(water_pump_1, GPIO.OUT)\nGPIO.setup(water_pump_2, GPIO.OUT)\n\n# Next, turn water_pump on. \n# 1 represents ON and 0 represents OFF:\n\nGPIO.output(water_pump_1, 1)\nGPIO.output(water_pump_2, 1)\n\nGPIO.cleanup()\n\n# print 'Success'; ","sub_path":"Raspberry Pi/Web_page/turn_water_on.py","file_name":"turn_water_on.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"60391632","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.dummy import DummyClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split, cross_val_score, cross_validate, GridSearchCV\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.pipeline import Pipeline\nimport gensim\nfrom gensim.utils import lemmatize\nfrom gensim.models import LdaModel\nfrom gensim.models.wrappers import LdaMallet\nfrom gensim.corpora import Dictionary\nfrom nltk.corpus import stopwords\nfrom nltk import sent_tokenize\nimport re\n\n\n#setting variables\n#APIKEY = HEADERS['Authorization']\nFILE_PATH = 'data/reviews.csv'\n#assuming that the data features will be: ['businessID', 'userID', 'rating', 'review', 'time']\n\n#retrieving data\n# reviews_df = pd.read_csv(FILE_PATH, index_col=0)\n# print(reviews_df.shape)\n# X_raw = reviews_df['review']\n# y_raw = reviews_df['ratings']\ny_raw = ['3.4','4', 'hella 3', '2 a3glsk2']\n\n\nX_raw = [\"STRICKLAND: Good morning.\",\n\n\"Marsha is on her way. She called from the car phone I think. It sounded like the car phone, to let us know that she would be delayed.\",\n\n\"I would like to welcome two people who haven't been with us before.\",\n\n\"Suzanne Clewell, we're delighted to have you with us today. Suzanne, would you tell us a little bit about what you do?\",\n\n\"CLEWELL: Yes. I'm the Coordinator for Reading Language Arts with the Montgomery County Public Schools which is the suburban district surrounding Washington. We have 173 schools and 25 elementary schools.\",\n\n\"It's great to be here.\",\n\n\"STRICKLAND: And I'll skip over to another member of the committee, but for her, this is her first meeting, too, Judith Langer. I think we all know her work, if we didn't know her.\",\n\n\"Judith.\",\n\n\"LANGER: Hello. I'm delighted to be here.\",\n\n\"I have carefully read and heard about all of the things that the group has discussed up until now.\",\n\n\"I'm a Professor of Education at the University of Albany, the State University of New York. And I'm also the Director of the National Research Center on English Learning and Achievement.\",\n\n\"STRICKLAND: Her mother wrote the stances.\"]\n\n#cleaning the target data\ny = []\nfor s in y_raw:\n l = []\n for t in s.split():\n try:\n l.append(float(t))\n except ValueError:\n pass\n y.append(l[0]>=4)\n \n #proprocessing the corpus\nX = []\nfor i in X_raw:\n X.append(gensim.utils.simple_preprocess(i, deacc=True, min_len=3))\nbigram = gensim.models.Phrases(X_raw)\nstops = set(stopwords.words('english'))\n\ndef process_texts(texts):\n texts = [[word for word in line if word not in stops] for line in texts]\n texts = [bigram[line] for line in texts]\n texts = [[word.decode(\"utf-8\").split('/')[0] for word in lemmatize(' '.join(line), allowed_tags=re.compile('(NN)'), min_length=5)] for line in texts]\n return texts\n\ntrain_texts = process_texts(X_raw)\n\ndictionary = Dictionary(train_texts)\ncorpus = [dictionary.doc2bow(text) for text in train_texts]\nprint(Dictionary)\nprint(corpus)\n","sub_path":"app/review_training.py","file_name":"review_training.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"126070542","text":"\n# coding: utf-8\n\n# # Iterate Destination Hosts and associated Ports, over time periods, to create an Analytical Data Set    for the In-Degree Entropy model\n\n# In[2]:\n\n\n# use print only as a function\nfrom __future__ import print_function\nimport sys\nsys.version\n\n\n# ## Connect to data and read into dataframe\n\n# In[3]:\n\n\n__author__ = 'swe03'\n\nimport numpy as np\nimport pandas as pd\nimport pandas.io.gbq as pdg\nimport matplotlib.pylab as plt\nimport matplotlib.pyplot as pplt\nfrom decimal import *\nimport re \n\nimport statsmodels.tsa as tsa\n\nfrom statsmodels.tsa.stattools import ccf \nfrom statsmodels.graphics.api import qqplot\nfrom statsmodels.tsa.base import datetools\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom statsmodels.tsa.arima_model import ARMA\n\nfrom statsmodels.tsa.stattools import acf \nfrom statsmodels.tsa.stattools import pacf\nfrom statsmodels.tsa.seasonal import seasonal_decompose\n\nfrom scipy.stats.stats import pearsonr\n\nfrom sklearn import linear_model\n\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom matplotlib.pylab import rcParams\nrcParams['figure.figsize'] = 15, 6\n\nfrom scipy import stats\n\nfrom datetime import datetime, timedelta\n\ndesired_width = 250\npd.set_option('display.width',desired_width)\npd.set_option('display.max_rows', 500)\n\n\n# ###### Install the SQL package if not already installed \n\n# In[4]:\n\n\n#!pip install pandasql\n\n\n# In[5]:\n\n\nfrom pandasql import PandaSQL \npdsql = PandaSQL()\n\n\n# ##### Use an existing table but change the timestamps to create a contiguous distribution.\n\n# In[6]:\n\n\ndef Get_recs_w_date_range(date_s,date_e, addr):\n \"\"\"Iterate through various date ranges to create the a timeframe sample for later aggregation\"\"\"\n global dfx2 # Otherwise, dfx2 is considered Local and will not be global scope of the dataframe created above\n query = \"\"\"SELECT Timestamp, src_addr, src_port, dst_addr, dst_port,\n cast(duration_ms as integer) as duration_ms,\n cast(bytes as integer) as bytes,\n protocol, flow_direction, tcp_flags \n FROM ipfix.ipfix \n WHERE Timestamp BETWEEN timestamp('{}') AND timestamp('{}')\n AND dst_addr in ({}) # single quotes unnecessary since the ip's are quoted in string \n LIMIT 50 \"\"\".format(date_s,date_e,addr)\n \n #print('The value of local var date_s is: {}'.format(date_s))\n #print('The value of local var date_e is: {}'.format(date_e))\n print('The value of local var addr is: {}'.format(addr))\n dfx1 = pd.read_gbq(query, project_id=\"network-sec-analytics\")\n dfx2 = dfx2.append(dfx1) # Append onto the dfx2 dataframe\n return \n\n\n# In[7]:\n\n\ndef Get_recs_w_date_range_lowgrain(date_s,date_e):\n \"\"\"Iterate through various date ranges to create the a timeframe sample for later aggregation\"\"\"\n global dfx2 # Otherwise, dfx2 is considered Local and will not be global scope of the dataframe created above\n query = \"\"\"SELECT Timestamp, src_addr, src_port, dst_addr, dst_port,\n cast(duration_ms as integer) as duration_ms,\n cast(bytes as integer) as bytes,\n protocol, flow_direction, tcp_flags \n FROM ipfix.ipfix \n WHERE Timestamp BETWEEN timestamp('{}') AND timestamp('{}')\n AND dst_addr in ('165.130.217.229') \n AND dst_port in ('443')\n AND src_addr in ('172.29.236.82')\"\"\".format(date_s,date_e)\n \n #print('The value of local var date_s is: {}'.format(date_s))\n #print('The value of local var date_e is: {}'.format(date_e))\n #print('The value of local var addr is: {}'.format(addr))\n dfx1 = pd.read_gbq(query, project_id=\"network-sec-analytics\")\n dfx2 = dfx2.append(dfx1) # Append onto the dfx2 dataframe\n return \n\n\n# In[8]:\n\n\ndef Write_to_gbq(addr_port_s):\n #model_addr_port = \"'\" + 'prod.' + addr_port_s + \"'\"\n model_addr_port = 'prod.' + addr_port_s \n parm_str = pd.Series([model_addr_port]) \n print(\"This is the parm str:\",parm_str)\n \n pdg.to_gbq(dfx2, model_addr_port, \"network-sec-analytics\", verbose=True, reauth=False, \n if_exists='replace', private_key=None)\n\n #dfx2.to_gbq(parm_str, \"network-sec-analytics\", verbose=True, reauth=False, \n #if_exists='replace', private_key=None)\n return\n\n\n# In[9]:\n\n\ndef Initialize_and_Iterate():\n date_start = pd.to_datetime('2017-02-06 00:00:00') # '2017-02-01 00:00:00'\n date_end_interval = pd.to_datetime('2017-02-10 23:59:59') # '2017-02-03 23:59:59'\n \n while date_start <= pd.to_datetime(date_end_interval):\n date_end = date_start + timedelta(minutes=59,seconds=59) # Set the datetime end of the hour interval\n print('For get_recs function date_start=',date_start)\n print('For get_recs function date_end=',date_end)\n \n Get_recs_w_date_range(date_start,date_end,out_str) # Extract the query Limit above within the specified hour \n \n date_start = date_end + timedelta(seconds=1) # Add a second to the nn:59:59 end date to start the next # hour on nn:00:00 start time\n \n return \n\n\n# In[10]:\n\n\ndef Initialize_and_Iterate_lowgrain():\n date_start = pd.to_datetime('2017-02-01 00:00:00') # '2017-02-01 00:00:00'\n date_end_interval = pd.to_datetime('2017-02-01 01:00:00') # '2017-02-01 10:59:59'\n \n while date_start <= pd.to_datetime(date_end_interval):\n date_end = date_start + timedelta(minutes=59,seconds=59) # Set the datetime end of the hour interval\n print('For get_recs function date_start=',date_start)\n print('For get_recs function date_end=',date_end)\n \n Get_recs_w_date_range_lowgrain(date_start,date_end) # Extract the query Limit above within the specified hour \n \n date_start = date_end + timedelta(seconds=1) \n \n return \n\n\n# In[11]:\n\n\ndef Create_date_hour():\n global dfx2\n dfx2['duration_ms'].fillna(0, inplace=True)\n dfx2['date_hour'] = dfx2.Timestamp.dt.strftime('%Y-%m-%d-%H') # This works and creates a Series with Date and Hour\n dfx2['date_hour'] = pd.to_datetime(dfx2['date_hour'] )\n dfx2.reset_index(drop=True, inplace=True)\n return \n\n\n# ### Initiate the Process\n\n# ##### Read the specific Host Segments reference table from BQ\n\n# In[12]:\n\n\n## This function accomplishes both: 1. Creating an enumerated list of Host Segments to be sent to the Get_recs... function and\n## 2. Parsing the text strings to enable generating the enumerated list\ndef read_in_host_segments():\n global out\n host_segs = pd.read_gbq(\"select Host_Range_Start, Host_Range_End from reference.Host_Segments\", project_id=\"network-sec-analytics\")\n host_start = host_segs.Host_Range_Start.str.split('.',expand=True).astype(int) # This creates a DF. type(host_start)\n host_end = host_segs.Host_Range_End.str.split('.',expand=True).astype(int) # This creates a DF. type(host_end)\n host_start2 = host_segs.join(host_start[3]) # Join the host_seg table with just the last component of the address as int\n host_start2 = host_start2.join(host_end[3],rsuffix='E') # Join to get the host range end value\n host_start2.rename(columns={\"3\":\"start\",\"3E\":\"end\"},inplace=True) \n host_start2.replace(to_replace='\\w+$', value=' ', inplace=True, limit=None, regex=True, method='pad', axis=None) # place a blank in the last addr component\n \n temp_list = []\n end_str = ''\n for index, row in host_start2.iterrows(): \n counter = host_start2['start'][index] # necessary to include index or will get \"truth value of a Series is ambiguous\"\n last = host_start2['end'][index]\n while counter <= last:\n end_str = counter.astype(str) ## counter retains int dtype\n temp_dict = {'host': row.Host_Range_Start.strip() + end_str}\n temp_list.append(temp_dict)\n counter = counter + 1\n \n out = pd.DataFrame(temp_list) ## Currently, this will overwrite each df and only retain the last record's df\n\n return\n\n\nread_in_host_segments()\n\n\n# In[13]:\n\n\n##out\n\n\n# In[14]:\n\n\nout_array=out['host'].values\n#out_array\nfor i in range(0, len(out_array)):\n if i == 0:\n out_str = \"'\" + out_array[i] + \"'\" + \",\"\n else:\n if i == (len(out_array)-1):\n out_str += \"'\" + out_array[i] + \"'\" \n else:\n out_str += \"'\" + out_array[i] + \"',\"\n\n\n# In[15]:\n\n\n#print(out_str)\n#out_str = out_str + ',' + '165.130.1.9'\nprint(out_str)\n\n\n# ##### Call the functions\n\n# In[16]:\n\n\n#global i \n#n = 2\n#del dfx2\n#for i in range(0, n): # Set n to be the n number of addr/port ads's to create\ndfx2 = pd.DataFrame() # Create the df that will be appended to for each timeframe\nInitialize_and_Iterate() # For each Host/Port, iterate through the timeframes \nCreate_date_hour() # Create a Day/Hour variable for the final, appended df\n #del dfx2 # df has been written to BQ so now delete it\n\n\n# In[17]:\n\n\n#dfx2 = pd.DataFrame() # Create the df that will be appended to for each timeframe\n#Initialize_and_Iterate_lowgrain() # For each Host/Port, iterate through the timeframes \n#Create_date_hour() # Create a Day/Hour variable for the final, appended df\n\n\n# In[18]:\n\n\ndfx_s=dfx2.sort_values(['date_hour','dst_addr'],ascending=True)\ndfx_s\n\n\n# ### Create the Behaviorial Metrics (i.e., In-Degree Entropy measures)\n\n# In[19]:\n\n\n## New\n## Total Unique Destination Hosts within the time period\nhost_count=dfx_s.groupby(['date_hour']).dst_addr.nunique() ## This creates a Series\nhost_count\n\n\n# In[20]:\n\n\n## Old\n#host_count = dfx_s.groupby(dfx_s['date_hour']).count() ## This creates a dataframe\n#host_count['dst_addr'] = pd.to_numeric(host_count['dst_addr'],downcast='float') ## another way to conver is below\n#host_count['dst_addr']\n\n\n# In[21]:\n\n\n## New\nhost_count_df = pdsql(\"\"\"Select * from host_count\"\"\", locals()) ## host_count is a Series\n#type(unq_src_count_df) ## test for a Dataframe\nhost_count_df['dst_addr'] = host_count_df.dst_addr.astype(float)\nhost_count_df ## Dataframe has cols: date_hour, dst_addr, and src_addr (which are the unique counts)\n\n\n# In[22]:\n\n\n### Number of Unique Source Hosts that connect to each Unique Destination Host\n#### Thus, in the 0 hour, dst host ..217.229 is contacted by two unique src hosts while dst host ..217.230 is only contacted by one unique src host.\n#### So we have a random variable that has two values (i.e., 2 and 1). Each of these two values happen twice so, within this set of dst hosts, \n#### the probability of being contacted by any src host is equal. For value 1: 2/4 = .5 and for value 2: 2/4 = .5 and Entropy is 1 (completely random)\n#### Thus, there is a distribution of values that allow us to describe the \n#### randomness of that distribution.\nunq_src_count=dfx_s.groupby(['date_hour','dst_addr']).src_addr.nunique() ## This creates a Series\nunq_src_count\n\n\n# In[23]:\n\n\n#type(unq_src_count)\n\n\n# In[24]:\n\n\n## Old\n#unq_src_count_df = pdsql(\"\"\"Select * from unq_src_count\"\"\", locals()) ## unq_src_count is a Series\n##type(unq_src_count_df) ## test is a Dataframe\n#unq_src_count_df['src_addr'] = unq_src_count_df.src_addr.astype(float)\n#unq_src_count_df ## Dataframe has cols: date_hour, dst_addr, \n ## and src_addr (which are the unique counts)\n\n\n# In[25]:\n\n\nunq_src_count_df = pdsql(\"\"\"Select * from unq_src_count\"\"\", locals()) ## unq_src_count is a Series\n\n\n# In[26]:\n\n\n## New\ncalc_ent1 = pdsql(\"\"\"SELECT s.date_hour, s.src_addr as unq_src_addr_cnt, count(src_addr) as xi_cnt \n from unq_src_count_df s\n group by s.date_hour, s.src_addr\n order by s.date_hour\"\"\",locals())\ncalc_ent1\n\n\n# In[27]:\n\n\n## Old\n#calc_ent1 = pdsql(\"\"\"SELECT s.date_hour, s.dst_addr as dst_addr_s, s.src_addr as unq_src_addr_cnt, \n# i.dst_addr as total_dst_addr_cnt, (s.src_addr / i.dst_addr) as ent1 \n# from host_count_df i join unq_src_count_df s\n# on i.date_hour = s.date_hour \n# order by s.date_hour\"\"\",locals())\n#calc_ent1\n\n\n# In[28]:\n\n\n## New\ncalc_ent2 = pdsql(\"\"\"SELECT s.date_hour, s.xi_cnt, i.dst_addr, s.unq_src_addr_cnt, \n (s.xi_cnt / i.dst_addr) as ent1 \n from host_count_df i join calc_ent1 s\n on i.date_hour = s.date_hour \n order by s.date_hour\"\"\",locals())\ncalc_ent2\n\n\n# In[29]:\n\n\n## Old\n#calc_ent1['ln_ent1'] = np.log(calc_ent1['ent1'])\n#calc_ent1\n\n\n# In[30]:\n\n\n## New\ncalc_ent2['ln_ent1'] = np.log(calc_ent2['ent1']) ### Natural Log \ncalc_ent2\n\n\n# In[31]:\n\n\n## Old\n## This is the step where the summation of each entt1(first ratio created above) * log of ent1 is calculated.\n## This summation is now reflected in the date_hour group by\n#calc_ent1['dst_addr_datehour_group'] = calc_ent1['dst_addr_s'] ## Create a new variable for better desc\n#calc_ent1['dst_addr_datehour_group'] = calc_ent1.date_hour.str.slice(start=0,stop=13,step=None) #substr the dt/hour only\n#calc_ent2 = pdsql(\"\"\"SELECT i.date_hour, i.dst_addr_datehour_group, i.total_dst_addr_cnt, i.ent1, i.ln_ent1,\n# sum(i.ent1 * i.ln_ent1) as hx_ent, count(dst_addr_s) as unq_dst_host_count,\n# sum(i.unq_src_addr_cnt) as unq_src_dst_addr_cnt\n# from calc_ent1 i\n# group by i.date_hour\n# order by i.date_hour\"\"\",locals())\n\n#calc_ent2\n\n\n# In[32]:\n\n\n## New\n#calc_ent1['dst_addr_datehour_group'] = calc_ent1['dst_addr_s'] ## Create a new variable for better desc\ncalc_ent2['dst_addr_datehour_group'] = calc_ent1.date_hour.str.slice(start=0,stop=13,step=None) #substr the dt/hour only\ncalc_ent3 = pdsql(\"\"\"SELECT i.date_hour, i.dst_addr_datehour_group, count(i.xi_cnt) as xi_cnt, i.dst_addr, i.unq_src_addr_cnt, i.ent1, i.ln_ent1,\n sum(i.ent1 * i.ln_ent1) as hx_ent, count(i.date_hour) as unq_dst_host_count\n from calc_ent2 i\n group by i.date_hour\n order by i.date_hour\"\"\",locals())\n\ncalc_ent3\n\n\n# In[33]:\n\n\n##### ENTROPY IS ZERO when 1 outcome is certain and ENTROPY IS ONE when all outcomes have an equal probability of occurring and, thus, no outcome is \n##### certain\ncalc_ent3['In_degree_entropy'] = -(calc_ent3['hx_ent'] / np.log(calc_ent3['unq_dst_host_count'])) ## Natural Log \ncalc_ent3.fillna(value=0, inplace=True)\ncalc_ent3\n\n\n# In[27]:\n\n\n##### Write the dataframe to BQ\n#dfx2.to_gbq('prod.host_group2', \"network-sec-analytics\", verbose=True, reauth=False, \n# if_exists='replace', private_key=None)\n\n\n# #### Create some visualizations and other stats\n\n# In[53]:\n\n\nimport matplotlib.pyplot as pplt\npplt.plot(calc_ent3['In_degree_entropy'])\npplt.xticks(range(len(calc_ent3['dst_addr_datehour_group'])),calc_ent3['dst_addr_datehour_group'])\npplt.xticks(rotation=80)\n#pplt.autoscale(enable=True, axis='x', tight=None)\npplt.show()\n\n\n# In[54]:\n\n\nhist_plot = calc_ent3['In_degree_entropy'].plot.hist()\n\n\n# In[56]:\n\n\n##### Run a correlation to see the relationship between calc_ents indicator features\n##### All correlations are statistically significant \ncorr1 = pearsonr(calc_ent3['dst_addr'],calc_ent3['unq_src_addr_cnt'])\ncorr2 = pearsonr(calc_ent3['dst_addr'],calc_ent3['In_degree_entropy'])\ncorr3 = pearsonr(calc_ent3['unq_src_addr_cnt'],calc_ent3['In_degree_entropy'])\nprint(\"feature correlation = \",corr1)\nprint(\"dst_addr_cnt x Entropy = \", corr2)\nprint(\"unq_src_addr_cnt x Entropy = \", corr3)\n\n\n# In[64]:\n\n\n# Create linear regression object\nregr = linear_model.LinearRegression()\n\n# Create the various feature arrays (1,5,6 for x and 7 for y)\nx1 = calc_ent3[['dst_addr']]\nx2 = calc_ent3['unq_dst_host_count'] * calc_ent3['dst_addr']\nx2 = x2.values.reshape(-1,1)\nx3 = calc_ent3['unq_src_addr_cnt'] * calc_ent3['dst_addr']\nx3 = x3.values.reshape(-1,1)\ny = calc_ent3['In_degree_entropy']\n\n\n# In[66]:\n\n\nx3\n\n\n# In[67]:\n\n\n# Fit the Regression Model using the arrays created above\ndef regression_plots(feature_array):\n regr.fit(feature_array, y)\n\n # The coefficients\n print('Coefficients: \\n', regr.coef_)\n # The mean squared error\n print(\"Mean squared error: %.2f\"\n % np.mean((regr.predict(feature_array) - y) ** 2))\n # Explained variance score: 1 is perfect prediction\n print('Variance score: %.2f' % regr.score(feature_array, y))\n\n # Plot outputs\n plt.scatter(feature_array, y, color='black')\n #plt.plot(x1, regr.predict(feature_array), color='blue',\n # linewidth=3)\n\n\n plt.show()\n \nregression_plots(x1)\nregression_plots(x2)\nregression_plots(x3)\n\n\n# In[68]:\n\n\ndecomposition = seasonal_decompose(calc_ent3.In_degree_entropy.values, freq=24) \nfig = plt.figure() \nfig = decomposition.plot() \nfig.set_size_inches(15, 8)\n\n\n# In[69]:\n\n\ncalc_ent3.index = calc_ent3['date_hour']\ntype(calc_ent2['date_hour'])\n\n\n# In[70]:\n\n\nmodel=ARIMA(calc_ent3['In_degree_entropy'],(1,0,0)) ## The endogenous variable needs to be type Float or you get a cast error\nmodel_fit = model.fit() # fit is a Function\nmodel_fitted = model_fit.fittedvalues # fittedvalues is a Series\nprint(model_fit.summary())\nprint(model_fitted)\n\n\n# In[ ]:\n\n\ndef create_unistats(group):\n return {'min': group.min(), 'max': group.max(), 'count': group.count(), 'mean': group.mean()}\n \n# These are DataFrames\nbytes_dist = dfx2['bytes'].groupby([dfx2['date_hour'], \n dfx2['dst_port']]).apply(create_unistats).unstack().reset_index()\nbytes_dist = bytes_dist[(bytes_dist['dst_port']==53) ] # all stats are displayed for just port 53\n\nduration_dist = dfx2['duration_ms'].groupby([dfx2['date_hour'], \n dfx2['dst_port']]).apply(create_unistats).unstack().reset_index()\n\n","sub_path":"Iterate-and-Create-ADS_for_In-Degree_Entropy.py","file_name":"Iterate-and-Create-ADS_for_In-Degree_Entropy.py","file_ext":"py","file_size_in_byte":18099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"30855217","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2020 by YOUR NAME HERE\n#\n# This file is part of RoboComp\n#\n# RoboComp 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# RoboComp 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 RoboComp. If not, see .\n\nimport sys, Ice, os\nfrom PySide2 import QtWidgets, QtCore\n\nROBOCOMP = ''\ntry:\n\tROBOCOMP = os.environ['ROBOCOMP']\nexcept KeyError:\n\tprint('$ROBOCOMP environment variable not set, using the default value /opt/robocomp')\n\tROBOCOMP = '/opt/robocomp'\n\npreStr = \"-I/opt/robocomp/interfaces/ -I\"+ROBOCOMP+\"/interfaces/ --all /opt/robocomp/interfaces/\"\nIce.loadSlice(preStr+\"CommonBehavior.ice\")\nimport RoboCompCommonBehavior\n\nadditionalPathStr = ''\nicePaths = [ '/opt/robocomp/interfaces' ]\ntry:\n\tSLICE_PATH = os.environ['SLICE_PATH'].split(':')\n\tfor p in SLICE_PATH:\n\t\ticePaths.append(p)\n\t\tadditionalPathStr += ' -I' + p + ' '\n\ticePaths.append('/opt/robocomp/interfaces')\nexcept:\n\tprint('SLICE_PATH environment variable was not exported. Using only the default paths')\n\tpass\n\n\n\n\n\nclass GenericWorker(QtCore.QObject):\n\n\tkill = QtCore.Signal()\n#Signals for State Machine\n\tt_init_to_lambscan = QtCore.Signal()\n\tt_lambscan_to_end = QtCore.Signal()\n\tt_start_streams_to_get_frames = QtCore.Signal()\n\tt_start_streams_to_exception = QtCore.Signal()\n\tt_start_streams_to_send_message = QtCore.Signal()\n\tt_get_frames_to_processing_and_filter = QtCore.Signal()\n\tt_get_frames_to_exception = QtCore.Signal()\n\tt_get_frames_to_get_frames = QtCore.Signal()\n\tt_get_frames_to_exit = QtCore.Signal()\n\tt_processing_and_filter_to_get_frames = QtCore.Signal()\n\tt_processing_and_filter_to_save = QtCore.Signal()\n\tt_save_to_get_frames = QtCore.Signal()\n\tt_save_to_exception = QtCore.Signal()\n\tt_exception_to_start_streams = QtCore.Signal()\n\tt_exception_to_get_frames = QtCore.Signal()\n\tt_exception_to_send_message = QtCore.Signal()\n\tt_exception_to_save = QtCore.Signal()\n\tt_send_message_to_exit = QtCore.Signal()\n\n#-------------------------\n\n\tdef __init__(self, mprx):\n\t\tsuper(GenericWorker, self).__init__()\n\n\n\n\t\t\n\t\tself.mutex = QtCore.QMutex(QtCore.QMutex.Recursive)\n\t\tself.Period = 30\n\t\tself.timer = QtCore.QTimer(self)\n\n#State Machine\n\t\tself.Application= QtCore.QStateMachine()\n\t\tself.lambscan_state = QtCore.QState(self.Application)\n\t\tself.init_state = QtCore.QState(self.Application)\n\n\t\tself.end_state = QtCore.QFinalState(self.Application)\n\n\n\n\t\tself.get_frames_state = QtCore.QState(self.lambscan_state)\n\t\tself.processing_and_filter_state = QtCore.QState(self.lambscan_state)\n\t\tself.save_state = QtCore.QState(self.lambscan_state)\n\t\tself.send_message_state = QtCore.QState(self.lambscan_state)\n\t\tself.exception_state = QtCore.QState(self.lambscan_state)\n\t\tself.start_streams_state = QtCore.QState(self.lambscan_state)\n\n\t\tself.exit_state = QtCore.QFinalState(self.lambscan_state)\n\n\n#------------------\n#Initialization State machine\n\t\tself.init_state.addTransition(self.t_init_to_lambscan, self.lambscan_state)\n\t\tself.lambscan_state.addTransition(self.t_lambscan_to_end, self.end_state)\n\t\tself.start_streams_state.addTransition(self.t_start_streams_to_get_frames, self.get_frames_state)\n\t\tself.start_streams_state.addTransition(self.t_start_streams_to_exception, self.exception_state)\n\t\tself.start_streams_state.addTransition(self.t_start_streams_to_send_message, self.send_message_state)\n\t\tself.get_frames_state.addTransition(self.t_get_frames_to_processing_and_filter, self.processing_and_filter_state)\n\t\tself.get_frames_state.addTransition(self.t_get_frames_to_exception, self.exception_state)\n\t\tself.get_frames_state.addTransition(self.t_get_frames_to_get_frames, self.get_frames_state)\n\t\tself.get_frames_state.addTransition(self.t_get_frames_to_exit, self.exit_state)\n\t\tself.processing_and_filter_state.addTransition(self.t_processing_and_filter_to_get_frames, self.get_frames_state)\n\t\tself.processing_and_filter_state.addTransition(self.t_processing_and_filter_to_save, self.save_state)\n\t\tself.save_state.addTransition(self.t_save_to_get_frames, self.get_frames_state)\n\t\tself.save_state.addTransition(self.t_save_to_exception, self.exception_state)\n\t\tself.exception_state.addTransition(self.t_exception_to_start_streams, self.start_streams_state)\n\t\tself.exception_state.addTransition(self.t_exception_to_get_frames, self.get_frames_state)\n\t\tself.exception_state.addTransition(self.t_exception_to_send_message, self.send_message_state)\n\t\tself.exception_state.addTransition(self.t_exception_to_save, self.save_state)\n\t\tself.send_message_state.addTransition(self.t_send_message_to_exit, self.exit_state)\n\n\n\t\tself.lambscan_state.entered.connect(self.sm_lambscan)\n\t\tself.init_state.entered.connect(self.sm_init)\n\t\tself.end_state.entered.connect(self.sm_end)\n\t\tself.start_streams_state.entered.connect(self.sm_start_streams)\n\t\tself.exit_state.entered.connect(self.sm_exit)\n\t\tself.get_frames_state.entered.connect(self.sm_get_frames)\n\t\tself.processing_and_filter_state.entered.connect(self.sm_processing_and_filter)\n\t\tself.save_state.entered.connect(self.sm_save)\n\t\tself.send_message_state.entered.connect(self.sm_send_message)\n\t\tself.exception_state.entered.connect(self.sm_exception)\n\n\t\tself.Application.setInitialState(self.init_state)\n\t\tself.lambscan_state.setInitialState(self.start_streams_state)\n\n#------------------\n\n#Slots funtion State Machine\n\t@QtCore.Slot()\n\tdef sm_lambscan(self):\n\t\tprint(\"Error: lack sm_lambscan in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_init(self):\n\t\tprint(\"Error: lack sm_init in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_end(self):\n\t\tprint(\"Error: lack sm_end in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_get_frames(self):\n\t\tprint(\"Error: lack sm_get_frames in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_processing_and_filter(self):\n\t\tprint(\"Error: lack sm_processing_and_filter in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_save(self):\n\t\tprint(\"Error: lack sm_save in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_send_message(self):\n\t\tprint(\"Error: lack sm_send_message in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_exception(self):\n\t\tprint(\"Error: lack sm_exception in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_start_streams(self):\n\t\tprint(\"Error: lack sm_start_streams in Specificworker\")\n\t\tsys.exit(-1)\n\n\t@QtCore.Slot()\n\tdef sm_exit(self):\n\t\tprint(\"Error: lack sm_exit in Specificworker\")\n\t\tsys.exit(-1)\n\n\n#-------------------------\n\t@QtCore.Slot()\n\tdef killYourSelf(self):\n\t\trDebug(\"Killing myself\")\n\t\tself.kill.emit()\n\n\t# \\brief Change compute period\n\t# @param per Period in ms\n\t@QtCore.Slot(int)\n\tdef setPeriod(self, p):\n\t\tprint(\"Period changed\", p)\n\t\tself.Period = p\n\t\tself.timer.start(self.Period)\n","sub_path":"src/genericworker.py","file_name":"genericworker.py","file_ext":"py","file_size_in_byte":7207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"543639304","text":"import tensorflow as tf\r\nimport tensorflow_datasets as tdfs\r\nimport numpy\r\nimport math\r\n\r\ndef normalize(images,labels):\r\n images = tf.cast(images,tf.float32)\r\n images /= 255\r\n return images,labels\r\n\r\n\r\ndataset, metadata = tdfs.load('fashion_mnist',as_supervised=True, with_info=True)\r\ntrain_dataset, test_dataset= dataset['train'],dataset['test']\r\nprint(\"Class names: {}\".format(metadata.features['label'].names))\r\n\r\ntrain_dataset = train_dataset.map(normalize)\r\ntest_dataset = test_dataset.map(normalize)\r\n\r\ntrain_dataset = train_dataset.cache()\r\ntest_dataset = test_dataset.cache()\r\n\r\n\r\nmodel = tf.keras.Sequential([\r\n tf.keras.layers.Conv2D(32, (3,3), padding='same', activation=tf.nn.relu,\r\n input_shape=(28, 28, 1)),\r\n tf.keras.layers.MaxPooling2D((2, 2), strides=2),\r\n tf.keras.layers.Conv2D(64, (3,3), padding='same', activation=tf.nn.relu),\r\n tf.keras.layers.MaxPooling2D((2, 2), strides=2),\r\n tf.keras.layers.Flatten(),\r\n tf.keras.layers.Dense(128, activation=tf.nn.relu),\r\n tf.keras.layers.Dense(10, activation=tf.nn.softmax)\r\n])\r\n\r\nmodel.compile(optimizer='adam',\r\n loss=tf.keras.losses.SparseCategoricalCrossentropy(),\r\n metrics=['accuracy'])\r\n\r\nBATCH_SIZE = 32\r\nnum_train_examples = 60000 # no of samples in train dataset\r\nnum_test_examples = metadata.splits['test'].num_examples\r\ntrain_dataset = train_dataset.cache().repeat().shuffle(num_train_examples).batch(BATCH_SIZE)\r\ntest_dataset = test_dataset.cache().batch(BATCH_SIZE)\r\n\r\nmodel.fit(train_dataset, epochs=10, steps_per_epoch=math.ceil(num_train_examples/BATCH_SIZE))\r\n\r\ntest_loss, test_accuracy = model.evaluate(test_dataset, steps=math.ceil(num_test_examples/32))\r\nprint('Accuracy on test dataset:', test_accuracy)\r\n","sub_path":"Tensorflow/classify_images_cnn.py","file_name":"classify_images_cnn.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"618944532","text":"import numpy as np\nfrom sympy import symbols, Derivative\n\nprint(\"We will solve the equation 5x^4 - 22.4x^3 + 15.85272x^2 + 24.161472x - 23.4824832\")\nprint(\"What method do you want?\")\nprint(\"Bisection : 1, Newton-Raphson : 2\")\nc = int(input(\"Your Choice : \"))\n\n#Bisection\nif c == 1:\n print(\"Your choice is Bisection\")\n def fx(x):\n result = 5*x**4 - 22.4*x**3 + 15.85272*x**2 + 24.161472*x - 23.4824832\n return result\n min = float(input(\"Input interval's Min value : \"))\n max = float(input(\"Input interval's Max value : \"))\n sc = fx(min) * fx(max)\n while True:\n if min >= max:\n print(\"Your input is wrong interval\")\n min = float(input(\"Input interval's Min value : \"))\n max = float(input(\"Input interval's Max value : \"))\n sc = fx(min) * fx(max)\n continue\n\n if sc == 0:\n if fx(min) == 0:\n print(\"The root is\", min)\n break\n elif fx(max) == 0:\n print(\"The root is\", max)\n break \n \n elif sc > 0:\n print(\"Your input is wrong interval\")\n min = float(input(\"Input interval's Min value : \"))\n max = float(input(\"Input interval's Max value : \"))\n sc = fx(min) * fx(max)\n continue\n \n elif sc < 0:\n if max - min < 0.0001:\n print(\"The root exists between %f, %f\" % (min, max))\n break\n while True:\n max2 = max - (max - min)/2\n sc = fx(min) * fx(max2)\n if sc > 0:\n min = max2\n sc = fx(min) * fx(max)\n continue\n \n elif sc < 0:\n if max - min < 0.0001:\n print(\"The root exists between %f, %0.12f\" % (min, max))\n break\n max = max2\n continue\n\n elif sc == 0:\n if fx(min) == 0:\n print(\"The root is\", min)\n break\n elif fx(max2) == 0:\n print(\"The root is\", max2)\n break\n break \n\n#Newton-Raphson\nelif c == 2:\n print(\"Your choice is Newton-Raphson\")\n init = float(input(\"Input initial value : \"))\n x = symbols('x')\n fx = 5*x**4 - 22.4*x**3 + 15.85272*x**2 + 24.161472*x - 23.4824832\n while True:\n v = fx.subs({x: init})\n if v == 0:\n print(\"The root is\", init)\n break\n elif v != 0:\n lim = Derivative(fx, x)\n d = lim.doit().subs({x: init})\n nv = init - v/d\n if abs((nv - init)/nv) * 100 < 0.0001:\n print(\"The approximated root is\", nv)\n break\n init = nv","sub_path":"HW#1/HW#1.py","file_name":"HW#1.py","file_ext":"py","file_size_in_byte":2884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"16669895","text":"import os\nimport sys\nimport subprocess\nfrom pathlib import Path\n\"\"\"\nFirst we do some pathing options\n\"\"\"\nsrc_directory = Path('.').resolve().parent\nproject_directory = Path('.').resolve().parent.parent\n\nsys.path.append(src_directory)\nsys.path.append(project_directory)\n\n\"\"\"\nSome imports\n\"\"\"\ntry:\n from .AbstractTester import AbstractTester\nexcept ModuleNotFoundError:\n try:\n from AbstractTester import AbstractTester\n except ModuleNotFoundError as e:\n print(e)\nfrom options import TestCase, TestOptions\nclass CPPTester(AbstractTester):\n def __init__(self,options: TestOptions,homework: str):\n super().__init__(options,homework)\n self._outputFile = homework.split('.cpp')[0]+'.out'\n def compileFile(self):\n subprocess.run([\"g++\",self.getHomework(),\"-o\",self._outputFile],cwd=self._cwd)\n def run(self):\n for i in range(len(self.getOtions())):\n p = subprocess.run(['./'+self._outputFile],input=self.getOptions()[i].getTestOptions(),universal_newlines=True,stdout=subprocess.PIPE,cwd=self._cwd)\n self.getProcess().append(p)","sub_path":"src/tester/CPPTester.py","file_name":"CPPTester.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"55519881","text":"import random\nimport sys\n\ndef get_length():\n # argv to get length, default to 3\n length = 3\n if len(sys.argv) > 1:\n try: \n length = int(sys.argv[1])\n except:\n print(\"Invalid Input\")\n return length\n\ndef random_int(length):\n\t# gen random number by length\n\tstart = 10**(length-1)\n\tend = 10**length -1\n\trandom_n = random.randint(start, end)\n\treturn random_n\n\ndef list_num(n):\n\tlist_n = [value for value in str(n)]\n\treturn list_n\n\ndef user_guess(n, length):\n\tmaxrounds = (2**length) + length\n\tprint(\"Let's play the mimsmind1 game. You have {} guesses.\".format(maxrounds))\n\tcount = 0\n\t# User types in first guess.\n\tuser_n = input(\"Guess a {}-digit number: \".format(length))\n\twhile count < maxrounds:\n\t\t# Checks if user input is an integer.\n\t\ttry:\n\t\t\tuser_n = int(user_n)\n\t\texcept:\n\t\t\tuser_n = input(\"Invalid input. Try again: \")\n\t\t\tcontinue\n\t\tcount += 1\n\t\tif n == user_n:\n\t\t\tprint(\"Congratulations. You guessed the correct number in {} times.\".format(count))\n\t\t\tbreak\n\t\t# Ends the game if user guesses maximum amount.\n\t\tif count == maxrounds:\n\t\t\tprint(\"Sorry you did not guess the number in {} tries. The correct number is {}.\".format(maxrounds, n))\n\t\t\tbreak\n\t\tcow = 0\n\t\tbull = 0\n\t\t# Translates user input and random number into a list in order to check individual digit. \n\t\trandom_list = list_num(n)\n\t\tuser_list = list_num(user_n)\n\t\tfor index, value in enumerate(user_list):\n\t\t\tif value in random_list:\n\t\t\t# Bull: Checks if the same value is in the same location and \n\t\t\t# replaces the value so it does not get checked again.\n\t\t\t\tif index == random_list.index(value):\n\t\t\t\t\tbull += 1\n\t\t\t\t\tuser_list[index] = 'B'\n\t\t\t\t\trandom_list[index] = \" \"\n\t\tfor index, value in enumerate(user_list):\n\t\t\t# Cow: Checks if the value is in the list with remaining numbers.\n\t\t\tif value in random_list:\n\t\t\t\tcow += 1\n\t\tuser_n = (input(\"{} bull(s), {} cow(s). Try again: \".format(bull, cow)))\n\n\ndef main():\n\tlength = get_length()\n\tn = random_int(length)\n\tuser_guess(n, length)\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"mimsmind1_lizlee.py","file_name":"mimsmind1_lizlee.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"281857943","text":"from tkinter import Tk, BOTH, IntVar, LEFT\nfrom tkinter.ttk import Frame, Label, Scale, Style\n\n\nclass Example(Frame):\n\n def __init__(self):\n super().__init__()\n\n self.initUI()\n\n def initUI(self):\n self.master.title(\"Scale\")\n self.style = Style()\n self.style.theme_use(\"default\")\n\n self.pack(fill=BOTH, expand=1)\n\n scale = Scale(self, from_=0, to=100, command=self.on_scale)\n scale.pack(side=LEFT, padx=15)\n\n self.var = IntVar()\n self.label = Label(self, text=0, textvariable=self.var)\n self.label.pack(side=LEFT)\n\n def on_scale(self,val):\n\n v = int(float(val))\n self.var.set(v)\n\n\ndef main():\n root = Tk()\n ex = Example()\n root.geometry('200x130+300+300')\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"test_Scale.py","file_name":"test_Scale.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"145434281","text":"#! /usr/bin/python\n# -*- encoding: utf-8 -*-\n\nimport pygame.locals\n\nfrom ..config import *\nfrom ..utils.display import get_text, relative2physic\nfrom .handler import EventHandler\nfrom ..element.text import Text\n\n__author__ = 'fyabc'\n\n\nclass ActiveText(EventHandler, Text):\n def __init__(self, game, scene,\n text, loc, fg_bg=(False, True), font_size=FontSize, font_name=FontName,\n visible=True,\n mouse_up_call=None):\n \"\"\"\n\n :param game:\n :param scene:\n :param text:\n :param loc:\n :param fg_bg:\n :param font_size:\n :param font_name:\n :param visible:\n :param mouse_up_call: callable or None.\n Call it on mouse up event.\n parameters: text(self), game, event, previous_scene_id, *args\n return: next_scene_id, *next_args\n \"\"\"\n\n super().__init__(game, {\n (pygame.locals.MOUSEBUTTONDOWN, 1),\n })\n Text.__init__(self, game, scene, text, loc, fg_bg, font_size, font_name, visible, 0)\n\n self.clicked = False\n\n # The default setting of active text:\n # Clicked color is inverted common color.\n self.text = text\n self.fg_bg = fg_bg\n self.font = font_size, font_name\n\n self.add_action((pygame.locals.MOUSEBUTTONDOWN, 1), self.on_mouse_down_1)\n self.mouse_up_call = (lambda game_, event_, pre_sid, *args: None) if mouse_up_call is None else mouse_up_call\n\n def __contains__(self, item):\n rect = self.image.get_rect()\n rect.center = self.loc\n return rect.collidepoint(item)\n\n def invert(self):\n self.clicked = not self.clicked\n self.fg_bg = [not c for c in self.fg_bg]\n self.image = get_text(self.text, *self.fg_bg, *self.font)\n\n def on_mouse_down_1(self, game, event, pre_sid, *args):\n self.invert()\n\n def on_mouse_up_1(self, game, event, pre_sid, *args):\n self.invert()\n return self.mouse_up_call(self, game, event, pre_sid, *args)\n","sub_path":"Shift_pygame/Shift_pygame/handler/active_text.py","file_name":"active_text.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"475474722","text":"# !/usr/bin/python\r\n# -*- coding:utf-8 -*-\r\n\r\nimport os\r\nimport re\r\nimport urllib.request\r\nfrom lxml import etree\r\nfrom NewUrl import tag_input, site, next_page_url\r\n\r\ndef getImg(temp):\r\n for new_url in temp:\r\n rsp = urllib.request.urlopen(new_url).read()\r\n rsp_parse = etree.HTML(rsp.lower().decode('utf-8'))\r\n url_title = rsp_parse.xpath('/html/body/div[5]/div[1]/div[2]/ul//div[1]/img/@alt')\r\n url_list = rsp_parse.xpath('/html/body/div[5]/div[1]/div[2]/ul/li/a/@href')\r\n total = 1\r\n for new_page in url_list:\r\n img_page = urllib.request.urlopen(new_page).read()\r\n img_html = etree.HTML(img_page.lower().decode('utf-8'))\r\n img_url = img_html.xpath('/html/body/div[5]/div[1]/div[2]/div[1]//img/@src')\r\n for title in url_title:\r\n filepath = os.getcwd() + '\\\\Pictures\\\\' + tag_input + '\\\\'\r\n if(os.path.exists(filepath) is False):\r\n os.makedirs(filepath)\r\n for pic in img_url:\r\n filename = filepath + pic.split('/')[6]\r\n if(os.path.isfile(filename)):\r\n break\r\n else:\r\n pic_content = site + str(pic)\r\n urllib.request.urlretrieve(pic_content, filename)\r\n print ('Downloading', total, 'Pictures')\r\n total += 1\r\n print(u'一共下载了', total, '张图片')\r\n\r\nif __name__ == '__main__':\r\n getImg(next_page_url)\r\n","sub_path":"meimeidabenyin/purl_get/mm.py","file_name":"mm.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"79102471","text":"#\n# Copyright (c) 2006, 2007 Canonical\n#\n# Written by Robert Collins \n#\n# This file is part of Storm Object Relational Mapper.\n#\n# Storm is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation; either version 2.1 of\n# the License, or (at your option) any later version.\n#\n# Storm 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 Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with this program. If not, see .\n#\n\n\"\"\"Glue to wire a storm timeline tracer up to a WSGI app.\"\"\"\n\nimport functools\nimport threading\n\n__all__ = ['make_app']\n\ndef make_app(app):\n \"\"\"Capture the per-request timeline object needed for storm tracing.\n\n To use firstly make your app and then wrap it with this make_app::\n\n >>> app, find_timeline = make_app(app)\n\n Then wrap the returned app with the timeline app (or anything that sets\n environ['timeline.timeline'])::\n\n >>> app = timeline.wsgi.make_app(app)\n\n Finally install a timeline tracer to capture storm queries::\n\n >>> install_tracer(TimelineTracer(find_timeline))\n\n @return: A wrapped WSGI app and a timeline factory function for use with\n TimelineTracer.\n \"\"\"\n timeline_map = threading.local()\n def wrapper(environ, start_response):\n timeline = environ.get('timeline.timeline')\n timeline_map.timeline = timeline\n try:\n gen = app(environ, start_response)\n for bytes in gen:\n yield bytes\n finally:\n del timeline_map.timeline\n return wrapper, functools.partial(getattr, timeline_map, 'timeline', None)\n","sub_path":"MyApp/storm/wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"43546214","text":"import json\n\nwith open( \"scrabble.txt\", \"r\" ) as f:\n words = []\n i = 0\n for word in f.readlines():\n if i % 3 == 0:\n word = word.lower()\n word = word.replace(\"\\n\",\"\")\n word = word.replace(\" \",\"\")\n words.append( word )\n i += 1\n\n with open( \"smalldict.txt\", \"w\" ) as g:\n for word in words:\n g.write( \"%s\\n\" % word )\n","sub_path":"cs454/dictionary/gen-small-dict.py","file_name":"gen-small-dict.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"74194988","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Wei, Shuowen\n\nhttps://leetcode.com/problems/walls-and-gates/\n\nhttps://tenderleo.gitbooks.io/leetcode-solutions-/content/GoogleMedium/286.html?q=\n\n\"\"\"\nclass Solution(object):\n def wallsAndGates(self, rooms):\n \"\"\"\n rooms: List[List[int]]\n Do not return anything, modify rooms in-place instead.\n \"\"\"\n # solution 1: DFS: https://zhenyu0519.github.io/2020/03/07/lc286/#sample-io\n if len(rooms) == 0:\n return []\n \n row, col = len(rooms), len(rooms[0])\n direction = [(1,0), (-1,0), (0,1), (0,-1)]\n def dfs(x, y, dis):\n for dx, dy in direction:\n nx, ny = x + dx, y + dy\n if 0 <= nx < row and 0 <= ny < col and rooms[nx][ny] > rooms[x][y]:\n rooms[nx][ny] = dis + 1\n dfs(nx, ny, dis + 1)\n\n for i in range(row):\n for j in range(col):\n if rooms[i][j] == 0:\n dfs(i, j, 0)\n # We iterate each cell will cost O(m*n) where m*n is the size of the 2D list. \n # Each cell will also iterate four directions O(m*n*4). In total O(4*m*n)\n \n def wallsAndGates_BFS(self, rooms):\n # solutioin 2: BFS\n if len(rooms) == 0:\n return []\n \n row, col = len(rooms), len(rooms[0])\n direction = [(1,0), (-1,0), (0,1), (0,-1)]\n import collections\n q = collections.deque()\n for i in range(row):\n for j in range(col):\n if rooms[i][j] == 0:\n q.append((i, j, 0))\n while q:\n size = len(q)\n for _ in range(size):\n i, j, dis = q.popleft()\n for di, dj in direction:\n ni, nj = i + di, j + dj\n if 0 <= ni < row and 0 <= nj < col and rooms[ni][nj] > dis + 1:\n rooms[ni][nj] = dis + 1\n q.append((ni, nj, dis + 1))\nsol = Solution()\nrooms=[[2**32, -1, 0, 2**32],\n [2**32, 2**32, 2**32, -1],\n [2**32, -1, 2**32, -1],\n [0, -1, 2**32, 2**32]]\nsol.wallsAndGates(rooms)\nprint(rooms)\n\nrooms=[[2**32, -1, 0, 2**32],\n [2**32, 2**32, 2**32, -1],\n [2**32, -1, 2**32, -1],\n [0, -1, 2**32, 2**32]]\nsol.wallsAndGates_BFS(rooms)\nprint(rooms)","sub_path":"Medium/LC286TODO.py","file_name":"LC286TODO.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"195942879","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 22 16:22:01 2020\r\n\r\n@author: guido\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.utils import shuffle\r\nimport pandas as pd\r\nimport tkinter as tk\r\nfrom glob import glob\r\nfrom datetime import datetime\r\nfrom brainbox.io.spikeglx import spikeglx\r\nfrom brainbox.numerical import ismember\r\nfrom ibllib.atlas import BrainRegions\r\nfrom one.api import ONE\r\n\r\n# This is the date at which I fixed a crucial bug in the laser driver, all optogenetics data\r\n# from before this date is not to be trusted\r\nDATE_GOOD_OPTO = '2021-07-01'\r\n\r\n# This is the date at which light shielding was added so that the mouse couldn't see the opto stim\r\nDATE_LIGHT_SHIELD = '2021-06-08'\r\n\r\n\r\ndef paths():\r\n \"\"\"\r\n Make a file in the root of the repository called 'serotonin_paths.py' with in it:\r\n\r\n DATA_PATH = '/path/to/Flatiron/data'\r\n FIG_PATH = '/path/to/save/figures'\r\n SAVE_PATH = '/path/to/save/data'\r\n\r\n \"\"\"\r\n from serotonin_paths import DATA_PATH, FIG_PATH, SAVE_PATH\r\n return DATA_PATH, FIG_PATH, SAVE_PATH\r\n\r\n\r\ndef figure_style():\r\n \"\"\"\r\n Set style for plotting figures\r\n \"\"\"\r\n sns.set(style=\"ticks\", context=\"paper\",\r\n font=\"Arial\",\r\n rc={\"font.size\": 7,\r\n \"axes.titlesize\": 8,\r\n \"axes.labelsize\": 7,\r\n \"axes.linewidth\": 0.5,\r\n \"lines.linewidth\": 1,\r\n \"lines.markersize\": 3,\r\n \"xtick.labelsize\": 7,\r\n \"ytick.labelsize\": 7,\r\n \"savefig.transparent\": True,\r\n \"xtick.major.size\": 2.5,\r\n \"ytick.major.size\": 2.5,\r\n \"xtick.major.width\": 0.5,\r\n \"ytick.major.width\": 0.5,\r\n \"xtick.minor.size\": 2,\r\n \"ytick.minor.size\": 2,\r\n \"xtick.minor.width\": 0.5,\r\n \"ytick.minor.width\": 0.5\r\n })\r\n matplotlib.rcParams['pdf.fonttype'] = 42\r\n matplotlib.rcParams['ps.fonttype'] = 42\r\n colors = {'sert': sns.color_palette('colorblind')[2],\r\n 'wt': sns.color_palette('colorblind')[7],\r\n 'left': sns.color_palette('colorblind')[1],\r\n 'right': sns.color_palette('colorblind')[0],\r\n 'enhanced': sns.color_palette('colorblind')[3],\r\n 'suppressed': sns.color_palette('colorblind')[0],\r\n 'no-modulation': sns.color_palette('colorblind')[7],\r\n 'both-significant': sns.color_palette('colorblind')[2],\r\n 'light-significant': sns.color_palette('colorblind')[0],\r\n 'stim-significant': sns.color_palette('colorblind')[4]}\r\n screen_width = tk.Tk().winfo_screenwidth()\r\n dpi = screen_width / 10\r\n return colors, dpi\r\n\r\n\r\ndef query_opto_sessions(subject, one=None):\r\n one = one or ONE()\r\n sessions = one.alyx.rest('sessions', 'list', subject=subject,\r\n task_protocol='_iblrig_tasks_opto_biasedChoiceWorld',\r\n project='serotonin_inference')\r\n return [sess['url'][-36:] for sess in sessions]\r\n\r\n\r\ndef query_ephys_sessions(selection='aligned', return_subjects=False, one=None):\r\n if one is None:\r\n one = ONE()\r\n if selection == 'all':\r\n # Query all opto_ephysChoiceWorld sessions\r\n ins = one.alyx.rest('insertions', 'list',\r\n django='session__project__name__icontains,serotonin_inference,'\r\n 'session__qc__lt,50')\r\n elif selection == 'aligned':\r\n # Query all ephys-histology aligned sessions\r\n ins = one.alyx.rest('insertions', 'list',\r\n django='session__project__name__icontains,serotonin_inference,'\r\n 'session__qc__lt,50,'\r\n 'json__extended_qc__alignment_count__gt,0')\r\n elif selection == 'aligned-behavior':\r\n # Query sessions with an alignment and that meet behavior criterion\r\n ins = one.alyx.rest('insertions', 'list',\r\n django='session__project__name__icontains,serotonin_inference,'\r\n 'session__qc__lt,50,'\r\n 'json__extended_qc__alignment_count__gt,0,'\r\n 'session__extended_qc__behavior,1')\r\n else:\r\n ins = []\r\n\r\n # Get list of eids and probes\r\n all_eids = np.array([i['session'] for i in ins])\r\n all_probes = np.array([i['name'] for i in ins])\r\n all_subjects = np.array([i['session_info']['subject'] for i in ins])\r\n eids, ind_unique = np.unique(all_eids, return_index=True)\r\n subjects = all_subjects[ind_unique]\r\n probes = []\r\n for i, eid in enumerate(eids):\r\n probes.append(all_probes[[s == eid for s in all_eids]])\r\n if return_subjects:\r\n return eids, probes, subjects\r\n else:\r\n return eids, probes\r\n\r\n\r\ndef load_trials(eid, laser_stimulation=False, invert_choice=False, invert_stimside=False,\r\n patch_old_opto=True, one=None):\r\n one = one or ONE()\r\n data, _ = one.load_datasets(eid, datasets=[\r\n '_ibl_trials.stimOn_times.npy', '_ibl_trials.feedback_times.npy',\r\n '_ibl_trials.goCue_times.npy', '_ibl_trials.probabilityLeft.npy',\r\n '_ibl_trials.contrastLeft.npy', '_ibl_trials.contrastRight.npy',\r\n '_ibl_trials.feedbackType.npy', '_ibl_trials.choice.npy',\r\n '_ibl_trials.firstMovement_times.npy'])\r\n trials = pd.DataFrame(data=np.vstack(data).T, columns=[\r\n 'stimOn_times', 'feedback_times', 'goCue_times', 'probabilityLeft', 'contrastLeft',\r\n 'contrastRight', 'feedbackType', 'choice', 'firstMovement_times'])\r\n if trials.shape[0] == 0:\r\n return\r\n trials['signed_contrast'] = trials['contrastRight']\r\n trials.loc[trials['signed_contrast'].isnull(), 'signed_contrast'] = -trials['contrastLeft']\r\n if laser_stimulation:\r\n trials['laser_stimulation'] = one.load_dataset(eid, dataset='_ibl_trials.laser_stimulation.npy')\r\n try:\r\n trials['laser_probability'] = one.load_dataset(eid, dataset='_ibl_trials.laser_probability.npy')\r\n trials['catch'] = ((trials['laser_stimulation'] == 0) & (trials['laser_probability'] == 0.75)\r\n | (trials['laser_stimulation'] == 1) & (trials['laser_probability'] == 0.25)).astype(int)\r\n except:\r\n trials['laser_probability'] = trials['laser_stimulation'].copy()\r\n trials.loc[(trials['signed_contrast'] == 0)\r\n & (trials['laser_stimulation'] == 0), 'laser_probability'] = 0.25\r\n trials.loc[(trials['signed_contrast'] == 0)\r\n & (trials['laser_stimulation'] == 1), 'laser_probability'] = 0.75\r\n trials['correct'] = trials['feedbackType']\r\n trials.loc[trials['correct'] == -1, 'correct'] = 0\r\n trials['right_choice'] = -trials['choice']\r\n trials.loc[trials['right_choice'] == -1, 'right_choice'] = 0\r\n trials['stim_side'] = (trials['signed_contrast'] > 0).astype(int)\r\n trials.loc[trials['stim_side'] == 0, 'stim_side'] = -1\r\n trials.loc[(trials['signed_contrast'] == 0) & (trials['contrastLeft'].isnull()),\r\n 'stim_side'] = 1\r\n trials.loc[(trials['signed_contrast'] == 0) & (trials['contrastRight'].isnull()),\r\n 'stim_side'] = -1\r\n if 'firstMovement_times' in trials.columns.values:\r\n trials['reaction_times'] = trials['firstMovement_times'] - trials['goCue_times']\r\n if invert_choice:\r\n trials['choice'] = -trials['choice']\r\n if invert_stimside:\r\n trials['stim_side'] = -trials['stim_side']\r\n trials['signed_contrast'] = -trials['signed_contrast']\r\n\r\n # Patch datasets that contained a bug in the laser driver code\r\n ses_date = datetime.strptime(one.get_details(eid)['start_time'][:10], '%Y-%m-%d')\r\n if ((ses_date < datetime.strptime(DATE_GOOD_OPTO, '%Y-%m-%d'))\r\n and patch_old_opto and laser_stimulation):\r\n\r\n # The bug flipped laser on and off pulses after a long reaction time trial\r\n bug_trial = ((trials.loc[trials['laser_stimulation'] == 1, 'feedback_times']\r\n - trials.loc[trials['laser_stimulation'] == 1, 'stimOn_times']) > 10).idxmax()\r\n print(f'Patching buggy opto data, excluding {trials.shape[0] - bug_trial} trials')\r\n trials = trials[:bug_trial]\r\n\r\n return trials\r\n\r\n\r\ndef remap(ids, source='Allen', dest='Beryl', output='acronym'):\r\n br = BrainRegions()\r\n _, inds = ismember(ids, br.id[br.mappings[source]])\r\n ids = br.id[br.mappings[dest][inds]]\r\n if output == 'id':\r\n return br.id[br.mappings[dest][inds]]\r\n elif output == 'acronym':\r\n return br.get(br.id[br.mappings[dest][inds]])['acronym']\r\n\r\n\r\ndef get_full_region_name(acronyms):\r\n brainregions = BrainRegions()\r\n full_region_names = []\r\n for i, acronym in enumerate(acronyms):\r\n try:\r\n regname = brainregions.name[np.argwhere(brainregions.acronym == acronym).flatten()][0]\r\n full_region_names.append(regname)\r\n except IndexError:\r\n full_region_names.append(acronym)\r\n if len(full_region_names) == 1:\r\n return full_region_names[0]\r\n else:\r\n return full_region_names\r\n\r\n\r\ndef behavioral_criterion(eids, max_lapse=0.25, max_bias=0.4, min_trials=1, one=None):\r\n if one is None:\r\n one = ONE()\r\n use_eids = []\r\n for j, eid in enumerate(eids):\r\n try:\r\n trials = load_trials(eid, one=one)\r\n lapse_l = 1 - (np.sum(trials.loc[trials['signed_contrast'] == -1, 'choice'] == 1)\r\n / trials.loc[trials['signed_contrast'] == -1, 'choice'].shape[0])\r\n lapse_r = 1 - (np.sum(trials.loc[trials['signed_contrast'] == 1, 'choice'] == -1)\r\n / trials.loc[trials['signed_contrast'] == 1, 'choice'].shape[0])\r\n bias = np.abs(0.5 - (np.sum(trials.loc[trials['signed_contrast'] == 0, 'choice'] == 1)\r\n / np.shape(trials.loc[trials['signed_contrast'] == 0, 'choice'] == 1)[0]))\r\n details = one.get_details(eid)\r\n if ((lapse_l < max_lapse) & (lapse_r < max_lapse) & (trials.shape[0] > min_trials)\r\n & (bias < max_bias)):\r\n use_eids.append(eid)\r\n else:\r\n print('%s %s excluded (n_trials: %d, lapse_l: %.2f, lapse_r: %.2f, bias: %.2f)'\r\n % (details['subject'], details['start_time'][:10], trials.shape[0], lapse_l, lapse_r, bias))\r\n except Exception:\r\n print('Could not load session %s' % eid)\r\n return use_eids\r\n\r\n\r\ndef load_exp_smoothing_trials(eids, stimulated=None, rt_cutoff=0.2, after_probe_trials=0,\r\n pseudo=False, patch_old_opto=True, min_trials=100, one=None):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n eids : list\r\n List of eids\r\n stimulated : None or string\r\n If None, do not return the stimulated array, if a string these are the options:\r\n all: all laser stimulated trials\r\n probe: only laser probe trials\r\n block: only laser block trials (no probes)\r\n rt: this is a weird one - return a reaction time cut off as stimulated trials\r\n rt_cutoff : float\r\n Only used if stimulated = 'rt'. Reaction time cutoff in seconds above which stimulated is 1\r\n after_probe_trials : int\r\n Only used if stimulated = 'probe'. How many trials after a probe trial are still counted.\r\n pseudo : bool\r\n Whether to use pseudo stimulated blocks or shuffled probes as control\r\n \"\"\"\r\n\r\n if isinstance(stimulated, str):\r\n assert stimulated in ['all', 'probe', 'block', 'rt']\r\n\r\n if one is None:\r\n one=ONE()\r\n stimuli_arr, actions_arr, stim_sides_arr, prob_left_arr, stimulated_arr, session_uuids = [], [], [], [], [], []\r\n for j, eid in enumerate(eids):\r\n try:\r\n # Load in trials vectors\r\n if stimulated is not None and stimulated != 'rt':\r\n trials = load_trials(eid, invert_stimside=True, laser_stimulation=True,\r\n patch_old_opto=patch_old_opto, one=one)\r\n else:\r\n trials = load_trials(eid, invert_stimside=True, laser_stimulation=False,\r\n patch_old_opto=patch_old_opto, one=one)\r\n if trials.shape[0] < min_trials:\r\n continue\r\n if stimulated == 'all':\r\n stimulated_arr.append(trials['laser_stimulation'].values)\r\n elif stimulated == 'probe':\r\n probe_trials = ((trials['laser_stimulation'] == 1) & (trials['laser_probability'] <= .5)).values\r\n if pseudo:\r\n probe_trials = shuffle(probe_trials)\r\n for k, ind in enumerate(np.where(probe_trials == 1)[0]):\r\n probe_trials[ind:ind + (after_probe_trials + 1)] = 1\r\n stimulated_arr.append(probe_trials)\r\n elif stimulated == 'block':\r\n block_trials = trials['laser_stimulation'].values\r\n if 'laser_probability' in trials.columns:\r\n block_trials[(trials['laser_stimulation'] == 0) & (trials['laser_probability'] == .75)] = 1\r\n block_trials[(trials['laser_stimulation'] == 1) & (trials['laser_probability'] == .25)] = 0\r\n stimulated_arr.append(block_trials)\r\n elif stimulated == 'rt':\r\n stimulated_arr.append((trials['reaction_times'] > rt_cutoff).values)\r\n stimuli_arr.append(trials['signed_contrast'].values)\r\n actions_arr.append(trials['choice'].values)\r\n stim_sides_arr.append(trials['stim_side'].values)\r\n prob_left_arr.append(trials['probabilityLeft'].values)\r\n session_uuids.append(eid)\r\n except:\r\n print(f'Could not load trials for {eid}')\r\n\r\n if (len(session_uuids) == 0) and (stimulated is not None and stimulated != 'rt'):\r\n return [], [], [], [], [], []\r\n elif len(session_uuids) == 0:\r\n return [], [], [], [], []\r\n\r\n # Get maximum number of trials across sessions\r\n max_len = np.array([len(stimuli_arr[k]) for k in range(len(stimuli_arr))]).max()\r\n\r\n # Pad with 0 such that we obtain nd arrays of size nb_sessions x nb_trials\r\n stimuli = np.array([np.concatenate((stimuli_arr[k], np.zeros(max_len-len(stimuli_arr[k]))))\r\n for k in range(len(stimuli_arr))])\r\n actions = np.array([np.concatenate((actions_arr[k], np.zeros(max_len-len(actions_arr[k]))))\r\n for k in range(len(actions_arr))])\r\n prob_left = np.array([np.concatenate((prob_left_arr[k], np.zeros(max_len-len(prob_left_arr[k]))))\r\n for k in range(len(prob_left_arr))])\r\n stim_side = np.array([np.concatenate((stim_sides_arr[k],\r\n np.zeros(max_len-len(stim_sides_arr[k]))))\r\n for k in range(len(stim_sides_arr))])\r\n if stimulated is not None and stimulated != 'rt':\r\n stimulated = np.array([np.concatenate((stimulated_arr[k], np.zeros(max_len-len(stimulated_arr[k]))))\r\n for k in range(len(stimulated_arr))])\r\n session_uuids = np.array(session_uuids)\r\n\r\n if session_uuids.shape[0] == 1:\r\n stimuli = np.array([np.squeeze(stimuli)])\r\n actions = np.array([np.squeeze(actions)])\r\n prob_left = np.array([np.squeeze(prob_left)])\r\n stim_side = np.array([np.squeeze(stim_side)])\r\n if stimulated is not None and stimulated != 'rt':\r\n stimulated = np.array([np.squeeze(stimulated)])\r\n\r\n if stimulated is not None and stimulated != 'rt':\r\n return actions, stimuli, stim_side, prob_left, stimulated, session_uuids\r\n else:\r\n return actions, stimuli, stim_side, prob_left, session_uuids\r\n\r\n\r\ndef load_opto_times(eid, one=None):\r\n if one is None:\r\n one = ONE()\r\n\r\n # Load in laser pulses\r\n try:\r\n one.load_datasets(eid, datasets=[\r\n '_spikeglx_ephysData_g0_t0.nidq.cbin', '_spikeglx_ephysData_g0_t0.nidq.meta',\r\n '_spikeglx_ephysData_g0_t0.nidq.ch'], download_only=True)\r\n except:\r\n one.load_datasets(eid, datasets=[\r\n '_spikeglx_ephysData_g1_t0.nidq.cbin', '_spikeglx_ephysData_g1_t0.nidq.meta',\r\n '_spikeglx_ephysData_g1_t0.nidq.ch'], download_only=True)\r\n session_path = one.eid2path(eid)\r\n nidq_file = glob(str(session_path.joinpath('raw_ephys_data/_spikeglx_ephysData_g*_t0.nidq.cbin')))[0]\r\n sr = spikeglx.Reader(nidq_file)\r\n offset = int((sr.shape[0] / sr.fs - 1800) * sr.fs)\r\n opto_trace = sr.read_sync_analog(slice(offset, offset + int(1800 * sr.fs)))[:, 1]\r\n opto_times = np.arange(offset, offset + len(opto_trace)) / sr.fs\r\n\r\n # Get start times of pulse trains\r\n opto_high_times = opto_times[opto_trace > 1]\r\n if len(opto_high_times) == 0:\r\n print(f'No pulses found for {eid}')\r\n return []\r\n else:\r\n opto_train_times = opto_high_times[np.concatenate(([True], np.diff(opto_high_times) > 1))]\r\n assert np.sum(np.diff(opto_train_times) > 300) == 1, 'Could not find passive laser pulses'\r\n opto_train_times = opto_train_times[np.where(np.diff(opto_train_times) > 300)[0][0]+1:]\r\n return opto_train_times\r\n\r\n\r\ndef query_bwm_sessions(selection='all', return_subjects=False, one=None):\r\n if one is None:\r\n one = ONE()\r\n if selection == 'all':\r\n # Query all ephysChoiceWorld sessions\r\n ins = one.alyx.rest('insertions', 'list',\r\n django='session__project__name__icontains,ibl_neuropixel_brainwide_01,'\r\n 'session__qc__lt,50')\r\n elif selection == 'aligned':\r\n # Query all sessions with at least one alignment\r\n ins = one.alyx.rest('insertions', 'list',\r\n django='session__project__name__icontains,ibl_neuropixel_brainwide_01,'\r\n 'session__qc__lt,50,'\r\n 'json__extended_qc__alignment_count__gt,0')\r\n elif selection == 'resolved':\r\n # Query all sessions with resolved alignment\r\n ins = one.alyx.rest('insertions', 'list',\r\n django='session__project__name__icontains,ibl_neuropixel_brainwide_01,'\r\n 'session__qc__lt,50,'\r\n 'json__extended_qc__alignment_resolved,True')\r\n elif selection == 'aligned-behavior':\r\n # Query sessions with at least one alignment and that meet behavior criterion\r\n ins = one.alyx.rest('insertions', 'list',\r\n django='session__project__name__icontains,ibl_neuropixel_brainwide_01,'\r\n 'session__qc__lt,50,'\r\n 'json__extended_qc__alignment_count__gt,0,'\r\n 'session__extended_qc__behavior,1')\r\n elif selection == 'resolved-behavior':\r\n # Query sessions with resolved alignment and that meet behavior criterion\r\n ins = one.alyx.rest('insertions', 'list',\r\n django='session__project__name__icontains,ibl_neuropixel_brainwide_01,'\r\n 'session__qc__lt,50,'\r\n 'json__extended_qc__alignment_resolved,True,'\r\n 'session__extended_qc__behavior,1')\r\n else:\r\n ins = []\r\n\r\n # Get list of eids and probes\r\n all_eids = np.array([i['session'] for i in ins])\r\n all_probes = np.array([i['name'] for i in ins])\r\n all_subjects = np.array([i['session_info']['subject'] for i in ins])\r\n eids, ind_unique = np.unique(all_eids, return_index=True)\r\n subjects = all_subjects[ind_unique]\r\n probes = []\r\n for i, eid in enumerate(eids):\r\n probes.append(all_probes[[s == eid for s in all_eids]])\r\n if return_subjects:\r\n return eids, probes, subjects\r\n else:\r\n return eids, probes\r\n\r\n\r\ndef fit_psychfunc(stim_levels, n_trials, proportion):\r\n # Fit a psychometric function with two lapse rates\r\n #\r\n # Returns vector pars with [bias, threshold, lapselow, lapsehigh]\r\n import psychofit as psy\r\n assert(stim_levels.shape == n_trials.shape == proportion.shape)\r\n if stim_levels.max() <= 1:\r\n stim_levels = stim_levels * 100\r\n\r\n pars, _ = psy.mle_fit_psycho(np.vstack((stim_levels, n_trials, proportion)),\r\n P_model='erf_psycho_2gammas',\r\n parstart=np.array([0, 20, 0.05, 0.05]),\r\n parmin=np.array([-100, 5, 0, 0]),\r\n parmax=np.array([100, 100, 1, 1]))\r\n return pars\r\n\r\n\r\ndef plot_psychometric(trials, ax, **kwargs):\r\n import psychofit as psy\r\n if trials['signed_contrast'].max() <= 1:\r\n trials['signed_contrast'] = trials['signed_contrast'] * 100\r\n\r\n stim_levels = np.sort(trials['signed_contrast'].unique())\r\n pars = fit_psychfunc(stim_levels, trials.groupby('signed_contrast').size(),\r\n trials.groupby('signed_contrast').mean()['right_choice'])\r\n\r\n # plot psychfunc\r\n sns.lineplot(x=np.arange(-27, 27), y=psy.erf_psycho_2gammas(pars, np.arange(-27, 27)),\r\n ax=ax, **kwargs)\r\n\r\n # plot psychfunc: -100, +100\r\n sns.lineplot(x=np.arange(-36, -31), y=psy.erf_psycho_2gammas(pars, np.arange(-103, -98)),\r\n ax=ax, **kwargs)\r\n sns.lineplot(x=np.arange(31, 36), y=psy.erf_psycho_2gammas(pars, np.arange(98, 103)),\r\n ax=ax, **kwargs)\r\n\r\n # now break the x-axis\r\n trials['signed_contrast'].replace(-100, -35)\r\n trials['signed_contrast'].replace(100, 35)\r\n\r\n # plot datapoints with errorbars on top\r\n sns.lineplot(x=trials['signed_contrast'], y=trials['right_choice'], ax=ax,\r\n **{**{'err_style':\"bars\",\r\n 'linewidth':0, 'linestyle':'None', 'mew':0.5,\r\n 'marker':'o', 'ci':68}, **kwargs})\r\n\r\n ax.set(xticks=[-35, -25, -12.5, 0, 12.5, 25, 35], xlim=[-40, 40], ylim=[0, 1.02],\r\n yticks=[0, 0.25, 0.5, 0.75, 1], yticklabels=['0', '25', '50', '75', '100'],\r\n ylabel='Right choices', xlabel='Contrast (%)')\r\n ax.set_xticklabels(['-100', '-25', '-12.5', '0', '12.5', '25', '100'],\r\n size='small')\r\n break_xaxis()\r\n\r\n\r\ndef break_xaxis(y=-0.004, **kwargs):\r\n\r\n # axisgate: show axis discontinuities with a quick hack\r\n # https://twitter.com/StevenDakin/status/1313744930246811653?s=19\r\n # first, white square for discontinuous axis\r\n plt.text(-30, y, '-', fontsize=14, fontweight='bold',\r\n horizontalalignment='center', verticalalignment='center',\r\n color='w')\r\n plt.text(30, y, '-', fontsize=14, fontweight='bold',\r\n horizontalalignment='center', verticalalignment='center',\r\n color='w')\r\n\r\n # put little dashes to cut axes\r\n plt.text(-30, y, '/ /', horizontalalignment='center',\r\n verticalalignment='center', fontsize=12, fontweight='bold')\r\n plt.text(30, y, '/ /', horizontalalignment='center',\r\n verticalalignment='center', fontsize=12, fontweight='bold')\r\n\r\n","sub_path":"serotonin_functions.py","file_name":"serotonin_functions.py","file_ext":"py","file_size_in_byte":23411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"504318970","text":"# test.py\r\nfrom python_src import *\r\nfrom python_src.berry_api import *\r\nfrom python_src.berry_factory import berry_factory\r\nimport sys\r\nfrom time import sleep\r\nimport random\r\n\r\n\r\ndef main(argv):\r\n init_host(argv)\r\n berry_list = get_berry_list()\r\n berries = [berry_factory('yo', berry[0], berry[1]) for berry in berry_list]\r\n\r\n btn = None\r\n led = None\r\n for berry in berries:\r\n print('name: {}, type: {}, guid: {}'.format(berry.name, berry.berry_type, berry.addr))\r\n if berry.berry_type == 'Button':\r\n btn = berry\r\n if berry.berry_type == 'RGB':\r\n led = berry\r\n\r\n try:\r\n v = 0\r\n i = 0\r\n while True:\r\n berries[i].set_status_led(v)\r\n i = (i + 1) % len(berries)\r\n v = random.randint(0, 1)\r\n if btn.state == 1:\r\n led.color = [150,150,150]\r\n else:\r\n led.color = [0,0,0]\r\n sleep(.01)\r\n except:\r\n print('End')\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv)\r\n","sub_path":"projects/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"78972156","text":"import os\n\nfrom click.testing import CliRunner\n\nimport dockman\nfrom dockman import dockman as commands\nfrom dockman.docker import SafeDocker\nfrom dockman.context import Context\n\n\ndef path(relpath):\n \"\"\"Returns path relative to the current file.\"\"\"\n return os.path.join(os.path.dirname(__file__), relpath)\n\n\ndef test_ps():\n container_ids = '944afe740314\\n2fb996a8e981\\n2ba796be766d\\nfc05dd6c5e9c\\n'\n container_info = open(path('inspect1.json'), 'r')\n dockman.DOCKER = SafeDocker(_output=[container_ids, container_info])\n dockman.CONTEXT = Context(path='src', config={})\n runner = CliRunner()\n result = runner.invoke(commands.ps)\n out = result.output\n assert out == ('-------------------------------------------\\n'\n 'Showing containers in project \"src\"\\n'\n '-------------------------------------------\\n'\n 'src.postgres running 5432 -> 0.0.0.0:5432\\n'\n ' 1112 -> 0.0.0.0:1111\\n'\n 'src.shared running \\n'\n '-------------------------------------------\\n')\n\n\ndef test_logs():\n container_ids = '944afe740314\\n2fb996a8e981\\n2ba796be766d\\nfc05dd6c5e9c\\n'\n container_info = open(path('inspect1.json'), 'r')\n\n docker_output = [container_ids, container_info]\n dockman.DOCKER = SafeDocker(_output=docker_output,\n _popenout_filename=path('logs_02_'),\n _log_max_iter=10)\n dockman.CONTEXT = Context(path='src', config={})\n\n runner = CliRunner()\n result = runner.invoke(commands.logs)\n out = result.output\n out = out.split('\\n')\n assert len(out) == 6 + 2 # 2 new lines at the end\n assert 'src.postgres: 02_src.postgres_1' in out\n assert 'src.postgres: 02_src.postgres_2' in out\n assert 'src.postgres: 02_src.postgres_3' in out\n assert 'src.shared: 02_src.shared_1' in out\n assert 'src.shared: 02_src.shared_2' in out\n assert 'src.shared: 02_src.shared_3' in out\n","sub_path":"test/test_commands.py","file_name":"test_commands.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"137732205","text":"from urllib.request import Request,urlopen\r\nimport json\r\nimport sys\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom datetime import datetime\r\nfrom datetime import timedelta\r\nimport os\r\n\r\nimport Parse_Social_utm_content\r\nParse_Social_utm_content=Parse_Social_utm_content.Parse_Social_utm_content\r\n\r\nimport FillNull_DataFrame\r\nClean_Null=FillNull_DataFrame.Clean_Null\r\n\r\nDate_Start=datetime(2016,12,16)\r\nDate_End=datetime(2016,12,31)\r\n\r\nMedia_Type='Social'\r\nCMPN='900'\r\nLinkedIn_File_Identifier='LinkedIn ad report'\r\nDCM_File_Identifier='DCM_PSO'\r\n\r\nWF=os.getcwd().strip()\r\nRF=os.path.dirname(os.path.dirname(os.path.dirname(WF)))+'\\\\Reference' \r\nMap=pd.read_csv(RF+'/Pega_Lookup.csv',encoding='latin-1')\r\n\r\n#read in GA data\r\nGA=pd.ExcelFile(WF+'/GA_Data.xlsx')\r\nEV=GA.parse('Event_900')\r\nEV['Event Category'][EV['Event Category'].str.lower().str.strip()=='browse']='navigate'\r\nTF=EV['Event Category'].str.lower().str.strip().isin(['navigate','interact','hand-raise'])\r\nEV=EV[TF]\r\n\r\nfor e in EV['Event Category'].unique():\r\n EV['Event: '+e]=0\r\n TF=EV['Event Category']==e\r\n EV['Event: '+e][TF]=EV['Total Events'][TF]\r\nEV_Col=[x for x in list(EV.columns) if x.startswith('Event:')]\r\nEV=EV.groupby(['Date','Ad Content','Campaign','Landing Page'],as_index=False)[EV_Col].sum()\r\nClean_Null(EV)\r\nEV['Engagement']=0\r\nfor c in EV_Col:\r\n EV['Engagement']=EV['Engagement']+EV[c] \r\n\r\nGA=GA.parse('PSO_900')\r\nprint('GA totals:')\r\nprint(GA[['Sessions','Goal 20 Completions']].sum())\r\nprint()\r\n\r\nClean_Null(GA)\r\nGA=pd.merge(GA,EV,on=['Date','Ad Content','Campaign','Landing Page'],how='outer')\r\n\r\nprint('GA total session after merging with event numbers.')\r\nprint(GA[['Sessions','Engagement','Goal 20 Completions']].sum())\r\nprint()\r\n\r\nGA['Ad Content']=GA['Ad Content'].str.lower().str.replace('+',' ')\r\nmp=Map[(Map['Usage']=='Social') & (Map['Map']=='Landing_Page')]\r\nmp=mp[['Key1']]\r\nmp.columns=['Landing Page']\r\nmp['LP']='Yes'\r\nGA=pd.merge(GA,mp,on='Landing Page',how='left')\r\nGA['LP'][GA['Landing Page'].str.lower().str.replace('-','').str.replace(' ','').str.contains('thankyou')]='Yes'\r\nGA['Landing Page'][GA['LP']=='Yes']=''\r\nTF=GA['LP'].isnull()\r\nGA['LP'][TF]='No'\r\nGA['Landing Page'][TF]=GA['Landing Page'][TF].str.lower()\r\n\r\nprint('GA total session after Landing Page inclusion. Should be same as above.')\r\nprint(GA[['Sessions','Engagement','Goal 20 Completions']].sum())\r\nprint()\r\n\r\n#read in DCM data\r\nj=0\r\nfor source in os.listdir(os.getcwd()):\r\n if (DCM_File_Identifier in source) & (source.endswith('.csv')):\r\n print(source)\r\n ifile=open(source,'r')\r\n line=ifile.readline()\r\n i=0\r\n while line:\r\n if line.startswith('Report Fields'):\r\n i=i+1\r\n line=ifile.readline()\r\n if j==0:\r\n target=WF+'/DCM.csv'\r\n ofile=open(target,'w+')\r\n if j==1:\r\n line=ifile.readline()\r\n if (i>=1) & ~(line.startswith('Grand Total')):\r\n ofile.write(line)\r\n line=ifile.readline()\r\n j=1\r\nifile.close()\r\nofile.close()\r\n\r\nDCM=pd.read_csv(target)\r\n\r\n# Change columns so it can be matched back to GA\r\nTF=DCM['Placement'].str.upper().str.contains('-ABM-')\r\nDCM['Campaign'][TF]='900 ABM1 - display'\r\nTF=DCM['Placement'].str.upper().str.contains('-PBM-')\r\nDCM['Campaign'][TF]='900 PBM1 - display'\r\nDCM['Ad Content']=''\r\nTF=DCM['Creative']=='8495-PaidMediaNovember-JA-1016-300x250-FSFinextraR2-Box'\r\nDCM['Ad Content'][TF]='LKI_CXD_STD_MG _COD_USA_AUD_XXX_XXX_300x250_FNX_FIE_FXR_XXX'.lower()\r\nTF=DCM['Creative']=='8495-PaidMediaNovember-JA-1016-300x250-FSFutureR2'\r\nDCM['Ad Content'][TF]='LKI_CXD_STD_MG _COD_USA_AUD_XXX_XXX_300x250_FUT_FIE_COG_XXX'.lower()\r\nprint('The unique campaign from DCM is: ',DCM['Campaign'].unique())\r\nprint()\r\nprint(\"The unique ad content from DCM is: \",DCM['Ad Content'].unique(),\". There should not be '' there.\")\r\nprint()\r\nDCM=DCM.groupby(['Campaign','Ad Content','Date'],as_index=False)[['Impressions','Clicks','Media Cost']].sum()\r\n\r\nTF=GA['Ad Content'].isin(DCM['Ad Content'].unique())\r\nGA['Campaign'][TF]=GA['Campaign'][TF]+' - display'\r\n\r\nprint('DCM total impressions.')\r\nprint(DCM['Impressions'].sum())\r\nprint()\r\n\r\n \r\n# read in LinkedIn raw data\r\nfor source in os.listdir(os.getcwd()):\r\n if (LinkedIn_File_Identifier in source) & (('.xlsx' in source) | ('.csv' in source)):\r\n if ('.xlsx' in source):\r\n LI=pd.ExcelFile(source)\r\n LI=LI.parse(0)\r\n else:\r\n LI=pd.read_csv(source,encoding='latin1')\r\n LI=LI.rename(columns={'Date (UTC time zone)':'Date','Total Spent':'Media Cost',\r\n '\\ufeffDate (UTC time zone)':'Date'})\r\n LI['Date']=pd.to_datetime(LI['Date'])\r\n LI=LI[(LI['Date']>=Date_Start) & (LI['Date']<=Date_End)]\r\n #LI['Campaign']=CMPN+' '+source.replace('.xlsx','1').replace('LinkedIn ad report ','')\r\n LI['Campaign']=''\r\n if 'ABM' in source.upper():\r\n LI['Campaign']='900 ABM1'\r\n if 'PBM' in source.upper():\r\n LI['Campaign']='900 PBM1'\r\n if '' in LI['Campaign'].unique():\r\n print(source+' campaign name is not defined')\r\n sys.exit()\r\n if 'LinkedIn' in locals() or 'LinkedIn' in globals():\r\n Date_Min=LI.groupby('Campaign',as_index=False)['Date'].min()\r\n Date_Min=Date_Min.rename(columns={'Date':'Date_min'})\r\n Date_Max=LI.groupby('Campaign',as_index=False)['Date'].max()\r\n Date_Max=Date_Max.rename(columns={'Date':'Date_max'})\r\n LinkedIn=pd.merge(LinkedIn,Date_Min,on='Campaign',how='left')\r\n LinkedIn=pd.merge(LinkedIn,Date_Max,on='Campaign',how='left')\r\n LinkedIn=LinkedIn[(LinkedIn['Date']LinkedIn['Date_max']) |\r\n (LinkedIn['Date_min'].isnull())]\r\n LinkedIn=pd.concat([LinkedIn,LI])\r\n LinkedIn=LinkedIn.drop(['Date_min','Date_max'],1)\r\n else:\r\n LinkedIn=LI\r\n \r\n\r\nLinkedIn=LinkedIn[LinkedIn['Creative Status']!='Cancelled']\r\nprint('Total Impressions from Linked in is:')\r\nprint(LinkedIn.groupby('Campaign')['Impressions'].sum())\r\nprint(LinkedIn['Impressions'].sum())\r\nprint()\r\n\r\nLinkedIn['Ad Introduction Text']=LinkedIn['Ad Introduction Text'].str.replace('https://https://','https://')\r\nLinkedIn['Query parameter']=LinkedIn['Ad Introduction Text'].map(lambda x: x[x.find('https://'):])\r\n\r\ni=0\r\nUTM=[]\r\nfor URL in LinkedIn['Query parameter'].unique():\r\n try:\r\n req = Request(URL, headers={'User-Agent': 'Mozilla/5.0'})\r\n f = urlopen(req)\r\n json_string = f.read().decode(\"utf-8\")\r\n\r\n find_str=''\r\n new=json_string[(json_string.find(find_str)+len(find_str)):]\r\n title=new[:new.find('')]\r\n find_str='utm_content='\r\n if json_string.find(find_str)>-1:\r\n new=json_string[(json_string.find(find_str)+len(find_str)):]\r\n utm_content=new[:new.find('\"')]\r\n\r\n find_str2='utm_campaign='\r\n new2=json_string[(json_string.find(find_str2)+len(find_str2)):]\r\n utm_campaign=new2[:new2.find('\\\\')]\r\n \r\n UTM.append([URL,utm_content,utm_campaign,title])\r\n else:\r\n UTM.append([URL,'','',title])\r\n except:\r\n UTM.append([URL,'','',title])\r\n\r\nUTM = pd.DataFrame(UTM)\r\nUTM.columns=['Query parameter','Ad Content','Campaign','Title']\r\n\r\nprint('Couldn''t get UTM_Content for the following URL:')\r\nprint(UTM[(UTM['Ad Content']=='') & (UTM['Title']!='Event Registration')]['Query parameter'].unique())\r\nprint()\r\nUTM=UTM[['Query parameter','Ad Content','Title']]\r\n\r\nLinkedIn=pd.merge(LinkedIn,UTM,how='left',on='Query parameter')\r\n\r\nprint('Total Impressions from Linked after retrieving UTM_Content. Should be the same as above.')\r\nprint(LinkedIn['Impressions'].sum())\r\nprint()\r\n\r\nLinkedIn=LinkedIn[LinkedIn['Title']!='Event Registration']\r\nprint('Total Impressions after taking out event registration. Could be smaller.')\r\nprint(LinkedIn['Impressions'].sum())\r\nprint()\r\n\r\n\r\nLinkedIn['Ad Content']=LinkedIn['Ad Content'].str.lower().str.replace('+',' ')\r\nLinkedIn=LinkedIn.groupby(['Date','Ad Content','Campaign'],as_index=False)['Impressions', 'Clicks', 'Likes', 'Comments', 'Shares',\r\n 'Follows', 'Other Clicks', 'Media Cost'].sum()\r\n#LinkedIn['Campaign']=LinkedIn['Campaign'].str.replace('+',' ')\r\n\r\n#concatenate LinkedIn and DCM\r\nLinkedIn=pd.concat([LinkedIn,DCM])\r\n\r\nprint('Total Impressions from LinkedIn after adding DCM amount. Should be sum of two #s above.')\r\nprint(LinkedIn['Impressions'].sum())\r\nprint()\r\n\r\n\r\n#Merge two data sources\r\nGA['Duration']=GA['Avg. Session Duration']*GA['Sessions']\r\nGA=GA.drop(['Avg. Session Duration'],1)\r\nMetrics=[x for x in list(GA.columns) if x not in ['Date','Campaign','Ad Content','Landing Page','LP']]\r\nGA=GA.groupby(['Date','Campaign','Ad Content','Landing Page','LP'],as_index=False)[Metrics].sum()\r\nGA1=GA[GA['LP']=='Yes']\r\nGA2=GA[GA['LP']=='No']\r\nPSO=pd.merge(GA1,LinkedIn,how='outer',on=['Campaign','Ad Content','Date'])\r\nPSO=pd.concat([PSO,GA2])\r\n\r\nprint('Totals after merge two sources. Should be same as above.'+\r\n 'Otherwise check LinkedIn Data Frame to see if there is any Ad Content that has multiple pages.')\r\nprint(PSO[['Impressions','Sessions','Goal 20 Completions']].sum())\r\nprint()\r\n\r\nTF=(PSO['Impressions'].isnull()) & (PSO['LP']=='Yes')\r\nQA1=PSO[TF].groupby(['Campaign','Ad Content'],as_index=False)['Sessions','Goal 20 Completions'].sum()\r\n\r\n#TF=(PSO['Page'].str.strip()=='') | (PSO['Page'].isnull())\r\n#PSO['Page'][TF]=PSO['Page_Update'][TF]\r\n#PSO=PSO.drop('Page_Update',1)\r\n\r\nmp=Map[(Map['Usage']=='Paid Social') & (Map['Map']=='Campaign_Date')]\r\nmp=mp[['Key1','Value1']]\r\nmp.columns=['Campaign','Start_Date']\r\nmp['Start_Date']=pd.to_datetime(mp['Start_Date'])\r\nPSO=pd.merge(PSO,mp,how='left',on='Campaign')\r\nif len(PSO[PSO['Start_Date'].isnull()]['Campaign'])>0:\r\n print('The followin Campaign needs start date.')\r\n print(PSO[PSO['Start_Date'].isnull()]['Campaign'].unique())\r\n\r\nPSO=PSO[PSO['Date']>=PSO['Start_Date']]\r\nPSO=PSO.drop('Start_Date',1)\r\n\r\nprint('Totals after filtering using campaign date. Could be smaller than numbers above.')\r\nprint(PSO[['Impressions','Sessions','Goal 20 Completions']].sum())\r\nprint()\r\n\r\n\r\n# parse the data\r\nClean_Null(PSO)\r\nPSO['Ad Content']=PSO['Ad Content'].str.replace('%20',' ')\r\nTF=(PSO['Ad Content'].str.endswith('xxx'))\r\nPSO['Ad Content'][TF]=PSO['Ad Content'][TF].apply(lambda x:x[:-3])+'zzz'\r\n\r\nPSO_Parsed=Parse_Social_utm_content(PSO,'Ad Content',Media_Type,CMPN,False,Map)\r\n\r\nPSO=PSO_Parsed[0]\r\nQA2=PSO_Parsed[1] #wrong # of CIDs\r\nQA3=PSO_Parsed[2] #missing maps\r\n\r\ncols=PSO_Parsed[3]\r\n\r\n \r\nClean_Null(PSO)\r\ndim=['Date','Campaign','Ad Content','LP','Landing Page']+cols\r\nmetric=[x for x in list(PSO.columns) if x not in dim]\r\n\r\nPSO=PSO.groupby(dim,as_index=False)[metric].sum() \r\nPSO=PSO[dim+metric]\r\n\r\nprint('PSO total session after parsing the data. Should be same as above')\r\nprint(PSO[['Impressions','Sessions','Goal 20 Completions']].sum())\r\nprint()\r\n\r\n#update definition of engagement\r\nClean_Null(PSO)\r\nPSO['Score']=(PSO['Sessions']-PSO['Bounces'])*.5+PSO['Event: navigate']*.25+PSO['Event: interact']*.5\r\nPSO['Score']=PSO['Score']+PSO['Event: hand-raise']+PSO['Goal 20 Completions']*5\r\nPSO=PSO.rename(columns={'Engagement':'Engagement_Count'})\r\nPSO=PSO.rename(columns={'Score':'Engagement'})\r\n\r\nwriter = pd.ExcelWriter(WF+'/PSO.xlsx', engine='xlsxwriter')\r\nPSO['Channel']='Paid Social'\r\nPSO.to_excel(writer,'PSO_Raw',index=False)\r\nif QA1['Ad Content'].count()>0:\r\n QA1.to_excel(writer,'GA_Not_LinkedIn',index=False)\r\nif QA2[QA2['Ad Content']!='']['Ad Content'].count()>0:\r\n QA2.to_excel(writer,'Wrong_UTM',index=False)\r\ntry:\r\n QA3.to_excel(writer,'MissingMaps',index=False)\r\nexcept:\r\n print()\r\nwriter.save() \r\n\r\n","sub_path":"Pandas_01_GA_Linkedin_Data.py","file_name":"Pandas_01_GA_Linkedin_Data.py","file_ext":"py","file_size_in_byte":11976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"646568821","text":"#########################################################################\n# \n# Copyright 2013 Cloud Sidekick\n# __________________\n# \n# All Rights Reserved.\n# \n# NOTICE: All information contained herein is, and remains\n# the property of Cloud Sidekick and its suppliers,\n# if any. The intellectual and technical concepts contained\n# herein are proprietary to Cloud Sidekick\n# and its suppliers and may be covered by U.S. and Foreign Patents,\n# patents in process, and are protected by trade secret or copyright law.\n# Dissemination of this information or reproduction of this material\n# is strictly forbidden unless prior written permission is obtained\n# from Cloud Sidekick.\n#\n#########################################################################\n\nimport catoclient.catocommand\nfrom catoclient.param import Param\n\nclass ListApplicationTemplates(catoclient.catocommand.CatoCommand):\n\n Description = 'Lists application deployment template and their high level properties'\n API = 'list_application_templates'\n Examples = '''\n_To list all application templates_\n \n maestro-list-application-templates\n\n_To list all application templates with a certain string in the name or description_\n\n maestro-list-application-templates -f \"sample app\"\n'''\n Options = [Param(name='filter', short_name='f', long_name='filter',\n optional=True, ptype='string',\n doc='matches if the filter string is in the result')]\n\n def main(self):\n results = self.call_api(self.API, ['filter'])\n print(results)\n","sub_path":"maestroclient/commands/listapplicationtemplates.py","file_name":"listapplicationtemplates.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"251311992","text":"from gevent import monkey; monkey.patch_all()\nimport gevent\n\nimport time\nimport uuid\n\nfrom syncstomp.json_wrap import Connection\nfrom syncstomp.conversation import SynchronousStomp, SynchronousStompErrorCode\nfrom syncstomp.conversation import RemoteException, repack_exception\n\nfrom nose.tools import eq_\n\n\nDEST_NAME = '/queue/test.%s.syncstomp' % uuid.uuid4()\nRECEIVED = []\nTIMEOUT = 5\n\nSOLICITOR = None\nLISTENER_CONV = None\n\n\ndef wait(max_time=30):\n '''\n Wait for a message or exception to show up.\n '''\n waited = 0\n while waited < max_time and not RECEIVED:\n time.sleep(1)\n waited += 1\n\n\nclass TestListener(SynchronousStomp):\n '''\n Test listener.\n '''\n def on_unsolicited(self, message, conversation):\n '''\n Handle the incoming connection.\n '''\n global LISTENER_CONV\n LISTENER_CONV = conversation\n RECEIVED.append(message)\n\n\ndef test_create_connections():\n # Create a sender and receiver SynchronousStomp object.\n global LISTENER\n global SOLICITOR\n\n SOLICITOR = SynchronousStomp(Connection())\n LISTENER = TestListener(Connection(), destination=DEST_NAME)\n\n\ndef test_conversation():\n # Have a nice, normal chat.\n solicitor_conv = SOLICITOR.solicit(DEST_NAME)\n solicitor_greenlet = gevent.spawn(\n solicitor_conv.reply,\n 'Hi there! Feel like going to dinner?'\n )\n wait()\n assert len(RECEIVED) == 1\n eq_(RECEIVED.pop(), 'Hi there! Feel like going to dinner?')\n\n listener_greenlet = gevent.spawn(\n LISTENER_CONV.reply,\n {'rejection': 'Sorry, going on a date.'}\n )\n eq_(solicitor_greenlet.get(), {'rejection': 'Sorry, going on a date.'})\n\n # This should not block\n solicitor_conv.reply('Oh well. I shall eat a sandwich alone.', final=True)\n eq_(listener_greenlet.get(), 'Oh well. I shall eat a sandwich alone.')\n\n\ndef test_remote_exception():\n # Test handling of remote exceptions.\n solicitor_conv = SOLICITOR.solicit(DEST_NAME)\n solicitor_greenlet = gevent.spawn(\n solicitor_conv.reply,\n 'Good morning!'\n )\n wait()\n assert len(RECEIVED) == 1\n eq_(RECEIVED.pop(), 'Good morning!')\n\n try:\n raise ValueError(\"Sorry, it's actually a bad morning.\") # Hi mom!\n except ValueError as exc:\n # This should not block\n LISTENER_CONV.error(\n SynchronousStompErrorCode.EXCEPTION,\n repack_exception(exc)\n )\n\n try:\n response = solicitor_greenlet.get()\n except RemoteException as exc:\n assert len(exc.trace) == 1\n assert 'Hi mom!' in exc.trace[0], exc.trace\n eq_(exc.exc_class,\n ValueError().__class__.__module__ + '.ValueError')\n eq_(exc.message, \"Sorry, it's actually a bad morning.\")\n except Exception as exc:\n assert False, 'Expected a RemoteException, got %r.' % exc\n else:\n assert False, 'Expected an exception, got response %r.' % response\n\n\ndef test_timeout():\n # Test handling of timeouts.\n solicitor_conv = SOLICITOR.solicit(DEST_NAME)\n solicitor_greenlet = gevent.spawn(\n solicitor_conv.reply,\n 'Badger badger badger.'\n )\n wait()\n assert len(RECEIVED) == 1\n eq_(RECEIVED.pop(), 'Badger badger badger.')\n\n try:\n resp = LISTENER_CONV.reply('Mushroom?', timeout=TIMEOUT)\n except gevent.Timeout as exc:\n assert str(TIMEOUT) in str(exc), exc\n except Exception as exc:\n assert False, 'Expected a Timeout, got %r.' % exc\n else:\n assert False, 'Expected an exception, got response %r.' % resp\n\n eq_(solicitor_greenlet.get(), 'Mushroom?')\n\n # We should have received a hangup message\n try:\n resp = solicitor_conv.reply('Aaah! A snake!')\n except RemoteException as exc:\n eq_(exc.err_code, SynchronousStompErrorCode.TIMEOUT)\n except Exception as exc:\n assert False, 'Expected a RemoteException, got %r.' % exc\n else:\n assert False, 'Expected an exception, got response %r.' % resp\n","sub_path":"tests/test_conversation.py","file_name":"test_conversation.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"263126100","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 21 04:25:43 2017\n\n@author: team_31 ((Nabanita Roy)17305618, (Abhimanyu Hazarika)17314158, (Bhavik Mer)17304936)\n\"\"\"\n\nimport os\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nextract_path = os.path.join(dir_path,'..','..')\n\nCHUNKS = [100, 500, 1000, 5000, 10000, 50000, 100000, 500000, 1000000, 5000000, 10000000, 50000000, 100000000]\n\n#SUM WITHOUR NOISE AND WITH NOISE DATASET RELATED CONSTANTS\nSUM_FEATURES_X_COMMON = ['Feature 1', 'Feature 2','Feature 3','Feature 4',\n\t\t\t\t'Feature 5 (meaningless but please still use it)','Feature 6',\n\t\t\t\t'Feature 7','Feature 8','Feature 9','Feature 10']\nSUM_CLASSIFIERLABELS_Y_COMMON = [\"Very Large Number\",\"Large Number\",\"Medium Number\",\"Small Number\",\"Very Small Number\"]\nSUM_REGRESSIONFEATURE_Y = ['Target']\nSUM_CLASSIFIERFEATURE_Y = ['Target Class']\nSUM_NOISE_REGRESSIONFEATURE_Y = ['Noisy Target']\nSUM_NOISE_CLASSIFIERFEATURE_Y = ['Noisy Target Class']\n\n#SKIN DATASET RELATED CONSTANTS\nSKIN_FEATURES_X = ['B', 'G', 'R']\nSKIN_FEATURES_Y = ['Skin']\nSKIN_CLASSIFIERLABELS_Y = [1, 2]\n\n#NEWS DATASET RELATED CONSTANTS\nNEWS_FEATURES_X = ['n_tokens_title', 'n_tokens_content', 'n_unique_tokens', 'n_non_stop_words', \n\t\t'n_non_stop_unique_tokens', 'num_hrefs', 'num_self_hrefs', 'num_imgs', 'num_videos', 'average_token_length',\n\t\t'num_keywords', 'data_channel_is_lifestyle', 'data_channel_is_entertainment', 'data_channel_is_bus',\n\t\t'data_channel_is_socmed', 'data_channel_is_tech', 'data_channel_is_world', 'kw_min_min', 'kw_max_min',\n\t\t'kw_avg_min', 'kw_min_max', 'kw_max_max', 'kw_avg_max', 'kw_min_avg', 'kw_max_avg', 'kw_avg_avg',\n\t\t'self_reference_min_shares', 'self_reference_max_shares', 'self_reference_avg_sharess', 'weekday_is_monday',\n\t\t'weekday_is_tuesday', 'weekday_is_wednesday', 'weekday_is_thursday', 'weekday_is_friday', 'weekday_is_saturday',\n\t\t'weekday_is_sunday', 'is_weekend', 'LDA_00', 'LDA_01', 'LDA_02', 'LDA_03', 'LDA_04', 'global_subjectivity',\n\t\t'global_sentiment_polarity', 'global_rate_positive_words', 'global_rate_negative_words', 'rate_positive_words',\n\t\t'rate_negative_words', 'avg_positive_polarity', 'min_positive_polarity', 'max_positive_polarity',\n\t\t'avg_negative_polarity', 'min_negative_polarity', 'max_negative_polarity', 'title_subjectivity',\n\t\t'title_sentiment_polarity', 'abs_title_subjectivity', 'abs_title_sentiment_polarity']\nNEWS_REGRESSIONFEATURE_Y = ['shares']\nNEWS_CLASSIFIERFEATURE_Y = ['sharesClass']\nNEWS_CLASSIFIERLABELS_Y = ['Not popular','Almost popular','Popular','Very popular']\n\n\nDATASET_ROOT = 'C:/Users/clantroops/Desktop/ML Assignment'\n\nREGRESSION = \"regression\"\nCLASSIFICATION = \"classification\"\n\nDATA_SETS = {\n 'sum_without_noise': {\n 'location': os.path.join(dir_path,'..','..','without noise','The SUM dataset, without noise.csv'),\n 'sep': ';',\n 'zip': True,\n 'zipLocation': os.path.join(dir_path,'..','..','The SUM dataset.zip'),\n 'scaleData': True,\n 'featuresX': SUM_FEATURES_X_COMMON,\n 'regressionFeaturesY' : SUM_REGRESSIONFEATURE_Y,\n 'classifierFeaturesY' : SUM_CLASSIFIERFEATURE_Y,\n 'classifierLabelsY' : SUM_CLASSIFIERLABELS_Y_COMMON\n },\n 'sum_with_noise': {\n 'location': os.path.join(dir_path,'..','..','with noise','The SUM dataset, with noise.csv'),\n 'sep': ';',\n 'zip': True,\n 'zipLocation': os.path.join(dir_path,'..','..','The SUM dataset.zip'),\n 'scaleData': True,\n 'featuresX': SUM_FEATURES_X_COMMON,\n 'regressionFeaturesY' : SUM_NOISE_REGRESSIONFEATURE_Y,\n 'classifierFeaturesY' : SUM_NOISE_CLASSIFIERFEATURE_Y,\n 'classifierLabelsY' : SUM_CLASSIFIERLABELS_Y_COMMON\n },\n 'skin_nonskin': {\n 'location': os.path.join(dir_path,'..','..','SkinNonSkin','Skin_NonSkin.txt'),\n 'sep': '\t',\n 'zip': False,\n 'scaleData': False,\n 'featuresX': SKIN_FEATURES_X,\n 'regressionFeaturesY' : SKIN_FEATURES_Y,\n 'classifierFeaturesY' : SKIN_FEATURES_Y,\n 'classifierLabelsY' : SKIN_CLASSIFIERLABELS_Y\n },\n 'online_news_popularity': {\n 'location': os.path.join(dir_path,'..','..','OnlineNewsPopularity', 'OnlineNewsPopularity.csv'),\n 'zip': True,\n 'zipLocation': os.path.join(dir_path,'..','..','OnlineNewsPopularity.zip'),\n 'sep': ', ',\n 'scaleData': True,\n 'featuresX': NEWS_FEATURES_X,\n 'regressionFeaturesY' : NEWS_REGRESSIONFEATURE_Y,\n 'classifierFeaturesY' : NEWS_CLASSIFIERFEATURE_Y,\n 'classifierLabelsY' : NEWS_CLASSIFIERLABELS_Y\n }\n}","sub_path":"Assignment1_Task1/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"247254126","text":"import os\nimport sys\n\ndef start_app():\n\n user_exit = False\n\n menu_options = {1: \"List of people\", 2: \"List of drinks\", 3: \"List of people and drinks\", 4: \"Edit people\",\n 5: \"Edit drinks\", 6: \"Exit\"}\n people_dict = start_dict(\"people.txt\")\n drinks_dict = start_dict(\"drinks.txt\")\n preferences_dict = {}\n\n while not user_exit:\n\n os.system(\"clear\")\n\n user_selection = draw_menu(menu_options)\n user_selection = int(user_selection)\n if user_selection > 6 or user_selection <= 0:\n input(\"\\nPlease only enter a number from the options provided. Press 'Enter' to try again.\")\n continue\n elif user_selection == 1:\n draw_table(\"people\", people_dict)\n elif user_selection == 2:\n draw_table(\"drinks\", drinks_dict)\n elif user_selection == 3:\n draw_table(\"people and drinks\", [people_dict, drinks_dict], 2)\n elif user_selection == 4:\n people_dict = add_data(\"people's names\", people_dict)\n elif user_selection == 5:\n people_dict = add_data(\"the drinks' names\", drinks_dict)\n elif user_selection == 6:\n exit_screen()\n\n user_exit = not user_continue()\n\n exit_screen()\n\n\ndef draw_menu(menu_options):\n #num_options = len(menu_options) #to add future functionality for a dynamic list in the message and menu_options is a string array argument\n os.system(\"clear\")\n\n print(\"Welcome to BrIW v2.0 beta\\n\\nWhat would you like to do? Choose from the following options:\\n\")\n for option in menu_options:\n print(f\"[{option}] {menu_options[option]}\")\n print()\n\n user_selection = input(\"Please enter the number of your selection: \")\n\n if user_selection.isdigit():\n user_selection = int(user_selection)\n else:\n user_selection = 0\n\n return user_selection\n\n\ndef start_dict(filename):\n dictionary = {}\n file = open(filename, \"r\")\n for item in file.readlines():\n item = item.strip(\"\\n\")\n item = item.split(\"- \")\n item[0] = int(item[0])\n dictionary.update({item[0]: item[1]})\n file.close()\n return dictionary\n\n\ndef find_width(data, cols=1):\n\n largest_item = 0\n\n if cols == 1:\n for item in data:\n item_size = len(item)\n if item_size > largest_item:\n largest_item = item_size\n else:\n for data_list in data:\n for item in data_list:\n item_size = len(item)\n if item_size > largest_item:\n largest_item = item_size\n\n return largest_item\n\n\ndef separator(data, word=\"\"):\n cols = len(data)\n width = find_width(data[0:-1], cols)\n spacing = \" \"*(width - len(word)) + \"\\t\"\n return spacing\n\n\ndef largest_list(list_set):\n longest_list = 0\n for list_num in range(0, len(list_set)):\n list_length = len(list_set[list_num])\n if list_length > longest_list:\n longest_list = list_length\n return longest_list\n\n\n'''\ndef largest_space(data, cols=1):\n if cols == 1:\n return 0\n else:\n for dataset_num in range(0, len(data)):\n largest_space = 0\n for list_num in range(0, len(data[dataset_num])):\n for item in range(0, cols):\n if len(data[item]) > list_num:\n spacing = separator(data, data[item][list_num])\n if len(spacing) > largest_space:\n largest_space = len(spacing)\n return largest_space'''\n\n\ndef largest_space(data, title, cols=1):\n max_lengths = []\n if cols == 1:\n data_width = find_width(data, cols)\n max_lengths.append(data_width)\n else:\n for list_num in range(0, cols):\n data_width = find_width(data[list_num])\n max_lengths.append(data_width)\n\n final_width = sum(max_lengths)\n\n title_width = find_width([title]) # requires an array input\n\n if final_width >= title_width:\n extra_space = final_width\n else:\n extra_space = title_width\n\n return extra_space\n\n\ndef draw_line(cols=1, extra_space=0):\n print(\"=\" * (4 + 8*(cols - 1)) + \"=\" * extra_space)\n\n\ndef draw_header(title, cols=1, extra_space=0):\n draw_line(cols, extra_space)\n print(title.upper())\n draw_line(cols, extra_space)\n\n\ndef draw_data(data, cols=1):\n if cols == 1:\n for item in data:\n print(\"-->\", item)\n else:\n for dataset_num in range(0, len(data)):\n for item in range(0, largest_list(data)):\n for list_num in range(0, cols):\n if len(data[list_num]) > item:\n spacing = separator(data, data[list_num][item])\n print(\"-->\", data[list_num][item], end=spacing)\n else:\n width = find_width(data, cols)\n spacing = separator(data)\n print(\" \", spacing, end=\"\")\n print()\n return\n\n\ndef draw_footer(cols=1, extra_space=0):\n draw_line(cols, extra_space)\n print()\n\n\ndef draw_table(title, data, cols=1):\n\n os.system('clear')\n\n data_list = []\n if cols == 1:\n data_list += list(data.values())\n else:\n for dictionary in data:\n data_list.append(list(dictionary.values()))\n\n extra_space = largest_space(data_list, title, cols)\n\n draw_header(title, cols, extra_space)\n\n draw_data(data_list, cols)\n\n draw_footer(cols, extra_space)\n\n\ndef add_data(data_name, data):\n\n os.system(\"clear\")\n\n added_data = input(f\"\\nPlease enter {data_name} separated by commas: \")\n print()\n added_data = added_data.split(\",\")\n\n for item in added_data:\n item_index = added_data.index(item)\n item = item.strip()\n item = item.strip('\"')\n item = item.strip(\"'\")\n item = item.title()\n added_data[item_index] = item\n\n if isinstance(data, list):\n data += added_data\n elif isinstance(data, dict):\n data = update_data(data_name, added_data, data)\n\n return data\n\n\ndef user_continue():\n keep_going = True\n user_response = input(\"Would you like to do something else?\\nY/N: \")\n user_response = user_response.upper()\n if user_response == \"N\" or user_response == \"NO\":\n keep_going = False\n return keep_going\n\n\ndef exit_screen():\n\n os.system(\"clear\")\n\n exit_message = \"\"\"\nThanks for using our app, hope you have enjoyed the experience :)\n \nContact us to report bugs, for help or troubleshooting, or just to give us feedback on our app!\n \nEmail: ahsc1997@gmail.com\nPhone: 07803407324\n \nCopyright: Eduardo Salazar, 2019\"\"\"\n\n print(exit_message)\n exit()\n\n\ndef save_to_file(data_name, data):\n if data_name == \"people's names\":\n file = open(\"people.txt\", \"w\")\n elif data_name == \"the drinks' names\":\n file = open(\"drinks.txt\", \"w\")\n else:\n raise Exception(\"Error: only supports 'people's names' (people) and 'the drinks' names' (drinks) for \"\n \"data_name string literal\")\n\n for key in data:\n file.write(str(key) + \"- \" + data[key] + \"\\n\")\n\n file.close()\n\n\ndef update_data(data_name, added_data, dictionary):\n for item in added_data:\n id = 1\n while id in dictionary:\n id += 1\n new_entry = {id: item}\n dictionary.update(new_entry)\n save_to_file(data_name, dictionary)\n return dictionary\n\n\n\n\n\nstart_app()","sub_path":"app/source/oldVersions/userInput3.py","file_name":"userInput3.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"370466717","text":"\"\"\"\n/helpers/base.py\n\"\"\"\n\nimport os\nimport unittest\n\nimport minimock\n\nfrom simplexpense import helpers as h\n\nclass TestLoadIni(unittest.TestCase):\n \"\"\"\n config loader\n \"\"\"\n\n def test_env_not_set(self):\n \"\"\"\n no ini set in environ\n \"\"\"\n os.environ = minimock.Mock(\"os.environ\")\n os.environ.get.mock_returns = None\n self.assertRaises(ValueError, h.base.load_ini)\n minimock.restore()\n\n def test_ini_non_exist_or_bad(self):\n \"\"\"\n bad file\n \"\"\"\n os.environ = minimock.Mock(\"os.environ\")\n os.environ.get.mock_returns = \"/tmp/tdtdtd\"\n self.assertEqual(h.base.load_ini().sections(), [])\n minimock.restore()\n","sub_path":"src/simplexpense/tests/units/test_helpers_base.py","file_name":"test_helpers_base.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"279981026","text":"import paho.mqtt.client as mqtt\n\ndef on_connect(client,userdata,rc):\n\tprint(\"Connected with result code \"+str(rc))\n\tclient.subcribe(\"$SYS/#\")\ndef on_message(client,userdata,msg):\n\tprint(msg.topic + \" \" + str(msg.payload))\n\n\nclient = mqtt.Client()\n\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(\"localhost\",1883,60)\n\nclient.loop_forever()\n\n","sub_path":"Simple_Example.py","file_name":"Simple_Example.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"567275427","text":"# %% IMPORT PACKAGES: \n# The packages listed must be imported following the instructions \n# on their respective documentation pages. It is also necessary to \n# install the extra dependencies they mention, specially for the \n# NDLIB package. Moreover, for the NDlib package it is necessary to \n# install the development version through their github following the\n# instructions described in the documentation . \n\n# NOTE: The code contains random selections so every iteration can lead to different \n# results. \n\nimport networkx as nx\nimport numpy as np \nimport ndlib.models.ModelConfig as mc\nimport ndlib.models.epidemics as ep\nfrom bokeh.io import show\nfrom ndlib.viz.bokeh.DiffusionTrend import DiffusionTrend\nimport matplotlib.pyplot as plt\nfrom ndlib.viz.bokeh.DiffusionPrevalence import DiffusionPrevalence\nimport matplotlib as plot\nimport selenium\nimport hvplot.networkx as hvnx\nfrom itertools import compress\nimport pandas as pd\nimport random\nfrom ndlib.viz.mpl.TrendComparison import DiffusionTrendComparison\n\n#%% PREPROCESSING: \n# Load graphs and remove isolated nodes to only study the main \n# connected component.\n\n# LOAD GRAPH FOR MAIN NETWORK (SCENARIO 1)\nraw_net = nx.read_graphml('budapest_large.graphml')\nraw = hvnx.draw(raw_net, node_color = 'lightblue')\nprint('Properties raw_net: '+ str(len(raw_net.nodes())) \n + ' and ' + str(len(raw_net.edges())))\n\n# Remove isolated nodes\nmain_net = raw_net \nmain_net.remove_nodes_from(list(nx.isolates(main_net)))\nprocessed = hvnx.draw(main_net, node_color = 'lightblue')\nprint('Properties main_net: '+ str(len(main_net.nodes())) \n +' and '+ str(len(main_net.edges())))\n\n# LOAD NETWORK SCENARIO 2\ndeg_net = nx.read_graphml('budapest_large.graphml')\ndeg_net.remove_nodes_from(list(nx.isolates(deg_net)))\n\n# LOAD NETWORK SCENARIO 3 \nvul_net = nx.read_graphml('budapest_large.graphml')\nvul_net.remove_nodes_from(list(nx.isolates(vul_net)))\n\n# LOAD NETWORK SCENARIO 4 \nalzh_net = nx.read_graphml('budapest_large.graphml')\nalzh_net.remove_nodes_from(list(nx.isolates(alzh_net)))\n\n# Visualise networks \nlayout = raw + processed\nlayout\n\n#%% SCENARIO 2: Isolate high degree nodes \n# Isolate 10 high degree nodes. High degree nodes are selected\n# randomly from the set of nodes in the top quartile of the\n# node degree distribution. \n\n# Identify high degree nodes\n\ndegree = list(dict(deg_net.degree).values())\n\n# Identify top quartile degree nodes: \nquartile = np.quantile(degree, 0.75) \nkeys = list(dict(deg_net.degree).keys())\nbool_quart = degree >= quartile\nquartile_keys = list(compress(keys, bool_quart))\n\n# Select a random set of top quartile nodes to isolate\nnodes_removed = 10\nselected_nodes = random.sample(quartile_keys,nodes_removed)\nedge_remove = list(deg_net.edges(selected_nodes))\ndeg_net.remove_edges_from(edge_remove)\n\n# Draw deg_net \nprint('Properties deg_net: '+ str(len(deg_net.nodes())) \n +' and '+ str(len(deg_net.edges())))\nhvnx.draw(deg_net, node_color = 'lightblue')\n\n# %% SCENARIO 3: Isolate vulnerable nodes \n# Isolate 10 vulnerable nodes in the network. Vulnerable nodes are \n# nodes which have an influence 1/degree which is smaller than the threshold.\n# These nodes are the most relevant from the dynamical point of view. \n \n# Identify influence in nodes (influence = 1/degree)\ndegree = list(dict(vul_net.degree).values())\ninfluence = []\nfor deg in degree: \n if (deg == 0):\n influence.append(0)\n else:\n influence.append(1/deg)\n\n# Identify vulnerable nodes\nthreshold = np.float64(0.15)\nbool_inf = influence >= threshold\n\n# Select random subset of vulnerable nodes \nnodes_removed = 10\nkeys = list(dict(vul_net.degree).keys())\nvulnerable_keys = list(compress(keys, bool_inf))\nselected_nodes = random.sample(vulnerable_keys, nodes_removed)\nedge_remove = list(vul_net.edges(selected_nodes))\nvul_net.remove_edges_from(edge_remove)\n\n# Draw vul_net\nprint('Properties vul_net: '+ str(len(vul_net.nodes())) \n +' and '+ str(len(vul_net.edges()))) \nhvnx.draw(vul_net, node_color = 'lightblue')\n\n\n#%% SCENARIO 4: Alzheimer related area\n# Isolate 10 nodes which are located in regions related to Alzheimer's \n# disease. \n\n#Identify nodes related to areas of interest \nnode_info = pd.DataFrame(alzh_net.nodes._nodes)\nareas = node_info.loc[['dn_fsname']]\n\narea_bool = []\nfor index, text in areas.iteritems() :\n string = str(text)\n result = string.find ('Hippocampus')\n result2 = string.find ('middletemporal')\n if (result == -1 & result2 == -1):\n area_bool.append(False)\n else: \n area_bool.append(True)\n\nkeys = list(dict(alzh_net.degree).keys())\nalzh_keys = list(compress(keys, area_bool))\n\n# Select a random subset of nodes in the area\nnodes_removed = 10\n\nselected_nodes = random.sample(alzh_keys, nodes_removed)\nedge_remove = list(alzh_net.edges(selected_nodes))\nalzh_net.remove_edges_from(edge_remove)\n\n#Draw alzh_net\nprint('Properties alzh_net: '+ str(len(alzh_net.nodes())) \n +' and '+ str(len(alzh_net.edges())))\nhvnx.draw(alzh_net, node_color = 'lightblue')\n\n#%% MODEL AND SIMULATION DEFINITION \n# Implement threshold model with a threshold parameter of \n# 0.15 a starting fraction of infected nodes of 0.01 and \n\n#Function definition \ndef model (net, frac_inf, threshold, iter):\n # Defines the model type, specification and implementation. \n # The function uses the network input in net as the main input\n # for the threshold model. Then the rest of parameters are \n # specified in the model configuration: \n # frac_inf: Initial fraction of infected nodes. \n # threshold: Fraction of active neighbours necessary to change \n # a node's state to active. \n # iter: Number of iterations to run from the dynamical process. \n\n # Model impolementation\n model = ep.ThresholdModel(net)\n\n # Model Configuration: initial conditions\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', frac_inf)\n\n for i in net.nodes():\n config.add_node_configuration(\"threshold\", i, threshold)\n\n model.set_initial_status(config)\n\n # Simulation execution\n iterations = model.iteration_bunch(iter)\n trends = model.build_trends(iterations)\n\n return [model, iterations, trends]\n\n#Parameter definition\ntimesteps = 20\nthreshold = 0.15\nfrac_inf = 0.01\n# Run models in the different scenarios\n[mod_norm, iter_norm, trends_normal] = model(main_net, frac_inf, threshold, timesteps)\n[mod_degree, iter_deg, trends_degree] = model(deg_net, frac_inf, threshold, timesteps)\n[mod_vul, iter_vul, trends_vul] = model(vul_net, frac_inf, threshold, timesteps)\n[mod_alzh, iter_alzh, trends_alzh] = model(alzh_net, frac_inf, threshold, timesteps)\n\n#%% VISUALIZATION:\n# Prepare networks for visualisation and create overall plot. \n# Save states on the simulation as variables in the network and also \n# save the se\n\n#Function definition\ndef state_complete (iter_norm):\n # Creates a dictionary containing the state of all nodes \n # at each timestep. Uses as input the iterations otuput from \n # the model () function. \n\n iter_complete = {}\n for it in iter_norm: \n if (it['iteration'] == 0):\n iter_complete[it['iteration']] = iter_norm[0]['status']\n else :\n iter_complete[it['iteration']] = {**iter_complete[it['iteration']-1], \n **iter_norm[it['iteration']]['status']}\n return iter_complete\n\n\ndef save_status (graph, iteration):\n # Stores as a graph variable the state (active=1 inactive=0) \n # of all nodes at 3 different iterations.\n # At the start (stat0), half way through the dynamics (stat10) \n # and end (stat19).\n\n for node in graph.nodes:\n #save state in grpah \n graph.nodes[node]['stat0'] = iteration[0][node]\n graph.nodes[node]['stat10'] = iteration[10][node]\n graph.nodes[node]['stat19'] = iteration[19][node]\n return graph\n\ndef save_variables (graph, boolean, scenario):\n # Stores as a graph variable the information regarding the nodes \n # of interest at each scenario. \n # Scenario 2: Assigns 1 to nodes in the top quartile, \n # assigns 0 otherwise.\n # Scenario 3: Assigns 1 to nodes with 1/degree <=threshold \n # (vulnerable nodes), assigns 0 otherwise.\n # Scenario 4: Assigns 1 to nodes in the areas related to \n # Alzheimer's disease, assigns 0 otherwise.\n\n for i, node in enumerate(graph.nodes):\n bin_bool = []\n\n if (scenario == 2):\n bin_bool = boolean*1\n graph.nodes[node]['high_deg'] = list(bin_bool)[i].item()\n\n elif (scenario == 3):\n bin_bool = boolean*1\n graph.nodes[node]['vulnerable'] = list(bin_bool)[i].item()\n \n elif (scenario == 4):\n bin_bool = np.array(boolean)*1\n graph.nodes[node]['Alzh'] = list(bin_bool)[i].item()\n \n return graph\n\n# Create complete list of states: \ncomplete_norm = state_complete (iter_norm)\ncomplete_deg = state_complete (iter_deg)\ncomplete_vul = state_complete (iter_vul)\ncomplete_alzh = state_complete (iter_alzh)\n\nav_norm = []\nav_deg = []\nav_vul = []\nav_alzh = []\n\n# Proportion of active nodes at each timempoint: \nfor di in complete_norm:\n av_norm.append(np.average(np.array(list(complete_norm[di].values()))))\n av_deg.append(np.average(np.array(list(complete_deg[di].values()))))\n av_vul.append( np.average(np.array(list(complete_vul[di].values()))))\n av_alzh.append(np.average(np.array(list(complete_alzh[di].values()))))\n\n#Plot % of active nodes \nplt.figure ()\nplt.title('Propagation progression')\nplt.plot(av_norm)\nplt.plot(av_deg)\nplt.plot(av_vul)\nplt.plot(av_alzh)\nplt.xlabel('Iteration')\nplt.xlim([0,19])\nplt.ylabel('Proportion of active nodes')\nplt.legend(['Baseline network','Hub nodes','Vulnerable nodes','Alzheimer scenario'])\nplt.savefig('proportionplot.svg')\n# Add information to graphs and export them for visualization\n\ngraph_normal = save_status (main_net, complete_norm)\ngraph_normal = save_variables (graph_normal, area_bool, 4)\ngraph_normal = save_variables (graph_normal, bool_inf, 3)\ngraph_normal = save_variables (graph_normal, bool_quart, 2)\nnx.write_graphml(graph_normal,'sim_baseline.graphml')\n\ngraph_deg = save_status (deg_net, complete_deg)\nnx.write_graphml(graph_deg,'sim_high_degree.graphml')\n\ngraph_vul = save_status (vul_net, complete_vul)\nnx.write_graphml(graph_vul,'sim_vulnerable.graphml')\n\ngraph_alzh = save_status (alzh_net, complete_alzh)\nnx.write_graphml(graph_alzh,'sim_alzheimer.graphml')\n\n#%%","sub_path":"MainNetBio.py","file_name":"MainNetBio.py","file_ext":"py","file_size_in_byte":10460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"75875468","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 10 20:54:40 2018\n\n@author: kavisha\n\"\"\"\n# Python3+ required\n\nimport os\nfrom lxml import etree\nimport time\nimport uuid\nimport argparse\nimport getcityobjects\n\ntry:\n to_unicode = unicode\nexcept NameError:\n to_unicode = str\n\ndef argRead(ar, default=None):\n \n \"\"\"Corrects the argument input in case it is not in the format True/False.\"\"\"\n if ar == \"0\" or ar == \"False\":\n ar = False\n elif ar == \"1\" or ar == \"True\":\n ar = True\n elif ar is None:\n if default:\n ar = default\n else:\n ar = False\n else:\n raise ValueError(\"Argument value not recognised.\")\n return ar\n\n\n# function for generating metadata for a CityGML model\ndef generatemetadata(inputfile, outputfile):\n tree = etree.parse(inputfile)\n root = tree.getroot()\n for key in root.nsmap.keys():\n if root.nsmap[key].find('http://www.opengis.net/citygml') != -1:\n if (root.nsmap[key][-3:] == '1.0'):\n citygmlversion = '1.0'\n break\n if (root.nsmap[key][-3:] == '2.0'):\n citygmlversion = '2.0'\n break \n if citygmlversion == \"1.0\":\n print (\"CityGML version not supported!\")\n elif citygmlversion == \"2.0\":\n ns=\"http://www.opengis.net/citygml/2.0\"\n ns_gml = \"http://www.opengis.net/gml\"\n ns_xAL=\"urn:oasis:names:tc:ciq:xsdschema:xAL:2.0\"\n ns_xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n ns_xlink=\"http://www.w3.org/1999/xlink\"\n ns_dem=\"http://www.opengis.net/citygml/relief/2.0\"\n ns_bldg=\"http://www.opengis.net/citygml/building/2.0\"\n ns_app=\"http://www.opengis.net/citygml/appearance/2.0\"\n ns_wtr=\"http://www.opengis.net/citygml/waterbody/2.0\"\n ns_gen=\"http://www.opengis.net/citygml/generics/2.0\"\n ns_luse=\"http://www.opengis.net/citygml/landuse/2.0\"\n ns_tran=\"http://www.opengis.net/citygml/transportation/2.0\"\n ns_frn=\"http://www.opengis.net/citygml/cityfurniture/2.0\"\n ns_veg=\"http://www.opengis.net/citygml/vegetation/2.0\"\n ns_tun=\"http://www.opengis.net/citygml/tunnel/2.0\"\n ns_tex=\"http://www.opengis.net/citygml/texturedsurface/2.0\"\n ns_brid=\"http://www.opengis.net/citygml/bridge/2.0\"\n ns_core=\"http://www.opengis.net/citygml/base/2.0\"\n ns_grp=\"http://www.opengis.net/citygml/cityobjectgroup/2.0\"\n ns_md = \"http://godzilla.bk.tudelft.nl/schemas/3DMD_ADE\"\n schemalocs=\"http://www.opengis.net/citygml/2.0 http://schemas.opengis.net/citygml/2.0/cityGMLBase.xsd \\\n http://www.opengis.net/citygml/building/2.0 http://schemas.opengis.net/citygml/building/2.0/building.xsd \\\n http://www.opengis.net/citygml/appearance/2.0 http://schemas.opengis.net/citygml/appearance/2.0/appearance.xsd \\\n http://www.opengis.net/citygml/bridge/2.0 http://schemas.opengis.net/citygml/bridge/2.0/bridge.xsd \\\n http://www.opengis.net/citygml/cityfurniture/2.0 http://schemas.opengis.net/citygml/cityfurniture/2.0/cityFurniture.xsd \\\n http://www.opengis.net/citygml/waterbody/2.0 http://schemas.opengis.net/citygml/waterbody/2.0/waterBody.xsd \\\n http://www.opengis.net/citygml/tunnel/2.0 http://schemas.opengis.net/citygml/tunnel/2.0/tunnel.xsd \\\n http://www.opengis.net/citygml/vegetation/2.0 http://schemas.opengis.net/citygml/vegetation/2.0/vegetation.xsd \\\n http://www.opengis.net/citygml/transportation/2.0 http://schemas.opengis.net/citygml/transportation/2.0/transportation.xsd \\\n http://www.opengis.net/citygml/texturedsurface/2.0 http://schemas.opengis.net/citygml/texturedsurface/2.0/texturedSurface.xsd \\\n http://www.opengis.net/citygml/relief/2.0 http://schemas.opengis.net/citygml/relief/2.0/relief.xsd \\\n http://www.opengis.net/citygml/landuse/2.0 http://schemas.opengis.net/citygml/landuse/2.0/landUse.xsd \\\n http://www.opengis.net/citygml/generics/2.0 http://schemas.opengis.net/citygml/generics/2.0/generics.xsd \\\n http://www.opengis.net/citygml/cityobjectgroup/2.0 http://schemas.opengis.net/citygml/cityobjectgroup/2.0/cityObjectGroup.xsd\\\n http://godzilla.bk.tudelft.nl/schemas/3DMD_ADE /Users/kavisha/Desktop/githubpvt/3D_Metadata_ADE/XSD/3DMD_ADE.xsd\" \n \n nsmap = {None : ns,\n 'gml' : ns_gml,\n 'xAL':ns_xAL,\n 'xsi':ns_xsi,\n 'xlink':ns_xlink ,\n 'dem':ns_dem,\n 'bldg':ns_bldg,\n 'app':ns_app,\n 'wtr':ns_wtr,\n 'gen':ns_gen,\n 'luse':ns_luse,\n 'tran':ns_tran,\n 'frn':ns_frn,\n 'veg':ns_veg,\n 'tun':ns_tun,\n 'tex':ns_tex,\n 'brid':ns_brid,\n 'core':ns_core,\n 'grp':ns_grp,\n 'md':ns_md\n \n }\n print (\"\\nReading elements ......\")\n attr_qname = etree.QName(\"http://www.w3.org/2001/XMLSchema-instance\",\"schemaLocation\")\n cityModel = etree.Element(\"CityModel\", {attr_qname: schemalocs}, nsmap=nsmap) \n \n # MDcitymodel {Metadata city model}\n cityObjectMember = etree.SubElement(cityModel, \"{%s}cityObjectMember\" %ns)\n mdcitymodel = etree.SubElement(cityObjectMember, \"{%s}MDcitymodel\" %ns_md)\n \n # metadata identifier\n metadataIdentifier = etree.SubElement(mdcitymodel, \"{%s}metadataIdentifier\" %ns_md)\n metadataIdentifier.text = \"GML_\" + str(uuid.uuid1())\n \n # citymodel identifier\n citymodelIdentifier = etree.SubElement(mdcitymodel, \"{%s}citymodelIdentifier\" %ns_md)\n if root.find('.//{%s}id' %ns_gml)!=None:\n gmlid = root.find('.//{%s}id' %ns_gml)\n citymodelIdentifier.text = gmlid.text\n else:\n citymodelIdentifier.text = \"GML_\" + str(uuid.uuid1())\n print (\"\\ncitymodelIdentifier not defined!! An arbitrary value is given.\")\n \n # ISO metadata\n print (\"\\nISO metadata: \") \n isometadata = etree.SubElement(mdcitymodel, \"{%s}ISOmetadata\" %ns_md)\n isoidentifier = etree.SubElement(isometadata, \"{%s}ISOidentifier\" %ns_md)\n # dataset title\n datasetTitle = etree.SubElement(isoidentifier, \"{%s}datasetTitle\" %ns_md)\n if root.find('{%s}name' %ns_gml)!=None:\n name = root.find('{%s}name' %ns_gml)\n datasetTitle.text = name.text\n else:\n datasetTitle.text = \"Name not defined!\"\n print (\"datasetTitle is not defined!!\")\n # dataset reference date\n datasetReferenceDate = etree.SubElement(isoidentifier, \"{%s}datasetReferenceDate\" %ns_md)\n if root.find('{%s}creationDate' %ns)!=None:\n creationDate = root.find('.//{%s}creationDate' %ns_gml)\n datasetReferenceDate.text = creationDate.text\n else:\n datasetReferenceDate.text = time.strftime(\"%Y-%m-%d\")\n print (\"datasetReferenceDate is not defined!!\")\n # dataset responsible party\n datasetResponsibleParty = etree.SubElement(isoidentifier, \"{%s}datasetResponsibleParty\" %ns_md)\n organizationalContact = etree.SubElement(datasetResponsibleParty, \"{%s}OrganizationalContact\" %ns_md)\n contactName = etree.SubElement(organizationalContact, \"{%s}contactName\" %ns_md)\n contactName.text = \"House of Slytherin\"\n phone = etree.SubElement(organizationalContact, \"{%s}phone\" %ns_md)\n phone.text = \"+00 00000000\"\n address = etree.SubElement(organizationalContact, \"{%s}address\" %ns_md)\n address.text = \"Hogwarts Castle, Highlands, Scotland, Great Britain\"\n emailAddress = etree.SubElement(organizationalContact, \"{%s}emailAddress\" %ns_md)\n emailAddress.text =\"slytherin@HogwartsSchoolofWitchcraftandWizardry.com\"\n website = etree.SubElement(organizationalContact, \"{%s}website\" %ns_md)\n website.text = \"http://www.HogwartsSchoolofWitchcraftandWizardry.com/Slytherin\"\n print (\"datasetResponsibleParty is not defined!!\")\n # geographic location\n geoLocation = etree.SubElement(isoidentifier, \"{%s}geoLocation\" %ns_md)\n geoLocation.text = \"No geoLocation available!\"\n print (\"geoLocation is not defined!!\")\n # dataset language\n datasetLanguage = etree.SubElement(isoidentifier, \"{%s}datasetLanguage\" %ns_md)\n datasetLanguage.text = \"English\"\n #\n datasetCharacterSet = etree.SubElement(isoidentifier, \"{%s}datasetCharacterSet\" %ns_md)\n datasetCharacterSet.text = \"UTF-8\"\n # dataset topic category\n datasetTopicCategory = etree.SubElement(isoidentifier, \"{%s}datasetTopicCategory\" %ns_md)\n datasetTopicCategory.attrib['codeSpace'] = \"http://godzilla.bk.tudelft.nl/schemas/3DMD_ADE//codelists/MDtopicCategory.xml\"\n datasetTopicCategory.text = \"geoscientificInformation\"\n # dataset description\n datasetDescription = etree.SubElement(isoidentifier, \"{%s}datasetDescription\" %ns_md)\n if root.find('{%s}description' %ns_gml)!=None:\n descrip = root.find('{%s}name' %ns_gml)\n datasetDescription.text = descrip.text\n else:\n datasetDescription.text = \"No description available!\"\n print (\"datasetDescription is not defined!!\")\n # distribution format version\n distributionFormatVersion = etree.SubElement(isoidentifier, \"{%s}distributionFormatVersion\" %ns_md)\n distributionFormatVersion.text = \"CityGML 2.0\"\n # spatial representation type\n spatialRepresentationType = etree.SubElement(isoidentifier, \"{%s}spatialRepresentationType\" %ns_md)\n spatialRepresentationType.attrib['codeSpace'] = \"http://godzilla.bk.tudelft.nl/schemas/3DMD_ADE//codelists/MDspatialRepTypeCode.xml\"\n spatialRepresentationType.text = \"vector\"\n # reference system/crs\n referenceSystem = etree.SubElement(isoidentifier, \"{%s}referenceSystem\" %ns_md)\n # temporal information\n temporalInformation = etree.SubElement(isoidentifier, \"{%s}temporalInformation\" %ns_md)\n temporalInformation.text = time.strftime(\"%Y-%m-%d\")\n print (\"temporalInformation is not defined!!\")\n # online resource\n onlineResource = etree.SubElement(isoidentifier, \"{%s}onlineResource\" %ns_md)\n onlineResource.text = \"https://www.citygml.org/samplefiles/\"\n print (\"onlineResource is not defined!!\")\n # file identifier\n fileIdentifier = etree.SubElement(isoidentifier, \"{%s}fileIdentifier\" %ns_md)\n fileIdentifier.text = os.path.split(inputfile)[1]\n # metadata standard\n metadataStandard = etree.SubElement(isoidentifier, \"{%s}metadataStandard\" %ns_md)\n metadataStandard.text = \"ISO 19115 - Geographic Information -Metadata\"\n # metadata standard version\n metadataStandardVersion = etree.SubElement(isoidentifier, \"{%s}metadataStandardVersion\" %ns_md)\n metadataStandardVersion.text = \"19115:2014(E)\"\n # metadata language\n metadataLanguage = etree.SubElement(isoidentifier, \"{%s}metadataLanguage\" %ns_md)\n metadataLanguage.text = \"English\"\n # metadata character set\n metadataCharacterSet = etree.SubElement(isoidentifier, \"{%s}metadataCharacterSet\" %ns_md)\n metadataCharacterSet.text = \"UTF-8\"\n # metadata point of contact\n metadataPointOfContact = etree.SubElement(isoidentifier, \"{%s}metadataPointOfContact\" %ns_md)\n organizationalContact = etree.SubElement(metadataPointOfContact, \"{%s}OrganizationalContact\" %ns_md)\n contactName = etree.SubElement(organizationalContact, \"{%s}contactName\" %ns_md)\n contactName.text = \"House of Slytherin\"\n phone = etree.SubElement(organizationalContact, \"{%s}phone\" %ns_md)\n phone.text = \"+00 00000000\"\n address = etree.SubElement(organizationalContact, \"{%s}address\" %ns_md)\n address.text = \"Hogwarts Castle, Highlands, Scotland, Great Britain\"\n emailAddress = etree.SubElement(organizationalContact, \"{%s}emailAddress\" %ns_md)\n emailAddress.text =\"slytherin@HogwartsSchoolofWitchcraftandWizardry.com\"\n website = etree.SubElement(organizationalContact, \"{%s}website\" %ns_md)\n website.text = \"http://www.HogwartsSchoolofWitchcraftandWizardry.com/Slytherin\"\n print (\"datasetResponsibleParty is not defined!!\")\n # metadata datestamp\n metadataDateStamp = etree.SubElement(isoidentifier, \"{%s}metadataDateStamp\" %ns_md)\n metadataDateStamp.text = time.strftime(\"%Y-%m-%d\")\n # lineage\n lineage = etree.SubElement(isoidentifier, \"{%s}lineage\" %ns_md)\n Lineage = etree.SubElement(lineage, \"{%s}Lineage\" %ns_md)\n source = etree.SubElement(Lineage, \"{%s}source\" %ns_md)\n source.text = \"Put source here..\"\n processStep = etree.SubElement(Lineage, \"{%s}processStep\" %ns_md)\n processStep.text = \"Put processStep here..\"\n print (\"lineage source and process steps are not defined!!\")\n # bounding box\n boundingBox3D = etree.SubElement(isoidentifier, \"{%s}boundingBox3D\" %ns_md)\n if root.find('{%s}boundedBy' %ns_gml)!=None:\n bby = root.find('{%s}boundedBy' %ns_gml)\n if bby.find('{%s}Envelope' %ns_gml)!=None:\n gmlEnvelope = etree.SubElement(boundingBox3D, \"{%s}Envelope\" %ns_gml)\n if bby.find('{%s}Envelope' %ns_gml)!=None:\n envlp = bby.find('{%s}Envelope' %ns_gml)\n if envlp.get(\"srsName\")!=None:\n# print (envlp.get(\"srsName\"))\n referenceSystem.text = envlp.get(\"srsName\")\n if envlp.find('{%s}lowerCorner' %ns_gml)!=None:\n envlplc = envlp.find('{%s}lowerCorner' %ns_gml)\n gmlLowerCorner = etree.SubElement(gmlEnvelope, \"{%s}lowerCorner\" %ns_gml)\n gmlLowerCorner.text = envlplc.text\n if envlp.find('{%s}upperCorner' %ns_gml)!=None:\n envlpuc = envlp.find('{%s}upperCorner' %ns_gml)\n gmlUpperCorner = etree.SubElement(gmlEnvelope, \"{%s}upperCorner\" %ns_gml)\n gmlUpperCorner.text = envlpuc.text \n # abstract \n abstract = etree.SubElement(isoidentifier, \"{%s}abstract\" %ns_md)\n abstract.text = \"la la la .....\"\n print (\"abstract is not defined!!\")\n # specific usage\n specificUsage = etree.SubElement(isoidentifier, \"{%s}specificUsage\" %ns_md)\n specificUsage.text = \"3D Geoinformation modelling\"\n print (\"specificUsage is not defined!!\")\n # keywords\n keywords = etree.SubElement(isoidentifier, \"{%s}keywords\" %ns_md)\n keywords.text = \"CityGML, 3D city modelling, Metadata\"\n print (\"keywords is not defined!!\")\n # constraints\n constraints = etree.SubElement(isoidentifier, \"{%s}constraints\" %ns_md)\n constraintsOnUsage = etree.SubElement(constraints, \"{%s}ConstraintsOnUsage\" %ns_md)\n legalConstraints = etree.SubElement(constraintsOnUsage, \"{%s}legalConstraints\" %ns_md)\n legalConstraints.attrib['codeSpace'] = \"http://godzilla.bk.tudelft.nl/schemas/3DMD_ADE//codelists/MDlegalConstraints.xml\"\n legalConstraints.text = \"unrestricted\"\n securityConstraints = etree.SubElement(constraintsOnUsage, \"{%s}legalConstraints\" %ns_md)\n securityConstraints.attrib['codeSpace'] = \"http://godzilla.bk.tudelft.nl/schemas/3DMD_ADE//codelists/MDsecurityConstraints.xml\"\n securityConstraints.text = \"owner\"\n userNote = etree.SubElement(constraintsOnUsage, \"{%s}legalConstraints\" %ns_md)\n userNote.text = \"Draco Dormiens Nunquam Titillandus\"\n print (\"constraints not defined!!\")\n \n \n # thematic models\n thematicModels = etree.SubElement(mdcitymodel, \"{%s}thematicModels\" %ns_md)\n presentThematicModels = etree.SubElement(thematicModels, \"{%s}presentThematicModels\" %ns_md) \n \n \n # textures \n textures = etree.SubElement(mdcitymodel, \"{%s}textures\" %ns_md)\n if root.find('.//{%s}ParameterizedTexture' %ns_app)!=None:\n textures.text = \"present\"\n else:\n textures.text = \"absent\"\n \n \n # materials\n materials = etree.SubElement(mdcitymodel, \"{%s}materials\" %ns_md)\n if root.find('.//{%s}X3DMaterial' %ns_app)!=None:\n materials.text = \"present\"\n else:\n materials.text = \"absent\"\n \n # MDcityfeatures\n thematicModelsSet = set()\n terrainTypeSet = set()\n cogSet = set()\n buildingCount = 0\n buildingpartsCount = 0\n buildinginstallationsCount = 0\n bridgeCount = 0\n bridgepartsCount = 0\n bridgeinstallationsCount = 0\n bridgeconstructionelementsCount = 0\n tunnelCount = 0\n tunnelpartsCount = 0\n tunnelinstallationsCount = 0\n vegCount = 0\n svoCount = 0\n plantcoverCount = 0\n waterCount = 0\n tinreliefCount = 0\n transportationCount = 0\n roadCount = 0\n railwayCount = 0\n squareCount = 0\n trackCount = 0\n genericsCount = 0\n cityfurnitureCount = 0\n cityobjectgroupCount = 0\n landuseCount = 0\n numberOfTriangles = 0\n \n lod0bldgCount = 0\n lod1bldgCount = 0\n lod2bldgCount = 0\n lod3bldgCount = 0\n lod4bldgCount = 0\n \n lod1bridgeCount = 0\n lod2bridgeCount = 0\n lod3bridgeCount = 0\n lod4bridgeCount = 0\n \n lod1tunnelCount = 0\n lod2tunnelCount = 0\n lod3tunnelCount = 0\n lod4tunnelCount = 0\n \n lod0tranCount = 0\n lod1tranCount = 0\n lod2tranCount = 0\n lod3tranCount = 0\n lod4tranCount = 0\n \n lod1vegCount = 0\n lod2vegCount = 0\n lod3vegCount = 0\n lod4vegCount = 0\n \n lod0waterCount = 0\n lod1waterCount = 0\n lod2waterCount = 0\n lod3waterCount = 0\n lod4waterCount = 0\n \n lod0tinreliefCount = 0\n lod1tinreliefCount = 0\n lod2tinreliefCount = 0\n lod3tinreliefCount = 0\n lod4tinreliefCount = 0\n \n lod0genCount = 0\n lod1genCount = 0\n lod2genCount = 0\n lod3genCount = 0\n lod4genCount = 0\n \n lod1cfCount = 0\n lod2cfCount = 0\n lod3cfCount = 0\n lod4cfCount = 0\n \n \n lod0luseCount = 0\n lod1luseCount = 0\n lod2luseCount = 0\n lod3luseCount = 0\n lod4luseCount = 0\n \n #for cityobject groups\n \n cogbuildingCount = 0\n cogbuildingpartsCount = 0\n cogbuildinginstallationsCount = 0\n cogbridgeCount = 0\n cogbridgepartsCount = 0\n cogbridgeinstallationsCount = 0\n cogbridgeconstructionelementsCount = 0\n cogtunnelCount = 0\n cogtunnelpartsCount = 0\n cogtunnelinstallationsCount = 0\n cogvegCount = 0\n cogsvoCount = 0\n cogplantcoverCount = 0\n cogwaterCount = 0\n cogtinreliefCount = 0\n cogtransportationCount = 0\n cogroadCount = 0\n cograilwayCount = 0\n cogsquareCount = 0\n cogtrackCount = 0\n coggenericsCount = 0\n cogcityfurnitureCount = 0\n coglanduseCount = 0\n cognumberOfTriangles = 0\n \n lod0cogbldgCount = 0\n lod1cogbldgCount = 0\n lod2cogbldgCount = 0\n lod3cogbldgCount = 0\n lod4cogbldgCount = 0\n \n lod1cogbridgeCount = 0\n lod2cogbridgeCount = 0\n lod3cogbridgeCount = 0\n lod4cogbridgeCount = 0\n \n lod1cogtunnelCount = 0\n lod2cogtunnelCount = 0\n lod3cogtunnelCount = 0\n lod4cogtunnelCount = 0\n \n lod0cogtranCount = 0\n lod1cogtranCount = 0\n lod2cogtranCount = 0\n lod3cogtranCount = 0\n lod4cogtranCount = 0\n \n lod1cogvegCount = 0\n lod2cogvegCount = 0\n lod3cogvegCount = 0\n lod4cogvegCount = 0\n \n lod0cogwaterCount = 0\n lod1cogwaterCount = 0\n lod2cogwaterCount = 0\n lod3cogwaterCount = 0\n lod4cogwaterCount = 0\n \n lod0coggenCount = 0\n lod1coggenCount = 0\n lod2coggenCount = 0\n lod3coggenCount = 0\n lod4coggenCount = 0\n \n lod1cogcfCount = 0\n lod2cogcfCount = 0\n lod3cogcfCount = 0\n lod4cogcfCount = 0\n \n \n lod0cogluseCount = 0\n lod1cogluseCount = 0\n lod2cogluseCount = 0\n lod3cogluseCount = 0\n lod4cogluseCount = 0\n\n lod0cogtinreliefCount = 0\n lod1cogtinreliefCount = 0\n lod2cogtinreliefCount = 0\n lod3cogtinreliefCount = 0\n lod4cogtinreliefCount = 0\n \n for obj in root.getiterator('{%s}cityObjectMember'% ns):\n for child in obj.getchildren():\n if child.tag not in thematicModelsSet:\n \n if child.tag == '{%s}Building' %ns_bldg:\n thematicModelsSet.add(\"Building\")\n buildingCount = buildingCount + 1\n lodcount = getcityobjects.getbuilding(child) \n lod0bldgCount = lod0bldgCount + lodcount[0]\n lod1bldgCount = lod1bldgCount + lodcount[1]\n lod2bldgCount = lod2bldgCount + lodcount[2]\n lod3bldgCount = lod3bldgCount + lodcount[3] \n lod4bldgCount = lod4bldgCount + lodcount[4]\n buildinginstallationsCount = buildinginstallationsCount + lodcount[5] \n buildingpartsCount = buildingpartsCount + lodcount[6]\n \n if child.tag == '{%s}Bridge' %ns_brid:\n thematicModelsSet.add(\"Bridge\") \n bridgeCount = bridgeCount + 1\n lodcount = getcityobjects.getbridge(child)\n lod1bridgeCount = lod1bridgeCount + lodcount[0]\n lod2bridgeCount = lod2bridgeCount + lodcount[1]\n lod3bridgeCount = lod3bridgeCount + lodcount[2]\n lod4bridgeCount = lod4bridgeCount + lodcount[3] \n bridgeinstallationsCount = bridgeinstallationsCount + lodcount[4] \n bridgepartsCount = bridgepartsCount + lodcount[5] \n bridgeconstructionelementsCount = bridgeconstructionelementsCount +lodcount[6] \n \n if child.tag == '{%s}Tunnel' %ns_tun:\n thematicModelsSet.add(\"Tunnel\")\n tunnelCount = tunnelCount + 1\n lodcount = getcityobjects.gettunnel(child)\n lod1tunnelCount = lod1tunnelCount + lodcount[0]\n lod2tunnelCount = lod2tunnelCount + lodcount[1]\n lod3tunnelCount = lod3tunnelCount + lodcount[2]\n lod4tunnelCount = lod4tunnelCount + lodcount[3] \n tunnelinstallationsCount = tunnelinstallationsCount + lodcount[4] \n tunnelpartsCount = tunnelpartsCount + lodcount[5] \n \n if child.tag == '{%s}SolitaryVegetationObject' %ns_veg or \\\n child.tag == '{%s}PlantCover' %ns_veg:\n thematicModelsSet.add(\"Vegetation\")\n vegCount = vegCount + 1\n lodcount = getcityobjects.getveg(child)\n lod1vegCount = lod1vegCount + lodcount[0]\n lod2vegCount = lod2vegCount + lodcount[1]\n lod3vegCount = lod3vegCount + lodcount[2]\n lod4vegCount = lod4vegCount + lodcount[3] \n svoCount = svoCount + lodcount[4] \n plantcoverCount = plantcoverCount + lodcount[5] \n \n if child.tag == '{%s}WaterBody' %ns_wtr:\n thematicModelsSet.add(\"WaterBody\")\n waterCount = waterCount + 1\n lodcount = getcityobjects.getwater(child)\n lod0waterCount = lod0waterCount + lodcount[0]\n lod1waterCount = lod1waterCount + lodcount[1]\n lod2waterCount = lod2waterCount + lodcount[2]\n lod3waterCount = lod3waterCount + lodcount[3]\n lod4waterCount = lod4waterCount + lodcount[4]\n \n if child.tag == '{%s}ReliefFeature' %ns_dem:\n if child.findall('.//{%s}TINRelief' %ns_dem):\n thematicModelsSet.add(\"Relief\")\n terrainTypeSet.add(\"TINRelief\")\n tinreliefCount = tinreliefCount + 1\n lodcount = getcityobjects.getrelief(child)\n lod0tinreliefCount = lod0tinreliefCount + lodcount[0]\n lod1tinreliefCount = lod1tinreliefCount + lodcount[1]\n lod2tinreliefCount = lod2tinreliefCount + lodcount[2]\n lod3tinreliefCount = lod3tinreliefCount + lodcount[3]\n lod4tinreliefCount = lod4tinreliefCount + lodcount[4]\n numberOfTriangles = numberOfTriangles + lodcount[5]\n \n if child.tag == '{%s}Road' %ns_tran or \\\n child.tag == '{%s}Railway' %ns_tran or \\\n child.tag == '{%s}Square' %ns_tran or \\\n child.tag == '{%s}Track' %ns_tran:\n thematicModelsSet.add(\"Transportation\")\n transportationCount = transportationCount + 1\n lodcount = getcityobjects.gettransport(child)\n lod0tranCount = lod0tranCount + lodcount[0]\n lod1tranCount = lod1tranCount + lodcount[1]\n lod2tranCount = lod2tranCount + lodcount[2]\n lod3tranCount = lod3tranCount + lodcount[3]\n lod4tranCount = lod4tranCount + lodcount[4]\n roadCount = roadCount + lodcount[5]\n railwayCount = railwayCount + lodcount[6]\n squareCount = squareCount + lodcount[7]\n trackCount = trackCount + lodcount[8] \n \n if child.tag == '{%s}GenericCityObject' %ns_gen: \n thematicModelsSet.add(\"Generics\")\n genericsCount = genericsCount + 1\n lodcount = getcityobjects.getgenerics(child)\n lod0genCount = lod0genCount + lodcount[0]\n lod1genCount = lod1genCount + lodcount[1]\n lod2genCount = lod2genCount + lodcount[2]\n lod3genCount = lod3genCount + lodcount[3]\n lod4genCount = lod4genCount + lodcount[4] \n \n if child.tag == '{%s}CityFurniture' %ns_frn: \n thematicModelsSet.add(\"CityFurniture\")\n cityfurnitureCount = cityfurnitureCount + 1\n lodcount = getcityobjects.getcityfurniture(child)\n lod1cfCount = lod1cfCount + lodcount[0]\n lod2cfCount = lod2cfCount + lodcount[1]\n lod3cfCount = lod3cfCount + lodcount[2]\n lod4cfCount = lod4cfCount + lodcount[3]\n \n if child.tag == '{%s}LandUse' %ns_luse: \n thematicModelsSet.add(\"LandUse\")\n landuseCount = landuseCount + 1\n lodcount = getcityobjects.getlanduse(child)\n lod0luseCount = lod0luseCount + lodcount[0]\n lod1luseCount = lod1luseCount + lodcount[1]\n lod2luseCount = lod2luseCount + lodcount[2]\n lod3luseCount = lod3luseCount + lodcount[3]\n lod4luseCount = lod4luseCount + lodcount[4]\n \n if child.tag == '{%s}CityObjectGroup' %ns_grp: \n thematicModelsSet.add(\"CityObjectGroup\")\n cityobjectgroupCount = cityobjectgroupCount + 1\n if child.findall('{%s}groupMember'%ns_grp):\n for gm in child.findall('{%s}groupMember'%ns_grp):\n for node in gm.getiterator():\n if (node.tag =='{%s}SolitaryVegetationObject' %ns_veg) or \\\n (node.tag =='{%s}PlantCover' %ns_veg):\n cogSet.add(\"Vegetation\")\n cogvegCount = cogvegCount + 1\n lodcount = getcityobjects.getveg(node)\n lod1cogvegCount = lod1cogvegCount + lodcount[0]\n lod2cogvegCount = lod2cogvegCount + lodcount[1]\n lod3cogvegCount = lod3cogvegCount + lodcount[2]\n lod4cogvegCount = lod4cogvegCount + lodcount[3]\n cogsvoCount = cogsvoCount + lodcount[4] \n cogplantcoverCount = cogplantcoverCount + lodcount[5] \n \n if (node.tag =='{%s}LandUse' %ns_luse):\n cogSet.add(\"LandUse\")\n coglanduseCount = coglanduseCount + 1\n lodcount = getcityobjects.getlanduse(node)\n lod0cogluseCount = lod0cogluseCount + lodcount[0]\n lod1cogluseCount = lod1cogluseCount + lodcount[1]\n lod2cogluseCount = lod2cogluseCount + lodcount[2]\n lod3cogluseCount = lod3cogluseCount + lodcount[3]\n lod4cogluseCount = lod4cogluseCount + lodcount[4]\n \n if (node.tag =='{%s}GenericCityObject' %ns_gen):\n cogSet.add(\"Generics\")\n coggenericsCount = coggenericsCount + 1\n lodcount = getcityobjects.getgenerics(node)\n lod0coggenCount = lod0coggenCount + lodcount[0]\n lod1coggenCount = lod1coggenCount + lodcount[1]\n lod2coggenCount = lod2coggenCount + lodcount[2]\n lod3coggenCount = lod3coggenCount + lodcount[3]\n lod4coggenCount = lod4coggenCount + lodcount[4]\n \n if (node.tag =='{%s}Road' %ns_tran) or \\\n (node.tag =='{%s}Railway' %ns_tran) or \\\n (node.tag =='{%s}Square' %ns_tran) or \\\n (node.tag =='{%s}Track' %ns_tran):\n cogSet.add(\"Transportation\")\n cogtransportationCount = cogtransportationCount + 1\n lodcount = getcityobjects.gettransport(node)\n lod0cogtranCount = lod0cogtranCount + lodcount[0]\n lod1cogtranCount = lod1cogtranCount + lodcount[1]\n lod2cogtranCount = lod2cogtranCount + lodcount[2]\n lod3cogtranCount = lod3cogtranCount + lodcount[3]\n lod4cogtranCount = lod4cogtranCount + lodcount[4]\n cogroadCount = cogroadCount + lodcount[5]\n cograilwayCount = cograilwayCount + lodcount[6]\n cogsquareCount = cogsquareCount + lodcount[7]\n cogtrackCount = cogtrackCount + lodcount[8] \n \n if (node.tag =='{%s}WaterBody' %ns_wtr):\n cogSet.add(\"WaterBody\")\n cogwaterCount = cogwaterCount + 1\n lodcount = getcityobjects.getwater(node)\n lod0cogwaterCount = lod0cogwaterCount + lodcount[0]\n lod1cogwaterCount = lod1cogwaterCount + lodcount[1]\n lod2cogwaterCount = lod2cogwaterCount + lodcount[2]\n lod3cogwaterCount = lod3cogwaterCount + lodcount[3]\n lod4cogwaterCount = lod4cogwaterCount + lodcount[4]\n \n if (node.tag =='{%s}CityFurniture' %ns_frn):\n cogSet.add(\"CityFurniture\")\n cogcityfurnitureCount = cogcityfurnitureCount + 1\n lodcount = getcityobjects.getcityfurniture(node)\n lod1cogcfCount = lod1cogcfCount + lodcount[0]\n lod2cogcfCount = lod2cogcfCount + lodcount[1]\n lod3cogcfCount = lod3cogcfCount + lodcount[2]\n lod4cogcfCount = lod4cogcfCount + lodcount[3]\n \n if (node.tag =='{%s}Tunnel' %ns_tun):\n cogSet.add(\"Tunnel\")\n cogtunnelCount = cogtunnelCount + 1\n lodcount = getcityobjects.gettunnel(node)\n lod1cogtunnelCount = lod1cogtunnelCount + lodcount[0]\n lod2cogtunnelCount = lod2cogtunnelCount + lodcount[1]\n lod3cogtunnelCount = lod3cogtunnelCount + lodcount[2]\n lod4cogtunnelCount = lod4cogtunnelCount + lodcount[3] \n cogtunnelinstallationsCount = cogtunnelinstallationsCount + lodcount[4] \n cogtunnelpartsCount = cogtunnelpartsCount + lodcount[5]\n \n if (node.tag =='{%s}Bridge' %ns_brid):\n cogSet.add(\"Bridge\")\n cogbridgeCount = cogbridgeCount + 1\n lodcount = getcityobjects.getbridge(node)\n lod1cogbridgeCount = lod1cogbridgeCount + lodcount[0]\n lod2cogbridgeCount = lod2cogbridgeCount + lodcount[1]\n lod3cogbridgeCount = lod3cogbridgeCount + lodcount[2]\n lod4cogbridgeCount = lod4cogbridgeCount + lodcount[3] \n cogbridgeinstallationsCount = cogbridgeinstallationsCount + lodcount[4] \n cogbridgepartsCount = cogbridgepartsCount + lodcount[5] \n cogbridgeconstructionelementsCount = cogbridgeconstructionelementsCount +lodcount[6]\n \n if (node.tag =='{%s}Building' %ns_bldg):\n cogSet.add(\"Building\")\n cogbuildingCount = cogbuildingCount + 1\n lodcount = getcityobjects.getbuilding(node) \n lod0cogbldgCount = lod0cogbldgCount + lodcount[0]\n lod1cogbldgCount = lod1cogbldgCount + lodcount[1]\n lod2cogbldgCount = lod2cogbldgCount + lodcount[2]\n lod3cogbldgCount = lod3cogbldgCount + lodcount[3] \n lod4cogbldgCount = lod4cogbldgCount + lodcount[4]\n cogbuildinginstallationsCount = cogbuildinginstallationsCount + lodcount[5] \n cogbuildingpartsCount = cogbuildingpartsCount + lodcount[6]\n if (node.tag =='{%s}Relief' %ns_bldg):\n cogSet.add(\"Relief\")\n cogtinreliefCount = cogtinreliefCount + 1\n lodcount = getcityobjects.getrelief(child)\n lod0cogtinreliefCount = lod0cogtinreliefCount + lodcount[0]\n lod1cogtinreliefCount = lod1cogtinreliefCount + lodcount[1]\n lod2cogtinreliefCount = lod2cogtinreliefCount + lodcount[2]\n lod3cogtinreliefCount = lod3cogtinreliefCount + lodcount[3]\n lod4cogtinreliefCount = lod4cogtinreliefCount + lodcount[4]\n cognumberOfTriangles = cognumberOfTriangles + lodcount[5]\n \n \n print (\"\\nThematic Models Present: \") \n for item in thematicModelsSet:\n print (item)\n thematicModel = etree.SubElement(presentThematicModels, \"{%s}thematicModel\" %ns_md)\n thematicModel.text = item \n mdCityfeatures = etree.SubElement(mdcitymodel, \"{%s}MDcityfeatures\" %ns_md)\n if item == \"Building\":\n mdbuilding = etree.SubElement(mdCityfeatures, \"{%s}MDbuilding\" %ns_md)\n featureType = etree.SubElement(mdbuilding, \"{%s}featureType\" %ns_md)\n featureType.text = \"Building\"\n featureCount = etree.SubElement(mdbuilding, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(buildingCount)\n lods = etree.SubElement(mdbuilding, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0bldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0bldgCount)\n if lod1bldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1bldgCount)\n if lod2bldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2bldgCount)\n if lod3bldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3bldgCount)\n if lod4bldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4bldgCount)\n \n buildingParts = etree.SubElement(mdbuilding, \"{%s}buildingParts\" %ns_md)\n buildingParts.text = str(buildingpartsCount)\n buildingInstallations = etree.SubElement(mdbuilding, \"{%s}buildingInstallations\" %ns_md)\n buildingInstallations.text = str(buildinginstallationsCount)\n \n if item == \"Bridge\":\n mdbridge = etree.SubElement(mdCityfeatures, \"{%s}MDbridge\" %ns_md)\n featureType = etree.SubElement(mdbridge, \"{%s}featureType\" %ns_md)\n featureType.text = \"Bridge\"\n featureCount = etree.SubElement(mdbridge, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(bridgeCount)\n lods = etree.SubElement(mdbridge, \"{%s}LevelsOfDetail\" %ns_md)\n if lod1bridgeCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1bridgeCount)\n if lod2bridgeCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2bridgeCount)\n if lod3bridgeCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3bridgeCount)\n if lod4bridgeCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4bridgeCount)\n bridgeParts = etree.SubElement(mdbridge, \"{%s}bridgeParts\" %ns_md)\n bridgeParts.text = str(bridgepartsCount)\n bridgeInstallations = etree.SubElement(mdbridge, \"{%s}bridgeInstallations\" %ns_md)\n bridgeInstallations.text = str(bridgeinstallationsCount)\n bridgeConstructionElements = etree.SubElement(mdbridge, \"{%s}bridgeConstructionElements\" %ns_md)\n bridgeConstructionElements.text = str(bridgeconstructionelementsCount)\n \n if item == \"Tunnel\":\n mdtunnel = etree.SubElement(mdCityfeatures, \"{%s}MDtunnel\" %ns_md)\n featureType = etree.SubElement(mdtunnel, \"{%s}featureType\" %ns_md)\n featureType.text = \"Tunnel\"\n featureCount = etree.SubElement(mdtunnel, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(tunnelCount)\n lods = etree.SubElement(mdtunnel, \"{%s}LevelsOfDetail\" %ns_md)\n if lod1tunnelCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1tunnelCount)\n if lod2tunnelCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2tunnelCount)\n if lod3tunnelCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3tunnelCount)\n if lod4tunnelCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4tunnelCount)\n tunnelParts = etree.SubElement(mdtunnel, \"{%s}tunnelParts\" %ns_md)\n tunnelParts.text = str(tunnelpartsCount)\n tunnelInstallations = etree.SubElement(mdtunnel, \"{%s}tunnelInstallations\" %ns_md)\n tunnelInstallations.text = str(tunnelinstallationsCount)\n \n if item == \"Vegetation\":\n mdvegetation = etree.SubElement(mdCityfeatures, \"{%s}MDvegetation\" %ns_md)\n featureType = etree.SubElement(mdvegetation, \"{%s}featureType\" %ns_md)\n featureType.text = \"Vegetation\"\n featureCount = etree.SubElement(mdvegetation, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(vegCount)\n lods = etree.SubElement(mdvegetation, \"{%s}LevelsOfDetail\" %ns_md)\n if lod1vegCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1vegCount)\n if lod2vegCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2vegCount)\n if lod3vegCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3vegCount)\n if lod4vegCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4vegCount)\n plantCovers = etree.SubElement(mdvegetation, \"{%s}plantCovers\" %ns_md)\n plantCovers.text = str(plantcoverCount)\n solitaryVegetationObjects = etree.SubElement(mdvegetation, \"{%s}solitaryVegetationObjects\" %ns_md)\n solitaryVegetationObjects.text = str(svoCount)\n \n if item == \"WaterBody\":\n mdwaterbody = etree.SubElement(mdCityfeatures, \"{%s}MDwaterBody\" %ns_md)\n featureType = etree.SubElement(mdwaterbody, \"{%s}featureType\" %ns_md)\n featureType.text = \"WaterBody\"\n featureCount = etree.SubElement(mdwaterbody, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(waterCount)\n lods = etree.SubElement(mdwaterbody, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0waterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0waterCount)\n if lod1waterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1waterCount)\n if lod2waterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2waterCount)\n if lod3waterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3waterCount)\n if lod4waterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4waterCount)\n \n if item == \"Relief\":\n for terrainItem in terrainTypeSet:\n if terrainItem == \"TINRelief\":\n mdrelief = etree.SubElement(mdCityfeatures, \"{%s}MDterrain\" %ns_md)\n featureType = etree.SubElement(mdrelief, \"{%s}featureType\" %ns_md)\n featureType.text = \"Relief\"\n featureCount = etree.SubElement(mdrelief, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(tinreliefCount)\n lods = etree.SubElement(mdrelief, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0tinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0tinreliefCount)\n if lod1tinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1tinreliefCount)\n if lod2tinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2tinreliefCount)\n if lod3tinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3tinreliefCount)\n if lod4tinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4tinreliefCount)\n terrainType = etree.SubElement(mdrelief, \"{%s}terrainType\" %ns_md)\n terrainType.text = \"TINRelief\"\n terrainProperties = etree.SubElement(mdrelief, \"{%s}TerrainProperties\" %ns_md)\n mdTINRelief = etree.SubElement(terrainProperties, \"{%s}MDTINRelief\" %ns_md)\n triangleCount = etree.SubElement(mdTINRelief, \"{%s}triangleCount\" %ns_md)\n triangleCount.text = str(numberOfTriangles)\n \n if item == \"Transportation\":\n mdtransportation = etree.SubElement(mdCityfeatures, \"{%s}MDtransportation\" %ns_md)\n featureType = etree.SubElement(mdtransportation, \"{%s}featureType\" %ns_md)\n featureType.text = \"Transportation\"\n featureCount = etree.SubElement(mdtransportation, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(transportationCount)\n lods = etree.SubElement(mdtransportation, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0tranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0tranCount)\n if lod1tranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1tranCount)\n if lod2tranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2tranCount)\n if lod3tranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3tranCount)\n if lod4tranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4tranCount)\n roads = etree.SubElement(mdtransportation, \"{%s}roads\" %ns_md)\n roads.text = str(roadCount)\n railways = etree.SubElement(mdtransportation, \"{%s}railways\" %ns_md)\n railways.text = str(railwayCount)\n tracks = etree.SubElement(mdtransportation, \"{%s}tracks\" %ns_md)\n tracks.text = str(trackCount)\n squares = etree.SubElement(mdtransportation, \"{%s}squares\" %ns_md)\n squares.text = str(squareCount)\n \n if item == \"Generics\":\n mdgenerics = etree.SubElement(mdCityfeatures, \"{%s}MDgenerics\" %ns_md)\n featureType = etree.SubElement(mdgenerics, \"{%s}featureType\" %ns_md)\n featureType.text = \"Generics\"\n featureCount = etree.SubElement(mdgenerics, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(genericsCount)\n lods = etree.SubElement(mdgenerics, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0genCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0genCount)\n if lod1genCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1genCount)\n if lod2genCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2genCount)\n if lod3genCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3genCount)\n if lod4genCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4genCount)\n \n if item == \"CityFurniture\":\n mdcityfurniture = etree.SubElement(mdCityfeatures, \"{%s}MDcityFurniture\" %ns_md)\n featureType = etree.SubElement(mdcityfurniture, \"{%s}featureType\" %ns_md)\n featureType.text = \"CityFurniture\"\n featureCount = etree.SubElement(mdcityfurniture, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cityfurnitureCount)\n lods = etree.SubElement(mdcityfurniture, \"{%s}LevelsOfDetail\" %ns_md)\n if lod1cfCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cfCount)\n if lod2cfCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cfCount)\n if lod3cfCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cfCount)\n if lod4cfCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cfCount)\n \n \n if item == \"LandUse\":\n mdlanduse = etree.SubElement(mdCityfeatures, \"{%s}MDlandUse\" %ns_md)\n featureType = etree.SubElement(mdlanduse, \"{%s}featureType\" %ns_md)\n featureType.text = \"LandUse\"\n featureCount = etree.SubElement(mdlanduse, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(landuseCount)\n lods = etree.SubElement(mdlanduse, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0luseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0luseCount)\n if lod1luseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1luseCount)\n if lod2luseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2luseCount)\n if lod3luseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3luseCount)\n if lod4luseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4luseCount)\n \n if item == \"CityObjectGroup\":\n mdcityobjectgroup = etree.SubElement(mdCityfeatures, \"{%s}MDcityObjectGroup\" %ns_md)\n featureType = etree.SubElement(mdcityobjectgroup, \"{%s}featureType\" %ns_md)\n featureType.text = \"CityObjectGroup\"\n featureCount = etree.SubElement(mdcityobjectgroup, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cityobjectgroupCount)\n for cogItem in cogSet:\n mdcogMember = etree.SubElement(mdcityobjectgroup, \"{%s}MDcityObjectGroupMember\" %ns_md)\n if cogItem == \"Vegetation\":\n mdvegetation = etree.SubElement(mdcogMember, \"{%s}MDvegetation\" %ns_md) \n featureType = etree.SubElement(mdvegetation, \"{%s}featureType\" %ns_md)\n featureType.text = \"Vegetation\"\n featureCount = etree.SubElement(mdvegetation, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cogvegCount)\n lods = etree.SubElement(mdvegetation, \"{%s}LevelsOfDetail\" %ns_md)\n if lod1cogvegCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogvegCount)\n if lod2cogvegCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogvegCount)\n if lod3cogvegCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogvegCount)\n if lod4cogvegCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogvegCount)\n plantCovers = etree.SubElement(mdvegetation, \"{%s}plantCovers\" %ns_md)\n plantCovers.text = str(plantcoverCount)\n solitaryVegetationObjects = etree.SubElement(mdvegetation, \"{%s}solitaryVegetationObjects\" %ns_md)\n solitaryVegetationObjects.text = str(svoCount)\n if cogItem == \"LandUse\":\n mdlanduse = etree.SubElement(mdcogMember, \"{%s}MDlandUse\" %ns_md)\n featureType = etree.SubElement(mdlanduse, \"{%s}featureType\" %ns_md)\n featureType.text = \"LandUse\"\n featureCount = etree.SubElement(mdlanduse, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(coglanduseCount)\n lods = etree.SubElement(mdlanduse, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0cogluseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0cogluseCount)\n if lod1cogluseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogluseCount)\n if lod2cogluseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogluseCount)\n if lod3cogluseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogluseCount)\n if lod4cogluseCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogluseCount)\n if cogItem == \"CityFurniture\":\n mdcityfurniture = etree.SubElement(mdcogMember, \"{%s}MDcityFurniture\" %ns_md)\n featureType = etree.SubElement(mdcityfurniture, \"{%s}featureType\" %ns_md)\n featureType.text = \"CityFurniture\"\n featureCount = etree.SubElement(mdcityfurniture, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cogcityfurnitureCount)\n lods = etree.SubElement(mdcityfurniture, \"{%s}LevelsOfDetail\" %ns_md)\n if lod1cogcfCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogcfCount)\n if lod2cogcfCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogcfCount)\n if lod3cogcfCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogcfCount)\n if lod4cogcfCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogcfCount)\n if cogItem == \"Generics\":\n mdgenerics = etree.SubElement(mdcogMember, \"{%s}MDgenerics\" %ns_md)\n featureType = etree.SubElement(mdgenerics, \"{%s}featureType\" %ns_md)\n featureType.text = \"Generics\"\n featureCount = etree.SubElement(mdgenerics, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(coggenericsCount)\n lods = etree.SubElement(mdgenerics, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0coggenCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0coggenCount)\n if lod1coggenCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1coggenCount)\n if lod2coggenCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2coggenCount)\n if lod3coggenCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3coggenCount)\n if lod4coggenCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4coggenCount)\n if cogItem == \"Transportation\":\n mdtransportation = etree.SubElement(mdcogMember, \"{%s}MDtransportation\" %ns_md)\n featureType = etree.SubElement(mdtransportation, \"{%s}featureType\" %ns_md)\n featureType.text = \"Transportation\"\n featureCount = etree.SubElement(mdtransportation, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cogtransportationCount)\n lods = etree.SubElement(mdtransportation, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0cogtranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0cogtranCount)\n if lod1cogtranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogtranCount)\n if lod2cogtranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogtranCount)\n if lod3cogtranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogtranCount)\n if lod4cogtranCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogtranCount)\n roads = etree.SubElement(mdtransportation, \"{%s}roads\" %ns_md)\n roads.text = str(cogroadCount)\n railways = etree.SubElement(mdtransportation, \"{%s}railways\" %ns_md)\n railways.text = str(cograilwayCount)\n tracks = etree.SubElement(mdtransportation, \"{%s}tracks\" %ns_md)\n tracks.text = str(cogtrackCount)\n squares = etree.SubElement(mdtransportation, \"{%s}squares\" %ns_md)\n squares.text = str(cogsquareCount)\n if cogItem == \"WaterBody\":\n mdwaterbody = etree.SubElement(mdcogMember, \"{%s}MDwaterBody\" %ns_md)\n featureType = etree.SubElement(mdwaterbody, \"{%s}featureType\" %ns_md)\n featureType.text = \"WaterBody\"\n featureCount = etree.SubElement(mdwaterbody, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cogwaterCount)\n lods = etree.SubElement(mdwaterbody, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0cogwaterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0cogwaterCount)\n if lod1cogwaterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogwaterCount)\n if lod2cogwaterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogwaterCount)\n if lod3cogwaterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogwaterCount)\n if lod4cogwaterCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogwaterCount)\n if cogItem == \"Tunnel\":\n mdtunnel = etree.SubElement(mdcogMember, \"{%s}MDtunnel\" %ns_md)\n featureType = etree.SubElement(mdtunnel, \"{%s}featureType\" %ns_md)\n featureType.text = \"Tunnel\"\n featureCount = etree.SubElement(mdtunnel, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cogtunnelCount)\n lods = etree.SubElement(mdtunnel, \"{%s}LevelsOfDetail\" %ns_md)\n if lod1cogtunnelCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogtunnelCount)\n if lod2cogtunnelCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogtunnelCount)\n if lod3cogtunnelCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogtunnelCount)\n if lod4cogtunnelCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogtunnelCount)\n tunnelParts = etree.SubElement(mdtunnel, \"{%s}tunnelParts\" %ns_md)\n tunnelParts.text = str(cogtunnelpartsCount)\n tunnelInstallations = etree.SubElement(mdtunnel, \"{%s}tunnelInstallations\" %ns_md)\n tunnelInstallations.text = str(cogtunnelinstallationsCount)\n if cogItem == \"Bridge\":\n mdbridge = etree.SubElement(mdcogMember, \"{%s}MDbridge\" %ns_md)\n featureType = etree.SubElement(mdbridge, \"{%s}featureType\" %ns_md)\n featureType.text = \"Bridge\"\n featureCount = etree.SubElement(mdbridge, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cogbridgeCount)\n lods = etree.SubElement(mdbridge, \"{%s}LevelsOfDetail\" %ns_md)\n if lod1cogbridgeCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogbridgeCount)\n if lod2cogbridgeCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogbridgeCount)\n if lod3cogbridgeCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogbridgeCount)\n if lod4cogbridgeCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogbridgeCount)\n bridgeParts = etree.SubElement(mdbridge, \"{%s}bridgeParts\" %ns_md)\n bridgeParts.text = str(cogbridgepartsCount)\n bridgeInstallations = etree.SubElement(mdbridge, \"{%s}bridgeInstallations\" %ns_md)\n bridgeInstallations.text = str(cogbridgeinstallationsCount)\n bridgeConstructionElements = etree.SubElement(mdbridge, \"{%s}bridgeConstructionElements\" %ns_md)\n bridgeConstructionElements.text = str(cogbridgeconstructionelementsCount)\n if cogItem == \"Building\":\n mdbuilding = etree.SubElement(mdcogMember, \"{%s}MDbuilding\" %ns_md)\n featureType = etree.SubElement(mdbuilding, \"{%s}featureType\" %ns_md)\n featureType.text = \"Building\"\n featureCount = etree.SubElement(mdbuilding, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cogbuildingCount)\n lods = etree.SubElement(mdbuilding, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0cogbldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0cogbldgCount)\n if lod1cogbldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogbldgCount)\n if lod2cogbldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogbldgCount)\n if lod3cogbldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogbldgCount)\n if lod4cogbldgCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogbldgCount)\n buildingParts = etree.SubElement(mdbuilding, \"{%s}buildingParts\" %ns_md)\n buildingParts.text = str(cogbuildingpartsCount)\n buildingInstallations = etree.SubElement(mdbuilding, \"{%s}buildingInstallations\" %ns_md)\n buildingInstallations.text = str(cogbuildinginstallationsCount)\n if cogItem == \"Relief\": \n mdrelief = etree.SubElement(mdcogMember, \"{%s}MDterrain\" %ns_md)\n featureType = etree.SubElement(mdrelief, \"{%s}featureType\" %ns_md)\n featureType.text = \"Relief\"\n featureCount = etree.SubElement(mdrelief, \"{%s}featureCount\" %ns_md)\n featureCount.text = str(cogtinreliefCount)\n lods = etree.SubElement(mdrelief, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0cogtinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0cogtinreliefCount)\n if lod1cogtinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1cogtinreliefCount)\n if lod2cogtinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2cogtinreliefCount)\n if lod3cogtinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3cogtinreliefCount)\n if lod4cogtinreliefCount != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4cogtinreliefCount)\n terrainType = etree.SubElement(mdrelief, \"{%s}terrainType\" %ns_md)\n terrainType.text = \"TINRelief\"\n terrainProperties = etree.SubElement(mdrelief, \"{%s}TerrainProperties\" %ns_md)\n mdTINRelief = etree.SubElement(terrainProperties, \"{%s}MDTINRelief\" %ns_md)\n triangleCount = etree.SubElement(mdTINRelief, \"{%s}triangleCount\" %ns_md)\n triangleCount.text = str(cognumberOfTriangles)\n \n \n lod0total = 0\n lod1total = 0\n lod2total = 0\n lod3total = 0\n lod4total = 0\n \n lod0total = lod0bldgCount + lod0tranCount + lod0waterCount + \\\n lod0tinreliefCount + \\\n lod0genCount + lod0luseCount + \\\n lod0cogbldgCount + lod0cogtranCount + lod0cogwaterCount + \\\n lod0coggenCount + lod0cogluseCount\n \n lod1total = lod1bldgCount + lod1bridgeCount + lod1tunnelCount + \\\n lod1tranCount + lod1vegCount + lod1waterCount + \\\n lod1tinreliefCount + \\\n lod1genCount + lod1cfCount + lod1luseCount + \\\n lod1cogbldgCount + lod1cogbridgeCount + lod1cogtunnelCount + \\\n lod1cogtranCount + lod1cogvegCount + lod1cogwaterCount + \\\n lod1coggenCount + lod1cogcfCount + lod1cogluseCount\n \n lod2total = lod2bldgCount + lod2bridgeCount + lod2tunnelCount+ \\\n lod2tranCount + lod2vegCount + lod2waterCount +\\\n lod2tinreliefCount + \\\n lod2genCount + lod2cfCount + lod2luseCount + \\\n lod2cogbldgCount + lod2cogbridgeCount + lod2cogtunnelCount + \\\n lod2cogtranCount + lod2cogvegCount + lod2cogwaterCount + \\\n lod2coggenCount + lod2cogcfCount + lod2cogluseCount\n \n lod3total = lod3bldgCount + lod3bridgeCount + lod3tunnelCount + \\\n lod3tranCount + lod3vegCount + lod3waterCount + \\\n lod3tinreliefCount + \\\n lod3genCount + lod3cfCount + lod3luseCount + \\\n lod3cogbldgCount + lod3cogbridgeCount + lod3cogtunnelCount + \\\n lod3cogtranCount + lod3cogvegCount + lod3cogwaterCount + \\\n lod3coggenCount + lod3cogcfCount + lod3cogluseCount\n \n lod4total = lod4bldgCount + lod4bridgeCount + lod4tunnelCount + \\\n lod4tranCount + lod4vegCount +lod4waterCount + \\\n lod4tinreliefCount + \\\n lod4genCount + lod4cfCount + lod4luseCount + \\\n lod4cogbldgCount + lod4cogbridgeCount + lod4cogtunnelCount + \\\n lod4cogtranCount + lod4cogvegCount +lod4cogwaterCount + \\\n lod4coggenCount + lod4cogcfCount + lod4cogluseCount\n \n \n # LevelsOfDetail\n lods = etree.SubElement(mdcitymodel, \"{%s}LevelsOfDetail\" %ns_md)\n if lod0total != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"0\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod0total)\n if lod1total != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"1\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod1total)\n if lod2total != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"2\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod2total)\n if lod3total != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"3\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod3total)\n if lod4total != 0:\n lod = etree.SubElement(lods, \"{%s}LevelOfDetail\" %ns_md)\n mdlod = etree.SubElement(lod, \"{%s}lod\" %ns_md)\n mdlod.text = \"4\"\n mdlodcount = etree.SubElement(lod, \"{%s}objectCount\" %ns_md)\n mdlodcount.text = str(lod4total)\n \n \n wf = open(outputfile,'wb')\n citygml = etree.tostring(cityModel, pretty_print=True, xml_declaration=True, encoding='UTF-8')\n wf.write(citygml)\n wf.close()\n\n#-------------start of program-------------------#\n\nargparser = argparse.ArgumentParser(description='******* Metadata Generator for 3D City Models *******')\nargparser.add_argument('-c', '--citygml', help='CityGML format', required=False)\nargparser.add_argument('-i', '--filename', help='CityGML Source input', required=False)\nargs = vars(argparser.parse_args())\n\n#CityGML source\ncitygmlsource = args['filename']\ncitygmlmetadata = argRead(args['citygml'])\nif citygmlsource:\n inputfile = str(citygmlsource)\n\nif citygmlmetadata:\n print (\"\\n ******* Metadata Generation *******\")\n print (\"\\nCityGML input file: \", citygmlsource)\n\n #--------------Output----------------#\n\n outputfile = citygmlsource.split(\".\")[0]+\"_metadata.gml\"\n print (\"\\nMetadata output file: \",outputfile)\n\n start = time.time()\n generatemetadata(inputfile,outputfile)\n end = time.time()\n \n print (\"\\nTime taken for metadata generation: \",end - start, \" sec\")","sub_path":"Code/generateMetadata.py","file_name":"generateMetadata.py","file_ext":"py","file_size_in_byte":90442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"459159396","text":"train_mass = 22680\ntrain_acceleration = 10\ntrain_distance = 100\n\nbomb_mass = 1\n#Converts fahrenheit to celsius\ndef f_to_c(f_temp):\n c_temp = (f_temp - 32 ) * 5/9\n return c_temp\nf100_in_celsius = f_to_c(100)\nprint(f100_in_celsius)\n#Converts celsius to fahrenheit\ndef c_to_f(c_temp):\n f_temp = (c_temp * 9/5 ) + 32\n return f_temp\nc0_in_fahrenheit = c_to_f(0)\nprint(c0_in_fahrenheit)\n#Calculate the force based the mass and acceleration\ndef get_force(mass,acceleration):\n\treturn mass * acceleration\ntrain_force = get_force(train_mass, train_acceleration)\nprint(\"The GE train supplies \" + str(train_force) + \" Newtons of force.\")\n#Defining the laws of energy\ndef get_energy(mass,c=3*10**8):\n\treturn mass * c**2\nbomb_energy = get_energy(bomb_mass)\nprint(\"A 1kg bomb supplies \" + str(bomb_energy) + \" Joules.\")\n#Deterimine the total amount of work\ndef get_work(mass,acceleration,distance):\n work = get_force(mass,acceleration) * distance\n return work\ntrain_work = get_work(train_mass,train_acceleration,train_distance)\nprint(\"The GE train does \" + str(train_work) + \" Joules of work over \" + str(train_distance) + \" meters.\")\n","sub_path":"intensive-python3/unit2w2project.py","file_name":"unit2w2project.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"392875093","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCRUD operation for sensor_type model\r\n\"\"\"\r\nfrom DB.api import database\r\nfrom DB.models import SensorType\r\nfrom DB.api import dbutils as utils\r\n\r\nSRC_EXISTED_FIELD = {\r\n 'id': 'id',\r\n 'type': 'type',\r\n}\r\n\r\n\r\n@database.run_in_session()\r\ndef add_sensor_type(session, src_dic, content={}):\r\n for k, v in SRC_EXISTED_FIELD.items():\r\n content[k] = src_dic.get(v, None)\r\n return utils.add_db_object(session, SensorType, **content)\r\n\r\n","sub_path":"smarthome-web-portal/DB/api/sensor_type.py","file_name":"sensor_type.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"345525818","text":"import os\n\n\nclass cmdparse(object):\n def __init__(self):\n self.commands = []\n self.cmdlist = []\n self.namespace = {}\n self.ntabs = 7\n\n def add_command(self, *command: str, requires_arg: bool = False, help: str = \"\", store: str,\n default: str = \"\", required: bool = False):\n command_arr = [i for i in command]\n cmdstr = \"\"\n for k, v in enumerate(command):\n self.cmdlist.append(v)\n if k < len(command) - 1:\n cmdstr += \"%s, \" % v if not requires_arg else \"%s arg, \" % v\n else:\n cmdstr += \"%s\" % v if not requires_arg else \"%s arg\" % v\n self.commands.append({\"arr\": command_arr, \"req_arg\": requires_arg,\n \"store\": store, \"def\": default, \"required\": required, \"help\": help, \"cmdstr\": cmdstr})\n\n def print_commands(self):\n for i in self.commands:\n print(\"%-40s\" % i[\"cmdstr\"], end=\"\")\n print(i[\"help\"] + \" (Required: \" + str(i[\"required\"]) + \")\")\n if i[\"def\"] != \"\":\n print(\"%40s%s\" % (\"\", \"Default: \" + i[\"def\"]))\n\n def parse(self, args):\n for i in args:\n for cmd in self.commands:\n if i in cmd[\"arr\"] and cmd[\"req_arg\"]:\n self.namespace[cmd[\"store\"]] = args[args.index(i) + 1]\n elif i in cmd[\"arr\"] and not cmd[\"req_arg\"]:\n self.namespace[cmd[\"store\"]] = True\n self.set_defaults()\n return self.namespace\n\n def set_defaults(self):\n for cmd in self.commands:\n store = cmd[\"store\"]\n default = cmd[\"def\"]\n if store not in self.namespace.keys():\n self.namespace[store] = default \\\n if default not in (\"False\", \"True\") \\\n else True if default == \"True\" \\\n else False\n\n\nclass commands(object):\n def __init__(self):\n self.parser = cmdparse()\n self.add_commands()\n\n def parse_commands(self, cmds):\n return self.parser.parse(cmds)\n\n def add_commands(self):\n self.parser.add_command(\"scatter_plot\", help=\"Print a scatter plot\", default=\"scatter.png\",\n requires_arg=False, store=\"scatter\")\n self.parser.add_command(\"save\", help=\"A location for where to save the file\",\n requires_arg=True, store=\"save\", default=os.getcwd() + \"/plots/\")\n self.parser.add_command(\"h\", \"help\", store=\"help\", help=\"Prints this help\", default=\"False\")\n self.parser.add_command(\"v\", \"version\", store=\"version\", help=\"Display the version number\", default=\"False\")\n\n def setargs(self, args, cmds):\n args.scatter = cmds['scatter']\n args.save = cmds['save']\n args.help = cmds['help'] if args.help is not True else args.help\n args.version = cmds['version'] if args.version is not True else args.version\n return args\n","sub_path":"V2V/Software/logger_nRF52840/modules/argumentparsers/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"608075152","text":"import sys\nDEBUG = False\nfor arg in sys.argv:\n if arg == '-v':\n DEBUG = True\n\n#Verbose for Debugging\ndef log(message):\n if DEBUG:\n print(message)\n\n\n\nimport numpy as np\nfrom matplotlib import pyplot as pl\n\n\n# Question 1 Starts here\n\ntrainInput = np.loadtxt(open(\"trainInput.csv\", \"rb\"), delimiter=\",\")\ntrainTarget = np.loadtxt(open(\"trainTarget.csv\", \"rb\"), delimiter=\",\")\n\nlog(trainInput.shape)\nlog(trainTarget.shape)\n\n#Labels are 1 and 0 we can take the sum for frequency 1 labeled data\nlengthOfData = trainTarget.shape[0]\ncountLabel1 = sum(trainTarget)\ncountLabel0 = lengthOfData - countLabel1\n\nprint(\"Output for Question 1\")\nprint(\"\")\nprint(\"Frequency of label 0 : \" + str(countLabel0 / lengthOfData))\nprint(\"Frequency of label 1 : \" + str(countLabel1 / lengthOfData))\nprint(\"\")\n\n#Question 2\nfrom sklearn.decomposition import PCA\n\ndecomp = PCA()\ndecomp.fit(trainInput)\ncount = 0\nlimit = 0.9\nvalue = 0.0\nwhile (value < limit):\n value += decomp.explained_variance_ratio_[count]\n count += 1\n\nlog(value)\nlog(count)\n\nprint(\"The number of Principal Components needed to explain 90% of the variance : \" + str(count))\nresults = np.matmul(trainInput, decomp.components_[:, 0:2])\n\nnew_pca = PCA(n_components=2)\nnew_pca.fit(trainInput)\nresults = new_pca.transform(trainInput)\n\n\n\nc1x = [results[i][0] for i in range(lengthOfData) if trainTarget[i] == 1]\nc2x = [results[i][0] for i in range(lengthOfData) if trainTarget[i] == 0]\nc1y = [results[i][1] for i in range(lengthOfData) if trainTarget[i] == 1]\nc2y = [results[i][1] for i in range(lengthOfData) if trainTarget[i] == 0]\n\n\n\nlog(len(c1x))\nlog(len(c2x))\nlog(len(c1y))\nlog(len(c2y))\nlog(c1x[0:5])\nlog(c2x[0:5])\nlog(c1y[0:5])\nlog(c2y[0:5])\npl.subplot(2, 1, 1)\npl.xlabel(\"Singular Value\")\npl.plot(decomp.explained_variance_)\n#pl.scatter([i for i in range(len(decomp.singular_values_))], decomp.singular_values_)\n\n\npl.subplot(2, 1, 2)\n\npl.scatter(c1x, c1y)\npl.scatter(c2x, c2y)\n\npl.show()\n\n\n#Question 3 (Clustering)\n\n\n#getting Index of first 0\ndef getIndex(label):\n index = 0\n while (trainTarget[index] != label):\n index += 1\n return index\n\nindex0 = getIndex(0)\nindex1 = getIndex(1)\n\nfirst0 = trainInput[index0, :]\nfirst1 = trainInput[index1, :]\n\nlog(\"Testing initial centers\")\nlog(\"index 0 : \" + str(index0))\nlog(\"index 0 : \" + str(index1))\nlog(\"Shapes of centers : \" + str(first0.shape) + \" \" + str(first1.shape))\n\nfrom sklearn.cluster import KMeans\n\ninitial_center = np.vstack(first0, first1)\ncluster = KMeans(n_clusters = 2, init = initial_center).fit(trainInput)\n\n\n\n\n\n","sub_path":"Machine_Learning/final/temp/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"242893106","text":"#!/usr/bin/env python\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\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport re\n\nWORD_PATTERN = re.compile('\\[([^\\]]+)\\]')\n\nCR_PATTERN = re.compile(r\"\\((\\d*),(\\d)*,\\[(\\d*),(\\d*)\\]\\) -> \\((\\d*),(\\d)*,\\[(\\d*),(\\d*)\\]\\), that is: \\\"(.*)\\\" -> \\\"(.*)\\\"\")\n\nSTATE_START, STATE_TEXT, STATE_WORDS, STATE_TREE, STATE_DEPENDENCY, STATE_COREFERENCE = 0, 1, 2, 3, 4, 5\n\n\nclass ParsedSentencesLoader(object):\n\n def parse_bracketed(self, s):\n '''Parse word features [abc=... def = ...]\n Also manages to parse out features that have XML within them\n '''\n word = None\n attrs = {}\n temp = {}\n # Substitute XML tags, to replace them later\n for i, tag in enumerate(re.findall(r\"(<[^<>]+>.*<\\/[^<>]+>)\", s)):\n if '' in tag or '' in tag:\n continue\n temp[\"^^^%d^^^\" % i] = tag\n s = s.replace(tag, \"^^^%d^^^\" % i)\n # Load key-value pairs, substituting as necessary\n for attr, val in re.findall(r\"([^=\\s]*)=([^=\\s]*)\", s):\n if val in temp:\n val = temp[val]\n if attr == 'Text':\n word = val\n else:\n attrs[attr] = val\n return (word, attrs)\n\n\n def __parse_dependency_entry(self, line):\n split_entry = re.split(\"\\(|, \", line[:-1])\n if len(split_entry) == 3:\n rel, left, right = split_entry\n return tuple([rel,left,right])\n else:\n return None\n\n def parse_parser_results(self, text):\n results = {\"sentences\": []}\n state = STATE_START\n for line in text.split(\"\\n\"):\n line = line.strip()\n if len(line) == 0:\n continue\n\n if line.startswith(\"Sentence #\"):\n sentence = {'words': [], 'parsetree': [], 'dependencies': []}\n results[\"sentences\"].append(sentence)\n state = STATE_TEXT\n\n elif state == STATE_TEXT:\n sentence['text'] = line\n state = STATE_WORDS\n\n elif state == STATE_WORDS:\n for s in WORD_PATTERN.findall(line):\n sentence['words'].append(self.parse_bracketed(s))\n state = STATE_TREE\n\n elif state == STATE_TREE:\n if line.startswith('root'):\n state = STATE_DEPENDENCY\n sentence['parsetree'] = \" \".join(sentence['parsetree'])\n sentence['dependencies'].append(self.__parse_dependency_entry(line))\n else:\n sentence['parsetree'].append(line)\n\n elif state == STATE_DEPENDENCY:\n entry = self.__parse_dependency_entry(line)\n if entry == None:\n state = STATE_COREFERENCE\n else:\n sentence['dependencies'].append(entry)\n\n elif state == STATE_COREFERENCE:\n if \"Coreference set\" in line:\n if 'coref' not in results:\n results['coref'] = []\n coref_set = []\n results['coref'].append(coref_set)\n else:\n for src_i, src_pos, src_l, src_r, sink_i, sink_pos, sink_l, sink_r, src_word, sink_word in CR_PATTERN.findall(line):\n src_i, src_pos, src_l, src_r = int(src_i)-1, int(src_pos)-1, int(src_l)-1, int(src_r)-1\n sink_i, sink_pos, sink_l, sink_r = int(sink_i)-1, int(sink_pos)-1, int(sink_l)-1, int(sink_r)-1\n coref_set.append(((src_word, src_i, src_pos, src_l, src_r), (sink_word, sink_i, sink_pos, sink_l, sink_r)))\n\n return results\n\n def load(self, sentence):\n return self.parse_parser_results(sentence)","sub_path":"parsedSentencesLoader.py","file_name":"parsedSentencesLoader.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"220796564","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport pdb\nimport time\nimport argparse\nimport sys\nfrom matplotlib import pyplot as plt\nimport matplotlib as mpl\nimport os\nimport numpy as np\nmpl.use('Agg')\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ntransform = transforms.Compose([transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))]\n )\n\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=32,\n shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4,\n shuffle=False, num_workers=2)\n\nclasses = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n\nclass Net(nn.Module):\n\n def __init__(self,\n lr = 0.001,\n momentum=0.9):\n \n super(Net,self).__init__()\n\n self.conv_block = nn.Sequential(\n nn.Conv2d(3,64,3,1,1),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.Conv2d(64,64,3,1,1),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2,stride=2),\n nn.Conv2d(64,128,3,1,1),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.Conv2d(128,128,3,1,1),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2,stride=2),\n nn.Conv2d(128,256,3,1,1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256,256,3,1,1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Conv2d(256,256,3,1,1),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2,stride=2),\n nn.Conv2d(256,512,3,1,1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512,512,3,1,1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512,512,3,1,1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2,stride=2),\n nn.Conv2d(512,512,3,1,1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512,512,3,1,1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Conv2d(512,512,3,1,1),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2,stride=2),\n )\n\n self.fc_block = nn.Sequential(\n nn.Linear(512,256),\n nn.ReLU(),\n nn.Linear(256,64),\n nn.ReLU(),\n nn.Linear(64,10),\n )\n\n self.criterion = nn.CrossEntropyLoss()\n self.optimizer = optim.SGD(self.parameters(), \n lr=lr, \n momentum=momentum)\n\n def forward(self, x):\n \n x = self.conv_block(x)\n x = x.view(-1, 512)\n x = self.fc_block(x)\n \n return x\n\n def save_model(self, path):\n torch.save(self.state_dict(),path)\n\n def load_model(self, path):\n self.load_state_dict(torch.load(path))\n\n\n\ndef train_network(net,num_epochs,path):\n\n epoch_loss_arr = []\n test_accuracy_arr = []\n report_loss_iter = 2000\n for epoch in range(num_epochs): # loop over the dataset multiple times\n \n running_loss = 0.0\n # pdb.set_trace()\n iterator = iter(trainloader)\n net = net.train()\n epoch_loss = 0.0\n for i, data in enumerate(trainloader, 0):\n # for i, data in enumerate(trial_dataloader):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data[0].to(device), data[1].to(device)\n \n # zero the parameter gradients\n net.optimizer.zero_grad()\n # forward + backward + optimize\n outputs = net(inputs)\n loss = net.criterion(outputs, labels)\n loss.backward()\n net.optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n epoch_loss = running_loss*1.0\n # if i % 2000 == 1999: # print every 2000 mini-batches\n if i%report_loss_iter==(report_loss_iter-1):\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / report_loss_iter))\n running_loss = 0.0\n epoch_loss_arr.append(epoch_loss/report_loss_iter)\n epoch_loss = 0.0\n if((epoch+1)%1==0):\n net.save_model(path)\n test_accuracy_arr.append(test_network(net))\n net = net.train()\n np.save(\"train_loss_arr\",epoch_loss_arr)\n np.save(\"test_accuracy_arr\",test_accuracy_arr)\n print('Finished Training')\n return epoch_loss_arr, test_accuracy_arr\n\ndef test_network(net):\n correct = 0\n total = 0\n net = net.eval()\n with torch.no_grad():\n for data in testloader:\n # for data in trial_dataloader:\n images, labels = data[0].to(device), data[1].to(device)\n outputs = net(images)\n _, predicted = torch.max(outputs.data,1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n print(\"Accuracy on 10000 test images: {} %%\".format(100*correct/total))\n return correct/total\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--lr', dest='lr', type=float, default=1e-3, help=\"learning rate\")\n parser.add_argument('--momentum', dest='momentum', type=float, default=0.9, help=\"learning rate\")\n parser.add_argument('--epochs', dest='epochs',type=int, default=50,help=\"learning_rate\")\n return parser.parse_args()\n\ndef plot_props(data,prop_name,plot_save_path):\n fig = plt.figure(figsize=(16,9))\n plt.plot(data)\n plt.ylabel(prop_name)\n plt.savefig(os.path.join(plot_save_path,prop_name+\".jpg\"))\n plt.close()\n\ndef main(args):\n args = parse_args()\n lr = args.lr\n num_epochs = args.epochs\n momentum = args.momentum\n path = \"./cifar_net_lr_{}_momentum_{}.pth\".format(lr,momentum)\n plot_path = './'\n print(\"device: {}\".format(device))\n net = Net(lr,momentum)\n net.to(device)\n start_time = time.time()\n train_loss_arr, test_accuracy_arr = train_network(net,num_epochs,path)\n plot_props(train_loss_arr, \"train_loss_lr_{}_momentum_{}\".format(lr,momentum), plot_path)\n plot_props(test_accuracy_arr, \"test_acc_lr_{}_momentum_{}\".format(lr,momentum), plot_path)\n\n print(\"Time taken train for {} epochs: {}\".format(num_epochs, time.time()-start_time))\n test_acc = test_network(net)\n\n\nif __name__==\"__main__\":\n main(sys.argv)\n","sub_path":"HW1/code/p2_v2.py","file_name":"p2_v2.py","file_ext":"py","file_size_in_byte":8891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"6236600","text":"import cv2\nimport numpy as np \nimport sqlite3\n\nfaceDetect = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\ncam = cv2.VideoCapture(0)\ncam.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH,280)\ncam.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT,240)\nid = raw_input('enter user id: ')\nname = raw_input(\"enter user name: \")\nlocal = raw_input(\"enter user local: \")\ncmd = sqlite3.connect(\"FaceBase.db\")\nv = (id, name,local)\nins = \"insert into People values(?,?,?);\"\ncmd.execute(ins, v)\nsampleNum = 0\ncmd.commit()\ncmd.close()\nwhile(True):\n\tret,img=cam.read()\n\tgray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\tfaces=faceDetect.detectMultiScale(gray,1.3,5)\n\tfor(x,y,w,h) in faces:\n\t\tsampleNum=sampleNum+1\n\t\tcv2.imwrite(\"dataSet/User.\" + str(id)+\".\"+str(sampleNum)+\".jpg\",gray[y:y+h,x:x+w])\n\t\tcv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)\n\tcv2.imshow(\"Face\",img)\n\tcv2.waitKey(1)\n\tif(sampleNum > 20):\n\t\t\tbreak \n\n \ncam.release()\ncv2.destroyAllWindows()","sub_path":"IntroToPyCV.py","file_name":"IntroToPyCV.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"279509390","text":"# from urllib.request import urlopen as uReq\nfrom urllib.request import Request, urlopen\nfrom bs4 import BeautifulSoup as soup\nimport datetime\nimport csv\n\n# url = 'https://www.google.com/search?rlz=1C5CHFA_enUS838US838&ei=8yYyXZ7NJIqUsgWJ7qzoDQ&q=voice+assistant+development&oq=voice+&gs_l=psy-ab.1.1.35i39i19l2j0i203l6.7055.8311..9688...0.0..0.294.1355.13j1j1......0....1..gws-wiz.uC9bSLf8SP8'\n# search_url_keyword = input('enter the keyword: ')\n# url = 'https://www.google.co.jp/search?hl=ja&num=10&q=' + search_url_keyword\n\n# data = uReq('https://www.google.com/search?hl=ja&num=100&q={}'.format(search_url_keyword))\n\n# data = uReq(url)\n# html_page = data.read()\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n\nreq = Request('https://www.google.com/search?q=voice+assistant+development&num=5&hl=en', headers=headers)\nhtml_page = urlopen(req).read()\npage_soup = soup(html_page, 'lxml')\n\n\n# now = datetime.datetime.now()\n# file_name = 'product'\n# f = open('[' + file_name + ']' + '{0:%Y-%m%d-%H%M}'.format(now) + '.csv', 'w', encoding='UTF-8')\n# headers = 'site_name, url_name, discription\\n'\n# f.write(headers)\n\n\n# git each product\ncontainer = page_soup.findAll('div', {'class': 'CAEQAA'})\n\nfor each in container:\n\n site_name_container = each.findAll('h3', {'class', 'LC20lb'})\n site_name = site_name_container[0].text\n\n url_container = each.findAll('cite', {'class':'iUh30'})\n url_name = url_container[0].text\n\n discription_container = each.findAll('span', {'class':'st'})\n discription = discription_container[0].text.strip()\n\n print('site_name: ' + site_name)\n print('url_name: ' + url_name)\n print('discription: ' + discription)\n\n # f.write(site_name + ',' + url_name.replace(',', '|') + ',' + discription + '\\n')\n\n# f.close()\n\n\n","sub_path":"SEO-Tool/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":1866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"263531196","text":"#Tyler Dockery for CSC121 5-19-2020 twdockery@waketech.edu\n'''\nWrite a program to do the following. Ask the customer to enter “S” for standard shipping or “E” for express shipping. Also ask the user to enter the weight of the package in pounds. Calculate and display shipping charge.\n''' \nprint('Thank you for choosing Dockery Shipping')\n\n# Ask for standard or express shipping\nshipment = input(\"Enter S for standard shipping, E for express \")\nif shipment.lower() != \"s\" and shipment.lower() != \"e\": # just to stop bad answers\n print(\"We don't have that kind of shipping. Please start again.\")\n charge = 0\n\n# Calculate the cost based on weight\nelse:\n weight = float(input(\"Enter weight (lbs): \"))\n if shipment.lower() == \"s\":\n if weight <= 4:\n charge = weight * 1.05\n elif 4 < weight <= 8:\n charge = weight * 0.95\n elif 8 < weight <= 15:\n charge = weight * 0.85\n else:\n charge = weight * 0.8\n if shipment.lower() == \"e\":\n if weight <= 2:\n charge = weight * 3.25\n elif 2 < weight <= 5:\n charge = weight * 2.95\n elif 5 < weight <= 10:\n charge = weight * 2.75\n else:\n charge = weight * 2.55\n# Output the cost\nprint(f'Shipping charge: ${charge:.2f} (${charge})')","sub_path":"DOCKERY-Lab03P3-CSC121.py","file_name":"DOCKERY-Lab03P3-CSC121.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"306086700","text":"import jieba\nimport gensim\nimport pickle\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\nfrom sklearn.cluster import DBSCAN\nplt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体:解决plot不能显示中文问题\nplt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题\n\n#从gensim以中文维基百科训练好的word2vec词向量抽取出来作为relate.csv的词向量\ndef get_save_vector():\n with open('./data/relate.csv', 'r',encoding='utf-8') as f:\n text = f.read().split('\\n')\n text = [list(jieba.cut(i)) for i in text]\n tmp = []\n for i in text:\n tmp.extend(i)\n del text\n tmp = set(tmp)\n model = gensim.models.KeyedVectors.load_word2vec_format('./store/w2v_vector.bin', binary = False)\n wordlist = []\n vectorlist = []\n for item in tmp:\n try:\n vector=model.get_vector(item)\n except:\n continue\n wordlist.append(item)\n vectorlist.append(vector)\n embending = dict(zip(wordlist, vectorlist))\n del wordlist, vectorlist\n with open('./store/word_embending', 'wb') as f:\n pickle.dump(embending, f)\n\ndef set_list(textlist):\n text = list(set(textlist))\n text.sort(key=textlist.index)\n return text\n\ndef relate_deal():\n with open('./store/word_embending', 'rb') as f:\n embending = pickle.load(f)\n wordlist = list(embending.keys())\n with open('./data/stopword.txt', 'r', encoding='utf-8') as f:\n stopwords = f.read().split('\\n')\n with open('./data/relate.csv', 'r', encoding='utf-8') as f:\n text = f.read().replace(' ','').split('\\n')\n text = [i for i in text if len(i) < 9]\n text = [list(jieba.cut(item)) for item in text]\n sentence = [' '.join([j for j in i if (j not in stopwords)]) for i in text]\n sentence = set_list(sentence)\n vector = [[j for j in i.split(' ') if (j in wordlist)] for i in sentence]\n for i, val in enumerate(vector):\n if vector[i] == []:\n del sentence[i],vector[i]\n sentence = [i.replace(' ','') for i in sentence]\n with open('./store/sentence', 'wb') as f:\n pickle.dump(sentence, f)\n with open('./store/vector', 'wb') as f:\n pickle.dump(vector, f)\n\ndef get_save_sentence_embending():\n with open('./store/word_embending', 'rb') as f:\n embending = pickle.load(f)\n with open('./store/vector', 'rb') as f:\n textvector = pickle.load(f)\n textvector = [np.array([embending[j] for j in i]) for i in textvector]\n textvector = [np.mean(i, axis=0) for i in textvector]\n low_dim_embs = TSNE(learning_rate=100).fit_transform(textvector)\n with open('./store/low_dim_word_embending', 'wb') as f:\n pickle.dump(low_dim_embs, f)\n\ndef draw():\n with open('./store/sentence', 'rb') as f:\n textsentence = pickle.load(f)\n with open('./store/low_dim_word_embending', 'rb') as f:\n low_dim_embs = pickle.load(f)\n figure = plt.figure(figsize=(100,100))\n db = DBSCAN(eps=3, min_samples=12).fit_predict(low_dim_embs)\n x=low_dim_embs[:, 0]\n y=low_dim_embs[:, 1]\n plt.scatter(x, y, c=db)\n for i, word in enumerate(textsentence):\n x, y = low_dim_embs[i, :]\n plt.annotate(word, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom')\n plt.tight_layout(pad=0.4, w_pad=3.0, h_pad=3.0)\n figure.savefig('./picture/log')\n plt.close(figure)\n\ndef show():\n img = Image.open('./picture/log.png')\n img.show()\n\n#如果你有训练好的中文维基百科的word2vec词向量,放到store文件夹,命名为w2v_vector.bin,去掉注释,没有的话别去掉\n#get_save_vector()\n\nrelate_deal()\nget_save_sentence_embending()\ndraw()\nshow()","sub_path":"word_cluster.py","file_name":"word_cluster.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"366705342","text":"# -*- coding: utf-8 -*-\nfrom pila import *\nclass Pelicula:\n \n def __init__(self,nombre,genero,año):\n self.n = nombre\n self.g = genero\n self.a = año\n\n \n def getNombre(self):\n return self.n \n \n def getGenero(self):\n return self.g\n \n def getAño(self):\n return self.a\n\npelicula1 = Pelicula(\"transformers\",\"ciencia ficcion\", 2007) \npelicula2 = Pelicula(\"Al filo del mañana\",\"ciencia Ficcion\",2014)\npelicula3 = Pelicula(\"Spiderman\", \"Accion\",2017)\npelicula4 = Pelicula(\"Avengers\",\"Accion\",2012)\npelicula5 = Pelicula(\"Avengers 2\", \"Accion\",2015)\npelicula6 = Pelicula(\"Mi Villano Favorito 3\" ,\"Infantil\",2017)\npelicula7 = Pelicula(\"Ex MAchina\",\"ciencia Ficcion\",2011)\n\npila = Pila()\n\nprint(\"a continuacion se agregaran a la pila las peliculas \"+ \"\\n\")\n\npila.apilar(pelicula1.getNombre())\npila.apilar(pelicula2.getNombre())\npila.apilar(pelicula3.getNombre())\npila.apilar(pelicula4.getNombre())\npila.apilar(pelicula5.getNombre())\npila.apilar(pelicula6.getNombre())\npila.apilar(pelicula7.getNombre())\n\nprint(\"los elementos de la pila son los siguientes :\"+ \"\\n\")\nprint(pila.items)\nprint(\"\\n\")\nprint(\"A continuacion se Desapilaran los elementos :\"+ \"\\n\") \n \nwhile pila.es_vacia() != True:\n print ( pila.desapilar())\nprint(\"\\n\")\nprint(\"la pila esta vacia \"+ \"\\n\")\nprint(pila.items)\n","sub_path":"pila_colas-master/Peliculas.py","file_name":"Peliculas.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"285019690","text":"import copy\nfrom functools import wraps\nfrom collections import UserList\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom water_sort_puzzle.exceptions import VialCannotAcceptThisException,\\\n VialIsFullException, \\\n NoEnoughtColorException\n\n\n# defination of colors\nLG = LIGHTGREEN = 'LIGHTGREEN'\nGY = GRAY = 'GRAY'\nOR = ORANGE = 'ORANGE'\nYE = YELLOW = 'YELLOW'\nRE = RED = 'RED'\nPU = PURPLE = 'PURPLE'\nGR = GREEN = 'GREEN'\nPI = PINK = 'PINK'\nBR = BROWN = 'BROWN'\nDG = DARKGREEN = 'DARKGREEN'\nBL = BLUE = 'BLUE'\nLB = LIGHTBLUE = 'SKYBLUE'\nBK = BLACK = 'BLACK'\n\ncolors = {\n 'LIGHTGREEN': '#79DF83',\n 'GRAY': '#55585E',\n 'ORANGE' : '#E88A45',\n 'YELLOW' : '#FDEA68',\n 'RED': '#B22923',\n 'PURPLE': '#571F86',\n 'GREEN': '#74931F',\n 'PINK': '#DF5D73',\n 'BROWN': '#6A3D11',\n 'DARKGREEN': '#20562B',\n 'BLUE': '#2920BC',\n 'LIGHTBLUE': '#5D9EEA',\n 'BLACK': '#03071e',\n '#a100f2': '#a100f2',\n '#6a00f4': '#6a00f4',\n}\n\ndef validate_path(path):\n if path is not None:\n assert isinstance(path, list), 'Path must be list type!'\n for i in path:\n assert isinstance(i, tuple), 'All path members must be tuples!'\n assert len(i) == 2, 'All path tuples must be length of 2!'\n\n\nclass Path(UserList):\n def __init__(self, initlist=None):\n validate_path(initlist)\n super().__init__(initlist)\n\n def __str__(self):\n if len(self) == 0:\n return super().__str__()\n\n result = []\n i_prev = None\n for i in self:\n if i_prev != i:\n result.append(f'{i[0] + 1}->{i[1] + 1}')\n i_prev = i\n return ', '.join(result)\n\n\nclass Vial(UserList):\n\n def __init__(self, max_size, initlist=None):\n check_vial_arguments_meet_requirements(max_size, initlist)\n\n super().__init__(initlist)\n self.max_size = max_size\n\n def is_full(self):\n if len(self.data) < self.max_size:\n return False\n else:\n return True\n\n def is_empty(self):\n if len(self.data) == 0:\n return True\n else:\n return False\n\n def can_accept(self, item):\n if self.is_empty():\n return True\n if not self.is_full():\n if item == self.data[-1]:\n return True\n return False\n\n def __raise_exception_if_full(self):\n if self.is_full():\n raise VialIsFullException('Vial is full and cannot accept more items')\n\n def append(self, item):\n self.__raise_exception_if_full()\n super().append(item)\n\n def count_unique(self):\n return len(set(self))\n\n\ndef check_vial_arguments_meet_requirements(max_size, initlist):\n assert max_size > 0, 'max_size must be greater than zero!'\n assert isinstance(max_size, int), 'max_size must be integer!'\n\n if initlist is not None:\n assert len(initlist) <= max_size, 'initlist size cannot be greater than max_size!'\n\n\ndef log_move(method):\n @wraps(method)\n def _impl(self, *method_args, **method_kwargs):\n method_output = method(self, *method_args, **method_kwargs)\n self.path.append(tuple(method_args))\n return method_output\n return _impl\n\n\ndef reset_path(method):\n @wraps(method)\n def _impl(self, *method_args, **method_kwargs):\n method_output = method(self, *method_args, **method_kwargs)\n self.path = Path()\n return method_output\n return _impl\n\n\ndef check_type_list_of_lists(input_list):\n if not isinstance(input_list, list):\n return False\n for i in input_list:\n if not isinstance(i, list):\n return False\n return True\n\n\ndef check_type_list_of_vials(input_list):\n if not isinstance(input_list, list):\n return False\n for i in input_list:\n if not isinstance(i, Vial):\n return False\n return True\n\n\ndef raise_exception_if_not_list_of_lists(input_list):\n if not check_type_list_of_lists(input_list):\n raise TypeError(f'expected list of lists, got {type(input_list)}')\n\n\ndef get_max_internal_list_size(list_of_lists):\n n = 0\n for l in list_of_lists:\n if len(l) > n:\n n = len(l)\n return n\n\n\ndef make_vials_from_lists(input_list):\n raise_exception_if_not_list_of_lists(input_list)\n max_size = get_max_internal_list_size(input_list)\n if max_size < 2:\n max_size = 2\n result = []\n\n for i in input_list:\n vial = Vial(max_size, i)\n result.append(vial)\n return result\n\n\nclass VialBoard(UserList):\n\n path = Path()\n\n @reset_path\n def __init__(self, vial_list):\n if check_type_list_of_lists(vial_list):\n vial_list = make_vials_from_lists(vial_list)\n\n check_board_arguments_meet_requirements(vial_list)\n\n super().__init__(vial_list)\n self.init_data = copy.deepcopy(self.data)\n self.gen = 0\n\n def __str__(self):\n result = ''\n size = self[0].max_size\n for line in range(size-1, -1, -1):\n for vial in self:\n if len(vial) > line:\n result += f'|{vial[line]:->3}|'\n else:\n result += f'|---|'\n result += '\\n'\n return result\n\n def can_move(self, donor_index, recipient_index):\n if donor_index == recipient_index:\n return False\n\n donor_vial = self[donor_index]\n recipient_vial = self[recipient_index]\n\n if donor_vial.is_empty():\n return False\n elif recipient_vial.can_accept(donor_vial[-1]):\n return True\n return False\n\n def get_set_of_items(self):\n s = set()\n for vial in self:\n s = s.union(vial)\n return s\n\n @log_move\n def __make_simple_move(self, donor_index, recipient_index):\n item = self[donor_index].pop()\n self[recipient_index].append(item)\n\n def move(self, donor_index, recipient_index):\n while self.can_move(donor_index, recipient_index):\n self.__make_simple_move(donor_index, recipient_index)\n\n @reset_path\n def restart_game(self):\n self.data = copy.deepcopy(self.init_data)\n\n def solved(self):\n game_items = set()\n for vial in self:\n if not vial.is_empty():\n if vial.count_unique() > 1:\n return False\n elif vial[0] in game_items:\n return False\n game_items.add(vial[0])\n return True\n\n def __get_last_step(self):\n return self.path[-1]\n\n def __get_last_step_size(self):\n i = 0\n while self.path[-i - 1] == self.__get_last_step():\n i += 1\n if i == len(self.path):\n break\n return i\n\n def step_back(self):\n n = self.__get_last_step_size()\n for i in range(n):\n step = self.path.pop()\n item = self[step[1]].pop()\n self[step[0]].append(item)\n\n def clone(self):\n board_data = copy.deepcopy(self.data)\n board_path = copy.deepcopy(self.path)\n board_init_data = copy.deepcopy(self.init_data)\n\n new_board = VialBoard(board_data)\n new_board.path = board_path\n new_board.init_data = board_init_data\n\n new_board.gen = self.gen + 1\n\n return new_board\n\n\ndef check_board_arguments_meet_requirements(vial_list):\n assert len(vial_list) > 1, 'VialBoard should contain at least 2 Vials!'\n first_vial = vial_list[0]\n for i in vial_list:\n assert isinstance(i, Vial), 'VialBoard elements all must be instances of Vial class!'\n assert first_vial.max_size == i.max_size\n\n\nclass PlotableVialBoard(VialBoard):\n \n \n def _get_color(self, n):\n if n in self.dict_n2c.keys():\n return self.dict_n2c[n]\n else:\n for i in self.colors.keys():\n if i not in self.dict_n2c.values():\n self.dict_n2c[n] = i\n self.dict_c2n[i] = n\n return i\n raise NoEnoughtColorException()\n\n def _get_num(self, c):\n if isinstance(c, int):\n return c\n if c in self.dict_c2n.keys():\n return self.dict_c2n[c]\n else:\n n = len(self.dict_c2n.keys())\n self.dict_c2n[c] = n\n self.dict_n2c[n] = c\n\n return n\n\n def __init__(self, vial_list_color):\n self.dict_n2c = {}\n self.dict_c2n = {}\n self.colors = colors\n\n via_list_num = []\n for l in vial_list_color:\n temp_list = []\n for c in l:\n temp_list.append(self._get_num(c))\n via_list_num.append(temp_list)\n\n super().__init__(via_list_num)\n\n def clone(self):\n board_dict_n2c = copy.deepcopy(self.dict_n2c)\n board_dict_c2n = copy.deepcopy(self.dict_c2n)\n board_colors = copy.deepcopy(self.colors)\n \n new_board = super().clone()\n new_board.__class__ = PlotableVialBoard\n\n\n new_board.dict_n2c = board_dict_n2c\n new_board.dict_c2n = board_dict_c2n\n new_board.colors = board_colors\n\n return new_board\n \n def show(self, scale=0.5):\n \n via_list_c = []\n for l in self:\n temp_list = []\n for n in l:\n temp_list.append(self._get_color(n))\n via_list_c.append(temp_list)\n\n bottles = via_list_c\n # calc the arrangement of bottles\n if len(bottles) > 5:\n row = 2\n column = int((len(bottles) + 1) / 2)\n else:\n row = 1\n column = len(bottles)\n \n # calc the height of bottles\n height_bottle = 4\n \n # generate bottles\n fig, axs = plt.subplots(row, column, figsize=(column * scale, row * height_bottle * scale))\n \n # draw water in each bottle\n for n, axn in enumerate(axs.flat):\n axn.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)\n \n # delete this bottle if it not exist\n if n >= len(bottles): \n axn.spines['top'].set_color('none')\n axn.spines['bottom'].set_color('none')\n axn.spines['left'].set_color('none')\n axn.spines['right'].set_color('none')\n continue\n \n # draw water\n for height, water in enumerate(bottles[n]):\n axn.add_patch(\n patches.Rectangle(\n (0, height / (height_bottle+0.5)), # (x,y) of rec\n 1, # width of \n 1 / (height_bottle+0.5), # height of rec\n color = water\n )\n )\n plt.show()","sub_path":"water_sort_puzzle/game_objects.py","file_name":"game_objects.py","file_ext":"py","file_size_in_byte":10926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"2440417","text":"import os, hashlib, argparse, hmac\n\nclass BaseCipher(object):\n LIBRARY = True\n CACHE = {}\n def __init__(self, key, ota=False):\n if self.KEY_LENGTH > 0:\n self.key = self.CACHE.get(b'key'+key)\n if self.key is None:\n keybuf = []\n while len(b''.join(keybuf)) < self.KEY_LENGTH:\n keybuf.append(hashlib.md5((keybuf[-1] if keybuf else b'') + key).digest())\n self.key = self.CACHE[b'key'+key] = b''.join(keybuf)[:self.KEY_LENGTH]\n else:\n self.key = key\n self.ota = ota\n self.iv = None\n def setup_iv(self, iv=None):\n self.iv = os.urandom(self.IV_LENGTH) if iv is None else iv\n self.setup()\n def decrypt(self, s):\n return self.cipher.decrypt(s)\n def encrypt(self, s):\n return self.cipher.encrypt(s)\n def patch_ota_reader(self, reader):\n chunk_id = 0\n async def patched_read():\n nonlocal chunk_id\n try:\n data_len = int.from_bytes(await reader.readexactly(2), 'big')\n except Exception:\n return None\n checksum = await reader.readexactly(10)\n data = await reader.readexactly(data_len)\n checksum_server = hmac.new(self.iv+chunk_id.to_bytes(4, 'big'), data, 'sha1').digest()\n assert checksum_server[:10] == checksum\n chunk_id += 1\n return data\n reader.read_ = patched_read\n def patch_ota_writer(self, writer):\n chunk_id = 0\n write = writer.write\n def patched_write(data):\n nonlocal chunk_id\n if not data: return\n checksum = hmac.new(self.iv+chunk_id.to_bytes(4, 'big'), data, 'sha1').digest()\n chunk_id += 1\n return write(len(data).to_bytes(2, 'big') + checksum[:10] + data)\n writer.write = patched_write\n\nclass RC4_Cipher(BaseCipher):\n KEY_LENGTH = 16\n IV_LENGTH = 0\n def setup(self):\n from Crypto.Cipher import ARC4\n self.cipher = ARC4.new(self.key)\n\nclass RC4_MD5_Cipher(RC4_Cipher):\n IV_LENGTH = 16\n def setup(self):\n self.key = hashlib.md5(self.key + self.iv).digest()\n RC4_Cipher.setup(self)\n\nclass ChaCha20_Cipher(BaseCipher):\n KEY_LENGTH = 32\n IV_LENGTH = 8\n def setup(self):\n from Crypto.Cipher import ChaCha20\n self.cipher = ChaCha20.new(key=self.key, nonce=self.iv)\n\nclass Salsa20_Cipher(BaseCipher):\n KEY_LENGTH = 32\n IV_LENGTH = 8\n def setup(self):\n from Crypto.Cipher import Salsa20\n self.cipher = Salsa20.new(key=self.key, nonce=self.iv)\n\nclass AES_256_CFB_Cipher(BaseCipher):\n KEY_LENGTH = 32\n IV_LENGTH = 16\n SEGMENT_SIZE = 128\n def setup(self):\n from Crypto.Cipher import AES\n self.cipher = AES.new(self.key, AES.MODE_CFB, iv=self.iv, segment_size=self.SEGMENT_SIZE)\n\nclass AES_128_CFB_Cipher(AES_256_CFB_Cipher):\n KEY_LENGTH = 16\n\nclass AES_192_CFB_Cipher(AES_256_CFB_Cipher):\n KEY_LENGTH = 24\n\nclass AES_256_CFB8_Cipher(AES_256_CFB_Cipher):\n SEGMENT_SIZE = 8\n\nclass AES_192_CFB8_Cipher(AES_256_CFB8_Cipher):\n KEY_LENGTH = 24\n\nclass AES_128_CFB8_Cipher(AES_256_CFB8_Cipher):\n KEY_LENGTH = 16\n\nclass BF_CFB_Cipher(BaseCipher):\n KEY_LENGTH = 16\n IV_LENGTH = 8\n def setup(self):\n from Crypto.Cipher import Blowfish\n self.cipher = Blowfish.new(self.key, Blowfish.MODE_CFB, iv=self.iv, segment_size=64)\n\nclass CAST5_CFB_Cipher(BaseCipher):\n KEY_LENGTH = 16\n IV_LENGTH = 8\n def setup(self):\n from Crypto.Cipher import CAST\n self.cipher = CAST.new(self.key, CAST.MODE_CFB, iv=self.iv, segment_size=64)\n\nclass DES_CFB_Cipher(BaseCipher):\n KEY_LENGTH = 8\n IV_LENGTH = 8\n def setup(self):\n from Crypto.Cipher import DES\n self.cipher = DES.new(self.key, DES.MODE_CFB, iv=self.iv, segment_size=64)\n\nMAP = {name[:-7].replace('_', '-').lower(): cls for name, cls in globals().items() if name.endswith('_Cipher')}\n\ndef get_cipher(cipher_key):\n from pproxy.cipherpy import MAP as MAP2\n CIPHER_MAP = dict(list(MAP.items())+list(MAP2.items()))\n cipher, _, key = cipher_key.partition(':')\n cipher_name, ota, _ = cipher.partition('!')\n if not key:\n raise argparse.ArgumentTypeError('empty key')\n if cipher_name not in CIPHER_MAP:\n raise argparse.ArgumentTypeError(f'existing ciphers: {list(sorted(CIPHER_MAP.keys()))}')\n cipher, key, ota = CIPHER_MAP[cipher_name], key.encode(), bool(ota) if ota else False\n if cipher.LIBRARY:\n try:\n assert __import__('Crypto').version_info >= (3, 4)\n except Exception:\n if cipher_name+'-py' in CIPHER_MAP:\n cipher = CIPHER_MAP[cipher_name+'-py']\n print(f'Switch to python cipher [{cipher_name}-py]')\n else:\n raise argparse.ArgumentTypeError(f'this cipher needs library: \"pip3 install pycryptodome\"')\n def apply_cipher(reader, writer):\n reader_cipher, writer_cipher = cipher(key, ota=ota), cipher(key, ota=ota)\n reader_cipher._buffer = b''\n def feed_data(s, o=reader.feed_data):\n if not reader_cipher.iv:\n s = reader_cipher._buffer + s\n if len(s) >= reader_cipher.IV_LENGTH:\n reader_cipher.setup_iv(s[:reader_cipher.IV_LENGTH])\n o(reader_cipher.decrypt(s[reader_cipher.IV_LENGTH:]))\n else:\n reader_cipher._buffer = s\n else:\n o(reader_cipher.decrypt(s))\n def write(s, o=writer.write):\n if not s:\n return\n if not writer_cipher.iv:\n writer_cipher.setup_iv()\n o(writer_cipher.iv)\n return o(writer_cipher.encrypt(s))\n reader.feed_data = feed_data\n writer.write = write\n return reader_cipher, writer_cipher\n apply_cipher.ota = ota\n return apply_cipher\n\n","sub_path":"pproxy/cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":5978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"614129167","text":"import time\r\nimport threading\r\nfrom threading import *\r\nd = dict()\r\ndef create(key,values,timeout=0):\r\n\tif key in d.keys():\r\n\t\tprint(\"error: This key is already exists\")\r\n\telse:\r\n\t\tif(key.isalpha()):\r\n\t\t\tif len(d)<(1024*1024*1024) and values<=(16*1024*1024):\r\n\t\t\t\tif timeout==0:\r\n\t\t\t\t\tl = [values,timeout]\r\n\t\t\t\telse:\r\n\t\t\t\t\tl = [values,time.time()+timeout]\t\r\n\t\t\t\tif len(key)<=32:\r\n\t\t\t\t\tprint(\"Data stored in the dictionary with time limit\",timeout,\"seconds!!!\")\r\n\t\t\t\t\td[key]= l\r\n\t\t\t\t\t\r\n\t\t\telse:\r\n\t\t\t\tprint(\"Error: Memory limits exceed\")\r\n\t\telse:\r\n\t\t\tprint(\"Error: Key name must be alphabets\") \t\r\ndef read(key):\r\n\tif key in d.keys():\r\n\t\tb = d[key]\r\n\t\tif b[1]!=0:\r\n\t\t\tif time.time() 0:\n lookup(search,jsonResponse)\n\n time.sleep(request_delay)\n\n\nsys.exit(0)\n# end\n","sub_path":"phishstats.py","file_name":"phishstats.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"620976864","text":"from services.scores_service import ScoresService\nimport pygame_gui\nimport pygame as pg\n\nrankings = {1: \"1st\", 2: \"2nd\", 3: \"3rd\", 4: \"4th\", 5: \"5th\",\n 6: \"6th\", 7: \"7th\", 8: \"8th\", 9: \"9th\", 10: \"10th\"}\n\nclass NewScoreWindow:\n def __init__(self, manager, game_view, service, difficulty):\n self._manager = manager\n self.score_service = service\n self.difficulty = difficulty.degree()\n self.window = None\n self.enter_button = None\n self.text_entry = None\n self.time = game_view.give_exact_time()\n self.built_new_score_window()\n\n def built_new_score_window(self):\n rect = pg.Rect(0, 0, 280, 280)\n self.window = pygame_gui.elements.UIWindow(rect=rect,\n manager=self._manager,\n window_display_title=\"Congratulations!\")\n self.built_text_box()\n\n def built_text_box(self):\n rect = pg.Rect(10, 10, 220, 170)\n text = f\"new score!
    time: {self.time:.2f} seconds
    level: {self.difficulty}\"\n ranking = self.score_service.check_ranking_of_a_score(self.time, self.difficulty)\n if self.score_service.is_score_a_high_score(self.time, self.difficulty):\n ranking = self.score_service.check_ranking_of_a_score(self.time, self.difficulty)\n text += f\"

    ranking: {rankings[ranking]} place \\\n

    insert your name below
    and press enter\"\n self.built_text_entry()\n self.built_enter_button()\n else:\n text += f\"

    score below top 10\"\n\n textbox = pygame_gui.elements.UITextBox(html_text=text,\n relative_rect=rect,\n manager=self._manager,\n container=self.window)\n\n def built_text_entry(self):\n rect = pg.Rect(10, 180, 120, 30)\n self.text_entry = pygame_gui.elements.UITextEntryLine(relative_rect=rect,\n manager=self._manager,\n container=self.window)\n \n\n def built_enter_button(self):\n rect = pg.Rect(140, 180, 80, 30)\n self.enter_button = pygame_gui.elements.UIButton(relative_rect=rect,\n text=\"enter\",\n manager=self._manager,\n container=self.window)\n\n def get_window(self):\n return self.window\n \n def get_enter_button(self):\n return self.enter_button\n\n def get_text_entry(self):\n return self.text_entry\n","sub_path":"src/ui/new_score_window.py","file_name":"new_score_window.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"454982549","text":"import os\nimport socket\nimport time\n\nimport mysql\nfrom flask import Blueprint, redirect, render_template, request, url_for, flash, Flask, jsonify, Response, make_response\nfrom flask_login import login_required, current_user\nfrom datetime import date\nfrom werkzeug.utils import secure_filename\nfrom .model import User, db, VehicleData, Activitylog\n\n# //////////////////\nimport base64\nimport json\nimport os\nimport ssl\nimport numpy as np\nimport cv2\nimport http.client as httplib\nimport mysql.connector\nfrom datetime import datetime, timedelta\nimport pathlib\nimport pdfkit\n# //////////////////\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"\",\n database=\"vehicle-detection\"\n)\n# google_maps = GoogleMaps(api_key=\"AIzaSyA0Dx_boXQiwvdz8sJHoYeZNVTdoWONYkU\")\n\n\napp = Flask(__name__)\nUPLOAD_FOLDER = './flask_project/uploads'\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'mp4'}\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\nmain = Blueprint('main', __name__)\n\n\n# @main.route('/')\n# @login_required\n# def index():\n# return render_template('index.html')\n\ndef allowed_file(filename):\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n@main.route('/dashboard')\n@login_required\ndef dashboard():\n global page_global, user_global, vehicle_global, vehicle_pagination_global, week_count, active_count,count_log,user_log\n page_global = request.args.get('page', 1, type=int)\n user_global = User.query.filter_by(email=current_user.email).first_or_404()\n vehicle_global = user_global.vehicledata\n vehicle_pagination_global = VehicleData.query.filter_by(author=user_global).paginate(page=page_global, per_page=3)\n now = datetime.now()\n week_ago = now - timedelta(hours=8)\n total_visit_today = now - timedelta(hours=12)\n\n week_count = VehicleData.query.filter(VehicleData.date_created > week_ago).filter(\n VehicleData.date_created < now).count()\n active_count = Activitylog.query.filter(Activitylog.date_updated <= total_visit_today).count()\n if camera is None or not camera.isOpened():\n print(\" Camera not working\")\n if request.method == 'GET':\n user_log = User.query.filter_by(email=current_user.email).first_or_404()\n count_log = Activitylog.query.filter_by(author=user_log).count()\n return render_template('index.html', count=week_count, log=count_log, active=active_count,\n data=vehicle_pagination_global, name=current_user.username)\n\n\n@main.route('/stop')\n@login_required\ndef video_stop():\n hide = False\n user_log = User.query.filter_by(email=current_user.email).first_or_404()\n count_log = Activitylog.query.filter_by(author=user_log).count()\n return render_template('index.html', hidden=hide, count=week_count, log=count_log, data=vehicle_pagination_global,\n name=current_user.username)\n\n\n# @main.route('/dashboard',methods=['GET'])\n# @login_required\n# def vehicleData():\n# user = User.query.filter_by(email=current_user.email).first_or_404()\n# vehicle=user.vehicledata\n# print(vehicle)\n# return render_template('index.html',data=vehicle,name=current_user.username)\n\n@main.route('/post', methods=['POST'])\n@login_required\ndef vehicle_post():\n vehicle = request.form.get('vehicle')\n model = request.form.get('model')\n color = request.form.get('color')\n type = request.form.get('type')\n numberplate = request.form.get('numberplate')\n date_created = date.today()\n print(vehicle, model, color, type, numberplate, date_created)\n vehicle_post = VehicleData(current_user.id, vehicle, model, color, type, numberplate, date_created)\n change = \"Added Vehicle\"\n log = Activitylog(current_user.id, current_user.username, change, \"192.168.0.1\", date_created)\n db.session.add(log)\n db.session.add(vehicle_post)\n db.session.commit()\n flash(\"added successfully!!\")\n return redirect(url_for('main.dashboard'))\n\n\n@main.route('/details//update', methods=['GET', 'POST'])\n@login_required\ndef vehicle_updates(vehicle_id):\n vehicle_details = VehicleData.query.get_or_404(vehicle_id)\n if request.method == 'POST':\n vehicle_details.vehicle = request.form['vehicle']\n vehicle_details.model = request.form['model']\n vehicle_details.color = request.form['color']\n vehicle_details.type = request.form['type']\n vehicle_details.number_plate = request.form['numberplate']\n vehicle_details.date_created = date.today()\n change = \"Updated Vehicle \"\n hostname = socket.gethostname()\n IP = socket.gethostbyname(hostname)\n log = Activitylog(current_user.id, current_user.username, change, IP, date.today())\n db.session.add(log)\n db.session.add(vehicle_details)\n db.session.commit()\n flash(\"Successfully updated!!\")\n return redirect(url_for('main.dashboard'))\n now = datetime.now()\n week_ago = now - timedelta(hours=8)\n page_log = request.args.get('page', 1, type=int)\n user_log = User.query.filter_by(email=current_user.email).first_or_404()\n vehicle_log = user_log.activitylog\n vehicle_pagination_log = Activitylog.query.filter_by(author=user_log).count()\n count_log = Activitylog.query.filter_by(author=user_log).count()\n return render_template('edit.html', count=week_count, log=count_log, active=active_count, vehicle=vehicle_details,\n name=current_user.username)\n\n\n@main.route('/details//delete', methods=['GET', 'POST'])\n@login_required\ndef vehicle_delete(vehicle_id):\n vehicle_details = VehicleData.query.get_or_404(vehicle_id)\n db.session.delete(vehicle_details)\n change = \"Deleted Vehicle \"\n hostname = socket.gethostname()\n IP = socket.gethostbyname(hostname)\n log = Activitylog(current_user.id, current_user.username, change, IP, date.today())\n db.session.add(log)\n db.session.commit()\n flash(\"Successfully Deleted!!\")\n return redirect(url_for('main.dashboard'))\n\n\ndef findCar(car_image):\n # Setting the authentication parameters -------------\n headers = {\"Content-type\": \"application/json\",\n \"X-Access-Token\": \"6sscGZ7BSOgvVOke1lm4sOwwiLtsGXhZ6Fdo\"}\n # ---------------------------------------------------\n\n # Connecting to the Sighthound API ------------------\n conn = httplib.HTTPSConnection(\"dev.sighthoundapi.com\",\n context=ssl.SSLContext(ssl.PROTOCOL_TLSv1))\n # ---------------------------------------------------\n\n # Selecting the image -------------------------------\n # To use a hosted image uncomment the following line and update the URL\n # image_data = \"http://example.com/path/to/hosted/image.jpg\"\n\n # To use a local file uncomment the following line and update the path\n image_data = base64.b64encode(open(car_image, \"rb\").read()).decode()\n # ---------------------------------------------------\n\n # Preparing a json to send --------------------------\n params = json.dumps({\"image\": image_data})\n # ---------------------------------------------------\n\n # Calling a service ---------------------------------\n # conn.request(\"POST\", \"/v1/detections?type=face,person&faceOption=landmark,gender\", params, headers)\n conn.request(\"POST\", \"/v1/recognition?objectType=vehicle,licenseplate\", params, headers)\n response = conn.getresponse()\n result = response.read()\n # ---------------------------------------------------\n\n # Displaying the response ---------------------------\n test = result\n # ---------------------------------------------------\n\n return test\n\n\ndef renderJSON(json_v):\n # ------------------------CAR-------------------------------------------------------\n\n # Forming Data\n data = {}\n\n # Car Make\n data[\"car_make\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"attributes\"][\"system\"][\"make\"]\n print(\"Car Name :: \" + data[\"car_make\"][\"name\"].upper())\n\n # Car Model\n data[\"car_model\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"attributes\"][\"system\"][\"model\"]\n print(\"Car Model :: \" + data[\"car_model\"][\"name\"].upper())\n\n # Car Color\n data[\"car_color\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"attributes\"][\"system\"][\"color\"]\n print(\"Car Color :: \" + data[\"car_color\"][\"name\"].upper())\n\n # Car Type\n data[\"car_type\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"attributes\"][\"system\"][\"vehicleType\"]\n print(\"Vehicle Type :: \" + data[\"car_type\"].upper())\n\n # Number Plate\n data[\"number_plate\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"licenseplate\"][\"attributes\"][\"system\"][\"string\"][\n \"name\"]\n data[\"number_plate_top_left\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"licenseplate\"][\"bounding\"][\"vertices\"][0]\n data[\"number_plate_top_left\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"licenseplate\"][\"bounding\"][\"vertices\"][2]\n print(\"Number Plate :: \" + data[\"number_plate\"].upper())\n\n vehicle_name = data[\"car_make\"][\"name\"].upper();\n vehicle_model = data[\"car_model\"][\"name\"].upper();\n vehicle_color = data[\"car_color\"][\"name\"].upper();\n vehicle_type = data[\"car_type\"].upper();\n vehicle_number_plate = data[\"number_plate\"].upper();\n date = datetime.now();\n\n if (mydb):\n print(\"connected with database \")\n mycursor = mydb.cursor()\n sql = \"INSERT INTO vehicle_data(user_id,vehicle,model,color,type,number_plate,date_created) VALUES (4,%(vehicle)s,%(model)s,%(color)s,%(type)s,%(number_plate)s,%(date_created)s)\"\n val = {\n 'vehicle': vehicle_name,\n 'model': vehicle_model,\n 'color': vehicle_color,\n 'type': vehicle_type,\n 'number_plate': vehicle_number_plate,\n 'date_created': date\n }\n\n # sql = VehicleData(4, vehicle_name, vehicle_model, vehicle_color, vehicle_type, vehicle_number_plate, date)\n change = \"Recognized Vehicle \"\n hostname = socket.gethostname()\n IP = socket.gethostbyname(hostname)\n log = Activitylog(4, current_user.username, change, IP, date.today())\n db.session.add(log)\n # db.session.add(sql)\n db.session.commit()\n # print(val)\n # g = geocoder.ip('me')\n # lat=g.lat\n # lng=g.lng\n # print(lat)\n # print(lng)\n # my_location = google_maps.search(lat=lat, lng=lng).first()\n # print(my_location)\n mycursor.execute(sql, val)\n mydb.commit()\n flash(\"Successfully Detected\")\n # ------------------------CAR-------------------------------------------------------\n\n return data\n\n\n@main.route('/uploader', methods=['GET', 'POST'])\n@login_required\ndef upload_file():\n if request.method == 'POST':\n f = request.files['file']\n index = f.filename.split('.')[1]\n if f.filename != '':\n if index != \"mp4\":\n filename = secure_filename(f.filename)\n file = pathlib.Path(UPLOAD_FOLDER + \"/\" + 'testimage.png')\n if file.exists():\n os.remove(UPLOAD_FOLDER + \"/\" + 'testimage.png')\n f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\n os.rename(UPLOAD_FOLDER + \"/\" + filename, UPLOAD_FOLDER + \"/\" + 'testimage.png')\n # f.save(secure_filename(f.filename))\n # flash(\"Uploaded Successfully\")\n file = pathlib.Path(UPLOAD_FOLDER + \"/\" + 'testimage.png')\n if file.exists():\n print(\"File exist\")\n car_image = \"./flask_project/uploads/testimage.png\"\n\n # Contacting External Server\n response = findCar(car_image)\n\n # Converting their Response to JSON\n json_response = json.loads(response)\n\n # Processing that JSON for our Parameters\n print(json_response)\n\n renderJSON(json_response)\n #flash(\"recognized Success\")\n else:\n print(\"File not exist\")\n # Car Image to be Processed\n else:\n filename_video = secure_filename(f.filename)\n file = pathlib.Path(UPLOAD_FOLDER + \"/\" + 'cars3.mp4')\n if file.exists():\n os.remove(UPLOAD_FOLDER + \"/\" + 'cars3.mp4')\n f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename_video))\n os.rename(UPLOAD_FOLDER + \"/\" + filename_video, UPLOAD_FOLDER + \"/\" + 'cars3.mp4')\n # f.save(secure_filename(f.filename))\n flash(\"Uploaded Successfully\")\n file = pathlib.Path(UPLOAD_FOLDER + \"/\" + 'cars3.mp4')\n\n return redirect(url_for('main.dashboard'))\n else:\n flash(\" Please select Video/Images\")\n return redirect(url_for('main.dashboard'))\n\n\n@main.route('/activity')\n@login_required\ndef activitylog():\n global page_log, user_log, vehicle_log, vehicle_pagination_log, count_log\n page_log = request.args.get('page', 1, type=int)\n user_log = User.query.filter_by(email=current_user.email).first_or_404()\n vehicle_log = user_log.activitylog\n vehicle_pagination_log = Activitylog.query.filter_by(author=user_log).paginate(page=page_log, per_page=5)\n count_log = Activitylog.query.filter_by(author=user_log).count()\n return render_template('activity.html', data=vehicle_pagination_log)\n\n\n# @main.route(\"/search\", methods=[\"POST\",\"GET\"])\n# @login_required\n# def search():\n# searchbox = request.form.get(\"search_text\")\n# search = \"%{}%\".format(searchbox)\n# vehicle_found = VehicleData.query.filter(VehicleData.vehicle.like(search)).all()\n# return render_template('index.html',data=vehicle_found)\n\n@main.route(\"/search\", methods=[\"POST\", \"GET\"])\n@login_required\ndef search():\n searchbox = request.form.get(\"search_text\")\n search = \"%{}%\".format(searchbox)\n page = request.args.get('page', 1, type=int)\n vehicle_pagination = VehicleData.query.filter(VehicleData.vehicle.like(search)).paginate(page=page, per_page=3)\n now = datetime.now()\n week_ago = now - timedelta(hours=8)\n total_visit_today = now - timedelta(hours=12)\n active_count = Activitylog.query.filter(Activitylog.date_updated <= total_visit_today).count()\n week_count = VehicleData.query.filter(VehicleData.date_created > week_ago).filter(\n VehicleData.date_created < now).count()\n user_log = User.query.filter_by(email=current_user.email).first_or_404()\n count_log = Activitylog.query.filter_by(author=user_log).count()\n return render_template('index.html', count=week_count, log=count_log, active=active_count, data=vehicle_pagination,\n name=current_user.username)\n\n\n# camera = cv2.VideoCapture(0)\ncamera = cv2.VideoCapture('D:/Project/flask-project/venv/flask_project/uploads/cars3.mp4')\n\n\ndef snapshot(frame, ctr):\n cv2.imwrite(\"D:/Project/flask-project/cardetect/Snaphots/ss\" + str(ctr) + \".jpg\", frame)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(frame, \"Taking Snapshot\", (15, 15), font, 0.5, (255, 255, 255), 1)\n cv2.imshow('Vehicle Detection System - Snapshot Screen', frame)\n return True\n\n\ndef renderJSON_video(json_v):\n # ------------------------CAR-------------------------------------------------------\n count = 0\n # Forming Data\n data = {}\n\n # Car Make\n data[\"car_make\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"attributes\"][\"system\"][\"make\"]\n print(\"Car Name :: \" + data[\"car_make\"][\"name\"].upper())\n\n # Car Model\n data[\"car_model\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"attributes\"][\"system\"][\"model\"]\n print(\"Car Model :: \" + data[\"car_model\"][\"name\"].upper())\n\n # Car Color\n data[\"car_color\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"attributes\"][\"system\"][\"color\"]\n print(\"Car Color :: \" + data[\"car_color\"][\"name\"].upper())\n\n # Car Type\n data[\"car_type\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"attributes\"][\"system\"][\"vehicleType\"]\n print(\"Vehicle Type :: \" + data[\"car_type\"].upper())\n\n # Number Plate\n data[\"number_plate\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"licenseplate\"][\"attributes\"][\"system\"][\"string\"][\n \"name\"]\n data[\"number_plate_top_left\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"licenseplate\"][\"bounding\"][\"vertices\"][0]\n data[\"number_plate_top_left\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"licenseplate\"][\"bounding\"][\"vertices\"][2]\n print(\"Number Plate :: \" + data[\"number_plate\"].upper())\n global vehicle_name, vehicle_model, vehicle_color, vehicle_type, vehicle_number_plate, date\n vehicle_name = data[\"car_make\"][\"name\"].upper();\n vehicle_model = data[\"car_model\"][\"name\"].upper();\n vehicle_color = data[\"car_color\"][\"name\"].upper();\n vehicle_type = data[\"car_type\"].upper();\n vehicle_number_plate = data[\"number_plate\"].upper();\n date = datetime.now();\n count = count + 1\n data[\"number_plate\"] = json_v[\"objects\"][0][\"vehicleAnnotation\"][\"recognitionConfidence\"]\n # print(\"{:.1f}\".format(data[\"number_plate\"]))\n # if (mydb):\n # print(\"connected with database \")\n # mycursor = mydb.cursor()\n # sql = \"INSERT INTO vehicle_data(user_id,vehicle,model,color,type,number_plate,date_created) VALUES (4,%(vehicle)s,%(model)s,%(color)s,%(type)s,%(number_plate)s,%(date_created)s)\"\n # val = {\n # 'vehicle': vehicle_name,\n # 'model': vehicle_model,\n # 'color': vehicle_color,\n # 'type': vehicle_type,\n # 'number_plate': vehicle_number_plate,\n # 'date_created': date\n # }\n # mycursor.execute(sql, val)\n # mydb.commit()\n\n # ------------------------CAR-------------------------------------------------------\n\n return data\n\n\ndef gen_frames(): # generate frame by frame from camera\n ctr = 0\n\n font = cv2.FONT_HERSHEY_SIMPLEX\n # Turn to TRUE to send stream to API\n carRecogMode = True\n\n car_cascade = cv2.CascadeClassifier('cars4.xml')\n while True:\n # Capture frame-by-frame\n ret, frame = camera.read() # read the camera frame\n if not ret:\n break\n else:\n\n # ret, buffer = cv2.imencode('.jpg', frame)\n #\n # frame = buffer.tobytes()\n imgencode = cv2.imencode('.jpg', frame)[1].tobytes()\n # stringData = imgencode.tostring()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + imgencode + b'\\r\\n') # concat frame one by one and show result\n\n cv2.imwrite(\"D:/Project/flask-project/venv/flask_project/Frames/f\" + str(ctr) + \".jpg\", frame)\n # cv2.imwrite(\"Frames/f\" + str(ctr) + \".jpg\", frame)\n response = findCar(\"D:/Project/flask-project/venv/flask_project/Frames/f\" + str(ctr) + \".jpg\")\n\n # Converting their Response to JSON\n json_response = json.loads(response)\n\n # Processing that JSON for our Parameters\n print(json_response)\n\n data = renderJSON_video(json_response)\n\n if data[\"car_color\"] != False:\n yield (data[\"car_color\"][\"name\"])\n cv2.putText(frame, data[\"car_color\"][\"name\"], (15, 60), font, 1, (0, 0, 0), 3)\n\n print(data[\"car_color\"][\"name\"])\n\n if data[\"number_plate\"] != False:\n # LPN\n cv2.putText(frame, str(data[\"number_plate\"]), (10, 100), font, 1, (255, 146, 0), 3)\n print(str(data[\"number_plate\"]))\n\n # display the resulting frame\n # cv2.imshow('Vehicle Detection System - Live Camera Footage', frame)\n ctr = ctr + 1\n\n # -------------------------------------------\n\n # press Q on keyboard to exit---------------\n c = cv2.waitKey(25)\n # print(\"NOT EXITING: Q is not Pressed!\")\n\n if c == ord('q'):\n # print(\"EXITING: Q is Pressed!\")\n break\n if c == ord('s'):\n snapshot(frame, ctr)\n # -------------------------------------------\n\n # ------------------------------------------------------------------------\n\n # release the videocapture object\n\n # camera.release()\n # close all the frames\n # cv2.destroyAllWindows()\n\n\n@main.route('/video_feed')\ndef video_feed():\n return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n\n@main.route('/video_process', methods=[\"POST\", \"GET\"])\ndef video_response():\n count = 1\n # camera.release()\n # cv2.destroyAllWindows()\n if (mydb):\n print(\"connected with database \")\n mycursor = mydb.cursor()\n if count == 1:\n sql = \"INSERT INTO vehicle_data(user_id,vehicle,model,color,type,number_plate,date_created) VALUES (4,%(vehicle)s,%(model)s,%(color)s,%(type)s,%(number_plate)s,%(date_created)s)\"\n val = {\n 'vehicle': vehicle_name,\n 'model': vehicle_model,\n 'color': vehicle_color,\n 'type': vehicle_type,\n 'number_plate': vehicle_number_plate,\n 'date_created': date\n }\n mycursor.execute(sql, val)\n mydb.commit()\n page = request.args.get('page', 1, type=int)\n user = User.query.filter_by(email=current_user.email).first_or_404()\n vehicle = user.vehicledata\n hide = False\n vehicle_pagination = VehicleData.query.filter_by(author=user).paginate(page=page, per_page=3)\n return render_template('index.html', count=week_count, response='ok', hidden=hide, data=vehicle_pagination,\n name=current_user.username)\n\n\n@main.route('/dashboard')\ndef video_restart():\n return redirect(url_for('main.dashboard'))\n\n\n@main.route('/start')\ndef video_start():\n hide = True\n if request.method == 'GET':\n return render_template('index.html', count=week_count, hidden=hide, data=vehicle_pagination_global,\n name=current_user.username)\n@main.route('/generate/')\ndef generate(id):\n vehicle_details = VehicleData.query.get_or_404(id)\n return render_template('generate.html',vehicle=vehicle_details)\n\nwkhtmltopdf_options = {\n 'enable-local-file-access': None,\n # 'javascript-delay': 2000\n}\n\n@main.route('/result/', methods=[\"POST\", \"GET\"])\ndef pdf_generator(vehicle_id):\n if request.method == 'POST':\n vehicle_details = VehicleData.query.get_or_404(vehicle_id)\n vehicle = request.form.get('vehicle')\n model = request.form.get('model')\n numberplate=request.form.get('numberplate')\n subject=request.form.get('subject')\n action=request.form.get('action')\n rendered=render_template('pdf.html',vehicle_id=vehicle_details.id,vehicle_type=vehicle_details.type,vehicle_name=vehicle,vehicle_model=model,vehicle_numberplate=numberplate,action=action,subject=subject,time=datetime.now(),incident_date=vehicle_details.date_created)\n pdf=pdfkit.from_string(rendered,False, options = wkhtmltopdf_options)\n response=make_response(pdf)\n response.headers['Content-Type'] = 'application/pdf'\n response.headers['Content-Disposition'] = 'inline; filename=report.pdf'\n return response","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":23165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"480412458","text":"from oauthlib.oauth2 import BackendApplicationClient, TokenExpiredError\nfrom requests_oauthlib import OAuth2Session\nfrom django.conf import settings\nfrom django.core.cache import cache\n\n\n__oauth_client = {}\n\n\ndef __get_battlenet_oauth(region: str):\n if region.upper() == 'US':\n client_id = settings.SOCIAL_AUTH_BATTLENET_OAUTH2_US_KEY\n client_secret = settings.SOCIAL_AUTH_BATTLENET_OAUTH2_US_SECRET\n else:\n client_id = settings.SOCIAL_AUTH_BATTLENET_OAUTH2_EU_KEY\n client_secret = settings.SOCIAL_AUTH_BATTLENET_OAUTH2_EU_SECRET\n client = BackendApplicationClient(client_id=client_id)\n token = cache.get(f'{region}_battlenet_token')\n if token:\n if region not in __oauth_client:\n __oauth_client[region] = OAuth2Session(client=client, token=token)\n else:\n __oauth_client[region] = OAuth2Session(client=client)\n token = __oauth_client[region].fetch_token(token_url=f\"https://{region}.battle.net/oauth/token\", client_id=client_id, client_secret=client_secret)\n cache.set(f'{region}_battlenet_token', token, 60*60*24)\n return __oauth_client[region]\n\n\ndef execute_battlenet_request(url, params=None):\n region = url.split(\".\")[0].split(\"//\")[1]\n try:\n return __get_battlenet_oauth(region).get(url, params=params)\n except TokenExpiredError as e:\n cache.delete(f'{region}_battlenet_token')\n return __get_battlenet_oauth(region).get(url, params=params)\n","sub_path":"utils/battlenet_util.py","file_name":"battlenet_util.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"129335358","text":"import frappe\nfrom frappe.utils import flt, cint\n\ndef validate(self, method):\t\t\n\n\timport siyar_erpnext.api\n\tsiyar_erpnext.api.load_customer_item_name(self, method)\n\tcalculate_customer_total(self)\n\n\ndef before_submit(self, method):\n\timport consoleerp_erpnext_client.customizations.item_stock_validation\t\n\tconsoleerp_erpnext_client.customizations.item_stock_validation.validate(self, method)\n\n\ndef on_submit(self, method):\n\tvalidate_with_delivery_note(self)\n\ndef on_cancel(self, method):\n\tvalidate_with_delivery_note(self)\n\ndef calculate_customer_total(self):\n\ttotal = 0\n\tfor cdoc in self.items:\n\t\tif cdoc.consoleerp_customer_rate:\n\t\t\ttotal += cdoc.consoleerp_customer_rate * cdoc.qty\n\t\t\tcdoc.consoleerp_original_amt = cdoc.consoleerp_customer_rate * cdoc.qty\n\t\telse:\n\t\t\ttotal += cdoc.rate * cdoc.qty\n\n\tself.consoleerp_customer_total = total\n\tself.consoleerp_customer_discount_total = self.consoleerp_customer_total - self.total\n\tself.consoleerp_order_total = self.total\n\n\ndef validate_with_delivery_note(self):\n\t# We are only doing this:\n\t# Make SLEs for changed qtys\n\t# Make the GL wrt abv\n\t# make_sl_entries & make_gl_entries handles cancellation\n\n\tif self.update_stock == 1:\n\t\t# do nothing if updating stock\n\t\treturn\n\tsl_entries = []\n\tchanged_rows = []\n\t# everything wrt stock_qty\n\tfor d in [x for x in self.items if x.validate_with_delivery_note and x.warehouse]:\n\t\tif frappe.db.get_value(\"Item\", d.item_code, \"is_stock_item\") == 1 and flt(d.stock_qty):\n\t\t\tdelivered_qty = 0\n\t\t\tif d.dn_detail:\n\t\t\t\tdelivered_qty = frappe.get_value(\"Delivery Note Item\", d.dn_detail, \"stock_qty\")\n\t\t\tqty_change = d.stock_qty - delivered_qty\n\t\t\t# qty_change\n\t\t\t# -ve\t: got return\n\t\t\t# +ve\t: gave more\n\t\t\t# 0\t\t: continue\n\t\t\tif qty_change == 0:\n\t\t\t\tcontinue\n\n\t\t\t# return rate- code copied from selling_controller.py\n\t\t\treturn_rate = 0\n\t\t\tif cint(self.is_return) and self.return_against and self.docstatus==1:\n\t\t\t\treturn_rate = self.get_incoming_rate_for_sales_return(d.item_code, self.return_against)\n\n\t\t\tsl_entries.append(self.get_sl_entries(d, {\n\t\t\t\t\t\t\t\t\"actual_qty\": -1*flt(qty_change),\n\t\t\t\t\t\t\t\t\"incoming_rate\": return_rate,\n\t\t\t\t\t\t\t\t\"parent\": \"consoleerp-{}\".format(self.name)\n\t\t\t\t\t\t\t}))\n\t\t\tchanged_rows.append(d)\n\tself.make_sl_entries(sl_entries)\n\t# above method inserts the SLEs\n\t# stock_value_difference is made only after the above method\n\t\n\t# STOCK GL ENTRIES\n\t# Proceed if perpetual inventory is enabled\n\timport erpnext\n\tif not erpnext.is_perpetual_inventory_enabled(self.company):\n\t\treturn\n\t\t\t\n\t#--- get stock ledger entries just made\n\tfrom erpnext.stock import get_warehouse_account_map\n\twarehouse_account = get_warehouse_account_map()\n\tsle_map = {}\n\tstock_ledger_entries = frappe.db.sql(\"\"\"\n\t\tselect\n\t\t\tname, warehouse, stock_value_difference, valuation_rate,\n\t\t\tvoucher_detail_no, item_code, posting_date, posting_time,\n\t\t\tactual_qty, qty_after_transaction\n\t\tfrom\n\t\t\t`tabStock Ledger Entry`\n\t\twhere\n\t\t\tvoucher_type=%s and voucher_no=%s and parent=%s\n\t\"\"\", (self.doctype, self.name, \"consoleerp-{}\".format(self.name)), as_dict=True)\n\n\tfor sle in stock_ledger_entries:\n\t\t\tsle_map.setdefault(sle.voucher_detail_no, []).append(sle)\n\n\twarehouse_with_no_account = []\n\tgl_list = []\n\t\t\t\n\t# loop it again\n\t# stock_controller.get_gl_entries()\n\tfor item_row in changed_rows:\n\t\tsle_list = sle_map.get(item_row .name)\n\t\tif sle_list:\n\t\t\tfor sle in sle_list:\n\t\t\t\tif warehouse_account.get(sle.warehouse):\n\t\t\t\t\t# from warehouse account\n\n\t\t\t\t\tself.check_expense_account(item_row)\n\n\t\t\t\t\t# If the item does not have the allow zero valuation rate flag set\n\t\t\t\t\t# and ( valuation rate not mentioned in an incoming entry\n\t\t\t\t\t# or incoming entry not found while delivering the item),\n\t\t\t\t\t# try to pick valuation rate from previous sle or Item master and update in SLE\n\t\t\t\t\t# Otherwise, throw an exception\n\n\t\t\t\t\tif not sle.stock_value_difference and self.doctype != \"Stock Reconciliation\" \\\n\t\t\t\t\t\tand not item_row.get(\"allow_zero_valuation_rate\"):\n\n\t\t\t\t\t\tsle = self.update_stock_ledger_entries(sle)\n\n\t\t\t\t\tgl_list.append(self.get_gl_dict({\n\t\t\t\t\t\t\"account\": warehouse_account[sle.warehouse][\"account\"],\n\t\t\t\t\t\t\"against\": item_row.expense_account,\n\t\t\t\t\t\t\"cost_center\": item_row.cost_center,\n\t\t\t\t\t\t\"remarks\": \"Delivery Note Validation Entry\",\n\t\t\t\t\t\t\"debit\": flt(sle.stock_value_difference, 2),\n\t\t\t\t\t}, warehouse_account[sle.warehouse][\"account_currency\"]))\n\n\t\t\t\t\t# to target warehouse / expense account\n\t\t\t\t\tgl_list.append(self.get_gl_dict({\n\t\t\t\t\t\t\"account\": item_row.expense_account,\n\t\t\t\t\t\t\"against\": warehouse_account[sle.warehouse][\"account\"],\n\t\t\t\t\t\t\"cost_center\": item_row.cost_center,\n\t\t\t\t\t\t\"remarks\": \"Delivery Note Validation Entry\",\n\t\t\t\t\t\t\"credit\": flt(sle.stock_value_difference, 2),\n\t\t\t\t\t\t\"project\": item_row.get(\"project\") or self.get(\"project\")\n\t\t\t\t\t}))\n\t\t\t\telif sle.warehouse not in warehouse_with_no_account:\n\t\t\t\t\twarehouse_with_no_account.append(sle.warehouse)\n\n\tif warehouse_with_no_account:\n\t\tfor wh in warehouse_with_no_account:\n\t\t\tif frappe.db.get_value(\"Warehouse\", wh, \"company\"):\n\t\t\t\tfrappe.throw(_(\"Warehouse {0} is not linked to any account, please mention the account in the warehouse record or set default inventory account in company {1}.\").format(wh, self.company))\n\n\tfrom erpnext.accounts.general_ledger import process_gl_map\n\tgl_list = process_gl_map(gl_list)\n\t\n\tfrom erpnext.accounts.general_ledger import merge_similar_entries\n\tgl_list = merge_similar_entries(gl_list)\n\t\n\tself.make_gl_entries(gl_list)","sub_path":"siyar_erpnext/customizations/sales_invoice/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"473079190","text":"\"\"\"\nDefinition of urls for AssetManagementProject.\n\"\"\"\n\nimport app.forms\nimport app.views\nimport app.controller\nimport django.contrib.auth.views\n\nfrom datetime import datetime\nfrom django.conf.urls import url\n\n# Uncomment the next lines to enable the admin:\nfrom django.conf.urls import include\nfrom django.contrib import admin\n\nadmin.autodiscover()\n\nurlpatterns = [\n # 测试\n url(r'^test', app.views.test, name='test'),\n # 临时页面\n # url(r'^imagelist$', app.views.imagelist, name='imagelist'),\n # Examples:\n url(r'^$', app.views.home, name='home'),\n\n #url(r'^hardware(/(?P-?\\d{1,})(/(?P\\w{1,})/(?P\\w{1,}))?)?$', app.views.hardware, name='hardware'),\n #url(r'^printer(/(?P-?\\d{1,}))?$', app.views.printer, name='printer'),\n #url(r'^person(/(?P\\d{1,}))?$', app.views.person, name='person'),\n #url(r'^log(/(?P\\d{1,}))?$', app.views.log, name='log'),\n\n url(r'^hardwareList$', app.views.hardwareList, name='hardwareList'),\n url(r'^hardwareDetail/(\\d*)$', app.views.hardwareDetail, name='hardwareDetail'),\n url(r'^hardware2List$', app.views.hardware2List, name='hardware2List'),\n url(r'^hardware2Detail/(\\d*)$', app.views.hardware2Detail, name='hardware2Detail'),\n url(r'^hardware3List$', app.views.hardware3List, name='hardware3List'),\n url(r'^hardware3Detail/(\\d*)$', app.views.hardware3Detail, name='hardware3Detail'),\n url(r'^printerList$', app.views.printerList, name='printerList'),\n url(r'^printerDetail/(\\d*)$', app.views.printerDetail, name='printerDetail'),\n url(r'^personList$', app.views.personList, name='personList'),\n url(r'^personDetail/(\\d*)$', app.views.personDetail, name='personDetail'),\n url(r'^changeList$', app.views.changeList, name='changeList'),\n url(r'^changeDetail/(\\d*)$', app.views.changeDetail, name='changeDetail'),\n url(r'^untreadList$', app.views.untreadList, name='untreadList'),\n url(r'^untreadDetail/(\\d*)$', app.views.untreadDetail, name='untreadDetail'),\n\n url(r'^task$', app.views.task, name='task'),\n\n url(r'^login$',\n django.contrib.auth.views.login,\n {\n 'template_name': 'app/login.html',\n 'authentication_form': app.forms.BootstrapAuthenticationForm,\n 'extra_context':\n {\n 'title': 'Log in',\n 'year': datetime.now().year,\n }\n },\n name='login'),\n url(r'^logout$',\n django.contrib.auth.views.logout,\n {\n 'next_page': '/',\n },\n name='logout'),\n \n # 控制器操作\n url(r'^get/(\\w+)/(\\d*)$', app.controller.controller.get, name='get'),\n url(r'^query/(\\w+)$', app.controller.controller.query, name='query'),\n url(r'^edit/(\\w+)$', app.controller.controller.edit, name='edit'),\n url(r'^remove/(\\w+)$', app.controller.controller.remove, name='remove'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n]\n","sub_path":"AssetManagementProject/AssetManagementProject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"360201217","text":"import numpy as np\nimport cv2\nimport glob\nimport os\nimport math\nfrom progress.bar import Bar\n\nSKIP = 2\nWIDTH = 416\nHEIGHT = 128\nFX = 910\nFY = 910\nCX = 1164\nCY = 874\n\n\nOUTPUT_DIR = '/mnt/Moar Bulk/comma/struct2depth/'\n\ndef crop(img, fx, fy, cx, cy):\n # Perform center cropping, preserving 50% vertically.\n middle_perc = 0.38\n left = 1 - middle_perc\n half = left / 2\n a = img[int(img.shape[0]*(half)):int(img.shape[0]*(1-half)), :]\n cy /= (1 / middle_perc)\n\n # Resize to match target height while preserving aspect ratio.\n wdt = int((float(HEIGHT)*a.shape[1]/a.shape[0]))\n x_scaling = float(wdt)/a.shape[1]\n y_scaling = float(HEIGHT)/a.shape[0]\n b = cv2.resize(a, (wdt, HEIGHT))\n\n # Adjust intrinsics.\n fx*=x_scaling\n fy*=y_scaling\n cx*=x_scaling\n cy*=y_scaling\n\n # Perform center cropping horizontally.\n remain = b.shape[1] - WIDTH\n cx /= (b.shape[1] / WIDTH)\n c = b[:, math.ceil(remain/2):b.shape[1]-math.floor(remain/2)]\n\n return c, fx, fy, cx, cy\n\n\ndef extract_segment(path):\n segment_number = os.path.basename(path)\n route_id = os.path.basename(os.path.dirname(path))\n output_dir = OUTPUT_DIR + route_id + '_' + segment_number\n if not os.path.isdir(output_dir):\n os.mkdir(output_dir)\n triplet = []\n ct = 1\n\n cam = cv2.VideoCapture(path + \"/video.hevc\")\n while(True):\n ret, frame = cam.read()\n\n if ret:\n smallimg, fx_this, fy_this, cx_this, cy_this = crop(frame, FX, FY, CX, CY)\n triplet.append(smallimg)\n if len(triplet) == 3:\n cmb = np.hstack(triplet)\n\n cv2.imwrite(os.path.join(output_dir, str(ct).zfill(10) + '.png'), cmb)\n f = open(os.path.join(output_dir, str(ct).zfill(10) + '_cam.txt'), 'w')\n f.write(str(fx_this) + ',0.0,' + str(cx_this) + ',0.0,' + str(fy_this) + ',' + str(cy_this) + ',0.0,0.0,1.0')\n f.close()\n del triplet[0]\n ct += 1\n else:\n break\n\nsegments = glob.glob(\"/mnt/Bulk Storage/commaai/comma2k19/*/*/*\")\n\nfor s in Bar('Processing').iter(segments):\n extract_segment(s)\n\nfn = open(OUTPUT_DIR + '/' + 'train.txt', 'w')\nfor f in glob.glob(OUTPUT_DIR + '/*/*.png'):\n if '-seg.png' in f or '-fseg.png' in f:\n continue\n folder_name = f.split('/')[-2]\n img_name = f.split('/')[-1].replace('.png', '')\n fn.write(folder_name + ' ' + img_name + '\\n')\nfn.close()\n","sub_path":"extract_comma_struct2depth.py","file_name":"extract_comma_struct2depth.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"220987557","text":"# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, ForeignKey, TEXT, UniqueConstraint, Index\nfrom sqlalchemy.orm import sessionmaker, relationship\nfrom sqlalchemy import create_engine\nimport re\n\nengine = create_engine(\n \"mysql+pymysql://root:root@localhost/scrapy?charset=utf8\", max_overflow=5)\nBase = declarative_base()\nSession = sessionmaker(bind=engine)\nsession = Session()\n\n\nclass Newstable(Base):\n __tablename__ = 'learn_newstable'\n \n id = Column(Integer, primary_key=True)\n news_body = Column(TEXT)\n news_title = Column(String(32))\n news_thread = Column(String(32))\n news_url = Column(String(64))\n __table_args__ = (\n UniqueConstraint('id', 'news_title', name='uix_id_name'),\n Index('ix_id_name', 'news_title', 'news_thread', 'news_url'),\n )\n\n\nBase.metadata.create_all(engine)\nsession.execute('alter table learn_newstable convert to character set gbk')\n\n\nclass News163Pipeline(object):\n def process_item(self, item, spider):\n return item\n\n\nclass News163InfoPipeline(object):\n def open_spider(self, spider):\n self.f = open('News163Info.txt', 'w')\n\n def close_spider(self, spider):\n self.f.close()\n\n def process_item(self, item, spider):\n try:\n line = str(dict(item)) + '\\n'\n self.f.write(line)\n dic = dict(item)\n obc = Newstable(news_body=re.sub('[\\[\\]]', ' ', str(\n dic['news_body'])), news_title=dic['news_title'], news_thread=dic['news_thread'], news_url=dic['news_url'])\n session.add(obc)\n session.commit()\n except:\n pass\n return item\n","sub_path":"news163/news163/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"200426501","text":"import attr\nimport trio\n\nfrom . import wordlist\nfrom .map import Map\nfrom .keyboard import Keyboard\nfrom .cells import BlueCell, RedCell, NeutralCell, KillerCell\n\n\n@attr.s\nclass Game:\n\n _bot = attr.ib()\n _chat_id = attr.ib()\n map_ = attr.ib(default=None)\n finished = attr.ib(default=False)\n spymasters = attr.ib(factory=set)\n\n async def __call__(self):\n await self.create_map()\n await self.choose_spymasters()\n await self.reveal_map_to_spymasters()\n await self.show_map()\n winner = await self.wait_winner()\n await self._broadcast(winner, reply_markup={\"remove_keyboard\": True})\n\n async def create_map(self):\n name = await self.choose_wordlist()\n words = wordlist.load(name)\n self.map_ = Map.random(words=words)\n\n async def choose_wordlist(self):\n names = set(wordlist.list())\n\n async with self._sub_for_messages() as updates:\n reply_markup = Keyboard([list(names)]).json()\n await self._broadcast(\"Выберите ��ловарь.\", reply_markup=reply_markup)\n\n async for update in updates:\n name = update[\"message\"][\"text\"]\n if name in names:\n return name\n\n await self._broadcast(\"Такого словаря нет.\")\n\n async def choose_spymasters(self):\n for i in range(1, 3):\n await self._broadcast(f\"Кто будет {i}-ым ведущим?\")\n update = await self._wait_message()\n self.spymasters.add(update[\"message\"][\"from\"][\"id\"])\n\n async def reveal_map_to_spymasters(self):\n text = self.map_.as_emojis()\n async with trio.open_nursery() as nursery:\n for spymaster in self.spymasters:\n nursery.start_soon(self._send, spymaster, text)\n\n async def show_map(self):\n text = \"Выберите клетку.\"\n reply_markup = self.map_.as_keyboard().json()\n await self._broadcast(text, reply_markup=reply_markup)\n\n async def wait_winner(self):\n async with self._sub_for_messages() as updates:\n async for update in updates:\n # FIXME: Parse text.\n word = update[\"message\"][\"text\"]\n\n try:\n cell = self.map_[word]\n except KeyError:\n await self._broadcast(\"Такой клетки нет.\")\n continue\n\n if cell.flipped:\n await self._broadcast(\"Клетка уже перевернута.\")\n continue\n\n cell.flip()\n\n if isinstance(cell, NeutralCell):\n pass\n elif isinstance(cell, KillerCell):\n return cell.emoji\n elif isinstance(cell, (BlueCell, RedCell)):\n if self.map_.all_flipped(type(cell)):\n return cell.emoji\n else:\n raise RuntimeError(\"Unreachable\")\n\n await self.show_map()\n\n async def _broadcast(self, text, **kwargs):\n await self._send(self._chat_id, text, **kwargs)\n\n async def _send(self, chat_id, text, **kwargs):\n await self._bot.api.send_message(\n json={\"chat_id\": chat_id, \"text\": text, **kwargs}\n )\n\n def _sub_for_messages(self):\n return self._bot.sub(self._new_message)\n\n async def _wait_message(self):\n return await self._bot.wait(self._new_message)\n\n def _new_message(self, update):\n msg = update.get(\"message\")\n if msg is None:\n return False\n\n from_ = msg.get(\"from\")\n if from_ is None:\n return False\n\n from_id = from_[\"id\"]\n chat_id = msg[\"chat\"][\"id\"]\n return from_id != chat_id and chat_id == self._chat_id\n","sub_path":"catnames/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"636863346","text":"#!/usr/bin/env python3\n\nimport aiohttp\nimport asyncio\n\nfrom aiohttp import web\n\nroutes = web.RouteTableDef()\n\n# @routes.get('/')\n# async def hello(request):\n# return web.Response(text=\"Hello, world\")\n\n\n@routes.get('/btxws')\nasync def websocket_handler(request):\n\n ws = web.WebSocketResponse()\n await ws.prepare(request)\n reader, writer = await asyncio.open_connection(\n 'belgradstr.dyndns.org', 20001)\n\n async def server_to_websocket():\n while True:\n try:\n data = await reader.read(64)\n if not data:\n print('socket connection closed')\n break\n await ws.send_bytes(data)\n except ConnectionError:\n await ws.close()\n break\n\n task = asyncio.get_event_loop().create_task(server_to_websocket())\n\n async for msg in ws:\n if msg.type == aiohttp.WSMsgType.BINARY:\n try:\n writer.write(msg.data)\n await writer.drain()\n except ConnectionError:\n await ws.close()\n writer.close()\n elif msg.type == aiohttp.WSMsgType.ERROR:\n if task:\n task.cancel()\n task = None\n writer.close()\n print('ws connection closed with exception %s' %\n ws.exception())\n\n writer.close()\n\n return ws\n\napp = web.Application()\n\napp.add_routes([web.static('/files', 'web/', show_index=True)])\napp.add_routes(routes)\n\nweb.run_app(app)\n","sub_path":"btxwebsocket.py","file_name":"btxwebsocket.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"221011835","text":"from peewee import *\nfrom .db import db\nfrom .player import Player\nfrom .item import Item\n\nclass Inventory(Model):\n player = ForeignKeyField(Player, backref='items')\n item = ForeignKeyField(Item, backref='inventories')\n count = IntegerField()\n equiped = BooleanField()\n durability = FloatField()\n\n class Meta:\n database = db\n\n def equip(self):\n if not self.equiped and self.item.equippable:\n for eq in Inventory.select().where(Inventory.equiped):\n if eq.item.is_armor and self.item.is_armor:\n eq.unequip()\n elif eq.item.is_weapon and self.item.is_weapon:\n eq.unequip()\n\n if self.count == 1:\n self.equiped = True\n self.durability = 1.0\n self.save()\n return {'eq': True}\n\n elif self.player.inventory_size > Inventory \\\n .select() \\\n .where(Inventory.player == self.player) \\\n .count():\n unpacked = Inventory.create(\n player=self.player,\n item=self.item,\n count=1,\n equiped=True,\n durability=1.0\n )\n unpacked.save()\n self.count -= 1\n self.save()\n return {'eq': True, 'new_item': unpacked}\n\n else:\n return {'eq': False, 'mes': \"Not enough space in inventory.\"}\n else:\n return {'eq': False, 'mes': \"Item is already equiped or item is not equippable.\"}\n ","sub_path":"models/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":1649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"134078756","text":"import pygame\nimport os\nimport sys\nimport random\nfrom my_classes import Card, Deck, Board, Player, Button\n\n\n# defining main instances\npygame.init()\n\n\ndeck = Deck()\nboard = Board()\nplayer = Player('harry', 888) # OLD\n\nplayers = [\n Player('1', 888),\n Player('2', 887),\n Player('3', 886),\n Player('4', 885)\n]\n\nfor player in players:\n for i in range(3):\n player.draw_card(deck)\n\n#def initialize_players(players):\n \nhand = player.hand # OLD\n\nangles = [0, 5, 10, 15, 20, 25, 30, 35, 45,\n 330, 335, 340, 345, 350, 355, 360]\n\n\n# action functions\ndef draw_card():\n drawn_card = deck.draw()\n hand.append(drawn_card)\n return drawn_card\n\n\n# display\ndisplay_width = 1280\ndisplay_height = 720\n\ngameDisplay = pygame.display.set_mode((display_width, display_height))\npygame.display.set_caption('troika')\n\ncrashed = False\n\n# BOARD\nboard_img = board.load_img()\nboard_bottom_half = board.load_bottom_img()\nboard_top_half = board.load_top_img()\ngameDisplay.blit(board_img, (0, 25))\n\n\ngame_zone = board.center_coord()\n\n# board center coordinates\ng_z_x = range(580, 640, 10)\ng_z_y = range(250, 300, 5)\n\n\n# buttons\ntake_all = Button()\nta_img = take_all.load_ta_img()\nta_rect = ta_img.get_rect()\nta_rect.center = (900, 250)\ngameDisplay.blit(ta_img, ta_rect)\n\n\nend_turn = Button()\net_img = end_turn.load_et_img()\net_rect = et_img.get_rect()\net_rect.center = (900, 180)\ngameDisplay.blit(et_img, et_rect)\n\n\n# HAND\n\ndef get_hand_card_pos():\n if len(hand) == 0:\n gameDisplay.blit(board_bottom_half, (0, 25))\n\n elif len(hand) == 2:\n x = 580\n y = 500\n for card in hand:\n card.img = card.load_img()\n card.rect = card.img.get_rect()\n card.rect.center = (x, y)\n display = gameDisplay.blit(card.img, card.rect)\n x += 100\n elif len(hand) == 4:\n x = 490\n y = 500\n for card in hand:\n card.img = card.load_img()\n card.rect = card.img.get_rect()\n card.rect.center = (x, y)\n display = gameDisplay.blit(card.img, card.rect)\n x += 101\n elif len(hand) == 1:\n x = 630\n y = 500\n for card in hand:\n card.img = card.load_img()\n card.rect = card.img.get_rect()\n card.rect.center = (x, y)\n display = gameDisplay.blit(card.img, card.rect)\n elif len(hand) == 3:\n x = 540\n y = 500\n for card in hand:\n card.img = card.load_img()\n card.rect = card.img.get_rect()\n card.rect.center = (x, y)\n display = gameDisplay.blit(card.img, card.rect)\n x += 100\n\n return\n\n\nget_hand_card_pos()\n\n\n\ndef play_card(card):\n board.cards_played.append(card)\n hand.remove(card)\n\n angle = random.choice(angles)\n gameDisplay.blit(pygame.transform.rotozoom(\n card.img, angle, 0.55), (r_g_z_x, r_g_z_y))\n gameDisplay.blit(board_bottom_half, (0, 25))\n get_hand_card_pos()\n\n \n # Check if another same rank card is in hand\n\n # Option to play another card\n\n # If card in hand - drop card, allow to play another card.\n \n return\n\n\ndef turn(player):\n for card in hand:\n if card.rect.collidepoint(pos) and card.playable == True:\n if len(board.cards_played) == 0:\n if card.rank == 10:\n play_card(card)\n board.cards_played.clear()\n gameDisplay.blit(board_top_half, (0, 25))\n \n\n elif card.rank == 3:\n play_card(card)\n board.cards_played.clear()\n gameDisplay.blit(board_top_half, (0, 25))\n \n else:\n play_card(card)\n \n\n elif len(board.cards_played) > 0:\n if card.rank == 10:\n play_card(card)\n board.cards_played.clear()\n gameDisplay.blit(board_top_half, (0, 25))\n \n\n elif card.rank == 2 or card.rank == 3:\n play_card(card)\n \n\n elif card.rank == 6:\n if board.cards_played[-1].rank < 6:\n play_card(card)\n \n\n elif board.cards_played[-1].rank < card.rank:\n if not board.cards_played[-1].rank == 6:\n play_card(card)\n \n elif board.cards_played[-1].rank == 6:\n if card.rank < 6:\n play_card(card)\n\n\n elif board.cards_played[-1].rank == card.rank:\n if len(board.cards_played) >= 3:\n if board.cards_played[-3].rank == board.cards_played[-2].rank and board.cards_played[-2].rank == board.cards_played[-1].rank and board.cards_played[-1].rank == card.rank:\n play_card(card)\n board.cards_played.clear()\n gameDisplay.blit(board_top_half, (0, 25))\n \n \n else:\n play_card(card)\n \n if et_rect.collidepoint(pos):\n print('End turn')\n\n\n# def set_playable():\n# test_hand = []\n# for card in hand:\n# test_hand.append(card.rank)\n# if len(board.cards_played) == 0:\n# card.playable = True\n# elif len(board.cards_played) > 0:\n# if card.rank == 10:\n# card.playable = True\n# elif card.rank == 2:\n# card.playable = True\n# elif card.rank == 3:\n# card.playable = True\n# elif card.rank == 6:\n# if board.cards_played[-1].rank < 6: \n\n# elif board.cards_played[-1].rank < card.rank:\n# if not board.cards_played[-1].rank == 6:\n \n# elif board.cards_played[-1].rank == 6:\n# if card.rank < 6:\n\n# elif board.cards_played[-1].rank == card.rank:\n# if len(board.cards_played) >= 3:\n# if board.cards_played[-3].rank == board.cards_played[-2].rank and board.cards_played[-2].rank == board.cards_played[-1].rank and board.cards_played[-1].rank == card.rank:\n \n# else:\n \n\n\n\nwhile not crashed:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n crashed = True\n\n if event.type == pygame.MOUSEBUTTONDOWN:\n pos = pygame.mouse.get_pos()\n\n\n r_g_z_x = random.choice(g_z_x)\n r_g_z_y = random.choice(g_z_y)\n turn(player)\n \n\n\n pygame.display.update()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"173351600","text":"import os\nimport moviepy.editor as mp\n\n\ndef convert_signle(video_path):\n clip = mp.VideoFileClip(video_path)\n clip.audio.write_audiofile(os.path.splitext(video_path)[0] + \".mp3\", verbose=False, progress_bar=False)\n\n\ndef convert_multiple(output_dir, list_path):\n lv = open(list_path, \"r\")\n line = lv.readline().rstrip('\\n')\n while line:\n clip = mp.VideoFileClip(output_dir + \"/\" + line)\n clip.audio.write_audiofile(os.path.splitext(output_dir + \"/\" + line)[0] + \".mp3\", verbose=False,\n progress_bar=False)\n line = lv.readline().rstrip('\\n')\n lv.close()\n","sub_path":"convert_mp3.py","file_name":"convert_mp3.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"320735108","text":"# Copyright (c) 2015-2019, Activision Publishing, Inc.\n# 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, this\n# 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# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\nimport re\nimport collections\n\nif sys.version_info[0] == 3:\n str_types = (str,)\n unicode = str\n Iterable = collections.abc.Iterable\nelse:\n str_types = (basestring,)\n unicode = unicode\n Iterable = collections.Iterable\n\n\nclass StringMixin(object):\n \"\"\"String assertions mixin.\"\"\"\n\n def is_equal_to_ignoring_case(self, other):\n \"\"\"Asserts that val is case-insensitive equal to other.\"\"\"\n if not isinstance(self.val, str_types):\n raise TypeError('val is not a string')\n if not isinstance(other, str_types):\n raise TypeError('given arg must be a string')\n if self.val.lower() != other.lower():\n self._err('Expected <%s> to be case-insensitive equal to <%s>, but was not.' % (self.val, other))\n return self\n\n def contains_ignoring_case(self, *items):\n \"\"\"Asserts that val is string and contains the given item or items.\"\"\"\n if len(items) == 0:\n raise ValueError('one or more args must be given')\n if isinstance(self.val, str_types):\n if len(items) == 1:\n if not isinstance(items[0], str_types):\n raise TypeError('given arg must be a string')\n if items[0].lower() not in self.val.lower():\n self._err('Expected <%s> to case-insensitive contain item <%s>, but did not.' % (self.val, items[0]))\n else:\n missing = []\n for i in items:\n if not isinstance(i, str_types):\n raise TypeError('given args must all be strings')\n if i.lower() not in self.val.lower():\n missing.append(i)\n if missing:\n self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n elif isinstance(self.val, Iterable):\n missing = []\n for i in items:\n if not isinstance(i, str_types):\n raise TypeError('given args must all be strings')\n found = False\n for v in self.val:\n if not isinstance(v, str_types):\n raise TypeError('val items must all be strings')\n if i.lower() == v.lower():\n found = True\n break\n if not found:\n missing.append(i)\n if missing:\n self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))\n else:\n raise TypeError('val is not a string or iterable')\n return self\n\n def starts_with(self, prefix):\n \"\"\"Asserts that val is string or iterable and starts with prefix.\"\"\"\n if prefix is None:\n raise TypeError('given prefix arg must not be none')\n if isinstance(self.val, str_types):\n if not isinstance(prefix, str_types):\n raise TypeError('given prefix arg must be a string')\n if len(prefix) == 0:\n raise ValueError('given prefix arg must not be empty')\n if not self.val.startswith(prefix):\n self._err('Expected <%s> to start with <%s>, but did not.' % (self.val, prefix))\n elif isinstance(self.val, Iterable):\n if len(self.val) == 0:\n raise ValueError('val must not be empty')\n first = next(iter(self.val))\n if first != prefix:\n self._err('Expected %s to start with <%s>, but did not.' % (self.val, prefix))\n else:\n raise TypeError('val is not a string or iterable')\n return self\n\n def ends_with(self, suffix):\n \"\"\"Asserts that val is string or iterable and ends with suffix.\"\"\"\n if suffix is None:\n raise TypeError('given suffix arg must not be none')\n if isinstance(self.val, str_types):\n if not isinstance(suffix, str_types):\n raise TypeError('given suffix arg must be a string')\n if len(suffix) == 0:\n raise ValueError('given suffix arg must not be empty')\n if not self.val.endswith(suffix):\n self._err('Expected <%s> to end with <%s>, but did not.' % (self.val, suffix))\n elif isinstance(self.val, Iterable):\n if len(self.val) == 0:\n raise ValueError('val must not be empty')\n last = None\n for last in self.val:\n pass\n if last != suffix:\n self._err('Expected %s to end with <%s>, but did not.' % (self.val, suffix))\n else:\n raise TypeError('val is not a string or iterable')\n return self\n\n def matches(self, pattern):\n \"\"\"Asserts that val is string and matches regex pattern.\"\"\"\n if not isinstance(self.val, str_types):\n raise TypeError('val is not a string')\n if not isinstance(pattern, str_types):\n raise TypeError('given pattern arg must be a string')\n if len(pattern) == 0:\n raise ValueError('given pattern arg must not be empty')\n if re.search(pattern, self.val) is None:\n self._err('Expected <%s> to match pattern <%s>, but did not.' % (self.val, pattern))\n return self\n\n def does_not_match(self, pattern):\n \"\"\"Asserts that val is string and does not match regex pattern.\"\"\"\n if not isinstance(self.val, str_types):\n raise TypeError('val is not a string')\n if not isinstance(pattern, str_types):\n raise TypeError('given pattern arg must be a string')\n if len(pattern) == 0:\n raise ValueError('given pattern arg must not be empty')\n if re.search(pattern, self.val) is not None:\n self._err('Expected <%s> to not match pattern <%s>, but did.' % (self.val, pattern))\n return self\n\n def is_alpha(self):\n \"\"\"Asserts that val is non-empty string and all characters are alphabetic.\"\"\"\n if not isinstance(self.val, str_types):\n raise TypeError('val is not a string')\n if len(self.val) == 0:\n raise ValueError('val is empty')\n if not self.val.isalpha():\n self._err('Expected <%s> to contain only alphabetic chars, but did not.' % self.val)\n return self\n\n def is_digit(self):\n \"\"\"Asserts that val is non-empty string and all characters are digits.\"\"\"\n if not isinstance(self.val, str_types):\n raise TypeError('val is not a string')\n if len(self.val) == 0:\n raise ValueError('val is empty')\n if not self.val.isdigit():\n self._err('Expected <%s> to contain only digits, but did not.' % self.val)\n return self\n\n def is_lower(self):\n \"\"\"Asserts that val is non-empty string and all characters are lowercase.\"\"\"\n if not isinstance(self.val, str_types):\n raise TypeError('val is not a string')\n if len(self.val) == 0:\n raise ValueError('val is empty')\n if self.val != self.val.lower():\n self._err('Expected <%s> to contain only lowercase chars, but did not.' % self.val)\n return self\n\n def is_upper(self):\n \"\"\"Asserts that val is non-empty string and all characters are uppercase.\"\"\"\n if not isinstance(self.val, str_types):\n raise TypeError('val is not a string')\n if len(self.val) == 0:\n raise ValueError('val is empty')\n if self.val != self.val.upper():\n self._err('Expected <%s> to contain only uppercase chars, but did not.' % self.val)\n return self\n\n def is_unicode(self):\n \"\"\"Asserts that val is a unicode string.\"\"\"\n if type(self.val) is not unicode:\n self._err('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__))\n return self\n","sub_path":"assertpy/string.py","file_name":"string.py","file_ext":"py","file_size_in_byte":9571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"635624386","text":"\"\"\"\n -----------------------------------------------------------------------------------------------------------\n Package: AequilibraE\n\n Name: Iterative proportinal fitting\n Purpose: Loads GUI for applying proportinal fitting\n\n Original Author: Pedro Camargo (c@margo.co)\n Contributors:\n Last edited by: Pedro Camargo\n\n Website: www.AequilibraE.com\n Repository: https://github.com/AequilibraE/AequilibraE\n\n Created: 2016-09-29\n Updated: 2017-06-13\n Copyright: (c) AequilibraE authors\n Licence: See LICENSE.TXT\n -----------------------------------------------------------------------------------------------------------\n \"\"\"\n\nimport os\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4 import uic\nfrom functools import partial\nimport numpy as np\nimport warnings\n\n\nfrom ..common_tools.auxiliary_functions import *\nfrom ..common_tools import ReportDialog\nfrom ..common_tools import LoadMatrixDialog, LoadVectorDialog\n\nfrom ipf_procedure import IpfProcedure\n\nFORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), 'forms/ui_ipf.ui'))\n\ntry:\n import omx\n OMX = True\nexcept:\n OMX = False\n\nwarnings.filterwarnings('ignore')\n\nclass IpfDialog(QDialog, FORM_CLASS):\n def __init__(self, iface):\n QDialog.__init__(self)\n self.iface = iface\n self.setupUi(self)\n self.error = None\n self.outname = None\n self.report = None\n\n self.path = standard_path()\n\n # Hide the progress bars\n self.progressbar.setVisible(False)\n self.progress_label.setVisible(False)\n self.progressbar.setValue(0)\n self.progress_label.setText('')\n\n # FIRST, we connect slot signals\n # For changing the input matrix\n self.but_load_new_matrix.clicked.connect(self.find_matrices)\n self.but_load_rows.clicked.connect(partial(self.find_vectors, 'zones'))\n self.but_load_columns.clicked.connect(partial(self.find_vectors, 'columns'))\n\n self.but_choose_output_name.clicked.connect(self.browse_outfile)\n\n # Create desire lines\n self.apply_ipf.clicked.connect(self.run)\n\n def browse_outfile(self):\n file_types = \"Comma-separated files(*.csv);;Numpy Binnary Array(*.npy)\"\n if OMX:\n file_types += \";;OpenMatrix(*.omx)\"\n new_name = QFileDialog.getSaveFileName(None, 'Result matrix', self.path, file_types)\n if new_name is not None:\n self.outname = new_name\n self.output_name.setText(new_name)\n\n def run_thread(self):\n QObject.connect(self.worker_thread, SIGNAL(\"ProgressValue( PyQt_PyObject )\"), self.progress_value_from_thread)\n QObject.connect(self.worker_thread, SIGNAL(\"ProgressText( PyQt_PyObject )\"), self.progress_text_from_thread)\n QObject.connect(self.worker_thread, SIGNAL(\"ProgressMaxValue( PyQt_PyObject )\"), self.progress_range_from_thread)\n QObject.connect(self.worker_thread, SIGNAL(\"finished_threaded_procedure( PyQt_PyObject )\"),\n self.job_finished_from_thread)\n self.worker_thread.start()\n self.exec_()\n\n def find_matrices(self):\n dlg2 = LoadMatrixDialog(self.iface)\n dlg2.show()\n dlg2.exec_()\n if dlg2.matrix is not None:\n self.matrix = dlg2.matrix\n self.matrix_name.setText('LOADED')\n self.matrix_total.setText(str(\"{:,.2f}\".format(float(np.sum(self.matrix)))))\n\n def find_vectors(self, destination):\n dlg2 = LoadVectorDialog(self.iface)\n dlg2.show()\n dlg2.exec_()\n if dlg2.vector is not None:\n if destination == 'zones':\n self.rows = dlg2.vector\n self.rows_name.setText('LOADED')\n self.rows_total.setText(\"{:20,.4f}\".format(np.sum(self.rows)))\n else:\n self.columns = dlg2.vector\n self.columns_name.setText('LOADED')\n self.columns_total.setText(\"{:20,.4f}\".format(np.sum(self.columns)))\n\n def progress_range_from_thread(self, val):\n self.progressbar.setRange(0, val[1])\n\n def progress_value_from_thread(self, value):\n self.progressbar.setValue(value[1])\n\n def progress_text_from_thread(self, value):\n self.progress_label.setText(value[1])\n\n def job_finished_from_thread(self, success):\n if self.worker_thread.error is not None:\n qgis.utils.iface.messageBar().pushMessage(\"Procedure error: \", self.worker_thread.error, level=3)\n else:\n self.output = self.worker_thread.ipf.output\n self.report = self.worker_thread.ipf.report\n\n if self.outname[-3:].upper() == 'NPY':\n np.save(self.outname, self.output)\n else:\n outp = open(self.outname, 'w')\n print >> outp, 'O,D,Flow'\n print_zeros = get_parameter_chain(['system', 'report zeros'])\n if print_zeros:\n for i in range(self.output.shape[0]):\n for j in range(self.output.shape[1]):\n print >> outp, str(i) + ',' + str(j) + ',' + str(self.output[i, j])\n else:\n for i in range(self.output.shape[0]):\n for j in range(self.output.shape[1]):\n if self.output[i, j]:\n print >> outp, str(i) + ',' + str(j) + ',' + str(self.output[i, j])\n outp.flush()\n outp.close()\n self.exit_procedure()\n\n def run(self):\n if self.matrix is not None and self.rows is not None and self.columns is not None:\n self.worker_thread = IpfProcedure(qgis.utils.iface.mainWindow(), self.matrix, self.rows, self.columns)\n self.run_thread()\n else:\n qgis.utils.iface.messageBar().pushMessage(\"Matrix not loaded\", '', level=3)\n\n def exit_procedure(self):\n self.close()\n dlg2 = ReportDialog(self.iface, self.report)\n dlg2.show()\n dlg2.exec_()\n\n\n\n","sub_path":"distribution/ipf_dialog.py","file_name":"ipf_dialog.py","file_ext":"py","file_size_in_byte":6044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"32705215","text":"import logging as log\nimport os\n\nfrom inspect import stack\n\ndef exec_and_check(cmd):\n exit_code = os.system(cmd)\n if exit_code != 0:\n raise RuntimeError(\"'{}' failed with exit code {}\".format(cmd, exit_code))\n\ndef log_call(level=log.DEBUG):\n method = stack()[1].function\n log.log(level, \"%s() called\", method)\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"503025835","text":"import pandas as pd\nfrom datetime import datetime\nfrom decimal import Decimal\n\nfrom cinderella.datatypes import Transactions, StatementCategory\nfrom cinderella.parsers.base import StatementParser\n\n\nclass Cathay(StatementParser):\n identifier = \"cathay\"\n\n def __init__(self):\n super().__init__()\n self.default_source_accounts = {\n StatementCategory.card: \"Liabilities:CreditCard:Cathay\",\n StatementCategory.bank: \"Assets:Bank:Cathay\",\n }\n\n def _read_statement(self, filepath: str) -> pd.DataFrame:\n if StatementCategory.bank.name in filepath:\n df = pd.read_csv(\n filepath, encoding=\"big5\", skiprows=1, encoding_errors=\"replace\"\n )\n elif StatementCategory.card.name in filepath:\n # 國泰帳單沒有提供年份,需由帳單第一行標題取得。可能有跨年份的問題\n with open(filepath, \"r\", encoding=\"big5\") as f:\n title = f.readline()\n self.statement_year = int(title[0:3]) + 1911\n self.statement_month = str(title.split(\"年\")[1][0:2])\n\n df = pd.read_csv(\n filepath, encoding=\"big5\", skiprows=20, encoding_errors=\"replace\"\n )\n\n df = df.applymap(str)\n return df\n\n def _parse_card_statement(self, records: pd.DataFrame) -> Transactions:\n category = StatementCategory.card\n transactions = Transactions(category, self.identifier)\n\n for _, record in records.iterrows():\n indicator = record[\"卡號末四碼\"]\n if pd.isna(indicator) or not indicator.strip().isdigit():\n continue\n\n item_month, item_day = record[0].split(\"/\", maxsplit=1)\n # 處理可能有跨年份的問題,1月帳單可能有去年12月的帳\n if self.statement_month == \"01\" and item_month == \"12\":\n date = datetime(\n year=self.statement_year - 1,\n month=int(item_month),\n day=int(item_day),\n )\n else:\n date = datetime(\n year=self.statement_year, month=int(item_month), day=int(item_day)\n )\n\n title = record[\"交易說明\"].strip()\n currency = \"TWD\"\n price = Decimal(record[\"臺幣金額\"])\n account = self.default_source_accounts[category]\n\n transaction = self.beancount_api.make_transaction(\n date, title, account, -price, currency\n )\n transactions.append(transaction)\n\n if record[\"外幣金額\"].strip():\n self.beancount_api.add_transaction_comment(\n transaction, f\"{record['幣別']}-{record['外幣金額']}\"\n )\n\n return transactions\n\n def _parse_bank_statement(self, records: pd.DataFrame) -> Transactions:\n category = StatementCategory.bank\n transactions = Transactions(category, self.identifier)\n for _, record in records.iterrows():\n date = datetime.strptime(str(record[0]), \"%Y%m%d\")\n\n if record[2].strip(): # 轉出\n price = Decimal(record[2])\n price *= -1\n elif record[3].strip(): # 轉入\n price = Decimal(record[3])\n else:\n raise RuntimeError(\n f\"Can not parse {self.identifier} {category.name} statement {record}\"\n )\n\n extra = None\n if record[\"備註\"].strip():\n title = record[\"備註\"]\n if record[\"交易資訊\"].strip():\n extra = record[\"交易資訊\"]\n elif record[\"交易資訊\"].strip():\n title = record[\"交易資訊\"]\n else:\n title = record[\"說明\"]\n\n title = title.strip()\n currency = \"TWD\"\n account = self.default_source_accounts[category]\n\n transaction = self.beancount_api.make_transaction(\n date, title, account, price, currency\n )\n transactions.append(transaction)\n\n self.beancount_api.add_transaction_comment(transaction, f\"{record['說明']}\")\n if extra:\n self.beancount_api.add_transaction_comment(transaction, extra)\n\n return transactions\n","sub_path":"cinderella/parsers/cathay.py","file_name":"cathay.py","file_ext":"py","file_size_in_byte":4376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"32175354","text":"from random import randint\n\n\nclass Computer():\n cpu = \"i5\"\n ram = \"8G\"\n storage = \"256G\"\n videoCard = \"GTX1050\"\n\n def configurationList(self):\n print(\"cpu:\", self.cpu)\n print(\"ram:\", self.ram)\n print(\"storage:\", self.storage)\n print(\"video card:\", self.videoCard)\n\n def updateComputer(self, c, r, s, v):\n self.cpu = c\n self.ram = r\n self.storage = s\n self.videoCard = v\n\n\nmacbookPro = Computer()\nmacbookPro.configurationList()\nprint(\"这是你的电脑配置:\")\nmacbookPro.configurationList()\n\n\nwhile True:\n k = input(\"你需要升级你的系统配置么?请输入y/n\")\n if k == \"y\":\n c = input(\"请输入新的cpu型号:\")\n r = input(\"请输入新的ram大小:\")\n s = input(\"请输入新的储存空间大小:\")\n v = input(\"请输入新的显卡型号:\")\n macbookPro.updateComputer(c, r, s, v)\n print(\"这是你的电脑配置:\")\n macbookPro.configurationList()\n\n elif k == \"n\":\n print(\"正在跳转到下一界面......\")\n\n else:\n print(\"抱歉,输入有误。\")\n\n v = input(\"是否还要继续修改配置?请输入y/n\")\n if v == \"y\":\n print(\"请稍后\", end=\" \")\n print(\"*\" * 20)\n\n elif v == \"n\":\n break\n else:\n print(\"抱歉,输入有误。\")\n\nprint(\"更新完毕!\")\n\n\n\n\n","sub_path":"oop/Student.py","file_name":"Student.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"37047089","text":"from reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import A4\n\nclass HarmWriter:\n line_width = 20\n line_spacing = 50\n word_spacing = 50\n width, height = A4\n marginw = 20\n marginh = 20\n\n def __init__(self, filename):\n self.c = canvas.Canvas(filename)\n self.c.setFont(\"Helvetica\", 15)\n self.line = 1\n self.word = 1\n self.bar = 1\n\n def writeTitle(self, title):\n self.c.setFont(\"Helvetica\", 30)\n self.c.drawString(self.width / 2 - len(title) * 8, self.height - self.marginh * 2, title)\n self.line += 0.5\n\n\n def write(self, label, chords):\n label = label.strip() \n self.c.setFont(\"Helvetica\", 20)\n self.drawS(label)\n self.c.setFont(\"Helvetica\", 15)\n self.word = 1\n self.line += 0.5\n for chord in chords:\n word_increment = 1\n chord = chord.strip()\n if chord == \"|\":\n self.bar += 1\n word_increment = 0.5\n #if self.bar == 6:\n # self.word = 1\n # self.line += 1\n # self.bar = 1\n if self.word * self.word_spacing > self.width - self.marginw:\n self.word = 1\n self.line += 1\n self.bar = 1\n self.drawS(chord)\n self.word += word_increment\n\n def writeStructTitle(self):\n self.drawS(\"Structure : \")\n self.nextLine(0.5)\n self.word_spacing = 50\n\n def writeStruct(self, label, iterations):\n self.drawS(label)\n self.word += 0.5\n if iterations != '1':\n self.drawS(\"X\" + iterations)\n\n def save(self):\n self.c.showPage()\n self.c.save()\n\n def drawS(self, string):\n self.c.drawString(self.word * self.word_spacing, self.height - self.line * self.line_spacing - self.marginh, string)\n\n def nextLine(self, increment):\n self.line += increment\n self.word = 1\n self.bar = 1\n","sub_path":"main/IO/writer.py","file_name":"writer.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"172144630","text":"from Handlers.GameAsset import *\nfrom Mine.Mine import *\nfrom Handlers.Card import *\n\n\nclass Save:\n def __init__(self):\n self.game_asset = None\n self.layer_player = None\n\n def save(self):\n # Save all components\n self.game_asset = GameAsset()\n player_1 = self.save_player(Content.GameAsset.player_1)\n player_2 = self.save_player(Content.GameAsset.player_2)\n self.save_game_asset(player_1, player_2)\n\n def save_player(self, p):\n # Save player components\n if p.getName() == Content.GameAsset.computer_name:\n player = CPUPlayer(p.getName())\n else:\n player = Player(p.getName())\n\n player.ships = self.save_ships(p.ships)\n player.ships_removed = self.save_ships(p.ships_removed)\n player.mines = self.save_player_mines(p)\n player.cards = self.save_cards(p.getCards())\n\n player.attacks_left = p.attacks_left\n player.cards_left = p.cards_left\n\n player.extra_sabotage = p.extra_sabotage\n player.extra_smokescreen = p.extra_smokescreen\n\n return player\n\n def save_ships(self, l):\n # Save ship components\n ships = []\n for s in range(len(l)):\n ship = Ship(l[s].health, Position(l[s].pos.getX(), l[s].pos.getY()), l[s].steps, l[s].atk_range)\n ship.length = l[s].length\n ship.health = l[s].health\n ship.health_max = l[s].health_max\n ship.pointing_up = l[s].pointing_up\n ship.steps_made = l[s].steps_made\n ship.attack = l[s].attack\n ship.turned = l[s].turned\n ship.immobile = l[s].immobile\n ship.extra_steps = l[s].extra_steps\n ship.immune_mine = l[s].immune_mine\n ship.reached_end = l[s].reached_end\n\n ship.parts = []\n for p in range(len(l[s].parts)):\n ship.parts.append(ShipPart(Position(l[s].parts[p].pos.getX(), l[s].parts[p].pos.getY())))\n\n ships.append(ship)\n return ships\n\n def save_player_mines(self, p):\n # Save mine components\n mines = []\n for m in range(len(p.mines)):\n mines.append(Mine(Position(p.mines[m].getPosition().getX(), p.mines[m].getPosition().getY()), p.mines[m].image))\n return mines\n\n def save_cards(self, l):\n # Save card components\n cards = []\n for c in range(len(l)):\n cards.append(Card(l[c].name, l[c].description, l[c].type, l[c].f, l[c].image))\n return cards\n\n def save_game_asset(self, player_1, player_2):\n # Save all information about the game\n self.game_asset.player_1 = player_1\n self.game_asset.player_2 = player_2\n\n self.game_asset.player_turn = Content.GameAsset.player_turn\n\n self.game_asset.player_1_health_to = Content.GameAsset.player_1_health_to\n self.game_asset.player_2_health_to = Content.GameAsset.player_2_health_to\n self.game_asset.player_1_health = Content.GameAsset.player_1_health\n self.game_asset.player_2_health = Content.GameAsset.player_2_health\n\n self.game_asset.init_game = Content.GameAsset.init_game\n\n self.game_asset.player_1_page = Content.GameAsset.player_1_page\n self.game_asset.player_2_page = Content.GameAsset.player_2_page\n self.game_asset.player_1_action = Content.GameAsset.player_1_action\n self.game_asset.player_2_action = Content.GameAsset.player_2_action\n\n self.game_asset.normal_deck = self.save_cards(Content.GameAsset.normal_deck)\n self.game_asset.special_deck = self.save_cards(Content.GameAsset.special_deck)\n\n self.game_asset.extra_damage = Content.GameAsset.extra_damage\n self.game_asset.extra_range = Content.GameAsset.extra_range\n self.game_asset.extra_move = Content.GameAsset.extra_move\n self.game_asset.extra_card_draw = Content.GameAsset.extra_card_draw\n self.game_asset.extra_sabotage = Content.GameAsset.extra_sabotage\n self.game_asset.sabotage = Content.GameAsset.sabotage\n self.game_asset.extra_smokescreen = Content.GameAsset.extra_smokescreen\n self.game_asset.smokescreen = Content.GameAsset.smokescreen\n self.game_asset.immobile = Content.GameAsset.immobile\n\n self.game_asset.received_card = Content.GameAsset.received_card\n self.game_asset.layer_action = Content.GameAsset.layer_action\n self.game_asset.stance_current = Content.GameAsset.stance_current\n\n def load(self):\n # Set current information to the desired save\n Content.GameAsset = self.game_asset\n Game.screenmanager.getScreen().layer.setPlayer(self.game_asset.getCurrentPlayer())\n","sub_path":"History/Save.py","file_name":"Save.py","file_ext":"py","file_size_in_byte":4693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"218472832","text":"import os\nimport pandas as pd\nimport json\nfrom common import *\n\nwith open(\"book_ids.json\") as book_ids_file:\n\tbook_ids = json.load(book_ids_file)\n\n\tall_books = pd.DataFrame()\n\tfor filename in os.listdir(\"raw_data/book/\"):\n\t\tprint(\"Reading file\", filename)\n\t\tcsv = pd.read_csv(\"raw_data/book/\" + filename)\n\t\tcsv.columns = map(str.lower, csv.columns)\n\t\tcsv[\"id\"] = csv.apply(lambda row: book_ids[process_book_name(row[\"name\"])], axis=1)\n\t\tall_books = all_books.append(csv, ignore_index=True)\n\n\tprint(all_books.head())\n\tprint(all_books.shape)\n\tall_books = all_books.set_index(\"id\")\n\tall_books.to_csv(\"all_books.csv\")","sub_path":"2020_1/DW-DCC189/FinalTP/Pre-process data/create_full_book_db.py","file_name":"create_full_book_db.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"199636792","text":"from core import *\nfrom sympy import *\nimport arities, functions, sys\n\ncode_page = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶'''\ncode_page += '''°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”'''\nescapemap = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`a\\bcdefghijklm\\nopq\\rs\\tuvwxyz{|}~¶'''\nescapemap += '''°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”'''\n\ncodeblock_tokens = {\n 'ß': 'BlockSortToken',\n 'Ɓ': 'BlockStackSortToken',\n '€': 'BlockMapToken',\n '£': 'BlockStackMapToken',\n 'þ': 'BlockFilterToken',\n 'ʠ': 'BlockFilterOutToken',\n '/': 'BlockReduceToken',\n '\\\\': 'BlockReduceCumulativeToken',\n '¿': 'ConditionalWhileToken',\n '¢': 'ConditionalPopWhileToken',\n '¡': 'ConditionalUniqueWhileToken'\n}\n\nextenders = ['Æ', 'Œ', 'æ', 'œ']\n\nbracket_closers = {\n '[': ']',\n '(': ')'\n}\n\nmultitokens = {\n '[': 'MultivalueListToken',\n '(': 'MultivalueSplatToken'\n}\n\nmultivalue_converters = {\n 'MultivalueListToken': list,\n 'MultivalueSplatToken': splat\n}\n\ndef debug(text):\n if verbose:\n print(text)\n\ndef escape(char):\n return escapemap[code_page.find(char)]\n\ndef unescape(char):\n return '\\\\' + code_page[escapemap.find(char)]\n\ndef unescapify(string):\n return string if type(string) != type('') else ''.join([char if char in code_page else unescape(char) for char in string])\n\ndef baseconvert(string, base):\n if '.' in string:\n left = string.split('.')[0]\n left = len(left) if base == 1 else len(left) and int(left, base)\n right = string.split('.')[1]\n return left + (len(right) if base == 1 else len(right) and int(right, base)) / base ** len(right)\n return int(string, base)\n\nclass Token():\n def __init__(self, type, content):\n self.type = type\n self.content = content\n def __str__(self):\n return '%s@{%s}' % (self.type, unescapify(self.content))\n def __repr__(self):\n return self.__str__()\n def isLiteral(self):\n return self.type.startswith('Literal')\n def isMultivalue(self):\n return self.type.startswith('Multivalue')\n def isBlock(self):\n return self.type.startswith('Block')\n def isBlockStack(self):\n return self.type.startswith('BlockStack')\n def isInstruction(self):\n return self.type.startswith('Instruction')\n def isCombo(self):\n return self.type.startswith('Combo')\n def isConditional(self):\n return self.type.startswith('Conditional')\n def isBlockToker(self):\n return self.isBlock() or self.isConditional()\n\nclass Tokenizer():\n def __init__(self, code):\n self.code = code.strip()\n self.index = 0\n self.tokens = []\n def tokenize(code):\n tokenizer = Tokenizer(code)\n while tokenizer.hasNext(): tokenizer.next()\n return tokenizer.tokens\n def hasNext(self):\n return self.index < len(self.code)\n def advance(self):\n self.index += 1\n return self.index - 1\n def current(self):\n return self.code[self.index]\n def take(self):\n self.next()\n token = self.tokens[-1]\n self.tokens = self.tokens[:-1]\n return token\n def peek(self):\n index = self.index\n self.advance()\n token = self.take()\n self.index = index\n return token\n def next(self):\n debug('( Now on $%s$ )' % self.current())\n if self.current() == ' ':\n self.advance()\n debug('( Tokenskip )')\n self.next()\n elif self.current() == '“':\n self.advance()\n strings = ['']\n while self.current() != '”':\n if self.current() == '\\\\':\n strings[-1] += escape(self.code[self.index + 1])\n self.advance()\n else:\n if self.current() == '“':\n strings.append('')\n else:\n strings[-1] += self.current()\n self.advance()\n self.advance()\n self.tokens.append(Token('LiteralStringToken', strings[0]) if len(strings) == 1 else Token('MultivalueListToken', [Token('LiteralStringToken', string) for string in strings]))\n elif self.current() == '”':\n self.advance()\n if self.current() == '\\\\':\n self.advance()\n self.tokens.append(Token('LiteralStringToken', escape(self.code[self.advance()])))\n else:\n self.tokens.append(Token('LiteralStringToken', self.code[self.advance()]))\n elif self.current() in '0123456789.':\n decimal = False\n number = ''\n while self.hasNext():\n if self.current() in '0123456789' or self.current() == '.' and not decimal:\n if self.current() == '.': decimal = True\n number += self.current()\n self.advance()\n else:\n break\n self.tokens.append(Token('LiteralNumberToken', Rational(number)))\n elif self.current() in bracket_closers:\n array = []\n opener = self.current()\n closer = bracket_closers[opener]\n self.advance()\n while self.hasNext() and self.current() != closer:\n array.append(self.take())\n self.advance()\n self.tokens.append(Token(multitokens[opener], array))\n elif self.current() in codeblock_tokens:\n self.tokens.append(Token(codeblock_tokens[self.current()], ''))\n self.advance()\n elif self.current() == '»':\n tokenlist = []\n buffer = 0\n while buffer or not self.tokens[-1].isBlockToker():\n debug('( Token Grouper found token %s )' % str(self.tokens[-1]))\n tokenlist = [self.tokens[-1]] + tokenlist\n self.tokens = self.tokens[:-1]\n debug('( Token list is now %s )' % str(self.tokens))\n if tokenlist[0].isCombo():\n buffer += 1\n elif tokenlist[0].isBlockToker():\n buffer -= 1\n self.tokens.append(Token('ComboToken', tokenlist))\n self.advance()\n elif self.current() in extenders:\n extender = self.current()\n self.advance()\n self.tokens.append(Token('InstructionToken', extender + self.code[self.advance()]))\n else:\n self.tokens.append(Token('InstructionToken', self.code[self.advance()]))\n debug('Token List: %s' % str(self.tokens))\n\nclass Interpreter():\n def __init__(self, tokens):\n self.tokens = tokens\n self.instruction_queue = []\n self.mem = []\n def operate(tokens, mem):\n debug('( Operating on %s )' % str(tokens))\n interpreter = Interpreter(tokens)\n interpreter.mem = mem\n debug('( Interpreter initialized with mem %s and tokens %s )' % (str(interpreter.mem), str(interpreter.tokens)))\n while interpreter.hasNext(): interpreter.next(); debug('( Stack is now %s )' % str(interpreter.mem))\n return interpreter.mem[::-1]\n def evaluate(code, mem):\n return Interpreter.operate(Tokenizer.tokenize(code), mem)\n def nextToken(self):\n return self.tokens[0]\n def peek(self):\n return self.mem[0]\n def count(self, count):\n return self.mem[:count]\n def pop(self):\n front = self.peek()\n self.mem = self.mem[1:]\n return front\n def popCount(self, count):\n front = self.count(count)\n self.mem = self.mem[count:]\n return front\n def popAll(self):\n return self.popCount(len(self.mem))\n def push(self, value):\n if value == None:\n pass\n elif type(value) == type(actualNone()):\n self.mem = [None] + self.mem\n elif hasattr(value, '__splat__') and value.__splat__:\n if value.force:\n self.pushAll(*value.array)\n else:\n self.mem = [list(value.array)] + self.mem\n else:\n self.mem = [value] + self.mem\n return self\n def pushAll(self, *values):\n for value in values[::-1]:\n self.push(value)\n def hasNext(self):\n return bool(self.tokens)\n def update(self):\n if self.instruction_queue:\n for i in range(len(self.instruction_queue)):\n token = self.instruction_queue[i]\n arity = arities.arities[token.content]\n if len(self.mem) >= arity:\n debug('( %s operates with enough items on stack after push )' % str(token))\n function = functions.functions[token.content]\n arguments = self.popCount(arity)\n self.push(function(*arguments))\n self.instruction_queue = self.instruction_queue[:i] + self.instruction_queue[i + 1:]\n self.update()\n def next(self):\n token = self.tokens[0]\n self.tokens = self.tokens[1:]\n debug('Tokens Left: %s' % str(self.tokens))\n debug('Evaluating %s' % str(token))\n if token.isLiteral():\n debug('( Literal token )')\n self.push(token.content)\n elif token.isMultivalue():\n debug('( Multivalue token )')\n tokenlist = token.content\n valuelist = Interpreter.operate(tokenlist, [])\n self.push(multivalue_converters[token.type](valuelist))\n elif token.isInstruction() and all(char in code_page for char in token.content):\n debug('( Instruction Token )')\n arity = arities.arities[token.content]\n debug('( Arity %d )' % arity)\n if arity == -1:\n debug('( Operates over entire stack )')\n function = functions.functions[token.content]\n arguments = self.popAll()\n self.push(function(*arguments))\n elif arity <= -2:\n debug('( Operates over iterable )')\n if self.mem:\n function = functions.functions[token.content]\n result = []\n top = None\n if isIterable(self.peek()) and (arity != -3 or type(self.peek()) != type('')):\n top = self.pop()\n result = function(*top)\n else:\n result = function(*self.popAll())\n if top != None:\n if (hasattr(result, '__splat__') and result.__splat__) and not result.force: result = result.array\n if type(top) != type(result) and isIterable(result):\n if type(top) == type(''):\n result = str(result)\n elif type(top) == type([]):\n result = list(result)\n self.push(result)\n elif len(self.mem) >= arity:\n debug('( Enough items on stack )')\n function = functions.functions[token.content]\n arguments = self.popCount(arity)\n self.push(function(*arguments))\n else:\n debug('( Not enough items on stack; adding to queue )')\n self.instruction_queue.append(token)\n elif token.isBlock():\n listmode = not token.isBlockStack() and isIterable(type(self.peek()))\n array = self.pop() if listmode else self.popAll()\n def push(array):\n if listmode: self.push(array)\n else: self.pushAll(*array)\n if token.type.endswith('SortToken'):\n push(list(sorted(array, key = lambda x: Interpreter.operate([self.nextToken()], [x]))))\n elif token.type.endswith('MapToken'):\n push(list(map(lambda x: Interpreter.operate([self.nextToken()], [x])[0], array)))\n elif token.type.endswith('FilterToken'):\n push(list(filter(lambda x: Interpreter.operate([self.nextToken()], [x])[0], array)))\n elif token.type.endswith('FilterOutToken'):\n push(list(filter(lambda x: not Interpreter.operate([self.nextToken()], [x])[0], array)))\n elif token.type.endswith('ReduceToken'):\n push(reduce(lambda x, y: Interpreter.operate([self.nextToken()], [x, y])[0], array))\n elif token.type.endswith('ReduceCumulativeToken'):\n push(cumulativeReduce(lambda x, y: Interpreter.operate([self.nextToken()], [x, y])[0], array))\n self.tokens = self.tokens[1:]\n elif token.isConditional():\n if token.type.endswith('WhileToken'):\n debug('Operating WHILE on stack %s' % str(self.mem))\n getter = self.pop if token.type == 'ConditionalPopWhileToken' else self.peek\n values = []\n condition = (lambda: len(set(map(lambda x: tuple(x) if isIterable(x) else x, values))) == len(values)) if token.type == 'ConditionalUniqueWhileToken' else (lambda: self.mem and getter())\n while condition():\n self.mem = Interpreter.operate([self.nextToken()], self.mem)\n values.append(self.mem)\n debug('Stack after WHILE loop: %s' % str(self.mem))\n self.tokens = self.tokens[1:]\n elif token.isCombo():\n self.mem = Interpreter.operate(token.content, self.mem)\n self.update()\n debug('Stack: %s' % str(self.mem))\n\nverbose = False\n\ncode = ''\ncode = sys.argv[1]\ntokens = Tokenizer.tokenize(code)\ndebug('TOKENS: %s' % str(tokens))\n\ninterpreter = Interpreter(tokens)\n\narguments = {}\n\nfor index in range(2, len(sys.argv)):\n if sys.argv[index].startswith('@'):\n arguments[sys.argv[index][1]] = sys.argv[index][2:]\n else:\n interpreter.mem.append(eval(sys.argv[index]))\n\ninterpreter.mem = interpreter.mem[::-1]\n\nwhile interpreter.hasNext():\n interpreter.next()\n\nprint(stringify(interpreter.mem, sigdig = (arguments['s'] if 's' in arguments else 0), chop = ('s' in arguments)))\n","sub_path":"lang.py","file_name":"lang.py","file_ext":"py","file_size_in_byte":14947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"403228053","text":"import Point3D\nimport math\nfrom CubeHV import CubeHV\nimport queue\n\n\nclass Node:\n id = None\n point = None\n lbb = None\n rtf = None\n direction = None\n is_deleted = None\n cube = None\n\n def __init__(self, id, point, cube, direction):\n self.id = id\n self.point = point\n self.direction = direction\n self.is_deleted = False\n self.cube = cube\n\n\nclass KdTree:\n\n root = None\n size = 0\n\n def __init__(self):\n self.size = 0\n\n def is_empty(self):\n return self.size == 0\n\n def get_size(self):\n print(self.size)\n return self.size\n\n def insert(self, id, point):\n self.root = self.insert_node(id, self.root, None, point, 0)\n\n def insert_node(self, id, node, parent, point, compare):\n\n if node is None:\n if self.size == 0:\n self.size += 1\n\n # print(id, point.to_string())\n # print(cube.to_string())\n return Node(id, point, None, 0)\n self.size += 1\n\n return Node(id, point, None, (parent.direction + 1) % 3)\n\n cmp = self.compare(point, node.point, node.direction)\n if cmp < 0:\n node.lbb = self.insert_node(id, node.lbb, node, point, cmp)\n elif cmp >= 0:\n node.rtf = self.insert_node(id, node.rtf, node, point, cmp)\n\n return node\n\n def delete(self, node):\n node.is_delete = True\n\n def nearest(self, point):\n if point is None:\n print(\"Invalid Query Point\")\n\n if self.root is None:\n return None\n return self.nearest_tool(self.root, self.root.point, point)\n\n def nearest_tool(self, node, nearest, point):\n\n if node is None:\n return nearest\n\n if point.dis_square_to(node.point) < point.dis_square_to(nearest):\n nearest = node.point\n\n cmp = self.compare(point, node.point, node.direction)\n\n if cmp < 0:\n nearest = self.nearest_tool(node.lbb, nearest, point)\n if node.rtf is not None:\n if self.cube_square_dis(node, point) < point.dis_square_to(nearest):\n nearest = self.nearest_tool(node.rtf, nearest, point)\n\n if cmp > 0:\n nearest = self.nearest_tool(node.rtf, nearest, point)\n if node.lbb is not None:\n if self.cube_square_dis(node, point) < point.dis_square_to(nearest):\n nearest = self.nearest_tool(node.lbb, nearest, point)\n\n return nearest\n\n def compare(self, p1, p2, direction):\n\n if p1.equals(p2):\n return 0\n\n cmp = None\n if direction == 0:\n if p1.z > p2.z:\n cmp = 1\n else:\n cmp = -1\n\n elif direction == 1:\n if p1.y > p2.y:\n cmp = 1\n else:\n cmp = -1\n\n elif direction == 2:\n if p1.x > p2.x:\n cmp = 1\n else:\n cmp = -1\n else:\n print(\"Distance Error in compare\")\n\n return cmp\n\n def cube_square_dis(self, node, point):\n if node is None:\n return\n if node.direction == 0:\n return abs(node.point.z - point.z) ** 2\n elif node.direction == 1:\n return abs(node.point.y - point.z) ** 2\n elif node.direction == 2:\n return abs(node.point.x - point.x) ** 2\n else:\n print(\"Distance Error in cube_dis\")\n return None\n\n def nearest_dis(self, point):\n return point.dis_to(self.nearest(point))\n\n def radius_query(self, point, dis):\n if point is None:\n print(\"Point is None!\")\n res = []\n return self.radius_query_tool(self.root, res, point, dis)\n\n def radius_query_tool(self, node, res, point, dis):\n if node is None:\n return res\n if node.cube.contained_by_ball(point, dis):\n self.push_all(res, node)\n else:\n if (not node.is_deleted) and point.dis_to(node.point) <= dis:\n res.append(node.id)\n node.is_deleted = True\n\n if node.lbb is not None and \\\n node.lbb.cube.intersect(point, dis):\n res = self.radius_query_tool(node.lbb, res, point, dis)\n if node.rtf is not None and \\\n node.rtf.cube.intersect(point, dis):\n res = self.radius_query_tool(node.rtf, res, point, dis)\n return res\n\n def push_all(self, res, node):\n if node is None:\n return\n else:\n if not node.is_deleted:\n res.append(node.id)\n node.is_deleted = True\n self.push_all(res, node.lbb)\n self.push_all(res, node.rtf)\n\n def visualize_tree(self):\n q = queue.Queue(maxsize=0)\n q.put(self.root)\n while not q.empty():\n len = q.qsize()\n line = ''\n for i in range(len):\n cur = q.get()\n line += (cur.point.to_string() + ' ')\n if cur.lbb is not None:\n q.put(cur.lbb)\n else:\n line += 'none '\n if cur.rtf is not None:\n q.put(cur.rtf)\n else:\n line += 'none '\n print(line)\n\n # def delete_node(self, point):\n # if point is None:\n # raise('None point delete error!')\n # self.root = self.delete_tool(self.root, point)\n #\n # def delete_tool(self, node, point):\n # if node.cube.contains(point):\n # # if the node to be delete has no child\n # if node.point.equals(point):\n # if node.lbb is None and node.rtf is None:\n # return None\n #\n # elif node.rtf is not None:\n # node = find_min(node, node, )\n #\n #\n # else:\n #\n #\n # def find_min_dim(self, node, minNode):\n # if node is None:\n # return minNode\n #\n # if node.direction == 0:\n\n\n\n\n\n\n","sub_path":"myKdtree/KdTree_noCube.py","file_name":"KdTree_noCube.py","file_ext":"py","file_size_in_byte":6103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"487296278","text":"#!/usr/bin/env python3\n\n#https://codeforces.com/problemset/problem/55/A\n#需要推导一下\n\ndef f(n):\n rl = [True]*n #True = nonvisited\n nn = (n*(n-1))//2\n for k in range(n):\n kk = (k*(k+1))//2\n rl[kk%n] = False\n if n%2==0:\n rl[(kk+nn)%n] = False\n return sum(rl)==0\n\nn = int(input())\nprint('YES' if f(n) else 'NO')\n","sub_path":"codeforces/math数学/1200/55A绕圈圈.py","file_name":"55A绕圈圈.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"422277191","text":"\"\"\"\n Handling of reduced data upload\n\n @author: M. Doucet, Oak Ridge National Laboratory\n @copyright: 2015 Oak Ridge National Laboratory\n\"\"\"\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.urlresolvers import reverse\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport urllib2\nimport os\nimport logging\nfrom report.models import DataRun, Instrument\nfrom file_handling.models import ReducedImage, JsonData\nimport users.view_util\n\nfrom django import forms\nfrom django.core.files.base import ContentFile\nfrom django.contrib.auth import login, authenticate\n\nclass UploadFileForm(forms.Form):\n \"\"\"\n Simple form to select a data file on the user's machine\n \"\"\"\n file = forms.FileField(required=False)\n data_url = forms.URLField(required=False)\n username = forms.CharField()\n password = forms.CharField()\n\n\n@csrf_exempt\n@users.view_util.monitor\ndef upload_image(request, instrument, run_id):\n \"\"\"\n Upload an image representing the reduced data\n for a given run\n @param instrument: instrument name\n @param run_id: run number\n \"\"\"\n if request.method == 'POST':\n form = UploadFileForm(request.POST, request.FILES)\n\n if form.is_valid():\n user = authenticate(username=request.POST['username'],\n password=request.POST['password'])\n if user is not None and not user.is_anonymous():\n login(request, user)\n else:\n return HttpResponse(status=401)\n if not request.user.is_authenticated():\n return HttpResponse(status=401)\n\n # Prepare to save data to disk\n if 'file' in request.FILES:\n # A file is uploaded directly\n file_name = request.FILES['file'].name\n raw_content = request.FILES['file'].read()\n else:\n # A file URL is provided, fetch it from the URL\n data_url = request.POST['data_url']\n f = urllib2.urlopen(urllib2.Request(url=data_url))\n file_name = data_url\n raw_content = f.read()\n file_content = ContentFile(raw_content)\n # Sanity check\n _, ext = os.path.splitext(file_name)\n if ext.lower() not in ['.jpeg', '.jpg', '.png', '.gif', '.json', '.dat']:\n logging.error(\"Uploaded file doesn't appear to be an image or json data: %s\", file_name)\n return HttpResponse(status=400)\n # Store file info to DB\n # Search to see whether a file with that name exists.\n # Check whether the file is owned by the user before deleting it.\n # If it's not, just create a new file with the same name.\n # Get instrument\n instrument_id = get_object_or_404(Instrument, name=instrument.lower())\n run_object = get_object_or_404(DataRun, instrument_id=instrument_id, run_number=run_id)\n\n # Look for a data file and treat it differently\n if ext.lower() in ['.json', '.dat']:\n json_data_entries = JsonData.objects.filter(name__endswith=file_name, run_id=run_object)\n if len(json_data_entries) > 0:\n json_data = json_data_entries[0]\n else:\n # No entry was found, create one\n json_data = JsonData()\n json_data.name = file_name\n json_data.run_id = run_object\n json_data.data = raw_content\n json_data.save()\n else:\n image_entries = ReducedImage.objects.filter(name__endswith=file_name, run_id=run_object)\n if len(image_entries) > 0:\n image = image_entries[0]\n image.file.delete(False)\n else:\n # No entry was found, create one\n image = ReducedImage()\n image.name = file_name\n image.run_id = run_object\n image.file.save(file_name, file_content)\n\n else:\n form = UploadFileForm()\n return render(request, 'file_handling/upload.html',\n {'form': form,\n 'upload_url': reverse('file_handling:upload_image',\n args=[instrument, run_id])})\n return HttpResponse()\n","sub_path":"reporting/file_handling/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"434065756","text":"from __future__ import absolute_import\nimport datetime as dt\nfrom decimal import Decimal\nimport six\nfrom six.moves import filter, map, range\nfrom sqlalchemy import event\nfrom sqlalchemy.ext.declarative import declared_attr\nfrom sqlalchemy.ext.hybrid import hybrid_property\nfrom sqlalchemy.event import listens_for\nfrom sqlalchemy.schema import DDL, DropIndex\nfrom flask import Markup, current_app, url_for\nfrom flask_babel import gettext, lazy_gettext\nfrom flask_login import current_user\n\nfrom . import db\nfrom .util import DeclEnum, classproperty, AutoID, Timestamped, AutoName,\\\n unistr, ensure_unicode, PrettyDecimal, PrettyNumeric, DateTime\nfrom .auth import PermissionType\n\n\nif six.PY3:\n unicode = str\n\nclass ActionType(DeclEnum):\n\n # The actual stored values are single character to make it easier on\n # engines that don't support native enum types.\n\n # TRANS: Name of the status a request is in when it has been submitted and\n # TRANS: is ready to be evaluated.\n evaluating = u'evaluating', lazy_gettext(u'Evaluating')\n \"\"\"Status for a request being evaluated.\"\"\"\n\n # TRANS: Name of the status where a request has had a payout amount set,\n # TRANS: and is ready to be paid out. In other words, approved for payout.\n approved = u'approved', lazy_gettext(u'Approved')\n \"\"\"Status for a request that has been evaluated and is awaitng payment.\"\"\"\n\n # TRANS: Name of the status a request is in if the ISK has been sent to the\n # TRANS: requesting person, and no further action is needed.\n paid = u'paid', lazy_gettext(u'Paid')\n \"\"\"Status for a request that has been paid. This is a terminatint state.\"\"\"\n\n # TRANS: Name of the status a request has where a reviewer has rejected the\n # TRANS: request for SRP.\n rejected = u'rejected', lazy_gettext(u'Rejected')\n \"\"\"Status for a requests that has been rejected. This is a terminating\n state.\n \"\"\"\n\n # TRANS: When a request needs more information to be approved or rejected,\n # TRANS: it is in this status.\n incomplete = u'incomplete', lazy_gettext(u'Incomplete')\n \"\"\"Status for a request that is missing details and needs further\n action.\n \"\"\"\n\n # TRANS: A comment made on a request.\n comment = u'comment', lazy_gettext(u'Comment')\n \"\"\"A special type of :py:class:`Action` representing a comment made on the\n request.\n \"\"\"\n\n @classproperty\n def finalized(cls):\n return frozenset((cls.paid, cls.rejected))\n\n @classproperty\n def pending(cls):\n return frozenset((cls.evaluating, cls.approved, cls.incomplete))\n\n @classproperty\n def statuses(cls):\n return frozenset((cls.evaluating, cls.approved, cls.paid, cls.rejected,\n cls.incomplete))\n\n\nclass ActionError(ValueError):\n \"\"\"Error raised for invalid state changes for a :py:class:`Request`.\"\"\"\n pass\n\n\nclass Action(db.Model, AutoID, Timestamped, AutoName):\n \"\"\"Actions change the state of a Request.\n \n :py:class:`Request`\\s enforce permissions when actions are added to them.\n If the user adding the action does not have the appropriate\n :py:class:`~.Permission`\\s in the request's :py:class:`Division`, an\n :py:exc:`ActionError` will be raised.\n\n With the exception of the :py:attr:`comment ` action\n (which just adds text to a request), actions change the\n :py:attr:`~Request.status` of a Request.\n \"\"\"\n\n #: The action be taken. See :py:class:`ActionType` for possible values.\n # See set_request_type below for the effect setting this attribute has on\n # the parent Request.\n type_ = db.Column(ActionType.db_type(), nullable=False)\n\n #: The ID of the :py:class:`Request` this action applies to.\n request_id = db.Column(db.Integer, db.ForeignKey('request.id'))\n\n #: The :py:class:`Request` this action applies to.\n request = db.relationship('Request', back_populates='actions',\n cascade='save-update,merge,refresh-expire,expunge')\n\n #: The ID of the :py:class:`~.User` who made this action.\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n\n #: The :py:class:`~.User` who made this action.\n user = db.relationship('User', back_populates='actions',\n cascade='save-update,merge,refresh-expire,expunge')\n\n #: Any additional notes for this action.\n note = db.Column(db.Text(convert_unicode=True))\n\n def __init__(self, request, user, note=None, type_=None):\n if type_ is not None:\n self.type_ = type_\n self.user = user\n self.note = ensure_unicode(note)\n # timestamp has to be an actual value (besides None) before the request\n # is set so thhe request's validation doesn't fail.\n self.timestamp = dt.datetime.utcnow()\n self.request = request\n\n def __repr__(self):\n return \"{x.__class__.__name__}({x.request}, {x.user}, {x.type_})\".\\\n format(x=self)\n\n def _json(self, extended=False):\n try:\n parent = super(Action, self)._json(extended)\n except AttributeError:\n parent = {}\n parent[u'type'] = self.type_\n if extended:\n parent[u'note'] = self.note or u''\n parent[u'timestamp'] = self.timestamp\n parent[u'user'] = self.user\n return parent\n\n\nclass ModifierError(ValueError):\n \"\"\"Error raised when a modification is attempted to a :py:class:`Request`\n when it's in an invalid state.\n \"\"\"\n pass\n\n\nclass Modifier(db.Model, AutoID, Timestamped, AutoName):\n \"\"\"Modifiers apply bonuses or penalties to Requests.\n\n This is an abstract base class for the pair of concrete implementations.\n Modifiers can be voided at a later date. The user who voided a modifier and\n when it was voided are recorded.\n\n :py:class:`Request`\\s enforce permissions when modifiers are added. If the\n user adding a modifier does not have the appropriate\n :py:class:`~.Permission`\\s in the request's :py:class:`~.Division`, a\n :py:exc:`ModifierError` will be raised.\n \"\"\"\n\n #: Discriminator column for SQLAlchemy\n _type = db.Column(db.String(20, convert_unicode=True), nullable=False)\n\n #: The ID of the :py:class:`Request` this modifier applies to.\n request_id = db.Column(db.Integer, db.ForeignKey('request.id'))\n\n #: The :py:class:`Request` this modifier applies to.\n request = db.relationship('Request', back_populates='modifiers',\n cascade='save-update,merge,refresh-expire,expunge')\n\n #: The ID of the :py:class`~.User` who added this modifier.\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n\n #: The :py:class:`~.User` who added this modifier.\n user = db.relationship('User', foreign_keys=[user_id],\n cascade='save-update,merge,refresh-expire,expunge')\n\n #: Any notes explaining this modification.\n note = db.Column(db.Text(convert_unicode=True))\n\n #: The ID of the :py:class:`~.User` who voided this modifier (if voided).\n voided_user_id = db.Column(db.Integer, db.ForeignKey('user.id'),\n nullable=True)\n\n #: The :py:class:`~.User` who voided this modifier if it has been voided.\n voided_user = db.relationship('User', foreign_keys=[voided_user_id],\n cascade='save-update,merge,refresh-expire,expunge')\n\n #: If this modifier has been voided, this will be the timestamp of when it\n #: was voided.\n voided_timestamp = db.Column(DateTime)\n\n @hybrid_property\n def voided(self):\n return self.voided_user is not None and \\\n self.voided_timestamp is not None\n\n @classmethod\n def _voided_select(cls):\n \"\"\"Create a subquery with two columns, ``modifier_id`` and ``voided``.\n\n Used for the expressions of :py:attr:`voided` and\n :py:attr:`Request.payout`.\n \"\"\"\n user = db.select([cls.id.label('modifier_id'),\n cls.voided_user_id.label('user_id')]).alias('user_sub')\n timestamp = db.select([cls.id.label('modifier_id'),\n cls.voided_timestamp.label('timestamp')]).alias('timestamp_sub')\n columns = [\n db.and_(\n user.c.user_id != None,\n timestamp.c.timestamp != None).label('voided'),\n user.c.modifier_id.label('modifier_id'),\n ]\n return db.select(columns).where(\n user.c.modifier_id == timestamp.c.modifier_id)\\\n .alias('voided_sub')\n\n @voided.expression\n def voided(cls):\n return cls._voided_select().c.voided\n\n @declared_attr\n def __mapper_args__(cls):\n \"\"\"SQLAlchemy late-binding attribute to set mapper arguments.\n\n Obviates subclasses from having to specify polymorphic identities.\n \"\"\"\n cls_name = unicode(cls.__name__)\n args = {'polymorphic_identity': cls_name}\n if cls_name == u'Modifier':\n args['polymorphic_on'] = cls._type\n return args\n\n def __init__(self, request, user, note, value):\n self.user = user\n self.note = ensure_unicode(note)\n self.value = value\n self.request = request\n\n def __repr__(self):\n return (\"{x.__class__.__name__}({x.request}, {x.user},\"\n \"{x}, {x.voided})\".format(x=self, value=self))\n\n def void(self, user):\n \"\"\"Mark this modifier as void.\n\n :param user: The user voiding this modifier\n :type user: :py:class:`~.User`\n \"\"\"\n if self.request.status != ActionType.evaluating:\n # TRANS: Error message shown when trying to void (cancel) a\n # modifier but the request is not in the evaluating state, so the\n # attempt fails.\n raise ModifierError(gettext(u\"Modifiers can only be voided when \"\n u\"the request is in the evaluating \"\n u\"state.\"))\n if not user.has_permission(PermissionType.review,\n self.request.division):\n # TRANS: Error message shown when you attempt to void a modifier\n # but are prevented from doing so because you do not hold the\n # reviewer permission.\n raise ModifierError(\"You must be a reviewer to be able to void \"\n \"modifiers.\")\n self.voided_user = user\n self.voided_timestamp = dt.datetime.utcnow()\n\n @db.validates('request')\n def _check_request_status(self, attr, request):\n if current_app.config['SRP_SKIP_VALIDATION']:\n return request\n if request.status != ActionType.evaluating:\n raise ModifierError(gettext(u\"Modifiers can only be added when the\"\n u\" request is in an evaluating \"\n u\"state.\"))\n if not self.user.has_permission(PermissionType.review,\n request.division):\n raise ModifierError(gettext(u\"Only reviewers can add modifiers.\"))\n return request\n\n def _json(self, extended=False):\n try:\n parent = super(Modifier, self)._json(extended)\n except AttributeError:\n parent = {}\n parent[u'value'] = self.value\n if extended:\n parent[u'note'] = self.note or u''\n parent[u'timestamp'] = self.timestamp\n parent[u'user'] = self.user\n if self.voided:\n parent[u'void'] = {\n u'user': self.voided_user,\n u'timestamp': self.voided_timestamp,\n }\n else:\n parent[u'void'] = False\n else:\n parent[u'void'] = self.voided\n return parent\n\n\n@unistr\nclass AbsoluteModifier(Modifier):\n \"\"\"Subclass of :py:class:`Modifier` for representing absolute\n modifications.\n\n Absolute modifications are those that are not dependent on the value of\n :py:attr:`Request.base_payout`.\n \"\"\"\n\n id = db.Column(db.Integer, db.ForeignKey('modifier.id'), primary_key=True)\n\n #: How much ISK to add or remove from the payout\n value = db.Column(PrettyNumeric(precision=15, scale=2), nullable=False,\n default=Decimal(0))\n\n def _json(self, extended=False):\n try:\n parent = super(AbsoluteModifier, self)._json(extended)\n except AttributeError:\n parent = {}\n parent[u'type'] = 'absolute'\n return parent\n\n\n@unistr\nclass RelativeModifier(Modifier):\n \"\"\"Subclass of :py:class:`Modifier` for representing relative modifiers.\n\n Relative modifiers depend on the value of :py:attr:`Modifier.base_payout`\n to calculate their effect.\n \"\"\"\n\n id = db.Column(db.Integer, db.ForeignKey('modifier.id'), primary_key=True)\n\n #: What percentage of the payout to add or remove\n value = db.Column(db.Numeric(precision=8, scale=5), nullable=False,\n default=Decimal(0))\n\n def _json(self, extended=False):\n try:\n parent = super(RelativeModifier, self)._json(extended)\n except AttributeError:\n parent = {}\n parent[u'type'] = 'relative'\n return parent\n\n\nclass Request(db.Model, AutoID, Timestamped, AutoName):\n \"\"\"Requests represent SRP requests.\"\"\"\n\n #: The ID of the :py:class:`~.User` who submitted this request.\n submitter_id = db.Column(db.Integer, db.ForeignKey('user.id'))\n\n #: The :py:class:`~.User` who submitted this request.\n submitter = db.relationship('User', back_populates='requests',\n cascade='save-update,merge,refresh-expire,expunge')\n\n #: The ID of the :py:class`~.Division` this request was submitted to.\n division_id = db.Column(db.Integer, db.ForeignKey('division.id'),\n nullable=False)\n\n #: The :py:class:`~.Division` this request was submitted to.\n division = db.relationship('Division', back_populates='requests',\n cascade='save-update,merge,refresh-expire,expunge')\n\n #: A list of :py:class:`Action`\\s that have been applied to this request,\n #: sorted in the order they were applied.\n actions = db.relationship('Action', back_populates='request',\n cascade='all,delete-orphan',\n order_by='desc(Action.timestamp)')\n\n #: A list of all :py:class:`Modifier`\\s that have been applied to this\n #: request, regardless of wether they have been voided or not. They're\n #: sorted in the order they were added.\n modifiers = db.relationship('Modifier', back_populates='request',\n cascade='all,delete-orphan',\n lazy='dynamic', order_by='desc(Modifier.timestamp)')\n\n #: The URL of the source killmail.\n killmail_url = db.Column(db.String(512, convert_unicode=True),\n nullable=False)\n\n #: The ID of the :py:class:`~.Pilot` for the killmail.\n pilot_id = db.Column(db.Integer, db.ForeignKey('pilot.id'), nullable=False)\n\n #: The :py:class:`~.Pilot` who was the victim in the killmail.\n pilot = db.relationship('Pilot', back_populates='requests',\n cascade='save-update,merge,refresh-expire,expunge')\n\n #: The corporation of the :py:attr:`pilot` at the time of the killmail.\n corporation = db.Column(db.String(150, convert_unicode=True),\n nullable=False, index=True)\n\n #: The alliance of the :py:attr:`pilot` at the time of the killmail.\n alliance = db.Column(db.String(150, convert_unicode=True), nullable=True,\n index=True)\n\n #: The type of ship that was destroyed.\n ship_type = db.Column(db.String(75, convert_unicode=True), nullable=False,\n index=True)\n\n # TODO: include timezones\n #: The date and time of when the ship was destroyed.\n kill_timestamp = db.Column(DateTime, nullable=False, index=True)\n\n base_payout = db.Column(PrettyNumeric(precision=15, scale=2),\n default=Decimal(0))\n \"\"\"The base payout for this request.\n\n This value is clamped to a lower limit of 0. It can only be changed when\n this request is in an :py:attr:`~ActionType.evaluating` state, or else a\n :py:exc:`ModifierError` will be raised.\n \"\"\"\n\n #: The payout for this requests taking into account all active modifiers.\n payout = db.Column(PrettyNumeric(precision=15, scale=2),\n default=Decimal(0), index=True, nullable=False)\n\n #: Supporting information for the request.\n details = db.deferred(db.Column(db.Text(convert_unicode=True)))\n\n #: The current status of this request\n status = db.Column(ActionType.db_type(), nullable=False,\n default=ActionType.evaluating)\n \"\"\"This attribute is automatically kept in sync as :py:class:`Action`\\s are\n added to the request. It should not be set otherwise.\n\n At the time an :py:class:`Action` is added to this request, the type of\n action is checked and the state diagram below is enforced. If the action is\n invalid, an :py:exc:`ActionError` is raised.\n\n .. digraph:: request_workflow\n\n rankdir=\"LR\";\n\n sub [label=\"submitted\", shape=plaintext];\n\n node [style=\"dashed, filled\"];\n\n eval [label=\"evaluating\", fillcolor=\"#fcf8e3\"];\n rej [label=\"rejected\", style=\"solid, filled\", fillcolor=\"#f2dede\"];\n app [label=\"approved\", fillcolor=\"#d9edf7\"];\n inc [label=\"incomplete\", fillcolor=\"#f2dede\"];\n paid [label=\"paid\", style=\"solid, filled\", fillcolor=\"#dff0d8\"];\n\n sub -> eval;\n eval -> rej [label=\"R\"];\n eval -> app [label=\"R\"];\n eval -> inc [label=\"R\"];\n rej -> eval [label=\"R\"];\n inc -> eval [label=\"R, S\"];\n inc -> rej [label=\"R\"];\n app -> paid [label=\"P\"];\n app -> eval [label=\"R\"];\n paid -> eval [label=\"P\"];\n paid -> app [label=\"P\"];\n\n R means a reviewer can make that change, S means the submitter can make\n that change, and P means payers can make that change. Solid borders are\n terminal states.\n \"\"\"\n\n #: The solar system this loss occured in.\n system = db.Column(db.String(25, convert_unicode=True), nullable=False,\n index=True)\n\n #: The constellation this loss occured in.\n constellation = db.Column(db.String(25, convert_unicode=True),\n nullable=False, index=True)\n\n #: The region this loss occured in.\n region = db.Column(db.String(25, convert_unicode=True), nullable=False,\n index=True)\n\n @hybrid_property\n def finalized(self):\n return self.status in ActionType.finalized\n\n @finalized.expression\n def finalized(cls):\n return db.or_(cls.status == ActionType.paid,\n cls.status == ActionType.rejected)\n\n def __init__(self, submitter, details, division, killmail, **kwargs):\n \"\"\"Create a :py:class:`Request`.\n\n :param submitter: The user submitting this request\n :type submitter: :py:class:`~.User`\n :param str details: Supporting details for this request\n :param division: The division this request is being submitted to\n :type division: :py:class:`~.Division`\n :param killmail: The killmail this request pertains to\n :type killmail: :py:class:`~.Killmail`\n \"\"\"\n with db.session.no_autoflush:\n self.division = division\n self.details = details\n self.submitter = submitter\n # Pull basically everything else from the killmail object\n # The base Killmail object has an iterator defined that returns tuples\n # of Request attributes and values for those attributes\n for attr, value in killmail:\n setattr(self, attr, value)\n # Set default values before a flush\n if self.base_payout is None and 'base_payout' not in kwargs:\n self.base_payout = Decimal(0)\n super(Request, self).__init__(**kwargs)\n\n @db.validates('base_payout')\n def _validate_payout(self, attr, value):\n \"\"\"Ensures that base_payout is positive. The value is clamped to 0.\"\"\"\n if current_app.config['SRP_SKIP_VALIDATION']:\n return Decimal(value)\n # Allow self.status == None, as the base payout may be set in the\n # initializing state before the status has been set.\n if self.status == ActionType.evaluating or self.status is None:\n if value is None or value < 0:\n return Decimal('0')\n else:\n return Decimal(value)\n else:\n raise ModifierError(gettext(u\"The request must be in the \"\n u\"evaluating state to change the base \"\n u\"payout.\"))\n\n state_rules = {\n ActionType.evaluating: {\n ActionType.incomplete: (PermissionType.review,\n PermissionType.admin),\n ActionType.rejected: (PermissionType.review,\n PermissionType.admin),\n ActionType.approved: (PermissionType.review,\n PermissionType.admin),\n },\n ActionType.incomplete: {\n ActionType.rejected: (PermissionType.review,\n PermissionType.admin),\n # Special case: the submitter can change it to evaluating by\n # changing the division or updating the details.\n ActionType.evaluating: (PermissionType.review,\n PermissionType.admin),\n },\n ActionType.rejected: {\n ActionType.evaluating: (PermissionType.review,\n PermissionType.admin),\n },\n ActionType.approved: {\n # Special case: the submitter can change it to evaluating by\n # changing the division.\n ActionType.evaluating: (PermissionType.review,\n PermissionType.admin),\n ActionType.paid: (PermissionType.pay, PermissionType.admin),\n },\n ActionType.paid: {\n ActionType.approved: (PermissionType.pay, PermissionType.admin),\n ActionType.evaluating: (PermissionType.pay, PermissionType.admin),\n },\n }\n\n def valid_actions(self, user):\n \"\"\"Get valid actions (besides comment) the given user can perform.\"\"\"\n possible_actions = self.state_rules[self.status]\n def action_filter(action):\n return user.has_permission(possible_actions[action],\n self.division)\n return filter(action_filter, possible_actions)\n\n @db.validates('status')\n def _validate_status(self, attr, new_status):\n \"\"\"Enforces that status changes follow the status state machine.\n When an invalid change is attempted, :py:class:`ActionError` is\n raised.\n \"\"\"\n if current_app.config['SRP_SKIP_VALIDATION']:\n return new_status\n if new_status == ActionType.comment:\n raise ValueError(gettext(\n u\"Comment is not a valid status\"))\n # Initial status\n if self.status is None:\n return new_status\n rules = self.state_rules[self.status]\n if new_status not in rules:\n error_text = gettext(u\"%(new_status)s is not a valid status to \"\n u\"change to from %(old_status)s.\",\n new_status=new_status,\n old_status=self.status)\n raise ActionError(error_text)\n return new_status\n\n @db.validates('actions')\n def _verify_action_permissions(self, attr, action):\n \"\"\"Verifies that permissions for Actions being added to a Request.\"\"\"\n if current_app.config['SRP_SKIP_VALIDATION']:\n return action\n if action.type_ is None:\n # Action.type_ are not nullable, so rely on the fact that it will\n # be set later to let it slide now.\n return action\n elif action.type_ != ActionType.comment:\n # Peek behind the curtain to see the history of the status\n # attribute.\n status_history = db.inspect(self).attrs.status.history\n if status_history.has_changes():\n new_status = status_history.added[0]\n old_status = status_history.deleted[0]\n else:\n new_status = action.type_\n old_status = self.status\n rules = self.state_rules[old_status]\n permissions = rules[new_status]\n # Handle the special cases called out in state_rules\n if action.user == self.submitter and \\\n new_status == ActionType.evaluating and \\\n old_status in ActionType.pending:\n # Equivalent to self.status in (approved, incomplete) as\n # going from evaluating to evaluating is invalid (as checked by\n # the status validator).\n return action\n if not action.user.has_permission(permissions, self.division):\n raise ActionError(gettext(u\"Insufficient permissions to \"\n u\"perform that action.\"))\n elif action.type_ == ActionType.comment:\n if action.user != self.submitter \\\n and not action.user.has_permission(\n (PermissionType.review, PermissionType.pay,\n PermissionType.admin),\n self.division):\n raise ActionError(gettext(u\"You must either own or have \"\n u\"special privileges to comment on \"\n u\"this request.\"))\n return action\n\n def __repr__(self):\n return \"{x.__class__.__name__}({x.submitter}, {x.division}, {x.id})\".\\\n format(x=self)\n\n @property\n def transformed(self):\n \"\"\"Get a special HTML representation of an attribute.\n\n Divisions can have a transformer defined on various attributes that\n output a URL associated with that attribute. This property provides\n easy access to the output of any transformed attributes on this\n request.\n \"\"\"\n class RequestTransformer(object):\n def __init__(self, request):\n self._request = request\n\n def __getattr__(self, attr):\n raw_value = getattr(self._request, attr)\n if attr in self._request.division.transformers:\n transformer = self._request.division.transformers[attr]\n return Markup(u''\n u'{value} '\n u'').format(\n link=transformer(raw_value),\n value=str(raw_value))\n else:\n return raw_value\n\n def __iter__(self):\n for attr, transformer in\\\n self._request.division.transformers.items():\n if attr == 'ship_type':\n yield ('ship', transformer(getattr(self._request,\n attr)))\n else:\n yield (attr, transformer(getattr(self._request, attr)))\n\n return RequestTransformer(self)\n\n def _json(self, extended=False):\n try:\n parent = super(Request, self)._json(extended)\n except AttributeError:\n parent = {}\n parent[u'href'] = url_for('requests.get_request_details',\n request_id=self.id)\n attrs = (u'killmail_url', u'kill_timestamp', u'pilot',\n u'alliance', u'corporation', u'submitter',\n u'division', u'status', u'base_payout', u'payout',\n u'details', u'id', u'ship_type', u'system', u'constellation',\n u'region')\n for attr in attrs:\n if attr == u'ship_type':\n parent['ship'] = self.ship_type\n elif u'payout' in attr:\n payout = getattr(self, attr)\n parent[attr] = payout.currency()\n else:\n parent[attr] = getattr(self, attr)\n parent[u'submit_timestamp'] = self.timestamp\n if extended:\n parent[u'actions'] = map(lambda a: a._json(True), self.actions)\n parent[u'modifiers'] = map(lambda m: m._json(True), self.modifiers)\n parent[u'valid_actions'] = self.valid_actions(current_user)\n parent[u'transformed'] = dict(self.transformed)\n return parent\n\n\n# Define event listeners for syncing the various denormalized attributes\n\n@listens_for(Action.type_, 'set')\ndef _action_type_to_request_status(action, new_status, old_status, initiator):\n \"\"\"Set the Action's Request's status when the Action's type is changed.\"\"\"\n if action.request is not None and new_status != ActionType.comment:\n action.request.status = new_status\n\n\n@listens_for(Request.actions, 'append')\ndef _request_status_from_actions(srp_request, action, initiator):\n \"\"\"Updates Request.status when new Actions are added.\"\"\"\n # Pass when Action.type_ is None, as it'll get updated later\n if action.type_ is not None and action.type_ != ActionType.comment:\n srp_request.status = action.type_\n\n\n@listens_for(Request.base_payout, 'set')\ndef _recalculate_payout_from_request(srp_request, base_payout, *args):\n \"\"\"Recalculate a Request's payout when the base payout changes.\"\"\"\n if base_payout is None:\n base_payout = Decimal(0)\n voided = Modifier._voided_select()\n modifiers = srp_request.modifiers.join(voided,\n voided.c.modifier_id==Modifier.id)\\\n .filter(~voided.c.voided)\\\n .order_by(False)\n absolute = modifiers.join(AbsoluteModifier).\\\n with_entities(db.func.sum(AbsoluteModifier.value)).\\\n scalar()\n if not isinstance(absolute, Decimal):\n absolute = Decimal(0)\n relative = modifiers.join(RelativeModifier).\\\n with_entities(db.func.sum(RelativeModifier.value)).\\\n scalar()\n if not isinstance(relative, Decimal):\n relative = Decimal(0)\n payout = (base_payout + absolute) * (Decimal(1) + relative)\n srp_request.payout = PrettyDecimal(payout)\n\n\n@listens_for(Modifier.request, 'set', propagate=True)\n@listens_for(Modifier.voided_user, 'set', propagate=True)\ndef _recalculate_payout_from_modifier(modifier, value, *args):\n \"\"\"Recalculate a Request's payout when it gains a Modifier or when one of\n its Modifiers is voided.\n \"\"\"\n # Force a flush at the beginning, then delay other flushes\n db.session.flush()\n with db.session.no_autoflush:\n # Get the request for this modifier\n if isinstance(value, Request):\n # Triggered by setting Modifier.request\n srp_request = value\n else:\n # Triggered by setting Modifier.voided_user\n srp_request = modifier.request\n voided = Modifier._voided_select()\n modifiers = srp_request.modifiers.join(voided,\n voided.c.modifier_id==Modifier.id)\\\n .filter(~voided.c.voided)\\\n .order_by(False)\n absolute = modifiers.join(AbsoluteModifier).\\\n with_entities(db.func.sum(AbsoluteModifier.value)).\\\n scalar()\n if not isinstance(absolute, Decimal):\n absolute = Decimal(0)\n relative = modifiers.join(RelativeModifier).\\\n with_entities(db.func.sum(RelativeModifier.value)).\\\n scalar()\n if not isinstance(relative, Decimal):\n relative = Decimal(0)\n # The modifier that's changed isn't reflected yet in the database, so we\n # apply it here.\n if isinstance(value, Request):\n # A modifier being added to the Request\n if modifier.voided:\n # The modifier being added is already void\n return\n direction = Decimal(1)\n else:\n # A modifier already on a request is being voided\n direction = Decimal(-1)\n if isinstance(modifier, AbsoluteModifier):\n absolute += direction * modifier.value\n elif isinstance(modifier, RelativeModifier):\n relative += direction * modifier.value\n payout = (srp_request.base_payout + absolute) * \\\n (Decimal(1) + relative)\n srp_request.payout = PrettyDecimal(payout)\n\n\n# The next few lines are responsible for adding a full text search index on the\n# Request.details column for MySQL.\n_create_fts = DDL('CREATE FULLTEXT INDEX ix_%(table)s_details_fulltext '\n 'ON %(table)s (details);')\n_drop_fts = DDL('DROP INDEX ix_%(table)s_details_fulltext ON %(table)s')\n\n\nevent.listen(\n Request.__table__,\n 'after_create',\n _create_fts.execute_if(dialect='mysql')\n)\n\n\nevent.listen(\n Request.__table__,\n 'before_drop',\n _drop_fts.execute_if(dialect='mysql')\n)\n","sub_path":"src/evesrp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":32863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"334892370","text":"# Copyright 2016 Canonical Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport amulet\nimport swiftclient\nimport time\n\nimport keystoneclient\nfrom keystoneclient.v3 import client as keystone_client_v3\nfrom keystoneclient.v2_0 import client as keystone_client\n\nfrom charmhelpers.contrib.openstack.amulet.deployment import (\n OpenStackAmuletDeployment\n)\n\nfrom charmhelpers.contrib.openstack.amulet.utils import (\n OpenStackAmuletUtils,\n DEBUG\n)\nfrom charmhelpers.contrib.openstack.utils import CompareOpenStackReleases\n\n# Use DEBUG to turn on debug logging\nu = OpenStackAmuletUtils(DEBUG)\n\n\nclass SwiftProxyBasicDeployment(OpenStackAmuletDeployment):\n \"\"\"Amulet tests on a basic swift-proxy deployment.\"\"\"\n\n def __init__(self, series, openstack=None, source=None, stable=False):\n \"\"\"Deploy the entire test environment.\"\"\"\n super(SwiftProxyBasicDeployment, self).__init__(series, openstack,\n source, stable)\n self._add_services()\n self._add_relations()\n self._configure_services()\n self._deploy()\n\n u.log.info('Waiting on extended status checks...')\n exclude_services = []\n self._auto_wait_for_status(exclude_services=exclude_services)\n\n self.d.sentry.wait()\n self._initialize_tests()\n\n def _add_services(self):\n \"\"\"Add services\n\n Add the services that we're testing, where swift-proxy is local,\n and the rest of the service are from lp branches that are\n compatible with the local charm (e.g. stable or next).\n \"\"\"\n this_service = {'name': 'swift-proxy'}\n other_services = [\n {'name': 'percona-cluster'},\n {'name': 'keystone'},\n {'name': 'glance'},\n {'name': 'swift-storage',\n 'storage': {'block-devices': 'cinder,10G'}},\n ]\n super(SwiftProxyBasicDeployment, self)._add_services(this_service,\n other_services)\n\n def _add_relations(self):\n \"\"\"Add all of the relations for the services.\"\"\"\n relations = {\n 'keystone:shared-db': 'percona-cluster:shared-db',\n 'swift-proxy:identity-service': 'keystone:identity-service',\n 'swift-storage:swift-storage': 'swift-proxy:swift-storage',\n 'glance:identity-service': 'keystone:identity-service',\n 'glance:shared-db': 'percona-cluster:shared-db',\n 'glance:object-store': 'swift-proxy:object-store'\n }\n super(SwiftProxyBasicDeployment, self)._add_relations(relations)\n\n def _configure_services(self):\n \"\"\"Configure all of the services.\"\"\"\n keystone_config = {\n 'admin-password': 'openstack',\n 'admin-token': 'ubuntutesting'\n }\n swift_proxy_config = {\n 'zone-assignment': 'manual',\n 'replicas': '1',\n 'swift-hash': 'fdfef9d4-8b06-11e2-8ac0-531c923c8fae'\n }\n swift_storage_config = {\n 'zone': '1',\n }\n pxc_config = {\n 'innodb-buffer-pool-size': '256M',\n 'max-connections': 1000,\n }\n configs = {\n 'keystone': keystone_config,\n 'swift-proxy': swift_proxy_config,\n 'swift-storage': swift_storage_config,\n 'percona-cluster': pxc_config,\n }\n super(SwiftProxyBasicDeployment, self)._configure_services(configs)\n\n def _init_keystone_admin_client(self, api_version):\n \"\"\"Create the keystone admin client based on release and API version\"\"\"\n self.keystone_sentry = self.d.sentry['keystone'][0]\n keystone_ip = self.keystone_sentry.info['public-address']\n if self._get_openstack_release() >= self.xenial_queens:\n api_version = 3\n client_class = keystone_client.Client\n if api_version == 3:\n client_class = keystone_client_v3.Client\n session, auth = u.get_keystone_session(\n keystone_ip,\n api_version=api_version,\n username='admin',\n password='openstack',\n project_name='admin',\n user_domain_name='admin_domain',\n project_domain_name='admin_domain')\n self.keystone = client_class(session=session)\n self.keystone.auth_ref = auth.get_access(session)\n\n def _initialize_tests(self, api_version=2):\n \"\"\"Perform final initialization before tests get run.\"\"\"\n # Access the sentries for inspecting service units\n self.pxc_sentry = self.d.sentry['percona-cluster'][0]\n self.keystone_sentry = self.d.sentry['keystone'][0]\n self.glance_sentry = self.d.sentry['glance'][0]\n self.swift_proxy_sentry = self.d.sentry['swift-proxy'][0]\n self.swift_storage_sentry = self.d.sentry['swift-storage'][0]\n\n u.log.debug('openstack release val: {}'.format(\n self._get_openstack_release()))\n u.log.debug('openstack release str: {}'.format(\n self._get_openstack_release_string()))\n\n # Authenticate admin with keystone\n self._init_keystone_admin_client(api_version)\n\n force_v1_client = False\n if self._get_openstack_release() == self.trusty_icehouse:\n # Updating image properties (such as arch or hypervisor) using the\n # v2 api in icehouse results in:\n # https://bugs.launchpad.net/python-glanceclient/+bug/1371559\n u.log.debug('Forcing glance to use v1 api')\n force_v1_client = True\n\n # Authenticate admin with glance endpoint\n self.glance = u.authenticate_glance_admin(\n self.keystone,\n force_v1_client=force_v1_client)\n\n keystone_ip = self.keystone_sentry.info['public-address']\n keystone_relation = self.keystone_sentry.relation(\n 'identity-service', 'swift-proxy:identity-service')\n\n # Create a demo tenant/role/user\n self.demo_tenant = 'demoTenant'\n self.demo_role = 'demoRole'\n self.demo_user = 'demoUser'\n self.demo_project = 'demoProject'\n self.demo_domain = 'demoDomain'\n\n if (self._get_openstack_release() >= self.xenial_queens or\n api_version == 3):\n self.create_users_v3()\n self.demo_user_session, _ = u.get_keystone_session(\n keystone_ip,\n self.demo_user,\n 'password',\n api_version=3,\n user_domain_name=self.demo_domain,\n project_domain_name=self.demo_domain,\n project_name=self.demo_project\n )\n self.keystone_demo = keystone_client_v3.Client(\n session=self.demo_user_session)\n self.service_session, _ = u.get_keystone_session(\n keystone_ip,\n keystone_relation['service_username'],\n keystone_relation['service_password'],\n api_version=3,\n user_domain_name=keystone_relation['service_domain'],\n project_domain_name=keystone_relation['service_domain'],\n project_name=keystone_relation['service_tenant']\n )\n else:\n self.create_users_v2()\n # Authenticate demo user with keystone\n self.keystone_demo = \\\n u.authenticate_keystone_user(\n self.keystone, user=self.demo_user,\n password='password',\n tenant=self.demo_tenant)\n self.service_session, _ = u.get_keystone_session(\n keystone_ip,\n keystone_relation['service_username'],\n keystone_relation['service_password'],\n api_version=2,\n project_name=keystone_relation['service_tenant']\n )\n self.swift = swiftclient.Connection(session=self.service_session)\n\n def create_users_v3(self):\n try:\n self.keystone.projects.find(name=self.demo_project)\n except keystoneclient.exceptions.NotFound:\n domain = self.keystone.domains.create(\n self.demo_domain,\n description='Demo Domain',\n enabled=True\n )\n project = self.keystone.projects.create(\n self.demo_project,\n domain,\n description='Demo Project',\n enabled=True,\n )\n user = self.keystone.users.create(\n self.demo_user,\n domain=domain.id,\n project=self.demo_project,\n password='password',\n email='demov3@demo.com',\n description='Demo',\n enabled=True)\n role = self.keystone.roles.find(name='Admin')\n self.keystone.roles.grant(\n role.id,\n user=user.id,\n project=project.id)\n\n def create_users_v2(self):\n if not u.tenant_exists(self.keystone, self.demo_tenant):\n tenant = self.keystone.tenants.create(tenant_name=self.demo_tenant,\n description='demo tenant',\n enabled=True)\n\n self.keystone.roles.create(name=self.demo_role)\n self.keystone.users.create(name=self.demo_user,\n password='password',\n tenant_id=tenant.id,\n email='demo@demo.com')\n\n def test_100_services(self):\n \"\"\"Verify the expected services are running on the corresponding\n service units.\"\"\"\n u.log.debug('Checking system services...')\n swift_storage_services = ['swift-account',\n 'swift-account-auditor',\n 'swift-account-reaper',\n 'swift-account-replicator',\n 'swift-container',\n 'swift-container-auditor',\n 'swift-container-replicator',\n 'swift-container-updater',\n 'swift-object',\n 'swift-object-auditor',\n 'swift-object-replicator',\n 'swift-object-updater',\n 'swift-container-sync']\n service_names = {\n self.keystone_sentry: ['keystone'],\n self.glance_sentry: ['glance-registry',\n 'glance-api'],\n self.swift_proxy_sentry: ['swift-proxy'],\n self.swift_storage_sentry: swift_storage_services\n }\n\n if self._get_openstack_release() >= self.trusty_liberty:\n service_names[self.keystone_sentry] = ['apache2']\n\n ret = u.validate_services_by_name(service_names)\n if ret:\n amulet.raise_status(amulet.FAIL, msg=ret)\n\n def test_104_keystone_service_catalog(self):\n \"\"\"Verify that the service catalog endpoint data is valid.\"\"\"\n u.log.debug('Checking keystone service catalog...')\n endpoint_id = {'adminURL': u.valid_url,\n 'region': 'RegionOne',\n 'publicURL': u.valid_url,\n 'internalURL': u.valid_url,\n 'id': u.not_null}\n\n expected = {'image': [endpoint_id], 'object-store': [endpoint_id],\n 'identity': [endpoint_id], 's3': [endpoint_id]}\n actual = self.keystone.service_catalog.get_endpoints()\n\n ret = u.validate_svc_catalog_endpoint_data(\n expected, actual,\n openstack_release=self._get_openstack_release()\n )\n if ret:\n amulet.raise_status(amulet.FAIL, msg=ret)\n\n def test_200_swift_proxy_identity_service_relation(self):\n \"\"\"Verify the swift-proxy to keystone identity relation data.\"\"\"\n u.log.debug('Checking swift-proxy:keystone identity relation...')\n unit = self.swift_proxy_sentry\n relation = ['identity-service', 'keystone:identity-service']\n expected = {\n 'swift_service': 'swift',\n 'swift_region': 'RegionOne',\n 'swift_public_url': u.valid_url,\n 'swift_internal_url': u.valid_url,\n 'swift_admin_url': u.valid_url,\n 's3_service': 's3',\n 's3_region': 'RegionOne',\n 's3_public_url': u.valid_url,\n 's3_internal_url': u.valid_url,\n 's3_admin_url': u.valid_url,\n 'private-address': u.valid_ip,\n }\n\n ret = u.validate_relation_data(unit, relation, expected)\n if ret:\n message = u.relation_error('swift-proxy identity-service', ret)\n amulet.raise_status(amulet.FAIL, msg=message)\n\n def test_202_keystone_identity_service_relation(self):\n \"\"\"Verify the keystone to swift-proxy identity relation data.\"\"\"\n u.log.debug('Checking keystone:swift-proxy identity relation...')\n unit = self.keystone_sentry\n relation = ['identity-service', 'swift-proxy:identity-service']\n expected = {\n 'service_protocol': 'http',\n 'service_tenant': 'services',\n 'admin_token': 'ubuntutesting',\n 'service_password': u.not_null,\n 'service_port': '5000',\n 'auth_port': '35357',\n 'auth_protocol': 'http',\n 'private-address': u.valid_ip,\n 'auth_host': u.valid_ip,\n 'service_username': 's3_swift',\n 'service_tenant_id': u.not_null,\n 'service_host': u.valid_ip\n }\n\n ret = u.validate_relation_data(unit, relation, expected)\n if ret:\n message = u.relation_error('keystone identity-service', ret)\n amulet.raise_status(amulet.FAIL, msg=message)\n\n def test_204_swift_storage_swift_storage_relation(self):\n \"\"\"Verify the swift-storage to swift-proxy swift-storage relation\n data.\"\"\"\n u.log.debug('Checking swift:swift-proxy swift-storage relation...')\n unit = self.swift_storage_sentry\n relation = ['swift-storage', 'swift-proxy:swift-storage']\n expected = {\n 'account_port': '6002',\n 'zone': '1',\n 'object_port': '6000',\n 'container_port': '6001',\n 'private-address': u.valid_ip,\n 'device': 'vdd'\n }\n\n ret = u.validate_relation_data(unit, relation, expected)\n if ret:\n message = u.relation_error('swift-storage swift-storage', ret)\n amulet.raise_status(amulet.FAIL, msg=message)\n\n def test_206_swift_proxy_swift_storage_relation(self):\n \"\"\"Verify the swift-proxy to swift-storage swift-storage relation\n data.\"\"\"\n u.log.debug('Checking swift-proxy:swift swift-storage relation...')\n unit = self.swift_proxy_sentry\n relation = ['swift-storage', 'swift-storage:swift-storage']\n expected = {\n 'private-address': u.valid_ip,\n 'trigger': u.not_null,\n 'rings_url': u.valid_url,\n 'swift_hash': u.not_null\n }\n\n ret = u.validate_relation_data(unit, relation, expected)\n if ret:\n message = u.relation_error('swift-proxy swift-storage', ret)\n amulet.raise_status(amulet.FAIL, msg=message)\n\n def test_208_glance_object_store_relation(self):\n \"\"\"Verify the glance to swift-proxy object-store relation data.\"\"\"\n u.log.debug('Checking glance:swift-proxy object-store relation...')\n unit = self.glance_sentry\n relation = ['object-store', 'swift-proxy:object-store']\n expected = {'private-address': u.valid_ip}\n\n ret = u.validate_relation_data(unit, relation, expected)\n if ret:\n message = u.relation_error('glance object-store', ret)\n amulet.raise_status(amulet.FAIL, msg=message)\n\n def test_210_swift_proxy_object_store_relation(self):\n \"\"\"Verify the swift-proxy to glance object-store relation data.\"\"\"\n u.log.debug('Checking swift-proxy:glance object-store relation...')\n unit = self.swift_proxy_sentry\n relation = ['object-store', 'glance:object-store']\n expected = {'private-address': u.valid_ip}\n ret = u.validate_relation_data(unit, relation, expected)\n if ret:\n message = u.relation_error('swift-proxy object-store', ret)\n amulet.raise_status(amulet.FAIL, msg=message)\n\n def test_300_swift_config(self):\n \"\"\"Verify the data in the swift-hash section of the swift config\n file.\"\"\"\n u.log.debug('Checking swift config...')\n unit = self.swift_storage_sentry\n conf = '/etc/swift/swift.conf'\n swift_proxy_relation = self.swift_proxy_sentry.relation(\n 'swift-storage', 'swift-storage:swift-storage')\n expected = {\n 'swift_hash_path_suffix': swift_proxy_relation['swift_hash']\n }\n\n ret = u.validate_config_data(unit, conf, 'swift-hash', expected)\n if ret:\n message = \"swift config error: {}\".format(ret)\n amulet.raise_status(amulet.FAIL, msg=message)\n\n def test_400_swift_backed_image_create(self):\n \"\"\"Create an instance in glance, which is backed by swift, and validate\n that some of the metadata for the image match in glance and swift.\"\"\"\n u.log.debug('Checking swift objects and containers with a '\n 'swift-backed glance image...')\n\n # Create swift-backed glance image\n img_id = u.create_cirros_image(self.glance, \"cirros-image-1\").id\n\n # Get the image from glance by ID\n img_md5 = self.glance.images.get(img_id).checksum\n img_size = self.glance.images.get(img_id).size\n\n # Validate that swift object's checksum/size match that from glance\n headers, containers = self.swift.get_account()\n if len(containers) != 1:\n msg = \"Expected 1 swift container, found {}\".format(\n len(containers))\n amulet.raise_status(amulet.FAIL, msg=msg)\n\n container_name = containers[0].get('name')\n\n # Until glance v2 and swift bug is resolved\n # https://bugs.launchpad.net/glance/+bug/1789748\n read_headers = {'X-Container-Read': \".r:*,.rlistings\"}\n self.swift.post_container(container_name, headers=read_headers)\n\n if float(self.glance.version) < 2.0:\n object_count = 1\n else:\n object_count = 2\n\n headers, objects = self.swift.get_container(container_name)\n if len(objects) != object_count:\n msg = \"Expected 2 swift object, found {}\".format(len(objects))\n amulet.raise_status(amulet.FAIL, msg=msg)\n\n swift_object_size = objects[object_count - 1].get('bytes')\n swift_object_md5 = objects[object_count - 1].get('hash')\n\n if img_size != swift_object_size:\n msg = \"Glance image size {} != swift object size {}\".format(\n img_size, swift_object_size)\n amulet.raise_status(amulet.FAIL, msg=msg)\n\n if img_md5 != swift_object_md5:\n msg = \"Glance image hash {} != swift object hash {}\".format(\n img_md5, swift_object_md5)\n amulet.raise_status(amulet.FAIL, msg=msg)\n\n # Cleanup\n u.delete_resource(self.glance.images, img_id, msg=\"glance image\")\n u.log.info('OK')\n\n def _set_auth_api_version(self, api_version, retry_count=5):\n \"\"\"Change Keystone preferred-api-version, wait for: propagation to\n relation data, update of service configuration file and restart of\n services on swift-proxy unit.\"\"\"\n configs = {'keystone': {'preferred-api-version': api_version}}\n super(SwiftProxyBasicDeployment, self)._configure_services(configs)\n mtime = u.get_sentry_time(self.swift_proxy_sentry)\n for i in range(retry_count, -1, -1):\n ks_gl_rel = self.keystone_sentry.relation(\n 'identity-service', 'glance:identity-service')\n ks_sw_rel = self.keystone_sentry.relation(\n 'identity-service', 'swift-proxy:identity-service')\n if not (ks_gl_rel['api_version'] == api_version and\n ks_sw_rel['api_version'] == api_version):\n u.log.info(\"change of api_version not propagated yet \"\n \"retries left: '{}' \"\n \"glance:identity-service api_version: '{}' \"\n \"swift-proxy:identity-service api_version: '{}' \"\n .format(i,\n ks_gl_rel['api_version'],\n ks_sw_rel['api_version']))\n u.log.info(\"sleeping {} seconds...\".format(i))\n time.sleep(i)\n elif not u.validate_service_config_changed(\n self.swift_proxy_sentry,\n mtime,\n 'swift-proxy-server',\n '/etc/swift/proxy-server.conf',\n sleep_time=i):\n msg = \"swift-proxy-server didn't restart after change of \"\\\n \"api_version\"\n amulet.raise_status(amulet.FAIL, msg=msg)\n else:\n return True\n return False\n\n def test_keystone_v3(self):\n \"\"\"Verify that the service is configured and operates correctly when\n using Keystone v3 auth.\"\"\"\n if self._get_openstack_release() >= self.xenial_queens:\n u.log.info('Skipping keystone v3 test for queens or later')\n return\n os_release = self._get_openstack_release_string()\n if CompareOpenStackReleases(os_release) < 'kilo':\n u.log.info('Skipping test, {} < kilo'.format(os_release))\n return\n u.log.info('Checking that service is configured and operate correctly '\n 'when using Keystine v3 auth...')\n if not self._set_auth_api_version('3'):\n msg = \"Unable to set auth_api_version to '3'\"\n amulet.raise_status(amulet.FAIL, msg=msg)\n return\n if self._get_openstack_release() >= self.trusty_mitaka:\n # NOTE(jamespage):\n # Re-init tests to create v3 versions of glance, swift and\n # keystone clients for mitaka or later, where glance uses\n # v3 to access backend swift services. Early v3 deployments\n # still use v2 credentials in glance for swift access.\n self._initialize_tests(api_version=3)\n self.test_400_swift_backed_image_create()\n\n def test_900_restart_on_config_change(self):\n \"\"\"Verify that the specified services are restarted when the config\n is changed.\"\"\"\n u.log.info('Checking that conf files and system services respond '\n 'to a charm config change...')\n\n sentry = self.swift_proxy_sentry\n juju_service = 'swift-proxy'\n\n # Process names, corresponding conf files\n services = {'swift-proxy-server': '/etc/swift/proxy-server.conf'}\n\n # Expected default and alternate values\n set_default = {'node-timeout': '60'}\n set_alternate = {'node-timeout': '90'}\n\n # Make config change, check for service restarts\n u.log.debug('Making config change on {}...'.format(juju_service))\n mtime = u.get_sentry_time(sentry)\n self.d.configure(juju_service, set_alternate)\n\n sleep_time = 40\n for s, conf_file in services.items():\n u.log.debug(\"Checking that service restarted: {}\".format(s))\n if not u.validate_service_config_changed(sentry, mtime, s,\n conf_file,\n sleep_time=sleep_time):\n self.d.configure(juju_service, set_default)\n msg = \"service {} didn't restart after config change\".format(s)\n amulet.raise_status(amulet.FAIL, msg=msg)\n sleep_time = 0\n\n self.d.configure(juju_service, set_default)\n\n def test_901_no_restart_on_config_change_when_paused(self):\n \"\"\"Verify that the specified services are not restarted when the config\n is changed and the unit is paused.\"\"\"\n u.log.info('Checking that system services do not get restarted '\n 'when charm config changes but unit is paused...')\n sentry = self.swift_proxy_sentry\n juju_service = 'swift-proxy'\n\n # Expected default and alternate values\n set_default = {'node-timeout': '60'}\n set_alternate = {'node-timeout': '90'}\n\n services = ['swift-proxy', 'haproxy', 'apache2', 'memcached']\n\n # Pause the unit\n u.log.debug('Pausing the unit...')\n pause_action_id = u.run_action(sentry, \"pause\")\n assert u.wait_on_action(pause_action_id), \"Pause action failed.\"\n # Make config change, check for service restarts\n u.log.debug('Making config change on {}...'.format(juju_service))\n self.d.configure(juju_service, set_alternate)\n\n for service in services:\n u.log.debug(\"Checking that service didn't start while \"\n \"paused: {}\".format(service))\n # No explicit assert because get_process_id_list will do it for us\n u.get_process_id_list(\n sentry, service, expect_success=False)\n\n self.d.configure(juju_service, set_default)\n resume_action_id = u.run_action(sentry, \"resume\")\n assert u.wait_on_action(resume_action_id), \"Resume action failed.\"\n\n def _assert_services(self, should_run):\n swift_proxy_services = ['swift-proxy-server',\n 'haproxy',\n 'apache2',\n 'memcached']\n u.get_unit_process_ids(\n {self.swift_proxy_sentry: swift_proxy_services},\n expect_success=should_run)\n # No point using validate_unit_process_ids, since we don't\n # care about how many PIDs, merely that they're running, so\n # would populate expected with either True or False. This\n # validation is already performed in get_process_id_list\n\n def _test_pause(self):\n u.log.info(\"Testing pause action\")\n self._assert_services(should_run=True)\n pause_action_id = u.run_action(self.swift_proxy_sentry, \"pause\")\n assert u.wait_on_action(pause_action_id), \"Pause action failed.\"\n\n self._assert_services(should_run=False)\n status, message = u.status_get(self.swift_proxy_sentry)\n if status != \"maintenance\":\n msg = (\"Pause action failed to move unit to maintenance \"\n \"status (got {} instead)\".format(status))\n amulet.raise_status(amulet.FAIL, msg=msg)\n if message != \"Paused. Use 'resume' action to resume normal service.\":\n msg = (\"Pause action failed to set message\"\n \" (got {} instead)\".format(message))\n amulet.raise_status(amulet.FAIL, msg=msg)\n\n def _test_resume(self):\n u.log.info(\"Testing resume action\")\n # service is left paused by _test_pause\n self._assert_services(should_run=False)\n resume_action_id = u.run_action(self.swift_proxy_sentry, \"resume\")\n assert u.wait_on_action(resume_action_id), \"Resume action failed.\"\n\n self._assert_services(should_run=True)\n status, message = u.status_get(self.swift_proxy_sentry)\n if status != \"active\":\n msg = (\"Resume action failed to move unit to active \"\n \"status (got {} instead)\".format(status))\n amulet.raise_status(amulet.FAIL, msg=msg)\n if message != \"Unit is ready\":\n msg = (\"Resume action failed to clear message\"\n \" (got {} instead)\".format(message))\n amulet.raise_status(amulet.FAIL, msg=msg)\n\n def test_902_pause_resume_actions(self):\n \"\"\"Pause and then resume swift-proxy.\"\"\"\n u.log.debug('Checking pause/resume actions...')\n self._test_pause()\n self._test_resume()\n\n def test_903_disk_usage_action(self):\n \"\"\"diskusage action can be run\"\"\"\n u.log.info(\"Testing diskusage action\")\n action_id = u.run_action(self.swift_proxy_sentry, \"diskusage\")\n assert u.wait_on_action(action_id), \"diskusage action failed.\"\n\n u.log.info('OK')\n","sub_path":"tests/basic_deployment.py","file_name":"basic_deployment.py","file_ext":"py","file_size_in_byte":29105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"419259051","text":"import re\ntab = []\n\nwith open ('./land.txt') as file:\n for line in file:\n cyfra = re.findall('\\d', line)\n for i in cyfra:\n tab.append(int(i))\n \nsuma = 0\nfor l in tab:\n suma += l\n \nprint (f'suma cyfr: {suma}')","sub_path":"03-FileHandling/z23.py","file_name":"z23.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"} +{"seq_id":"6893611","text":"\"\"\"\nThis module provides the tools for Garry's Mod Lua interoperability such as getting, setting values, indexing tables\nand calling functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom numbers import Number\n\nfrom luastack import LuaStack, Special, IN_GMOD, ValueType\n\n__all__ = ['G', 'exec', 'eval', 'table', 'LuaObjectWrapper']\n\nls = LuaStack()\n\n\nclass Reference:\n def __init__(self, ref):\n self.ref = int(ref)\n\n def __enter__(self):\n ls.push_ref(self.ref)\n\n def __exit__(self, exc_type, exc_value, traceback):\n ls.pop(1)\n\n\ndef push_pyval_to_stack(val):\n \"\"\"Converts a Python value to a Lua value and pushes it to the Lua stack.\n\n Supported types:\n\n ============================== ========================================================\n Python type Lua type\n ============================== ========================================================\n ``None`` ``nil``\n Any number number\n :class:`LuaObject` Whatever ``LuaObject.ref`` is pointing to\n :class:`str`, :class:`bytes` string\n :class:`bool` bool\n :class:`LuaObjectWrapper` Whatever ``LuaObjectWrapper.lua_obj.ref is pointing to\n \"\"\"\n if val is None:\n ls.push_nil()\n if isinstance(val, Number):\n ls.push_number(val)\n elif isinstance(val, LuaObject):\n ls.push_ref(val.ref)\n elif isinstance(val, str):\n ls.push_string(val.encode())\n elif isinstance(val, bytes):\n ls.push_string(val)\n elif isinstance(val, bool):\n ls.push_bool(val)\n elif isinstance(val, LuaObjectWrapper):\n ls.push_ref(val.lua_obj.ref)\n else:\n raise TypeError(f'unsupported value type: {type(val)}')\n\n\nclass LuaObject:\n def __init__(self):\n \"\"\"Creates a :class:`LuaObject` which points to the topmost stack value and pops it.\"\"\"\n self.ref = ls.create_ref()\n self._context = Reference(self.ref)\n\n def __del__(self):\n ls.free_ref(self.ref)\n\n @property\n def type(self):\n \"\"\"Returns the :class:`luastack.ValueType` of the held value.\"\"\"\n with self._context:\n return ls.get_type(-1)\n\n @property\n def type_name(self):\n \"\"\"Returns the :class:`str` type representation of the held value.\"\"\"\n with self._context:\n return ls.get_type_name(ls.get_type(-1))\n\n def __str__(self):\n if self.type == ValueType.NIL:\n return 'None'\n\n with self._context:\n val = ls.get_string(-1)\n if val is None:\n raise ValueError(\"can't convert this value to str/bytes\")\n if isinstance(val, bytes):\n return val.decode()\n else:\n return val\n\n def __int__(self):\n with self._context:\n return int(ls.get_number(-1))\n\n def __float__(self):\n with self._context:\n return float(ls.get_number(-1))\n\n def __bool__(self):\n with self._context:\n return ls.get_bool(-1)\n\n def __setitem__(self, key, value):\n if self.type == ValueType.NIL:\n raise ValueError(\"can't index nil\")\n\n with self._context:\n push_pyval_to_stack(key)\n push_pyval_to_stack(value)\n ls.set_table(-3)\n\n def __getitem__(self, key):\n if self.type == ValueType.NIL:\n raise ValueError(\"can't index nil\")\n\n with self._context:\n push_pyval_to_stack(key)\n ls.get_table(-2)\n return LuaObject()\n\n def __call__(self, *args):\n if self.type == ValueType.NIL:\n raise ValueError(\"can't call nil\")\n\n ls.push_ref(self.ref)\n for val in args:\n push_pyval_to_stack(val)\n ls.call(len(args), -1)\n returns = []\n while ls.top() > 1:\n returns.insert(0, LuaObject())\n if len(returns) == 1:\n return returns[0]\n elif len(returns) > 1:\n return tuple(returns)\n\n def __repr__(self):\n return f''\n\n\n# Lua global table\nif IN_GMOD:\n ls.push_special(Special.GLOBAL)\n G = LuaObject()\nelse:\n G = None\n\n\ndef exec(code):\n \"\"\"Executes the given Lua code block. Returns nothing.\n\n ::\n\n code = 'MsgN(\"test\")'\n lua.exec(code) # 'test' will be printed to the console\n \"\"\"\n if not isinstance(code, str):\n raise TypeError('code must be str, not ' + type(code).__name__)\n\n ls.push_special(Special.GLOBAL)\n\n ls.get_field(-1, b'RunString')\n ls.push_string(code.encode()) # Arg 1: code\n ls.push_string(b'GPython lua.exec') # Arg 2: identifier\n ls.push_bool(True) # Arg 3: throw error if error occurred during code exec\n\n ls.call(3, 0) # Call RunString and pop it from the stack\n\n ls.pop(1) # GLOBAL\n\n\ndef eval(expr):\n \"\"\"Evaluates a single Lua expression. Returns a :class:`LuaObject` with an evaluation result.\n\n ::\n\n expr = 'game.SinglePlayer()' # Returns \"true\" if the current session is a single player game\n single_player_luaobj = lua.eval(expr)\n # Remember that we need to convert the evaluation result to bool explicitly\n single_player = bool(single_player_luaobj)\n\n # Now we can use it\n if single_player:\n ...\n \"\"\"\n if not isinstance(expr, str):\n raise TypeError('expr must be str, not ' + type(expr).__name__)\n\n ls.push_special(Special.GLOBAL)\n\n ls.get_field(-1, b'RunString')\n ls.push_string(f'_gpy_temp = {expr}'.encode()) # Assign expression to a temporary variable \"_gpy_temp\"\n ls.push_string(b'GPython lua.eval')\n ls.push_bool(True)\n\n ls.call(3, 0)\n\n # Grabbing the result from _gpy_temp\n ls.get_field(-1, b'_gpy_temp')\n obj = LuaObject()\n\n # Cleaning up: setting _gpy_temp to nil\n ls.push_nil()\n ls.set_field(-2, b'_gpy_temp')\n\n ls.pop(1) # GLOBAL\n return obj\n\n\ndef table(iterable):\n \"\"\"Creates and returns a :class:`LuaObject` of a new Lua table from ``iterable``.\n\n ::\n\n tbl = lua.table(1, 2, 3)\n lua.G['PrintTable'](tbl)\n \"\"\"\n ls.clear() # Everything might go wrong if the stack is not empty\n\n ls.create_table()\n ls.push_special(Special.GLOBAL)\n ls.get_field(-1, b'table')\n for v in iterable:\n ls.get_field(-1, b'insert')\n ls.push(1) # Pushing that new table again\n try:\n push_pyval_to_stack(v)\n except TypeError: # In case of a value that can't be pushed\n ls.clear()\n raise # Raising TypeError again\n ls.call(2, 0)\n ls.pop(2) # Pop the 'table' namespace and the global table\n\n return LuaObject() # The new table is grabbed and popped by the LuaObject's constructor\n\n\nclass LuaObjectWrapper(ABC):\n \"\"\"Abstract class for Lua class wrappers, such as :class:`gmod.entity.Entity`.\n Subclasses of ``LuaObjectWrapper`` can be used in :class:`LuaObject` calls and :const:`G` indexing operations.\n\n Subclasses must implement a ``lua_obj`` property that should return the wrapped :class:`LuaObject`.\n \"\"\"\n\n @property\n @abstractmethod\n def lua_obj(self):\n pass\n","sub_path":"python_extensions/gmod/lua.py","file_name":"lua.py","file_ext":"py","file_size_in_byte":7241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}